Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,10 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac
indexes a sample.
- The first full backfill of a namespace also re-derives every file's edges after the
name table is complete, so cross-file references bind (`--no-edges-second-pass` skips
it). `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect their
directory agrees on.
it). The run records that it owes the pass before its first batch and clears the record
once the pass is done, so a resumed run, or a rerun after an interrupted pass, still
runs it. `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect
their directory agrees on.
- `backfill-prs` loads merged-PR history from GitHub, resumable by cursor and bounded by
GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12). `backfill-reviews`
adds inline review comments, `backfill-assignees` requested reviewers, and
Expand Down
65 changes: 46 additions & 19 deletions server/cli/code_backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,10 @@ async def _backfill(args: argparse.Namespace) -> int:
print(f"twin label: rows written under embedding_model={model_name!r}")
denylist = await load_denylist(cfg, head, gitrepo.show_file)
cursor_key = f"backfill_cursor:index{suffix}"
owed_key = f"backfill_edges_owed:index{suffix}"
mode = "repair" if paths_file else "twin" if suffix else "backfill"
done_upto = "" if paths_file else await repo.get_state(org, ns, cursor_key)
owed, recorded = await _record_edge_pass(repo, org, ns, args, owed_key, str(done_upto or ""))
start_idx = int(done_upto) if done_upto.isdigit() else 0
started = time.monotonic()
sem = asyncio.Semaphore(max(1, args.concurrency))
Expand Down Expand Up @@ -196,13 +198,10 @@ async def _one(reads: Any, path: str, source: bytes) -> None:
f"({rate:.1f} files/s)"
)

if second_pass_wanted(
explicit=bool(getattr(args, "edges_second_pass", False)),
declined=bool(getattr(args, "no_edges_second_pass", False)),
paths_file=bool(paths_file),
done_upto=str(done_upto or ""),
):
if not getattr(args, "edges_second_pass", False):
if owed:
if recorded:
print(f"edge second pass owed by an earlier run of this backfill ({recorded})")
elif owed == "first-backfill":
print("first full backfill of this namespace: edge second pass implied")
second = await _second_edge_pass(
repo,
Expand All @@ -218,6 +217,8 @@ async def _one(reads: Any, path: str, source: bytes) -> None:
)
counters["edges_second_pass"] = second["edges"]
counters["errors"] += second["errors"]
if not paths_file and not second["errors"]:
await repo.set_state(org, ns, owed_key, "")
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
if getattr(args, "dialect_folder_pass", False):
folder = await _dialect_folder_pass(repo, org, ns, head)
counters["dialect_inherited"] = folder["inherited"]
Expand Down Expand Up @@ -307,20 +308,46 @@ async def _backfill_paths(
return headers_first(paths)


def second_pass_wanted(*, explicit: bool, declined: bool, paths_file: bool, done_upto: str) -> bool:
"""A namespace's FIRST full backfill indexes files in
tree order, so a call to a function whose file comes later binds
nothing (a call in fastify.js to `buildRouting(…)` reads `unresolved,
0 candidates` while lib/route.js is not yet indexed). The edges-only
second pass is what repairs that, so a first full
backfill implies it; `--edges-second-pass` asks for it on any run,
`--no-edges-second-pass` declines the implied one. A resumed run
(cursor set) or a `--paths-file` repair implies nothing."""
async def _record_edge_pass(
repo: Any, org: str, ns: str, args: argparse.Namespace, owed_key: str, done_upto: str
) -> tuple[str, str]:
"""(why this run owes the edge pass, why an earlier run recorded it owed). A cursor
run records its reason before its first batch, so a run interrupted from there on
leaves the pass owed; a `--paths-file` repair records nothing."""
paths_file = bool(getattr(args, "paths_file", ""))
recorded = "" if paths_file else await repo.get_state(org, ns, owed_key)
owed = edge_pass_owed(
explicit=bool(getattr(args, "edges_second_pass", False)),
declined=bool(getattr(args, "no_edges_second_pass", False)),
paths_file=paths_file,
done_upto=done_upto,
recorded=recorded,
)
if not paths_file and owed != recorded:
await repo.set_state(org, ns, owed_key, owed)
return owed, recorded


def edge_pass_owed(
*, explicit: bool, declined: bool, paths_file: bool, done_upto: str, recorded: str
) -> str:
"""Why this run owes the edges-only second pass, '' when it does not. A
namespace's FIRST full backfill indexes files in tree order, so a call to a
function whose file comes later binds nothing (a call in fastify.js to
`buildRouting(…)` reads `unresolved, 0 candidates` while lib/route.js is not
yet indexed); the second pass repairs that, so a first full backfill implies
it. `--edges-second-pass` asks for it on any run, `--no-edges-second-pass`
declines it. A cursor run records the reason before its first batch and
clears it once the pass is done (`recorded`), so a resumed run, or a rerun
after an interrupted pass, still runs it. A resumed run with nothing
recorded, and a `--paths-file` repair, imply nothing."""
if explicit:
return True
return "requested"
if declined or paths_file:
return False
return not done_upto
return ""
if recorded:
return recorded
return "" if done_upto else "first-backfill"


async def _second_edge_pass(
Expand Down
195 changes: 183 additions & 12 deletions tests/unit/test_cli_backfill_second_pass.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,201 @@
"""A namespace's first full backfill implies the edges-only
second pass — indexing order otherwise leaves every call
to a later file unresolved with zero candidates."""
to a later file unresolved with zero candidates. The pass is recorded as owed
before the first batch, so a run interrupted before it finishes leaves it to the
next run."""

from __future__ import annotations

from server.cli.code_backfill import second_pass_wanted
import argparse
import asyncio
from typing import Any

import pytest

from server.cli import code_backfill
from server.cli.code_backfill import edge_pass_owed
from tests.unit.code_fixtures import repo_config


def test_first_full_backfill_implies_the_second_pass() -> None:
assert (
second_pass_wanted(explicit=False, declined=False, paths_file=False, done_upto="") is True
owed = edge_pass_owed(
explicit=False, declined=False, paths_file=False, done_upto="", recorded=""
)
assert owed == "first-backfill"


def test_a_resumed_run_or_a_repair_does_not_imply_it() -> None:
assert (
second_pass_wanted(explicit=False, declined=False, paths_file=False, done_upto="412")
is False
assert not edge_pass_owed(
explicit=False, declined=False, paths_file=False, done_upto="412", recorded=""
)
assert not edge_pass_owed(
explicit=False, declined=False, paths_file=True, done_upto="", recorded=""
)
assert (
second_pass_wanted(explicit=False, declined=False, paths_file=True, done_upto="") is False


def test_a_resumed_run_runs_the_pass_an_earlier_run_owed() -> None:
owed = edge_pass_owed(
explicit=False, declined=False, paths_file=False, done_upto="412", recorded="first-backfill"
)
assert owed == "first-backfill"


def test_the_flags_decide_when_given() -> None:
assert second_pass_wanted(explicit=True, declined=False, paths_file=True, done_upto="9") is True
assert (
second_pass_wanted(explicit=False, declined=True, paths_file=False, done_upto="") is False
owed = edge_pass_owed(
explicit=True, declined=False, paths_file=True, done_upto="9", recorded=""
)
assert owed == "requested"
assert not edge_pass_owed(
explicit=False, declined=True, paths_file=False, done_upto="", recorded="first-backfill"
)


class _Interrupted(Exception):
"""The process went away in the middle of a pass."""


class _Store:
"""The namespace's state rows, kept across the runs of one test."""

def __init__(self) -> None:
self.state: dict[str, str] = {}

def __call__(self) -> _Store:
return self # `CodeRepo()` in `_backfill`

async def get_state(self, org: str, ns: str, key: str) -> str:
return self.state.get(key, "")

async def set_state(self, org: str, ns: str, key: str, value: str, **_k: Any) -> None:
self.state[key] = value


def _harness(
monkeypatch: pytest.MonkeyPatch, tmp_path: Any, paths: list[str]
) -> tuple[_Store, dict[str, Any]]:
"""`_backfill` on a stubbed store and checkout; `plan` says which batch or pass
is interrupted, and records the batches and edge passes that ran."""
from server.code.app.index import bootstrap, denylist
from server.code.store import index

store = _Store()
plan: dict[str, Any] = {
"fail_batch": None,
"fail_edges": False,
"edge_errors": 0,
"batches": [],
"edges": 0,
}
cfg = repo_config(org="acme", namespace="code-x", git_dir=str(tmp_path))

async def _noop(*_a: object, **_k: object) -> None:
return None

async def _head(*_a: object) -> str:
return "f" * 40

async def _paths(*_a: object) -> list[str]:
return list(paths)

async def _batch(_repo: Any, _org: str, _ns: str, chunk: list[str], **_k: Any) -> str:
if chunk[0] == plan["fail_batch"]:
raise _Interrupted(chunk[0])
plan["batches"].append(chunk[0])
return ""

async def _edges(*_a: object, **_k: object) -> dict[str, int]:
if plan["fail_edges"]:
raise _Interrupted("edge pass")
plan["edges"] += 1
return {"files": len(paths), "edges": 0, "errors": plan["edge_errors"]}

monkeypatch.setattr(index, "CodeRepo", store)
monkeypatch.setattr(code_backfill, "_repo_cfg", lambda _a: cfg)
monkeypatch.setattr(code_backfill, "connect_code_plane", _noop)
monkeypatch.setattr(code_backfill, "_backfill_head", _head)
monkeypatch.setattr(code_backfill, "_backfill_paths", _paths)
monkeypatch.setattr(code_backfill, "_held_batch", _batch)
monkeypatch.setattr(code_backfill, "_second_edge_pass", _edges)
monkeypatch.setattr(code_backfill, "_close_index", _noop)
monkeypatch.setattr(denylist, "load_denylist", _noop)
monkeypatch.setattr(bootstrap, "record_backfill_stamps", _noop)
return store, plan


def _backfill(**kw: Any) -> int:
base: dict[str, Any] = {
"org": "acme",
"namespace": "code-x",
"phase": "index",
"embed": False,
"paths_file": "",
"limit": 0,
"concurrency": 2,
"edges_second_pass": False,
"no_edges_second_pass": False,
"dialect_folder_pass": False,
"embedding_model_suffix": "",
}
base.update(kw)
return asyncio.run(code_backfill._backfill(argparse.Namespace(**base)))


_PATHS = [f"f{i}.py" for i in range(450)]


def test_a_first_backfill_interrupted_in_its_index_phase_gets_its_edge_pass_on_resume(
monkeypatch: pytest.MonkeyPatch, tmp_path: Any
) -> None:
store, plan = _harness(monkeypatch, tmp_path, _PATHS)
plan["fail_batch"] = "f200.py"
with pytest.raises(_Interrupted):
_backfill()
assert store.state["backfill_cursor:index"] == "200"
plan["fail_batch"] = None
assert _backfill() == 0 # resumed at 200
assert plan["batches"] == ["f0.py", "f200.py", "f400.py"]
assert plan["edges"] == 1
assert store.state["backfill_edges_owed:index"] == ""
assert store.state["git_head"] == "f" * 40


def test_a_rerun_after_an_interrupted_edge_pass_runs_the_pass(
monkeypatch: pytest.MonkeyPatch, tmp_path: Any
) -> None:
store, plan = _harness(monkeypatch, tmp_path, _PATHS)
plan["fail_edges"] = True
with pytest.raises(_Interrupted):
_backfill()
assert store.state["backfill_cursor:index"] == str(len(_PATHS))
assert "git_head" not in store.state
plan["fail_edges"] = False
assert _backfill() == 0 # no batch left, the pass still owed
assert plan["edges"] == 1
assert store.state["git_head"] == "f" * 40


def test_declining_the_pass_clears_what_an_earlier_run_owed(
monkeypatch: pytest.MonkeyPatch, tmp_path: Any
) -> None:
store, plan = _harness(monkeypatch, tmp_path, _PATHS)
plan["fail_batch"] = "f200.py"
with pytest.raises(_Interrupted):
_backfill()
plan["fail_batch"] = None
assert _backfill(no_edges_second_pass=True) == 0
assert plan["edges"] == 0
assert store.state["backfill_edges_owed:index"] == ""


def test_an_edge_pass_with_a_failed_file_write_stays_owed_until_a_rerun_finishes_clean(
monkeypatch: pytest.MonkeyPatch, tmp_path: Any
) -> None:
store, plan = _harness(monkeypatch, tmp_path, _PATHS)
plan["edge_errors"] = 1 # one file's edge write failed
_backfill()
assert plan["edges"] == 1
assert store.state["backfill_edges_owed:index"] == "first-backfill"
plan["edge_errors"] = 0
assert _backfill() == 0 # no batch left, the pass still owed
assert plan["edges"] == 2
assert store.state["backfill_edges_owed:index"] == ""
Loading