Skip to content
13 changes: 8 additions & 5 deletions docs/architecture/code-index-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,14 @@ remote, and any host can rebuild the mirror from it.
`git blame` runs, which makes a history read a network read and would reach the
remote outside the repository-job sandbox.
- **The gate.** Every history read goes through `mirrors.history_dir`, which returns
the mirror or why there is none. Until the mirror
is there the read answers `no_git_mirror: cloning <entry>` (or why it will not be
cloned here) instead of a git error, and starts the clone if none is running.
`LOOM_GIT_HISTORY=none` turns history off on a host: those reads answer
`no_git_history`.
the mirror of the namespace's own repository entry or why there is none. For a
namespace no entry indexes, `history_dir` answers
`no_git_mirror: the namespace has no repository entry` and reads no mirror, the scalar
entry's (`LOOM_CODE_*`) included. The PR overlay checks the entry before that and
answers `overlay_note: no_repo_entry`. Until the mirror is there the read answers
`no_git_mirror: cloning <entry>` (or why it will not be cloned here) instead of a git
error, and starts the clone if none is running. `LOOM_GIT_HISTORY=none` turns history
off on a host: those reads answer `no_git_history`.
- **The host loop.** Only the leader asks the remote what changed (`ls-remote` of the
extra branches and the PR heads). What its pass fetched is in ClickHouse: each
entry's branch tip (`clone_head`), the open PRs' heads (`code_gh_items.head_sha`) and
Expand Down
31 changes: 15 additions & 16 deletions docs/features/code-index/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -703,21 +703,20 @@ statement removed after it) is not listed. So when nothing matches at an older c
never wrote.

The commit must be one the indexed head contains
([the bound](history-and-prs.md#history-stays-inside-the-indexed-head)), on the
namespace's mirror; `at_commit` equal to the indexed head's full sha reads no mirror. A
namespace with no indexed head, a commit the mirror places outside the indexed head, an
abbreviation that matches more than one object on the mirror and no single commit, or
hex that git reads as a branch or tag name whose commit's sha does not start with it, is
refused with a validation error that names why: the last one asks for the full sha, which
git always reads as the commit. An entry's mirror that is still cloning, retrying a
failed clone or has not fetched the indexed head yet answers 503 `BACKEND_UNAVAILABLE`
with a retry hint when this host clones or fetches it (the entry names a remote this host
may reach): the read starts that clone or fetch. Otherwise what the mirror lacks is
refused. A git call that fails or times out answers 503 too. A namespace no entry indexes
reads the scalar entry's mirror when it is in the scalar entry's org (`LOOM_CODE_ORG`),
and is refused otherwise. Nothing fetches into its mirror for such a read, so a host that
keeps no mirrors or holds none of it, or a mirror that does not hold the indexed head, is
refused too. No refusal falls back to an answer at the head.
([the bound](history-and-prs.md#history-stays-inside-the-indexed-head)), on the mirror
of the namespace's repository entry; `at_commit` equal to the indexed head's full sha
reads no mirror. A namespace no entry indexes is refused for any other commit with
`no_git_mirror: the namespace has no repository entry` and reads no mirror, the scalar
entry's (`LOOM_CODE_*`) included. A namespace with no indexed head, a commit the mirror
lacks or places outside the indexed head, an abbreviation that matches more than one
object on the mirror and no single commit, or hex that git reads as a branch or tag name
whose commit's sha does not start with it, is refused with a validation error that names
why: the last one asks for the full sha, which git always reads as the commit. An
entry's mirror that is still cloning, retrying a failed clone or has not fetched the
indexed head yet answers 503 `BACKEND_UNAVAILABLE` with a retry hint when this host
clones or fetches it (the entry names a remote this host may reach): the read starts
that clone or fetch. Otherwise what the mirror lacks is refused. A git call that fails
or times out answers 503 too. No refusal falls back to an answer at the head.

## History, PRs and releases

Expand Down Expand Up @@ -768,7 +767,7 @@ no GitHub call; a title alone never reads as a duplicate.
| `code.scip_status` | viewer | the state of an uploaded compiler-tier delta |
| `code.refresh` | writer | trigger an ingest pass now ([freshness.md](freshness.md#pushing-freshness-from-ci)) |
| `code.scip_ingest` | writer | upload a compiler-tier delta from an external producer (applied by `code_scip_apply`) |
| `code.reindex` | admin | move the ingest watermark to a commit |
| `code.reindex` | admin | move an indexed namespace's ingest watermark to a commit |
| `code.calibrate` | admin | refit the search's noise floor, abstain threshold and confident-hit cosine, the top of the `retrieval_confidence` scale |

`code.repos` finds a fork's parent by asking GitHub whether a `repos` candidate is a fork.
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/operations/code.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ Rank PRs that may have introduced a bug; Loom does not test or reproduce it.
| `bad_version` | `str` | `''` | The first release on which the caller or an upstream test observed the bug (`26.3`, or a full version cut to its minor); Loom does not test it, and the value wins over the issue's `reproduces_on`. "" = from the issue. |
| `before` | `str` | `''` | The inclusive upper bound of an approximate merge-time investigation window when release observations are unavailable; it narrows candidate history and does not mean Loom reproduced the bug. |
| `after` | `str` | `''` | Optional lower bound of the merge-time window (ISO-8601); must be earlier than `before`. |
| `bad_sha` | `str` | `''` | A commit (hex) whose commit time on the code mirror becomes `before` when `before` is unset; a sha the mirror lacks, or holds past the namespace's indexed head, is refused with `BAD_SHA`. |
| `bad_sha` | `str` | `''` | A commit (hex) whose commit time on the code mirror becomes `before` when `before` is unset; a namespace with no repository entry, or a sha the mirror lacks or holds past the namespace's indexed head, is refused with `BAD_SHA`. |
| `good_version` | `str` | `''` | The newest release that the caller or an upstream test observed as clean; Loom does not test it, and the value wins over the issue's `clean_on`. "" = from the issue, or a lookback from `bad_version`. |
| `widen_to_directories` | `bool` | `True` | widen the candidate set from the frames' files to their directories when frames or patterns can rank within it |
| `wideners` | `list[str]` | *(computed)* | What may bound the scan when no frame resolves to a file — `patterns` (the window's diffs carrying the issue's rarest identifiers), `component` (the directories the issue's component touches), `fix_candidate` (the fix's own files: the… |
Expand Down
4 changes: 2 additions & 2 deletions server/code/api/models_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ class CodeBisectCandidatesInput(_CodeIdentity):
# Optional lower bound of the merge-time window (ISO-8601); must be earlier than `before`.
after: str = Field(default="", max_length=40)
# A commit (hex) whose commit time on the code mirror becomes `before` when `before`
# is unset; a sha the mirror lacks, or holds past the namespace's indexed head, is
# refused with `BAD_SHA`.
# is unset; a namespace with no repository entry, or a sha the mirror lacks or holds
# past the namespace's indexed head, is refused with `BAD_SHA`.
bad_sha: str = Field(default="", max_length=64)
# The newest release that the caller or an upstream test observed as clean; Loom
# does not test it, and the value wins over the issue's `clean_on`. "" = from the
Expand Down
11 changes: 9 additions & 2 deletions server/code/app/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
CodeReindexOutput,
)
from server.code.app.common import require_code_intel, resolve_code_identity
from server.code.domain.index.repos import repo_for_namespace
from server.code.store.index import CodeRepo
from server.core.errors import ValidationError
from server.core.errors import NotFoundError, ValidationError
from server.core.paths import REPO_ROOT

logger = logging.getLogger(__name__)
Expand All @@ -24,11 +25,17 @@
async def handle_code_reindex(input: CodeReindexInput) -> CodeReindexOutput:
"""Operator repair: move the git watermark (e.g. back N commits after a
bad pass, or to a specific sha). The ingest worker re-walks from there;
all writes are idempotent upserts, so re-walking is always safe."""
all writes are idempotent upserts, so re-walking is always safe. A
namespace no repository entry indexes is refused: no ingest walks it."""
require_code_intel()
org, ns = resolve_code_identity(input.org, input.namespace)
if not input.git_head or len(input.git_head) != 40:
raise ValidationError("git_head must be a full 40-char commit sha")
if repo_for_namespace(org, ns) is None: # as code.refresh: not configured is a 404
raise NotFoundError(
f"namespace {org}/{ns} has no repository entry, so no ingest walks it; "
"code.repos lists the indexed namespaces"
)
repo = CodeRepo()
previous = await repo.get_state(org, ns, "git_head")
await repo.set_state(
Expand Down
59 changes: 21 additions & 38 deletions server/code/app/at_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,32 @@
source files are compared in the same batch, so a touched definition in one that differs
at the head carries the flag too.

The commit must be one the indexed head contains, on the namespace's mirror; the indexed
head's full sha needs no mirror. A namespace no entry indexes reads the scalar entry's
mirror (`LOOM_CODE_*`) when it is in the scalar entry's org. A namespace with no indexed
head is refused before any mirror read, and one no entry indexes outside the scalar entry's
org is refused as naming no repository. A commit the mirror places outside the head, an
abbreviation that matches more than one object on it and no single commit, or hex git reads
as a ref to a commit whose sha does not start with it, is refused with a validation error.
An entry's mirror still cloning, retrying a failed clone or not yet holding the indexed
head answers `BackendUnavailableError`, a retry, when this host clones or fetches it: the
read starts that clone or fetch. A read whose mirror nothing fetches into for it (the
scalar entry's, or an entry's whose remote this host may not reach) is refused (422) when
it lacks the mirror or the indexed head. A git call that fails or times out is a retry. No
refusal falls back to an answer at the head.
The commit must be one the indexed head contains, on the mirror of the namespace's
repository entry; the indexed head's full sha needs no mirror. A namespace with no indexed
head is refused before any mirror read, and one no entry indexes is refused with
`mirrors.NO_REPO_ENTRY`: it reads no mirror, the scalar entry's (`LOOM_CODE_*`) included. A
commit the mirror lacks or places outside the head, an abbreviation that matches more than
one object on it and no single commit, or hex git reads as a ref to a commit whose sha does
not start with it, is refused with a validation error. An entry's mirror still cloning,
retrying a failed clone or not yet holding the indexed head answers
`BackendUnavailableError`, a retry, when this host clones or fetches it: the read starts
that clone or fetch. Otherwise (this host neither clones nor fetches it) what the mirror
lacks is refused (422). A git call that fails or times out is a retry. No refusal falls
back to an answer at the head.
"""

from __future__ import annotations

import asyncio
import os
from collections.abc import Iterable
from dataclasses import dataclass, field, replace
from typing import Any

from server.code.app.index import commit_coverage, gitrepo, mirrors
from server.code.app.index.bootstrap import fetches_into, history_enabled
from server.code.app.index.bootstrap import fetches_into
from server.code.app.spans import code_span
from server.code.app.symbol.test_links import Links
from server.code.domain.index.repos import default_git_dir, repo_for_namespace
from server.code.domain.index.repos import repo_for_namespace
from server.code.domain.index.test_gate import is_test_path
from server.core.errors import BackendUnavailableError, ValidationError
from server.settings import settings
Expand Down Expand Up @@ -111,25 +109,6 @@ def _refused(op: str, why: str) -> ValidationError:
return ValidationError(f"{op}: `at_commit` reads the namespace's git mirror: {why}")


async def _mirror(cfg: Any, org: str, head: str, *, op: str) -> str:
"""The mirror an `at_commit` read uses: the entry's, which `history_dir` clones when it
is missing and this host may, so those gaps are retried; else the scalar entry's mirror,
for a namespace of the scalar entry's org only, when this host holds it."""
if cfg is not None:
git_dir, gap = await mirrors.history_dir(cfg, op=op, head=head)
if not git_dir:
raise _retry(op, gap) if mirrors.clones_here(cfg) else _refused(op, gap)
return git_dir
if not history_enabled():
raise _refused(op, mirrors.NO_GIT_HISTORY)
git_dir = default_git_dir() if org == settings.code_org else ""
if not git_dir:
raise _refused(op, "the namespace names no repository")
if not await asyncio.to_thread(os.path.isdir, git_dir):
raise _refused(op, "this host holds no mirror of the scalar entry's repository")
return git_dir


async def resolve(repo: Any, org: str, ns: str, at: str, *, op: str) -> AtCommit | None:
"""The commit `at_commit` names, None for ''; the module docstring lists its 422s and 503s."""
at = at.lower()
Expand All @@ -142,15 +121,19 @@ async def resolve(repo: Any, org: str, ns: str, at: str, *, op: str) -> AtCommit
if at == head.lower():
return AtCommit(sha=head, head=head, git_dir="")
cfg = repo_for_namespace(org, ns)
git_dir = await _mirror(cfg, org, head, op=op)
if cfg is None:
raise _refused(op, mirrors.NO_REPO_ENTRY)
# A gap `history_dir` closes on this host (a clone, a fetch of the head) is a retry.
git_dir, gap = await mirrors.history_dir(cfg, op=op, head=head)
if not git_dir:
raise _retry(op, gap) if mirrors.clones_here(cfg) else _refused(op, gap)
try:
named, ambiguous = await gitrepo.commit_ids(git_dir, (at, head))
except gitrepo.GitError as e:
raise _retry(op, "git did not answer") from e
if head not in named:
why = f"it does not hold the indexed head {head[:12]}"
fetched = cfg is not None and fetches_into(cfg)
raise _retry(op, f"{why} yet") if fetched else _refused(op, why)
raise _retry(op, f"{why} yet") if fetches_into(cfg) else _refused(op, why)
if at in ambiguous:
raise ValidationError(
f"{op}: at_commit {at} is ambiguous on the mirror; give more characters"
Expand Down
3 changes: 1 addition & 2 deletions server/code/app/backport.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,7 @@ async def _history_stage(
git_dir, refs = branch_refs(org, code_ns)
if not namespaces or not groups:
return {}
cfg = repo_for_namespace(org, code_ns)
if cfg is not None and (gap := (await history_dir(cfg))[1]):
if gap := (await history_dir(repo_for_namespace(org, code_ns)))[1]:
return {ns: ph.HistoryPresence(reason=gap) for ns in namespaces}
gate = asyncio.Semaphore(_HISTORY_GIT_PROCS)
tasks = {
Expand Down
28 changes: 12 additions & 16 deletions server/code/app/bisect.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@
from server.code.app.spans import code_span, set_code_span_attributes
from server.code.domain.index import blame_range as br
from server.code.domain.index.coverage_claim import is_test_file
from server.code.domain.index.repos import default_git_dir
from server.code.domain.time_window import _iso, _parse_when
from server.code.store.index import CodeRepo
from server.core.errors import ValidationError
Expand Down Expand Up @@ -274,7 +273,7 @@ async def _mark_stage(
records, stage.status = {}, "ledger_failed"
first = bi.mark_bisect_candidates(pool, records=records, frames=frames, diff_kinds={})
cfg, _siblings = cb.repo_siblings(org, ns)
git_dir, stage.reason = await cb.history_git_dir(cfg, "code.bisect_candidates")
git_dir, stage.reason = await history_dir(cfg, op="code.bisect_candidates")
targets = (
_diff_targets(pool, first, records, frames_or_paths=bool(frames or paths))
if git_dir
Expand Down Expand Up @@ -319,14 +318,16 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi.
logger.info("bisect: ledger merge commits unread (%s)", e)
stored = {}
cfg, _siblings = cb.repo_siblings(org, ns)
# no mirror here yet: the ledger's shas alone (history_dir starts the clone)
git_dir = (await history_dir(cfg))[0] if cfg is not None else default_git_dir()
branch = (cfg.git_branch if cfg is not None else "") or settings.code_git_branch
try:
ref = await cb.indexed_head(repo, org, ns) or (f"refs/heads/{branch}" if branch else "")
except Exception as e: # noqa: BLE001 — the head is unknown: no search past it
logger.info("bisect: indexed head unread, mirror search skipped (%s)", e)
ref = ""
# no entry or no mirror yet: the ledger's shas alone (history_dir starts the clone)
git_dir = (await history_dir(cfg))[0]
ref = ""
if git_dir:
try:
ref = await cb.indexed_head(repo, org, ns) or (
f"refs/heads/{cfg.git_branch}" if cfg.git_branch else ""
)
except Exception as e: # noqa: BLE001 — the head is unknown: no search past it
logger.info("bisect: indexed head unread, mirror search skipped (%s)", e)
since = min((br.unix_of(c.merged_at) for c in ranked), default=0)
got = await merge_shas.resolve(git_dir, ref, numbers, stored, since_unix=since)
for c in ranked:
Expand Down Expand Up @@ -948,12 +949,7 @@ async def _time_window(input: Any, org: str, ns: str) -> tuple[datetime | None,
from server.code.domain.index.repos import repo_for_namespace
from server.core.errors import ValidationError

cfg = repo_for_namespace(org, ns)
if cfg is None:
raise ValidationError(
f"{ns} has no repository mirror to resolve {sha!r}", code="BAD_SHA"
)
git_dir, gap = await history_dir(cfg)
git_dir, gap = await history_dir(repo_for_namespace(org, ns))
if gap:
raise ValidationError(f"{gap}; pass `before` as a time instead", code="BAD_SHA")
try:
Expand Down
5 changes: 3 additions & 2 deletions server/code/app/bisect_fix.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,9 @@ async def _fix_blame_stage(
`code.blame_range`, name the PR that wrote them; those PRs go first with `blamed_by_fix`.
Bounded (a few ranges, a wall budget) and fail-open: the pool as it was, and a summary
saying why."""
from server.code.app.blame import handle_code_blame_range, history_git_dir, repo_siblings
from server.code.app.blame import handle_code_blame_range, repo_siblings
from server.code.app.index import gitrepo
from server.code.app.index.mirrors import history_dir
from server.code.domain.index import fix_blame as fb

summary: dict[str, Any] = {"fix_pr": fix_pr}
Expand All @@ -319,7 +320,7 @@ async def _fix_blame_stage(
summary["skipped"] = "fix_not_in_ledger"
return pool, summary
cfg, _ = repo_siblings(org, ns)
git_dir, gap = await history_git_dir(cfg, "code.bisect_candidates")
git_dir, gap = await history_dir(cfg, op="code.bisect_candidates")
if gap:
summary["skipped"] = gap
return pool, summary
Expand Down
Loading
Loading