From e21252dc0a151ebedb1d1bd73a360a1139ec9a45 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 05:40:08 +0000 Subject: [PATCH 01/26] A merged PR's brief stored at an older payload version is rebuilt on read A stored brief whose payload version is below PAYLOAD_VERSION answered `unsettled` with `brief:v` on every read, and rule changes that alter a brief's answer did not bump the version. A read of a merged PR's brief of an older version now builds it again from its merge commit through the miss path and stores it in its place. The stored brief is served, with `code.review_brief: stale_brief_served` in `degraded`, when the read may not store, the host has no mirror, or the build fails or is left unstored; a failed build marks the row with the version it tried, so it runs at most once per stored row and version. A brief of a newer version is served as it is. PAYLOAD_VERSION is 3, and its comment says when to bump it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 16 +- server/code/app/index/review_brief.py | 13 +- server/code/app/review_brief.py | 59 +++++++ tests/unit/test_code_review_brief_mirror.py | 160 ++++++++++++++++++ .../unit/test_code_review_brief_no_groups.py | 2 +- tests/unit/test_code_review_brief_sections.py | 6 +- 6 files changed, 246 insertions(+), 10 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 8794a107f1e..360b3361f2c 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -242,7 +242,8 @@ values are tried in this order: spent, or a parse could not run here), whose parse of a file raised or ran past its limits, or that parsed another head than the one the brief's diff is read at (a push between the two reads, `head moved` in `overlay_note`); - - `brief:v` for a brief stored at an older payload version. + - `brief:v` for a brief stored at an older payload version, built by rules that + have changed since and served without a rebuild (see below). - `no_source_change`: every changed path is a test, a document, configuration, a file the ingest reads no symbols of (an image, a file its denylist refuses) or outside the index; a file a lane parser reads for its symbols (C++, Python, shell, TypeScript, Go, @@ -289,8 +290,17 @@ or parsed another head. A parse of a file that raised or ran past its limits doe same on every build of that file, at an open PR's head and at a merged PR's parent alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for the file, and an open PR's `overlay_note` counts it. A stored brief is served as it was -built: one of an older payload version (`v` in the payload) records no cap or failed -read, so its verdict is `gaps` or `unsettled`. +built, unless it is of an older payload version (`v` in the payload), which a change +to what a brief stores or how its verdict reads it raises. A read of a merged PR's brief +of an older version builds it again from its merge commit and stores the new brief in +its place (`source` names the build), once per stored row and version. The old brief is +served, its verdict `gaps` or `unsettled` with `brief:v`, and `degraded` names +`code.review_brief: stale_brief_served` with why, when the read does not store +(`store: false` or a measurement consumer), when the host has no mirror of the +repository (a host with one rebuilds it), or when the build raised, found nothing or was +not stored. In the last case the stored row records the version that tried and the +cause, and later reads of that version serve it without a build. A brief stored at a +newer version than the serving build's, during a rolling upgrade, is served as it is. `code.impact` maps a diff on its old side onto the index rows, which are at the indexed head (at the merge commit when the ingest builds a merged PR's brief, before it moves diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index dee741e831e..42305d9882b 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -73,10 +73,13 @@ logger = logging.getLogger(__name__) -# The payload's shape. A stored brief is served as it was built, and one of a lower -# version does not record its fan-out caps or the reads that raised, so its verdict -# cannot settle (`brief_verdict`). -PAYLOAD_VERSION = 2 +# The version of the rules a brief is built and answered by. Bump it in the change that +# alters what a build stores (a section, a row field, a cap, a cause) or what +# `brief_verdict` answers over a stored brief. A brief stored at a lower version answers +# `unsettled` with `brief:v`, and a read of a merged PR's builds it again from its merge +# commit and stores it, once per stored row and version +# (`server.code.app.review_brief._rebuild`). +PAYLOAD_VERSION = 3 SECTION_ORDER: tuple[str, ...] = ( "paths", @@ -725,7 +728,7 @@ def brief_verdict( (`symbols:ungraphed:`), a changed file whose row records an index error (`symbols:index_error:`), an open PR's overlay that was off (`overlay:`) or partial (`overlay:partial`), a brief stored at an older - payload `version`, which records no cap or failed read (`brief:v`); + payload `version`, built by rules that have changed since (`brief:v`); - `no_source_change`: every changed path is a test, a document, configuration or outside the index; - `unsettled`, when a check did not run in full, did not decide or rests on a diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 6b677570912..5d50a21b6a8 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -264,6 +264,8 @@ async def _payload_for( if not await _stored_inside_head(repo, org, ns, payload): payload = None # stored while the head held the merge; it no longer does if payload is not None: + if not is_open and int(payload.get("v") or 0) < rb.PAYLOAD_VERSION: + return await _rebuild(repo, org, ns, payload, store=store) return payload, "precomputed" with code_span("review_brief.build") as sp: if is_open: @@ -293,6 +295,63 @@ async def _payload_for( return payload, source +# What a stored brief of an older payload version records of the one build that tried to +# replace it: the version that build was of, and why its brief was not stored. +REBUILT_FOR = "rebuilt_for" +REBUILD_CAUSE = "rebuild_cause" + + +async def _rebuild( + repo: CodeRepo, org: str, ns: str, stale: dict[str, Any], *, store: bool +) -> tuple[dict[str, Any], Source]: + """A merged PR's brief stored at an older payload version, built again from its merge + commit through the miss path and stored in its place, at most once per stored row and + version. The stored brief is served instead, `unsettled` with `brief:v` and with + `stale_brief_served` in `degraded`, when this read may not store (`store: false`, a + measurement consumer), when this host has no mirror to read the diff from (a host with + one builds it), when a build of this version already tried, or when this build raised, + found nothing or left its brief unstored. In the last case the stored row is written + again with `rebuilt_for` and `rebuild_cause`, so no later read of this version builds + it again; a build of a newer version tries once more. A brief stored at a newer version + than this build's (a rolling upgrade) is never rebuilt here.""" + from server.code.domain.index.repos import repo_for_namespace + + pr_number, merge_sha = int(stale.get("pr_number") or 0), str(stale.get("merge_sha") or "") + if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: + return _stale_served(stale, str(stale.get(REBUILD_CAUSE) or "")) + if not store: + return _stale_served(stale, "store: false") + if not await present_dir(repo_for_namespace(org, ns)): + return _stale_served(stale, "no mirror on this host") + with code_span("review_brief.rebuild") as sp, degradations.scoped(): + fresh, source = await _build_on_miss( + repo, org, ns, pr_number=pr_number, merge_sha=merge_sha, store=True + ) + notes = degradations.current() + span_attrs(sp, results=int(fresh is not None)) + if fresh is not None and fresh.get("stored", True): + return fresh, source + cause = notes[0] if notes else ("unstored" if fresh is not None else "missing") + try: + # Another replica may have stored the rebuilt brief while this build ran. + row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=merge_sha) + latest = json.loads(str((row or {}).get("payload") or "{}")) + if int(latest.get("v") or 0) >= rb.PAYLOAD_VERSION: + return latest, "precomputed" + marked = {**stale, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} + await repo.insert_rows( + "code_review_briefs", [review_brief_build.brief_row(org, ns, marked)] + ) + except Exception as e: # noqa: BLE001 — unmarked, the next read builds it again + logger.warning("code.review_brief: rebuild of PR %s not recorded: %s", pr_number, e) + return _stale_served(stale, cause) + + +def _stale_served(stale: dict[str, Any], cause: str) -> tuple[dict[str, Any], Source]: + degradations.partial("code.review_brief", "stale_brief_served", cause) + return stale, "precomputed" + + async def _stored_inside_head(repo: CodeRepo, org: str, ns: str, payload: dict[str, Any]) -> bool: """Whether a stored merged brief is of a change the indexed head contains. The point read left out a PR the ledger places after the head; a brief built from the diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index f0fb156b95a..0cf175fe458 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -544,6 +544,166 @@ async def _no_mirror_here(cfg: Any) -> str: assert kept.source == "precomputed" +# ---- a brief stored at an older payload version ------------------------------ + + +async def _stale_row(wired: dict[str, Any], **extra: Any) -> dict[str, Any]: + """The stored row of the mirror PR's brief as an older build wrote it: payload version 2.""" + import json + + await h.handle_code_review_brief( + CodeReviewBriefInput(pr_number=MIRROR_FACTS["pr_number"], tier="full") + ) + [(_table, [row])] = wired["repo"].inserted + wired["repo"].inserted.clear() + wired["mirror"].clear() + payload = {**json.loads(row["payload"]), "v": 2, **extra} + return {**row, "payload": json.dumps(payload)} + + +async def _read(**kw: Any) -> tuple[CodeReviewBriefOutput, list[str]]: + from server.observability import degradations + + # every stored section; the rationale, read on each call, has no trunk to read here + sections = [n for n in rb.SECTION_ORDER if n != "tracker"] + with degradations.scoped(): + out = await h.handle_code_review_brief( + CodeReviewBriefInput( + pr_number=MIRROR_FACTS["pr_number"], tier="full", sections=sections, **kw + ) + ) + return out, degradations.current() + + +@pytest.mark.asyncio +async def test_a_brief_stored_at_an_older_version_is_rebuilt_once_and_stored_in_its_place( + wired: dict[str, Any], +) -> None: + import json + + repo = wired["repo"] + repo.stored = await _stale_row(wired) + stale, _ = await _read(store=False) + assert stale.source == "precomputed" and stale.built_at + + out, notes = await _read() + assert out.source == "built_from_mirror" and out.stored is True and notes == [] + assert wired["mirror"] == [("/nonexistent/mirror.git", "master", MIRROR_FACTS["pr_number"])] + [(_table, [row])] = repo.inserted + assert (row["pr_number"], row["merge_sha"]) == (MIRROR_FACTS["pr_number"], MIRROR_SHA) + assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION + # the rebuilt row is the one the next read finds: served as stored, nothing built + repo.stored = row + again, notes = await _read() + assert again.source == "precomputed" and notes == [] and len(repo.inserted) == 1 + assert (again.verdict, again.verdict_causes) == (out.verdict, out.verdict_causes) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("consumer", ["reviewer", "eval-b12"]) +async def test_a_read_that_may_not_store_or_has_no_mirror_serves_the_stale_brief_unbuilt( + wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch, consumer: str +) -> None: + """A rebuild nobody stores would run again on every read: a read that may not store + serves the stored brief, and so does a host whose mirror cannot read the diff.""" + repo = wired["repo"] + repo.stored = await _stale_row(wired) + store = consumer != "reviewer" # the measurement label never stores, whatever it passes + out, notes = await _read(consumer=consumer, store=store) + assert out.source == "precomputed" + assert notes == ["code.review_brief: stale_brief_served (store: false)"] + assert wired["mirror"] == [] and repo.inserted == [] + + async def _no_mirror_here(cfg: Any) -> str: + return "" + + monkeypatch.setattr(h, "present_dir", _no_mirror_here) + out, notes = await _read() + assert out.source == "precomputed" + assert notes == ["code.review_brief: stale_brief_served (no mirror on this host)"] + assert wired["mirror"] == [] and repo.inserted == [] + + +@pytest.mark.asyncio +async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( + wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A build whose diff cannot be read is not stored. The stale brief is served with + the cause and written again with the version that tried, so the next read of that + version builds nothing; a newer build's version tries again.""" + import json + + import server.code.app.index.gitrepo as gitrepo_mod + + repo = wired["repo"] + repo.stored = stale = await _stale_row(wired) + + async def _diff_fails(git_dir: str, *args: str, **kw: Any) -> str: + if args[0] == "rev-parse": + return PARENT + "\n" + raise RuntimeError("git diff failed") + + monkeypatch.setattr(gitrepo_mod, "run", _diff_fails) + out, notes = await _read() + cause = "git_mirror: diff_unread (RuntimeError)" + assert out.source == "precomputed" + assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert len(wired["mirror"]) == 1 + [(_table, [row])] = repo.inserted + marked = json.loads(row["payload"]) + assert marked == { + **json.loads(stale["payload"]), + h.REBUILT_FOR: rb.PAYLOAD_VERSION, + h.REBUILD_CAUSE: cause, + } + repo.stored = row + again, notes = await _read() + assert again.source == "precomputed" and again.sections == out.sections + assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert len(wired["mirror"]) == 1 and len(repo.inserted) == 1 + + monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION + 1) + await _read() + assert len(wired["mirror"]) == 2 and len(repo.inserted) == 2 + + +@pytest.mark.asyncio +async def test_a_failed_rebuild_serves_what_another_replica_stored_meanwhile( + wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + import json + + repo = wired["repo"] + stale = await _stale_row(wired) + fresh = {**stale, "payload": json.dumps({**json.loads(stale["payload"]), "v": 3})} + reads = iter([stale, fresh]) + + async def _point_read(org: str, ns: str, **kw: Any) -> dict[str, Any]: + return next(reads) + + async def _fails(*a: Any, **kw: Any) -> dict[str, Any]: + raise RuntimeError("build failed") + + monkeypatch.setattr(repo, "review_brief", _point_read) + monkeypatch.setattr(review_brief_build, "build_for_merge", _fails) + out, notes = await _read() + assert out.source == "precomputed" and notes == [] and repo.inserted == [] + + +@pytest.mark.asyncio +async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(wired: dict[str, Any]) -> None: + """During a rolling upgrade the older build never rebuilds what the newer one stored.""" + repo = wired["repo"] + stale = await _stale_row(wired) + import json + + newer = {**json.loads(stale["payload"]), "v": rb.PAYLOAD_VERSION + 1} + repo.stored = {**stale, "payload": json.dumps(newer)} + out, notes = await _read() + assert out.source == "precomputed" and notes == [] and repo.inserted == [] + assert not any(c.startswith("brief:") for c in out.verdict_causes) + + # ---- the ledger path is byte-identical to the base brief --------------------- diff --git a/tests/unit/test_code_review_brief_no_groups.py b/tests/unit/test_code_review_brief_no_groups.py index 9a6095f76bb..99222f2b0e3 100644 --- a/tests/unit/test_code_review_brief_no_groups.py +++ b/tests/unit/test_code_review_brief_no_groups.py @@ -18,7 +18,7 @@ from server.code.app.index import review_brief_build # pinned canonical digest of the brief below -PAYLOAD_DIGEST = "1607bbe37cb7cd2b34d50bb337c8b5f4d3119f54ef5b0467af48f1cf70cc2cfb" +PAYLOAD_DIGEST = "779d8ac5bcd771bc0c1ef7ab9ae18e3446abfc2e436aabacf95ea1dfe5a420ef" ORG, NS = "clickhouse", "code-clickhouse" SHA = "1e93c0a25f177d3a971668e058745a6e8bfe3e2c" PARENT = "b41b780feecc85780bebca041acda03358719a79" diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index ca28bdc2b54..bef987de0ed 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -3129,6 +3129,7 @@ async def _decisions(org: str, trunk: str, paths: Any, *, limit: int, **kw: Any) test_path, src_path = "tests/queries/0_stateless/03999_x.sql", "src/Core/Settings.cpp" paths = [{"path": test_path, "class": "test"}, {"path": src_path, "class": "src"}] payload = { + "v": rb.PAYLOAD_VERSION, "pr_number": 117354, "merge_sha": SHA, "sections": {"paths": rb.section(rb.SERVED, verdict="src", rows=paths)}, @@ -3251,7 +3252,9 @@ async def _diff(*a: Any, **kw: Any) -> tuple[str, bool]: }, } wired["repo"] = _HandlerRepo(stored={"payload": json.dumps(payload)}) - out = await h.handle_code_review_brief(CodeReviewBriefInput(pr_number=117354)) + # a read that does not store serves an older version's stored brief as it is + out = await h.handle_code_review_brief(CodeReviewBriefInput(pr_number=117354, store=False)) + assert out.source == "precomputed" sec = out.sections["rationale"] assert sec["rows"][0]["verdict"] == "clear" and sec["verdict"] == verdict assert sec["causes"] == (["paths_maybe_cut"] if verdict == "unknown" else []) @@ -3289,6 +3292,7 @@ async def _decisions(org: str, trunk: str, paths: Any, *, limit: int, **kw: Any) monkeypatch.setattr(memory_links, "trunk_namespace", lambda org, ns: ns) monkeypatch.setattr(code_plane_reads, "decisions_for_paths", _decisions) payload = { + "v": rb.PAYLOAD_VERSION, "pr_number": 117354, "merge_sha": SHA, "sections": {"paths": rb.section(rb.SERVED, verdict="no_paths", rows=[])}, From 73b245d198d69ac78488e6fc6c8f9adee0cdb3f4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 05:50:02 +0000 Subject: [PATCH 02/26] A failed rebuild's marker loses to any rebuild and never brings back a deleted row The marker row takes the version of the row it replaces plus one, below any build's, so a rebuild another replica stores in either order wins. A row deleted while the build ran is not written again. The new tests use a made-up repository, and cover a ledger-backed rebuild. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 14 +- server/code/app/index/review_brief.py | 6 +- server/code/app/review_brief.py | 36 +-- server/code/store/index/reviews.py | 2 +- tests/analyzer/shapes.txt | 6 +- tests/unit/test_code_review_brief_mirror.py | 241 ++++++++++++++------ 6 files changed, 200 insertions(+), 105 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 360b3361f2c..31509445b56 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -289,17 +289,17 @@ a changed file unreached when its parse time was spent or its parse could not ru or parsed another head. A parse of a file that raised or ran past its limits does the same on every build of that file, at an open PR's head and at a merged PR's parent alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for -the file, and an open PR's `overlay_note` counts it. A stored brief is served as it was -built, unless it is of an older payload version (`v` in the payload), which a change -to what a brief stores or how its verdict reads it raises. A read of a merged PR's brief -of an older version builds it again from its merge commit and stores the new brief in -its place (`source` names the build), once per stored row and version. The old brief is -served, its verdict `gaps` or `unsettled` with `brief:v`, and `degraded` names +the file, and an open PR's `overlay_note` counts it. A change to what a brief stores or +how its verdict reads it raises the payload version (`v` in the payload). A stored brief +of the current version is served as it was built. A read of a merged PR's brief of an +older version builds it again from its merge commit and stores the new brief in its +place (`source` names the build); a read after that serves it as stored. The old brief is +served, its verdict `gaps`, or `unsettled` with `brief:v`, and `degraded` names `code.review_brief: stale_brief_served` with why, when the read does not store (`store: false` or a measurement consumer), when the host has no mirror of the repository (a host with one rebuilds it), or when the build raised, found nothing or was not stored. In the last case the stored row records the version that tried and the -cause, and later reads of that version serve it without a build. A brief stored at a +cause, and a later read of that version serves it without a build. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. `code.impact` maps a diff on its old side onto the index rows, which are at the indexed diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index 42305d9882b..a291b5685a1 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -75,10 +75,8 @@ # The version of the rules a brief is built and answered by. Bump it in the change that # alters what a build stores (a section, a row field, a cap, a cause) or what -# `brief_verdict` answers over a stored brief. A brief stored at a lower version answers -# `unsettled` with `brief:v`, and a read of a merged PR's builds it again from its merge -# commit and stores it, once per stored row and version -# (`server.code.app.review_brief._rebuild`). +# `brief_verdict` answers over a stored brief: a read of a merged PR's brief stored at a +# lower version builds it again (`server.code.app.review_brief._rebuild`). PAYLOAD_VERSION = 3 SECTION_ORDER: tuple[str, ...] = ( diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 5d50a21b6a8..27a796a4014 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -305,22 +305,22 @@ async def _rebuild( repo: CodeRepo, org: str, ns: str, stale: dict[str, Any], *, store: bool ) -> tuple[dict[str, Any], Source]: """A merged PR's brief stored at an older payload version, built again from its merge - commit through the miss path and stored in its place, at most once per stored row and - version. The stored brief is served instead, `unsettled` with `brief:v` and with - `stale_brief_served` in `degraded`, when this read may not store (`store: false`, a - measurement consumer), when this host has no mirror to read the diff from (a host with - one builds it), when a build of this version already tried, or when this build raised, - found nothing or left its brief unstored. In the last case the stored row is written - again with `rebuilt_for` and `rebuild_cause`, so no later read of this version builds - it again; a build of a newer version tries once more. A brief stored at a newer version - than this build's (a rolling upgrade) is never rebuilt here.""" + commit through the miss path and stored in its place. The stored brief is served + instead, with `stale_brief_served` and why in `degraded`, when this read does not + store (`store: false`, a measurement consumer), when this host has no mirror to read + the diff from (a host with one builds it), when a build of this version already + tried, or when this build raised, found nothing or left its brief unstored. In the + last case the stored row is written again with `rebuilt_for` and `rebuild_cause`, so a + later read of this version builds nothing; a build of a newer version tries once more. + A brief stored at a newer version than this build's (a rolling upgrade) is never + rebuilt here.""" from server.code.domain.index.repos import repo_for_namespace pr_number, merge_sha = int(stale.get("pr_number") or 0), str(stale.get("merge_sha") or "") if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: return _stale_served(stale, str(stale.get(REBUILD_CAUSE) or "")) if not store: - return _stale_served(stale, "store: false") + return _stale_served(stale, "not stored by this read") if not await present_dir(repo_for_namespace(org, ns)): return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): @@ -333,15 +333,19 @@ async def _rebuild( return fresh, source cause = notes[0] if notes else ("unstored" if fresh is not None else "missing") try: - # Another replica may have stored the rebuilt brief while this build ran. row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=merge_sha) - latest = json.loads(str((row or {}).get("payload") or "{}")) + if row is None: + return _stale_served(stale, cause) # deleted while the build ran + latest = json.loads(str(row.get("payload") or "{}")) if int(latest.get("v") or 0) >= rb.PAYLOAD_VERSION: - return latest, "precomputed" - marked = {**stale, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} - await repo.insert_rows( - "code_review_briefs", [review_brief_build.brief_row(org, ns, marked)] + return latest, "precomputed" # another replica stored the rebuilt brief + marked = review_brief_build.brief_row( + org, ns, {**stale, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} ) + # One above the row it replaces and below any build's, which is stamped with the + # time it is stored: a rebuild another replica stores after this read still wins. + marked["version"] = int(row.get("version") or 0) + 1 + await repo.insert_rows("code_review_briefs", [marked]) except Exception as e: # noqa: BLE001 — unmarked, the next read builds it again logger.warning("code.review_brief: rebuild of PR %s not recorded: %s", pr_number, e) return _stale_served(stale, cause) diff --git a/server/code/store/index/reviews.py b/server/code/store/index/reviews.py index e64e1feba73..0175d02c04b 100644 --- a/server/code/store/index/reviews.py +++ b/server/code/store/index/reviews.py @@ -224,7 +224,7 @@ async def review_brief( return await self._ch.query_one( f""" SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, - tokens, build_ms + tokens, build_ms, version FROM loom.code_review_briefs FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tombstoned_at IS NULL{clauses} diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index ba74a79c29b..ca403aabdea 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -29,6 +29,7 @@ 0313cfe27052 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 031cbd122ba7 ALTER TABLE loom.memory_ask_precedents DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 0326955f9efe SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} +033c8534c834 SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms, version FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombston 03637287975f SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 036cec1eaa08 ALTER TABLE loom.subject_last_seen DELETE WHERE (org = {org:String} AND subject = {p:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 038a0ae6d69c SELECT subject, role, status, pending_role, pending_since, granted_at, granted_by FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND revoked_at IS NULL ORDER BY @@ -523,7 +524,6 @@ 3876ef68b0ad SELECT org, code_namespace, branch_namespace, pr_number, branch, verdict, epistemic, basis, reason, cherry_pick_pr, cherry_pick_sha, backport_pr, label_wanted, wanted_branch, wanted_source, settled, p 38785f9683a4 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 388d90f60983 ALTER TABLE loom.code_search_trace DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -389519ce3dd9 SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS 38bfb0862017 SELECT chunk_id, path, kind, start_line, end_line FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND pa 38d2fca41ece SELECT org, namespace, agent, user_id, session_id, run_id, goal, user_request, expected_outcome, environment, model, consumer, status, started_at, completed_at, duration_ms, final_response, confidence 38e943a0aef0 SELECT count() AS n FROM loom.skills WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? @@ -608,7 +608,6 @@ 40e24f5cf835 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 4113c01ac87f SELECT memory_key, count() AS matches FROM (SELECT tm.memory_key FROM loom.entity_triple_memories AS tm INNER JOIN loom.entity_triples AS t ON t.org = tm.org AND t.namespace = tm.namespace AND t.subje 413546300ccb SELECT namespace, name, credential_mode, toString(source_id) AS source_id, owner_subject FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND namespace IN {names:Array(String)} AND active AN -413b4ddac97c SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS 415f2e580ed9 SELECT * FROM loom.service_accounts FINAL WHERE org = {org:String} AND (created_by = {by:String} OR has(lineage, {by:String})) AND NOT hasAll(lineage, {above:Array(String)}) AND (expires_at IS NULL OR 4162e2756b17 ALTER TABLE loom.memory_term_freq DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 419367e4e84e SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN @@ -907,7 +906,6 @@ 5f8abb21c668 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 5f90239138ff ALTER TABLE loom.memory_webhook_outbox DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 5f90abe11671 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -5f9526c466e1 SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS 5fa4c7105dc5 SELECT count() AS n FROM loom.code_search_trace WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 5fb487a531c5 SELECT org, namespace, agent, user_id, session_id, queue_id, payload, message_count, content_chars, status, attempts, lease_until, last_error, written, enqueued_at, updated_at, version, enqueued_by FR 5fbf0c799d3d SELECT sumIf(toUInt64OrZero(args[?]), mirror_marked = ?) AS cache_hits, sumIf(toFloat64OrZero(args[?]), mirror_marked = ?) AS cache_saved_usd FROM (SELECT ts, org, namespace, agent, user_id, session_i @@ -1690,6 +1688,7 @@ ad9ab785eb2e SELECT number, state, author, title, labels, head_sha, base_sha, fi ada9a712953c SELECT count() AS n, if(n = ?, NULL, max(updated_at)) AS latest FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) adc43eb8c1dd SELECT toString(record_id) AS rid, field_name, value_state FROM loom.memory_record_fields WHERE org = {org:String} AND namespace = {ns:String} AND record_id IN {ids:Array(UUID)} AND tombstoned_at IS N ade54f89df99 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +adfdc8957b62 SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms, version FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombston ae454dd59278 WITH cand AS ( SELECT path FROM loom.code_test_facets FINAL WHERE org = {org:String} AND namespace = {ns:String} AND (facet_kind, name) IN {pairs:Array(Tuple(String, String))} AND tombstoned_at IS NUL ae4e819b95ea SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} ae5b8ffb587a SELECT l.memory_key AS memory_key, toString(l.memory_id) AS memory_id, l.code_namespace AS code_namespace, l.path AS path, l.qualified_name AS qualified_name, l.state AS state, l.changed_since AS chan @@ -2246,6 +2245,7 @@ e1bbf72c5367 SELECT org, namespace, name, source_id, provider, generation, finge e1d3cfd2dea5 ALTER TABLE loom.entity_canonical_map DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? e1def4eb2c85 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, version, value, toString(value_json) AS object_text FROM loom.memory FINAL WHERE tombstoned_at IS NULL AND sensitivity = ? AND e1eb0c7b7e97 SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} +e1f2bbe4f238 SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms, version FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombston e213a06bdbbf ALTER TABLE loom.memory_copy_rules DELETE WHERE (org = {org:String} AND (namespace = {ns:String} OR from_namespace = {ns:String})) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) S e226762a2e02 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to e25d8681d2ed SELECT sumForEach(arrayMap((hit, pre) -> toUInt32(hit > ? AND startsWith(path, pre)), multiSearchAllPositions(content, {pats:Array(String)}), {prefixes:Array(String)})) AS hits, count() AS chunks FROM diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 0cf175fe458..0d65a7fe383 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -8,6 +8,7 @@ from __future__ import annotations import asyncio +import json import subprocess from pathlib import Path from typing import Any @@ -545,18 +546,89 @@ async def _no_mirror_here(cfg: Any) -> str: # ---- a brief stored at an older payload version ------------------------------ +# A made-up Python repository: none of the conventions of the repository above. + +DEMO_ORG, DEMO_NS = "acme", "code-greeter" +DEMO_SHA = "a1" * 20 +DEMO_PARENT = "b2" * 20 +DEMO_FACTS = { + "pr_number": 42, + "merge_sha": DEMO_SHA, + "title": "Greet by first name", + "subject": "Greet by first name (#42)", + "files": ["greeter/core.py", "checks/core_check.py"], +} +DEMO_DIFF = """diff --git a/greeter/core.py b/greeter/core.py +--- a/greeter/core.py ++++ b/greeter/core.py +@@ -3,2 +3,2 @@ def greet(name): + \"\"\"Say hello.\"\"\" +- return f"Hello {name}" ++ return f"Hello {name.split()[0]}" +diff --git a/checks/core_check.py b/checks/core_check.py +--- a/checks/core_check.py ++++ b/checks/core_check.py +@@ -1 +1,2 @@ + from greeter.core import greet ++assert greet("Ada Lovelace") == "Hello Ada" +""" + + +async def _demo_calls(op: str, body: dict[str, Any]) -> dict[str, Any]: + """The code ops over the made-up repository: one touched function, named by a check.""" + assert (body["org"], body["namespace"]) == (DEMO_ORG, DEMO_NS) + if op == "code.impact": + fn = {"qualified_name": "greeter.core.greet", "path": "greeter/core.py"} + return { + "touched_symbols": [{**fn, "start_line": 1, "tier": "treesitter", "via": "span"}], + "by_hop_counts": {1: 1}, + "verdict": "", + "epistemic": "exact", + "causes": [], + "paths_seen": [{"path": "greeter/core.py", "class": "src"}], + } + if op == "code.coverage_claim": + check = {"test_path": "checks/core_check.py", "tier": "exact_scoped"} + return {"verdict": "covered_by", "strongest_tier": "exact_scoped", "tests": [check]} + if op == "code.symbol_history": + return {"verdict": "history", "summary": {"prs_total": 1, "fix_prs": 0}, "prs": []} + return {"verdict": "none"} -async def _stale_row(wired: dict[str, Any], **extra: Any) -> dict[str, Any]: - """The stored row of the mirror PR's brief as an older build wrote it: payload version 2.""" - import json +@pytest.fixture +def demo(wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + import server.code.app.index.gitrepo as gitrepo_mod + import server.code.domain.index.repos as repos_mod - await h.handle_code_review_brief( - CodeReviewBriefInput(pr_number=MIRROR_FACTS["pr_number"], tier="full") - ) - [(_table, [row])] = wired["repo"].inserted - wired["repo"].inserted.clear() - wired["mirror"].clear() + class _DemoCfg: + git_dir = "/nonexistent/greeter.git" + git_branch = "trunk" + path_prefixes = ("greeter/", "checks/") + + async def _mirror(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: + wired["mirror"].append((git_dir, branch, pr_number)) + return dict(DEMO_FACTS) if pr_number == 42 else None + + async def _git_run(git_dir: str, *args: str, **kw: Any) -> str: + if args[0] == "rev-parse": + return DEMO_PARENT + "\n" + return DEMO_DIFF if args[0] == "diff" else "" + + monkeypatch.setattr(h, "resolve_code_identity", lambda o, n: (DEMO_ORG, DEMO_NS)) + monkeypatch.setattr(repos_mod, "repo_for_namespace", lambda o, n: _DemoCfg()) + monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _mirror) + monkeypatch.setattr(h, "call_code_op", _demo_calls) + monkeypatch.setattr(gitrepo_mod, "run", _git_run) + return wired + + +async def _stale_row(state: dict[str, Any], **extra: Any) -> dict[str, Any]: + """The stored row of the PR's brief as an older build wrote it: payload version 2.""" + out = await h.handle_code_review_brief(CodeReviewBriefInput(pr_number=42, tier="full")) + assert out.stored, out + [(_table, [row])] = state["repo"].inserted + state["repo"].inserted.clear() + state["mirror"].clear() payload = {**json.loads(row["payload"]), "v": 2, **extra} return {**row, "payload": json.dumps(payload)} @@ -568,29 +640,26 @@ async def _read(**kw: Any) -> tuple[CodeReviewBriefOutput, list[str]]: sections = [n for n in rb.SECTION_ORDER if n != "tracker"] with degradations.scoped(): out = await h.handle_code_review_brief( - CodeReviewBriefInput( - pr_number=MIRROR_FACTS["pr_number"], tier="full", sections=sections, **kw - ) + CodeReviewBriefInput(pr_number=42, tier="full", sections=sections, **kw) ) return out, degradations.current() @pytest.mark.asyncio async def test_a_brief_stored_at_an_older_version_is_rebuilt_once_and_stored_in_its_place( - wired: dict[str, Any], + demo: dict[str, Any], ) -> None: - import json - - repo = wired["repo"] - repo.stored = await _stale_row(wired) + repo = demo["repo"] + repo.stored = await _stale_row(demo) stale, _ = await _read(store=False) - assert stale.source == "precomputed" and stale.built_at + assert stale.source == "precomputed" and "brief:v2" in stale.verdict_causes out, notes = await _read() assert out.source == "built_from_mirror" and out.stored is True and notes == [] - assert wired["mirror"] == [("/nonexistent/mirror.git", "master", MIRROR_FACTS["pr_number"])] + assert not any(c.startswith("brief:") for c in out.verdict_causes) + assert demo["mirror"] == [("/nonexistent/greeter.git", "trunk", 42)] [(_table, [row])] = repo.inserted - assert (row["pr_number"], row["merge_sha"]) == (MIRROR_FACTS["pr_number"], MIRROR_SHA) + assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION # the rebuilt row is the one the next read finds: served as stored, nothing built repo.stored = row @@ -599,104 +668,128 @@ async def test_a_brief_stored_at_an_older_version_is_rebuilt_once_and_stored_in_ assert (again.verdict, again.verdict_causes) == (out.verdict, out.verdict_causes) +@pytest.mark.asyncio +async def test_a_ledger_backed_brief_is_rebuilt_from_its_ledger_row( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + repo.stored = await _stale_row(demo) + + async def _ledger(org: str, ns: str, **kw: Any) -> dict[str, Any]: + return {**DEMO_FACTS, "merge_sha": DEMO_SHA.encode("ascii")} + + monkeypatch.setattr(repo, "pr_merge_facts", _ledger) + out, notes = await _read() + assert out.source == "built" and out.ledger == "present" and out.stored is True + assert notes == [] and demo["mirror"] == [] + assert json.loads(repo.inserted[0][1][0]["payload"])["v"] == rb.PAYLOAD_VERSION + + @pytest.mark.asyncio @pytest.mark.parametrize("consumer", ["reviewer", "eval-b12"]) async def test_a_read_that_may_not_store_or_has_no_mirror_serves_the_stale_brief_unbuilt( - wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch, consumer: str + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch, consumer: str ) -> None: - """A rebuild nobody stores would run again on every read: a read that may not store + """A rebuild nobody stores would run again on every read: a read that does not store serves the stored brief, and so does a host whose mirror cannot read the diff.""" - repo = wired["repo"] - repo.stored = await _stale_row(wired) + repo = demo["repo"] + repo.stored = await _stale_row(demo) store = consumer != "reviewer" # the measurement label never stores, whatever it passes out, notes = await _read(consumer=consumer, store=store) - assert out.source == "precomputed" - assert notes == ["code.review_brief: stale_brief_served (store: false)"] - assert wired["mirror"] == [] and repo.inserted == [] + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == ["code.review_brief: stale_brief_served (not stored by this read)"] + assert demo["mirror"] == [] and repo.inserted == [] async def _no_mirror_here(cfg: Any) -> str: return "" monkeypatch.setattr(h, "present_dir", _no_mirror_here) out, notes = await _read() - assert out.source == "precomputed" + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes assert notes == ["code.review_brief: stale_brief_served (no mirror on this host)"] - assert wired["mirror"] == [] and repo.inserted == [] + assert demo["mirror"] == [] and repo.inserted == [] + + +def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> str: + """Make the mirror's diff read fail; the note a build then records.""" + import server.code.app.index.gitrepo as gitrepo_mod + + async def _run(git_dir: str, *args: str, **kw: Any) -> str: + if args[0] == "rev-parse": + return DEMO_PARENT + "\n" + raise RuntimeError("git diff failed") + + monkeypatch.setattr(gitrepo_mod, "run", _run) + return "git_mirror: diff_unread (RuntimeError)" @pytest.mark.asyncio async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( - wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: """A build whose diff cannot be read is not stored. The stale brief is served with the cause and written again with the version that tried, so the next read of that version builds nothing; a newer build's version tries again.""" - import json - - import server.code.app.index.gitrepo as gitrepo_mod - - repo = wired["repo"] - repo.stored = stale = await _stale_row(wired) - - async def _diff_fails(git_dir: str, *args: str, **kw: Any) -> str: - if args[0] == "rev-parse": - return PARENT + "\n" - raise RuntimeError("git diff failed") - - monkeypatch.setattr(gitrepo_mod, "run", _diff_fails) + repo = demo["repo"] + repo.stored = stale = await _stale_row(demo) + cause = _diff_fails(monkeypatch) out, notes = await _read() - cause = "git_mirror: diff_unread (RuntimeError)" - assert out.source == "precomputed" + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes assert notes == [f"code.review_brief: stale_brief_served ({cause})"] - assert len(wired["mirror"]) == 1 + assert len(demo["mirror"]) == 1 [(_table, [row])] = repo.inserted - marked = json.loads(row["payload"]) - assert marked == { + assert json.loads(row["payload"]) == { **json.loads(stale["payload"]), h.REBUILT_FOR: rb.PAYLOAD_VERSION, h.REBUILD_CAUSE: cause, } + # one above the row it replaces, so a rebuild stored by another replica still wins + assert row["version"] == stale["version"] + 1 repo.stored = row again, notes = await _read() assert again.source == "precomputed" and again.sections == out.sections assert notes == [f"code.review_brief: stale_brief_served ({cause})"] - assert len(wired["mirror"]) == 1 and len(repo.inserted) == 1 + assert len(demo["mirror"]) == 1 and len(repo.inserted) == 1 monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION + 1) await _read() - assert len(wired["mirror"]) == 2 and len(repo.inserted) == 2 + assert len(demo["mirror"]) == 2 and len(repo.inserted) == 2 @pytest.mark.asyncio -async def test_a_failed_rebuild_serves_what_another_replica_stored_meanwhile( - wired: dict[str, Any], monkeypatch: pytest.MonkeyPatch +async def test_a_failed_rebuild_writes_nothing_over_a_newer_or_a_deleted_row( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: - import json - - repo = wired["repo"] - stale = await _stale_row(wired) - fresh = {**stale, "payload": json.dumps({**json.loads(stale["payload"]), "v": 3})} - reads = iter([stale, fresh]) - - async def _point_read(org: str, ns: str, **kw: Any) -> dict[str, Any]: - return next(reads) - - async def _fails(*a: Any, **kw: Any) -> dict[str, Any]: - raise RuntimeError("build failed") - - monkeypatch.setattr(repo, "review_brief", _point_read) - monkeypatch.setattr(review_brief_build, "build_for_merge", _fails) - out, notes = await _read() - assert out.source == "precomputed" and notes == [] and repo.inserted == [] + """Read again after the build: a brief another replica stored meanwhile is served, and + a row deleted meanwhile is not brought back.""" + repo = demo["repo"] + stale = await _stale_row(demo) + fresh_payload = {**json.loads(stale["payload"]), "v": rb.PAYLOAD_VERSION} + fresh = {**stale, "payload": json.dumps(fresh_payload)} + cause = _diff_fails(monkeypatch) + for after, served in ((fresh, "fresh"), (None, "stale")): + reads = iter([stale, after]) + + async def _point_read( + org: str, ns: str, *, _reads: Any = reads, **kw: Any + ) -> dict[str, Any] | None: + return next(_reads) + + monkeypatch.setattr(repo, "review_brief", _point_read) + out, notes = await _read() + assert out.source == "precomputed" and repo.inserted == [] + if served == "fresh": + assert notes == [] and "brief:v2" not in out.verdict_causes + else: + assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert "brief:v2" in out.verdict_causes @pytest.mark.asyncio -async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(wired: dict[str, Any]) -> None: +async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(demo: dict[str, Any]) -> None: """During a rolling upgrade the older build never rebuilds what the newer one stored.""" - repo = wired["repo"] - stale = await _stale_row(wired) - import json - + repo = demo["repo"] + stale = await _stale_row(demo) newer = {**json.loads(stale["payload"]), "v": rb.PAYLOAD_VERSION + 1} repo.stored = {**stale, "payload": json.dumps(newer)} out, notes = await _read() From f38c51d4ec7f53a93c7a41e480ccc2d11113b4c9 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:06:09 +0000 Subject: [PATCH 03/26] An open PR's stale brief is rebuilt at its head, and a marker keeps its row's key Raising the payload version left open-PR briefs unsettled until a push; they now rebuild through the open build under the same bound. The failed-build marker is written from the re-read row with its merge_sha key and built_at, so it never lands under a new key or outranks a later build of another merge commit. An open PR's brief found by a merged read is served, not built as a merged one. rolling-upgrades.md gains rule 100 for the payload version. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 13 +++ docs/features/code-index/history-and-prs.md | 33 ++++--- server/code/app/review_brief.py | 97 +++++++++++---------- tests/unit/test_code_review_brief_mirror.py | 71 +++++++++++++++ 4 files changed, 157 insertions(+), 57 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index cf9d2b52bb2..f577b9e8ba3 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1630,6 +1630,19 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline and `tests/unit/test_knowledge_search_synced_from.py` check N's side, and the mixed-version gate does not check this rule. +100. **A review brief's payload version** (`PAYLOAD_VERSION` in + `server/code/app/index/review_brief.py`, no migration): N rebuilds a stored brief of + a lower version on read and stores it under the same key; N-1 serves a brief of N's + higher version as it is and never rewrites a stored row. A brief N-1's ingest writes + while both serve is of N-1's version, and N rebuilds it once. A build that cannot + store its brief writes the old one again with `rebuilt_for` set to its version, at + the replaced row's version plus one, so any build stored later replaces it, and + neither build tries that row again until a higher version serves. Both builds read + the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they + are ([PR history](../features/code-index/history-and-prs.md)). No gate holds the + rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the + mixed-version gate does not check this rule. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 31509445b56..18c5b9a96d7 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -243,7 +243,7 @@ values are tried in this order: limits, or that parsed another head than the one the brief's diff is read at (a push between the two reads, `head moved` in `overlay_note`); - `brief:v` for a brief stored at an older payload version, built by rules that - have changed since and served without a rebuild (see below). + have changed since, when the read cannot rebuild it (see below). - `no_source_change`: every changed path is a test, a document, configuration, a file the ingest reads no symbols of (an image, a file its denylist refuses) or outside the index; a file a lane parser reads for its symbols (C++, Python, shell, TypeScript, Go, @@ -289,18 +289,25 @@ a changed file unreached when its parse time was spent or its parse could not ru or parsed another head. A parse of a file that raised or ran past its limits does the same on every build of that file, at an open PR's head and at a merged PR's parent alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for -the file, and an open PR's `overlay_note` counts it. A change to what a brief stores or -how its verdict reads it raises the payload version (`v` in the payload). A stored brief -of the current version is served as it was built. A read of a merged PR's brief of an -older version builds it again from its merge commit and stores the new brief in its -place (`source` names the build); a read after that serves it as stored. The old brief is -served, its verdict `gaps`, or `unsettled` with `brief:v`, and `degraded` names -`code.review_brief: stale_brief_served` with why, when the read does not store -(`store: false` or a measurement consumer), when the host has no mirror of the -repository (a host with one rebuilds it), or when the build raised, found nothing or was -not stored. In the last case the stored row records the version that tried and the -cause, and a later read of that version serves it without a build. A brief stored at a -newer version than the serving build's, during a rolling upgrade, is served as it is. +the file, and an open PR's `overlay_note` counts it. + +A change to what a brief stores or how its verdict reads it raises the payload version +(`v` in the payload). A stored brief of the current version is served as it was built. +A read of a brief of an older version builds it again, a merged PR's from its merge +commit and an open PR's at the same head, and stores the new brief in its place +(`source` names the build); a read after that serves it as stored. The old brief is +served instead, its verdict `gaps`, or `unsettled` with `brief:v`, and `degraded` +names `code.review_brief: stale_brief_served` with the reason. That happens when: + +- the read does not store (`store: false`, a measurement consumer, a posted diff); +- the host has no mirror of the repository; +- an open PR's brief is found by its number on a merged read; +- the build raised, found nothing or was not stored. The stored row then records the + version that tried and the cause, and a later read by a build of the same version + serves it without a build. + +A brief stored at a newer version than the serving build's, during a rolling upgrade, +is served as it is. `code.impact` maps a diff on its old side onto the index rows, which are at the indexed head (at the merge commit when the ingest builds a merged PR's brief, before it moves diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 27a796a4014..712b031736b 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -14,6 +14,7 @@ import json import logging import time +from collections.abc import Awaitable, Callable from typing import Any, Literal from server.code.api.models_conventions import CodeSettingFactsInput @@ -263,34 +264,33 @@ async def _payload_for( if payload is not None and not is_open: if not await _stored_inside_head(repo, org, ns, payload): payload = None # stored while the head held the merge; it no longer does + + async def build(sha: str) -> tuple[dict[str, Any] | None, Source]: + """The brief built afresh: of the open head, or of the merge commit `sha`.""" + if not is_open: + return await _build_on_miss( + repo, org, ns, pr_number=pr_number, merge_sha=sha, store=store + ) + built = ( + await _build_open(repo, org, ns, pr_number=pr_number, head_sha=head_sha, store=store) + if head_sha + else None + ) + return built, "built" if built is not None else "missing" + + if payload is not None and int(payload.get("v") or 0) < rb.PAYLOAD_VERSION: + if bool(payload.get("overlay")) != is_open: + # an open PR's brief the merged read found by its number: only the open read + # builds it + return _stale_served(payload, "an open PR's brief read as merged") + key = head_sha if is_open else str(payload.get("merge_sha") or "") + return await _rebuild( + repo, org, ns, payload, (pr_number, key), store=store, build=lambda: build(key) + ) if payload is not None: - if not is_open and int(payload.get("v") or 0) < rb.PAYLOAD_VERSION: - return await _rebuild(repo, org, ns, payload, store=store) return payload, "precomputed" with code_span("review_brief.build") as sp: - if is_open: - payload = ( - await _build_open( - repo, - org, - ns, - pr_number=pr_number, - head_sha=head_sha, - store=store, - ) - if head_sha - else None - ) - source: Source = "built" if payload is not None else "missing" - else: - payload, source = await _build_on_miss( - repo, - org, - ns, - pr_number=pr_number, - merge_sha=merge_sha, - store=store, - ) + payload, source = await build(merge_sha) span_attrs(sp, results=int(payload is not None)) return payload, source @@ -302,21 +302,27 @@ async def _payload_for( async def _rebuild( - repo: CodeRepo, org: str, ns: str, stale: dict[str, Any], *, store: bool + repo: CodeRepo, + org: str, + ns: str, + stale: dict[str, Any], + key: tuple[int, str], + *, + store: bool, + build: Callable[[], Awaitable[tuple[dict[str, Any] | None, Source]]], ) -> tuple[dict[str, Any], Source]: - """A merged PR's brief stored at an older payload version, built again from its merge - commit through the miss path and stored in its place. The stored brief is served - instead, with `stale_brief_served` and why in `degraded`, when this read does not - store (`store: false`, a measurement consumer), when this host has no mirror to read - the diff from (a host with one builds it), when a build of this version already - tried, or when this build raised, found nothing or left its brief unstored. In the - last case the stored row is written again with `rebuilt_for` and `rebuild_cause`, so a - later read of this version builds nothing; a build of a newer version tries once more. - A brief stored at a newer version than this build's (a rolling upgrade) is never - rebuilt here.""" + """A stored brief of an older payload version, built again (a merged PR's from its + merge commit, an open PR's from the same head) and stored in its place, the row keyed + `key` (pr_number, merge commit or head). The stored brief is served instead, with + `stale_brief_served` and why in `degraded`, when this read does not store + (`store: false`, a measurement consumer, a posted diff), when this host has no mirror + to read the diff from, when a build of this version already tried, or when this build + raised, found nothing or left its brief unstored. In the last case the row is written + again with `rebuilt_for` and `rebuild_cause`, so a later read by a build of the same + version builds nothing; a build of a newer version tries once more. A brief stored at + a newer version than this build's (a rolling upgrade) is never rebuilt here.""" from server.code.domain.index.repos import repo_for_namespace - pr_number, merge_sha = int(stale.get("pr_number") or 0), str(stale.get("merge_sha") or "") if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: return _stale_served(stale, str(stale.get(REBUILD_CAUSE) or "")) if not store: @@ -324,26 +330,29 @@ async def _rebuild( if not await present_dir(repo_for_namespace(org, ns)): return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): - fresh, source = await _build_on_miss( - repo, org, ns, pr_number=pr_number, merge_sha=merge_sha, store=True - ) + fresh, source = await build() notes = degradations.current() span_attrs(sp, results=int(fresh is not None)) if fresh is not None and fresh.get("stored", True): return fresh, source cause = notes[0] if notes else ("unstored" if fresh is not None else "missing") + pr_number, sha = key try: - row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=merge_sha) + row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: return _stale_served(stale, cause) # deleted while the build ran latest = json.loads(str(row.get("payload") or "{}")) if int(latest.get("v") or 0) >= rb.PAYLOAD_VERSION: return latest, "precomputed" # another replica stored the rebuilt brief + stale = latest marked = review_brief_build.brief_row( - org, ns, {**stale, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} + org, ns, {**latest, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} ) - # One above the row it replaces and below any build's, which is stamped with the - # time it is stored: a rebuild another replica stores after this read still wins. + # The row it replaces keeps its key and build time (an open PR's payload names no + # merge commit), and its version plus one, below any build's, which is stamped with + # the time it is stored: a rebuild another replica stores after this read wins. + marked["merge_sha"] = sha_text(row.get("merge_sha")) + marked["built_at"] = row.get("built_at") or marked["built_at"] marked["version"] = int(row.get("version") or 0) + 1 await repo.insert_rows("code_review_briefs", [marked]) except Exception as e: # noqa: BLE001 — unmarked, the next read builds it again diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 0d65a7fe383..f0e11dded29 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -785,6 +785,77 @@ async def _point_read( assert "brief:v2" in out.verdict_causes +@pytest.mark.asyncio +async def test_an_older_build_reads_a_newer_builds_marker_without_building( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A row below both builds' versions that the newer build marked: the older build, + whose version is lower than the marker's, builds nothing either.""" + repo = demo["repo"] + marked = {h.REBUILT_FOR: rb.PAYLOAD_VERSION, h.REBUILD_CAUSE: "git_mirror: diff_unread"} + repo.stored = await _stale_row(demo, v=rb.PAYLOAD_VERSION - 2, **marked) + monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION - 1) + monkeypatch.setattr(review_brief_build, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION) + out, notes = await _read() + assert out.source == "precomputed" and demo["mirror"] == [] and repo.inserted == [] + assert notes == ["code.review_brief: stale_brief_served (git_mirror: diff_unread)"] + + +DEMO_HEAD = "c3" * 20 + + +async def _open_stale_row(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> Any: + """An open PR's brief of payload version 2, stored under (PR, head): its payload names + no merge commit.""" + stale = await _stale_row(demo) + payload = {**json.loads(stale["payload"]), "overlay": True, "merge_sha": ""} + payload["head_sha"] = DEMO_HEAD + demo["repo"].stored = {**stale, "merge_sha": DEMO_HEAD, "payload": json.dumps(payload)} + + async def _head(repo: Any, org: str, ns: str, pr_number: int) -> tuple[str, str]: + return DEMO_HEAD, "" + + monkeypatch.setattr(h, "_open_head", _head) + return payload + + +@pytest.mark.asyncio +async def test_an_open_prs_brief_of_an_older_version_is_rebuilt_at_its_head( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + payload = await _open_stale_row(demo, monkeypatch) + heads: list[str] = [] + + async def _build_open(repo: Any, org: str, ns: str, **kw: Any) -> dict[str, Any]: + heads.append(kw["head_sha"]) + return {**payload, "v": rb.PAYLOAD_VERSION} + + monkeypatch.setattr(h, "_build_open", _build_open) + out, notes = await _read(open=True) + assert out.source == "built" and heads == [DEMO_HEAD] and notes == [] + assert not any(c.startswith("brief:") for c in out.verdict_causes) + + # the same build left unstored: the marker keeps the row's key and build time + async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: + return None + + monkeypatch.setattr(h, "_build_open", _unbuilt) + out, notes = await _read(open=True) + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == ["code.review_brief: stale_brief_served (missing)"] + [(_table, [row])] = repo.inserted + assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) + assert row["built_at"] == repo.stored["built_at"] + assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION + + # read by its number as merged, an open PR's brief is not built as a merged one + repo.inserted.clear() + out, notes = await _read() + assert out.source == "precomputed" and repo.inserted == [] and demo["mirror"] == [] + assert notes == ["code.review_brief: stale_brief_served (an open PR's brief read as merged)"] + + @pytest.mark.asyncio async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(demo: dict[str, Any]) -> None: """During a rolling upgrade the older build never rebuilds what the newer one stored.""" From 94f5a4239491eaf94fc841674518c9b7ac907dde Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:14:10 +0000 Subject: [PATCH 04/26] A rebuild stored under another merge commit marks the stale row, and its cause names every note A merged rebuild the mirror places at another merge commit is stored under that key and leaves the stale row; it now counts as not stored, so the row is marked and a read of the old commit does not build on every call. The cause joins all of the build's notes. _rebuild takes pr_number and the sha and calls the build with it; the docstrings name the rebuild beside the miss. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/index/review_brief.py | 4 +- server/code/app/review_brief.py | 48 ++++++++++++--------- tests/unit/test_code_review_brief_mirror.py | 46 +++++++++++++++++++- 3 files changed, 73 insertions(+), 25 deletions(-) diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index a291b5685a1..002f2e9245d 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -75,8 +75,8 @@ # The version of the rules a brief is built and answered by. Bump it in the change that # alters what a build stores (a section, a row field, a cap, a cause) or what -# `brief_verdict` answers over a stored brief: a read of a merged PR's brief stored at a -# lower version builds it again (`server.code.app.review_brief._rebuild`). +# `brief_verdict` answers over a stored brief: a read of a brief stored at a lower version +# builds it again (`server.code.app.review_brief._rebuild`). PAYLOAD_VERSION = 3 SECTION_ORDER: tuple[str, ...] = ( diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 712b031736b..49a12445bfb 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -1,5 +1,6 @@ """code.review_brief handler: a point read of the brief the ingest step built for a merged -PR; on a miss, build it from the ledger and the mirror, store it, serve it. A PR the ledger +PR; on a miss, or for a brief stored at an older payload version (`_rebuild`), build it from +the ledger and the mirror, store it, serve it. A PR the ledger never saw is built from the merge commit the mirror's first-parent chain names for it (`source: built_from_mirror`, `ledger: absent`), and the on-demand store is the caller's `store` flag — never for a measurement consumer. @@ -240,7 +241,8 @@ async def _payload_for( store: bool, ) -> tuple[dict[str, Any] | None, Source]: """(payload, source): the point read — keyed (pr_number, merge_sha), or - (pr_number, head) for an open PR — then the build on a miss.""" + (pr_number, head) for an open PR — then the build on a miss or of a brief stored at an + older payload version.""" with code_span("review_brief.point_read") as sp: try: if is_open and not head_sha: @@ -266,14 +268,14 @@ async def _payload_for( payload = None # stored while the head held the merge; it no longer does async def build(sha: str) -> tuple[dict[str, Any] | None, Source]: - """The brief built afresh: of the open head, or of the merge commit `sha`.""" + """The brief built afresh at `sha`: the open PR's head, or the merge commit.""" if not is_open: return await _build_on_miss( repo, org, ns, pr_number=pr_number, merge_sha=sha, store=store ) built = ( - await _build_open(repo, org, ns, pr_number=pr_number, head_sha=head_sha, store=store) - if head_sha + await _build_open(repo, org, ns, pr_number=pr_number, head_sha=sha, store=store) + if sha else None ) return built, "built" if built is not None else "missing" @@ -283,14 +285,13 @@ async def build(sha: str) -> tuple[dict[str, Any] | None, Source]: # an open PR's brief the merged read found by its number: only the open read # builds it return _stale_served(payload, "an open PR's brief read as merged") - key = head_sha if is_open else str(payload.get("merge_sha") or "") - return await _rebuild( - repo, org, ns, payload, (pr_number, key), store=store, build=lambda: build(key) - ) + sha = head_sha if is_open else str(payload.get("merge_sha") or "") + number = int(payload.get("pr_number") or pr_number) + return await _rebuild(repo, org, ns, payload, number, sha, store=store, build=build) if payload is not None: return payload, "precomputed" with code_span("review_brief.build") as sp: - payload, source = await build(merge_sha) + payload, source = await build(head_sha if is_open else merge_sha) span_attrs(sp, results=int(payload is not None)) return payload, source @@ -306,18 +307,20 @@ async def _rebuild( org: str, ns: str, stale: dict[str, Any], - key: tuple[int, str], + pr_number: int, + sha: str, *, store: bool, - build: Callable[[], Awaitable[tuple[dict[str, Any] | None, Source]]], + build: Callable[[str], Awaitable[tuple[dict[str, Any] | None, Source]]], ) -> tuple[dict[str, Any], Source]: - """A stored brief of an older payload version, built again (a merged PR's from its - merge commit, an open PR's from the same head) and stored in its place, the row keyed - `key` (pr_number, merge commit or head). The stored brief is served instead, with + """A stored brief of an older payload version, built again at `sha` (a merged PR's + merge commit, an open PR's head: the row's key with `pr_number`) and stored in its + place. The stored brief is served instead, with `stale_brief_served` and why in `degraded`, when this read does not store (`store: false`, a measurement consumer, a posted diff), when this host has no mirror to read the diff from, when a build of this version already tried, or when this build - raised, found nothing or left its brief unstored. In the last case the row is written + raised, found nothing, left its brief unstored or stored it under another commit (the + mirror names another merge commit for the PR). In the last case the row is written again with `rebuilt_for` and `rebuild_cause`, so a later read by a build of the same version builds nothing; a build of a newer version tries once more. A brief stored at a newer version than this build's (a rolling upgrade) is never rebuilt here.""" @@ -330,13 +333,16 @@ async def _rebuild( if not await present_dir(repo_for_namespace(org, ns)): return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): - fresh, source = await build() + fresh, source = await build(sha) notes = degradations.current() span_attrs(sp, results=int(fresh is not None)) - if fresh is not None and fresh.get("stored", True): - return fresh, source - cause = notes[0] if notes else ("unstored" if fresh is not None else "missing") - pr_number, sha = key + if fresh is not None: + at = str(fresh.get("head_sha" if fresh.get("overlay") else "merge_sha") or "") + if at != sha: + notes.append(f"built at {at[:12] or 'no commit'}") # stored under another key + elif fresh.get("stored", True): + return fresh, source + cause = "; ".join(notes) or ("unstored" if fresh is not None else "missing") try: row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index f0e11dded29..bd521c45825 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -711,7 +711,7 @@ async def _no_mirror_here(cfg: Any) -> str: def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> str: - """Make the mirror's diff read fail; the note a build then records.""" + """Make the mirror's diff reads fail; the notes a build then records, as one cause.""" import server.code.app.index.gitrepo as gitrepo_mod async def _run(git_dir: str, *args: str, **kw: Any) -> str: @@ -720,7 +720,7 @@ async def _run(git_dir: str, *args: str, **kw: Any) -> str: raise RuntimeError("git diff failed") monkeypatch.setattr(gitrepo_mod, "run", _run) - return "git_mirror: diff_unread (RuntimeError)" + return "git_mirror: diff_unread (RuntimeError); git_mirror: drift_unread (RuntimeError)" @pytest.mark.asyncio @@ -785,6 +785,48 @@ async def _point_read( assert "brief:v2" in out.verdict_causes +@pytest.mark.asyncio +async def test_a_rebuild_the_mirror_places_at_another_merge_commit_marks_the_stale_row( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A build stored under another key leaves the stale row as it was: the row is marked, + so a read that names the old merge commit does not build again on every call.""" + repo = demo["repo"] + repo.stored = stale = await _stale_row(demo) + other = "d4" * 20 + + async def _moved(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: + demo["mirror"].append((git_dir, branch, pr_number)) + return {**DEMO_FACTS, "merge_sha": other} + + monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _moved) + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == [f"code.review_brief: stale_brief_served (built at {other[:12]})"] + assert [r["merge_sha"] for _t, [r] in repo.inserted] == [other, DEMO_SHA] + marker = repo.inserted[1][1][0] + assert marker["version"] == stale["version"] + 1 + assert json.loads(marker["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION + + +@pytest.mark.asyncio +async def test_a_read_by_merge_commit_alone_rebuilds_under_the_stored_rows_key( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + repo.stored = await _stale_row(demo) + + async def _by_sha(git_dir: str, sha: str, **kw: Any) -> dict[str, Any] | None: + return dict(DEMO_FACTS) if sha == DEMO_SHA else None + + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _by_sha) + out = await h.handle_code_review_brief(CodeReviewBriefInput(merge_sha=DEMO_SHA, tier="full")) + assert out.source == "built_from_mirror" and out.stored is True and out.pr_number == 42 + [(_table, [row])] = repo.inserted + assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) + assert repo.reads[-1] == (0, DEMO_SHA) + + @pytest.mark.asyncio async def test_an_older_build_reads_a_newer_builds_marker_without_building( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch From c738e7d22feb56a24aff52e22d62de08970aac87 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:20:38 +0000 Subject: [PATCH 05/26] A rebuild whose reads raise serves the stored brief; rule 100 says which rules N-1 answers by The ledger read in the miss path raises outside its try; a rebuild now catches any exception from its build and serves the stored brief with the cause. The PR number comes from the stored row alone. The docs list a build stored under another merge commit, and the rolling-upgrade rule says N-1 answers a newer brief by its own rules. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 24 +++++------ docs/features/code-index/history-and-prs.md | 7 ++-- server/code/app/review_brief.py | 44 ++++++++++++--------- tests/unit/test_code_review_brief_mirror.py | 19 +++++++++ 4 files changed, 61 insertions(+), 33 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index f577b9e8ba3..8f125c36acb 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1631,17 +1631,19 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline mixed-version gate does not check this rule. 100. **A review brief's payload version** (`PAYLOAD_VERSION` in - `server/code/app/index/review_brief.py`, no migration): N rebuilds a stored brief of - a lower version on read and stores it under the same key; N-1 serves a brief of N's - higher version as it is and never rewrites a stored row. A brief N-1's ingest writes - while both serve is of N-1's version, and N rebuilds it once. A build that cannot - store its brief writes the old one again with `rebuilt_for` set to its version, at - the replaced row's version plus one, so any build stored later replaces it, and - neither build tries that row again until a higher version serves. Both builds read - the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they - are ([PR history](../features/code-index/history-and-prs.md)). No gate holds the - rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the - mixed-version gate does not check this rule. + `server/code/app/index/review_brief.py`, no migration): N rebuilds a stored brief of a + lower version on read and stores it under the same key; N-1 serves a brief of N's + higher version as it is, answering its verdict by N-1's own rules, and never rewrites a + stored row. So a bump that adds a cause N-1 does not know ships N-1's reading of that + cause first (rule 3), or N-1 can settle a brief N leaves `unsettled`. A brief N-1's + ingest writes while both serve is of N-1's version, and N rebuilds it once. A build + that cannot store its brief writes the old one again with `rebuilt_for` set to its + version, at the replaced row's version plus one, so any build stored later replaces it, + and neither build tries that row again until a higher version serves. Both builds read + the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are + ([PR history](../features/code-index/history-and-prs.md)). No gate holds the rollout. + `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version + gate does not check this rule. ## What checks them diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 18c5b9a96d7..03e297a970c 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -302,9 +302,10 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the read does not store (`store: false`, a measurement consumer, a posted diff); - the host has no mirror of the repository; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing or was not stored. The stored row then records the - version that tried and the cause, and a later read by a build of the same version - serves it without a build. +- the build raised, found nothing, was not stored, or was stored under another merge + commit the mirror names for the PR. The stored row then records the version that + tried and the cause, and a later read by a build of the same version serves it + without a build. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 49a12445bfb..b2de2138f9d 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -1,9 +1,9 @@ """code.review_brief handler: a point read of the brief the ingest step built for a merged -PR; on a miss, or for a brief stored at an older payload version (`_rebuild`), build it from -the ledger and the mirror, store it, serve it. A PR the ledger -never saw is built from the merge commit the mirror's first-parent chain names for it -(`source: built_from_mirror`, `ledger: absent`), and the on-demand store is the caller's -`store` flag — never for a measurement consumer. +PR; on a miss, or for a brief stored at an older payload version (`_rebuild`), build it +from the ledger and the mirror, store it, serve it. A PR the ledger never saw is built from +the merge commit the mirror's first-parent chain names for it (`source: built_from_mirror`, +`ledger: absent`), and the on-demand store is the caller's `store` flag — never for a +measurement consumer. A merged PR is briefed only when the namespace's indexed head contains it: the ledger and stored-brief reads carry the head bound, and a merge commit the mirror names is asked of @@ -285,9 +285,10 @@ async def build(sha: str) -> tuple[dict[str, Any] | None, Source]: # an open PR's brief the merged read found by its number: only the open read # builds it return _stale_served(payload, "an open PR's brief read as merged") + # the stored row's key: a read by merge commit alone names no number + pr_number = int(payload.get("pr_number") or pr_number) sha = head_sha if is_open else str(payload.get("merge_sha") or "") - number = int(payload.get("pr_number") or pr_number) - return await _rebuild(repo, org, ns, payload, number, sha, store=store, build=build) + return await _rebuild(repo, org, ns, payload, sha, store=store, build=build) if payload is not None: return payload, "precomputed" with code_span("review_brief.build") as sp: @@ -307,23 +308,22 @@ async def _rebuild( org: str, ns: str, stale: dict[str, Any], - pr_number: int, sha: str, *, store: bool, build: Callable[[str], Awaitable[tuple[dict[str, Any] | None, Source]]], ) -> tuple[dict[str, Any], Source]: """A stored brief of an older payload version, built again at `sha` (a merged PR's - merge commit, an open PR's head: the row's key with `pr_number`) and stored in its - place. The stored brief is served instead, with - `stale_brief_served` and why in `degraded`, when this read does not store - (`store: false`, a measurement consumer, a posted diff), when this host has no mirror - to read the diff from, when a build of this version already tried, or when this build - raised, found nothing, left its brief unstored or stored it under another commit (the - mirror names another merge commit for the PR). In the last case the row is written - again with `rebuilt_for` and `rebuild_cause`, so a later read by a build of the same - version builds nothing; a build of a newer version tries once more. A brief stored at - a newer version than this build's (a rolling upgrade) is never rebuilt here.""" + merge commit, an open PR's head: the row's key with its PR number) and stored in its + place. The stored brief is served instead, with `stale_brief_served` and why in + `degraded`, when this read does not store (`store: false`, a measurement consumer, a + posted diff), when this host has no mirror to read the diff from, when a build of + this version already tried, or when this build raised, found nothing, left its brief + unstored or stored it under another commit (the mirror names another merge commit for + the PR). In the last case the row is written again with `rebuilt_for` and + `rebuild_cause`, so a later read by a build of the same version builds nothing; a + build of a newer version tries once more. A brief stored at a newer version than this + build's (a rolling upgrade) is never rebuilt here.""" from server.code.domain.index.repos import repo_for_namespace if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: @@ -333,7 +333,12 @@ async def _rebuild( if not await present_dir(repo_for_namespace(org, ns)): return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): - fresh, source = await build(sha) + try: + fresh, source = await build(sha) + except Exception as e: # noqa: BLE001 — a rebuild that raises serves the stored brief + logger.warning("code.review_brief: rebuild at %s raised: %s", sha[:12], e) + degradations.partial("code.review_brief", "brief_missing", e) + fresh, source = None, "missing" notes = degradations.current() span_attrs(sp, results=int(fresh is not None)) if fresh is not None: @@ -343,6 +348,7 @@ async def _rebuild( elif fresh.get("stored", True): return fresh, source cause = "; ".join(notes) or ("unstored" if fresh is not None else "missing") + pr_number = int(stale.get("pr_number") or 0) try: row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index bd521c45825..563b5237740 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -785,6 +785,25 @@ async def _point_read( assert "brief:v2" in out.verdict_causes +@pytest.mark.asyncio +async def test_a_rebuild_whose_ledger_read_raises_serves_the_stored_brief( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + repo.stored = await _stale_row(demo) + + async def _ledger_down(org: str, ns: str, **kw: Any) -> None: + raise TimeoutError("ledger timed out") + + monkeypatch.setattr(repo, "pr_merge_facts", _ledger_down) + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + [note] = notes + assert note.startswith("code.review_brief: stale_brief_served (code.review_brief: brief_") + [(_table, [row])] = repo.inserted + assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION + + @pytest.mark.asyncio async def test_a_rebuild_the_mirror_places_at_another_merge_commit_marks_the_stale_row( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch From ee7a4dca6514660d8c9d706d586673dbfeb1f2fa Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:29:33 +0000 Subject: [PATCH 06/26] Rule 101 and the history page say which builds a marker stops; a marker write that fails is tested Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 17 ++++++++------- docs/features/code-index/history-and-prs.md | 23 +++++++++++---------- server/code/app/index/review_brief.py | 4 +++- tests/unit/test_code_review_brief_mirror.py | 19 +++++++++++++++++ 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 37016e1512a..0d6d0f41d34 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1661,14 +1661,15 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `server/code/app/index/review_brief.py`, no migration): N rebuilds a stored brief of a lower version on read and stores it under the same key; N-1 serves a brief of N's higher version as it is, answering its verdict by N-1's own rules, and never rewrites a - stored row. So a bump that adds a cause N-1 does not know ships N-1's reading of that - cause first (rule 3), or N-1 can settle a brief N leaves `unsettled`. A brief N-1's - ingest writes while both serve is of N-1's version, and N rebuilds it once. A build - that cannot store its brief writes the old one again with `rebuilt_for` set to its - version, at the replaced row's version plus one, so any build stored later replaces it, - and neither build tries that row again until a higher version serves. Both builds read - the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are - ([PR history](../features/code-index/history-and-prs.md)). No gate holds the rollout. + row of its own version or higher, or one a newer build marked. So a bump that adds a + cause N-1 does not know ships N-1's reading of that cause first (rule 3), or N-1 can + settle a brief N leaves `unsettled`. A brief N-1's ingest writes while both serve is of + N-1's version, and N rebuilds it once. A build that cannot store its brief writes the + old one again with `rebuilt_for` set to its version, at the replaced row's version plus + one, so any build stored later replaces it, and neither build tries that row again + until a higher version serves. Both builds read the same rows, so a rollback leaves + rebuilt briefs as newer rows N-1 serves as they are ([PR + history](../features/code-index/history-and-prs.md)). No gate holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version gate does not check this rule. diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 03e297a970c..970ace5cbc3 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -281,15 +281,16 @@ every changed path. The `rationale` section is never stored, so a read that does serve it (the trivial tier, or `sections` without it) answers `gaps`, `unsettled` with `rationale:not_requested`, or `no_source_change`: `covered_no_gaps` needs `rationale` in `sections` (or `sections` empty) on the standard or full tier. A brief one of whose -reads raised is served and not stored, and the next read builds it again (the test home -is advice: a read of it that raised or was refused decides no verdict, though one that -raised still keeps the brief unstored); so is an open PR's brief built without its diff, -or from an overlay that was off (`overlay:error` when git could not read its diff), left -a changed file unreached when its parse time was spent or its parse could not run here, -or parsed another head. A parse of a file that raised or ran past its limits does the -same on every build of that file, at an open PR's head and at a merged PR's parent -alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for -the file, and an open PR's `overlay_note` counts it. +reads raised is served and not stored, and the next read builds it again (one that +replaces a brief of an older version is tried once, below; the test home is advice: a +read of it that raised or was refused decides no verdict, though one that raised still +keeps the brief unstored); so is an open PR's brief built without its diff, or from an +overlay that was off (`overlay:error` when git could not read its diff), left a changed +file unreached when its parse time was spent or its parse could not run here, or parsed +another head. A parse of a file that raised or ran past its limits does the same on +every build of that file, at an open PR's head and at a merged PR's parent alike, so +that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for the file, +and an open PR's `overlay_note` counts it. A change to what a brief stores or how its verdict reads it raises the payload version (`v` in the payload). A stored brief of the current version is served as it was built. @@ -304,8 +305,8 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - an open PR's brief is found by its number on a merged read; - the build raised, found nothing, was not stored, or was stored under another merge commit the mirror names for the PR. The stored row then records the version that - tried and the cause, and a later read by a build of the same version serves it - without a build. + tried and the cause, and a later read by a build of the same or a lower version + serves it without a build. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index 002f2e9245d..1500d4c5961 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -76,7 +76,9 @@ # The version of the rules a brief is built and answered by. Bump it in the change that # alters what a build stores (a section, a row field, a cap, a cause) or what # `brief_verdict` answers over a stored brief: a read of a brief stored at a lower version -# builds it again (`server.code.app.review_brief._rebuild`). +# builds it again (`server.code.app.review_brief._rebuild`). The build before answers a +# brief of this version by its own rules, so a new cause ships its reading there first +# (rolling-upgrades rule 101). PAYLOAD_VERSION = 3 SECTION_ORDER: tuple[str, ...] = ( diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 563b5237740..f14c0188682 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -804,6 +804,25 @@ async def _ledger_down(org: str, ns: str, **kw: Any) -> None: assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION +@pytest.mark.asyncio +async def test_a_marker_that_cannot_be_written_serves_the_stored_brief_and_tries_again( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + repo.stored = await _stale_row(demo) + cause = _diff_fails(monkeypatch) + + async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: + raise TimeoutError("insert timed out") + + monkeypatch.setattr(repo, "insert_rows", _store_down) + for builds in (1, 2): + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert len(demo["mirror"]) == builds # unmarked, the next read builds again + + @pytest.mark.asyncio async def test_a_rebuild_the_mirror_places_at_another_merge_commit_marks_the_stale_row( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch From bbcefb828b7f1c56e9baa30326064c8405b44e8a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:41:39 +0000 Subject: [PATCH 07/26] The store field says it decides a rebuild, and an open rebuild is tested through the open build The store comment (and its reference page) names the rebuild of an older brief. A test runs the real open build and checks the row is stored under the PR's head. The _rebuild docstring points to the docs page; rule 101 notes an N-1 without a verdict. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 18 ++++++------ docs/features/code-index/history-and-prs.md | 20 ++++++------- docs/reference/operations/code.md | 2 +- server/code/api/models_review.py | 5 ++-- server/code/app/review_brief.py | 16 +++-------- tests/unit/test_code_review_brief_mirror.py | 32 +++++++++++++++++++++ 6 files changed, 59 insertions(+), 34 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 0d6d0f41d34..230e5c3645d 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1660,15 +1660,15 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline 101. **A review brief's payload version** (`PAYLOAD_VERSION` in `server/code/app/index/review_brief.py`, no migration): N rebuilds a stored brief of a lower version on read and stores it under the same key; N-1 serves a brief of N's - higher version as it is, answering its verdict by N-1's own rules, and never rewrites a - row of its own version or higher, or one a newer build marked. So a bump that adds a - cause N-1 does not know ships N-1's reading of that cause first (rule 3), or N-1 can - settle a brief N leaves `unsettled`. A brief N-1's ingest writes while both serve is of - N-1's version, and N rebuilds it once. A build that cannot store its brief writes the - old one again with `rebuilt_for` set to its version, at the replaced row's version plus - one, so any build stored later replaces it, and neither build tries that row again - until a higher version serves. Both builds read the same rows, so a rollback leaves - rebuilt briefs as newer rows N-1 serves as they are ([PR + higher version as it is, answering its verdict (where N-1 has one) by its own rules, + and never rewrites a row of its own version or higher, or one a newer build marked. So + a bump that adds a cause N-1 does not know ships N-1's reading of that cause first + (rule 3), or N-1 can settle a brief N leaves `unsettled`. A brief N-1's ingest writes + while both serve is of N-1's version, and N rebuilds it once. A build that cannot store + its brief writes the old one again with `rebuilt_for` set to its version, at the + replaced row's version plus one, so any build stored later replaces it, and neither + build tries that row again until a higher version serves. Both builds read the same + rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are ([PR history](../features/code-index/history-and-prs.md)). No gate holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version gate does not check this rule. diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 970ace5cbc3..f9f18ec8c66 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -281,16 +281,16 @@ every changed path. The `rationale` section is never stored, so a read that does serve it (the trivial tier, or `sections` without it) answers `gaps`, `unsettled` with `rationale:not_requested`, or `no_source_change`: `covered_no_gaps` needs `rationale` in `sections` (or `sections` empty) on the standard or full tier. A brief one of whose -reads raised is served and not stored, and the next read builds it again (one that -replaces a brief of an older version is tried once, below; the test home is advice: a -read of it that raised or was refused decides no verdict, though one that raised still -keeps the brief unstored); so is an open PR's brief built without its diff, or from an -overlay that was off (`overlay:error` when git could not read its diff), left a changed -file unreached when its parse time was spent or its parse could not run here, or parsed -another head. A parse of a file that raised or ran past its limits does the same on -every build of that file, at an open PR's head and at a merged PR's parent alike, so -that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for the file, -and an open PR's `overlay_note` counts it. +reads raised is served and not stored, and the next read builds it again (the test home +is advice: a read of it that raised or was refused decides no verdict, though one that +raised still keeps the brief unstored); so is an open PR's brief built without its diff, +or from an overlay that was off (`overlay:error` when git could not read its diff), left +a changed file unreached when its parse time was spent or its parse could not run here, +or parsed another head. A parse of a file that raised or ran past its limits does the +same on every build of that file, at an open PR's head and at a merged PR's parent +alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for +the file, and an open PR's `overlay_note` counts it. A build that replaces a brief of an +older version is tried once (below). A change to what a brief stores or how its verdict reads it raises the payload version (`v` in the payload). A stored brief of the current version is served as it was built. diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index d271d547248..20f5c7a6d1e 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1449,7 +1449,7 @@ A merged PR's review brief: the point read of what the ingest built at merge — | `sections` | `list[Literal['paths', 'symbols', 'tests', 'settings', 'history', 'blame', 'qa', 'risk', 'do_not_flag', 'rationale']]` | *(computed)* | Serve only these of the tier's sections; empty = every section the tier carries. | | `tier` | `Literal['trivial', 'standard', 'full']` | `'standard'` | Which sections: trivial (paths, symbols), standard (+ tests, settings, history, risk, rationale) or full (+ blame, qa). | | `token_budget` | `int` | `0` | Estimated-token cap on served sections; 0 (default) is unlimited. | -| `store` | `bool` | `True` | Whether a brief this call builds on a miss is stored for the next reader (the default). | +| `store` | `bool` | `True` | Whether a brief this call builds on a miss is stored for the next reader (the default), and whether a stored brief of an older payload version is rebuilt: a read that does not store serves it as stored. | | `open` | `bool` | `False` | The PR is OPEN — brief its head (`refs/pull/N/head` on the mirror) diffed against its merge-base with the indexed branch, with the post-image overlay on the impact read (added functions are seeds). | | Output field | Type | Meaning | diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index eb56c773ad9..bcf10278863 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -98,8 +98,9 @@ class CodeReviewBriefInput(_CodeIdentity, _PrPostImage): # Estimated-token cap on served sections; 0 (default) is unlimited. token_budget: int = Field(default=0, ge=0) # Whether a brief this call builds on a miss is stored for the next reader (the - # default). A measurement consumer (`eval-*`, the bench sentinels) never stores, - # whatever it passes. + # default), and whether a stored brief of an older payload version is rebuilt: a read + # that does not store serves it as stored. A measurement consumer (`eval-*`, the bench + # sentinels) never stores, whatever it passes. store: bool = True # "pr_number or merge_sha" is checked by the handler, not a model validator: the # namespace gate answers a refused principal (403/404) before any shape complaint, diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index b2de2138f9d..a6963f0e9a3 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -313,17 +313,9 @@ async def _rebuild( store: bool, build: Callable[[str], Awaitable[tuple[dict[str, Any] | None, Source]]], ) -> tuple[dict[str, Any], Source]: - """A stored brief of an older payload version, built again at `sha` (a merged PR's - merge commit, an open PR's head: the row's key with its PR number) and stored in its - place. The stored brief is served instead, with `stale_brief_served` and why in - `degraded`, when this read does not store (`store: false`, a measurement consumer, a - posted diff), when this host has no mirror to read the diff from, when a build of - this version already tried, or when this build raised, found nothing, left its brief - unstored or stored it under another commit (the mirror names another merge commit for - the PR). In the last case the row is written again with `rebuilt_for` and - `rebuild_cause`, so a later read by a build of the same version builds nothing; a - build of a newer version tries once more. A brief stored at a newer version than this - build's (a rolling upgrade) is never rebuilt here.""" + """A stored brief of an older payload version, built again at `sha` and stored in its + place, at most once per row and version; when it is served instead is in + docs/features/code-index/history-and-prs.md.""" from server.code.domain.index.repos import repo_for_namespace if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: @@ -344,7 +336,7 @@ async def _rebuild( if fresh is not None: at = str(fresh.get("head_sha" if fresh.get("overlay") else "merge_sha") or "") if at != sha: - notes.append(f"built at {at[:12] or 'no commit'}") # stored under another key + notes.append(f"built at {at[:12]}") # another key than the stored row's elif fresh.get("stored", True): return fresh, source cause = "; ".join(notes) or ("unstored" if fresh is not None else "missing") diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index f14c0188682..7d325228bf4 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -936,6 +936,38 @@ async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: assert notes == ["code.review_brief: stale_brief_served (an open PR's brief read as merged)"] +@pytest.mark.asyncio +async def test_an_open_rebuild_through_the_open_build_is_stored_under_its_head( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + import server.code.app.index.gitrepo as gitrepo_mod + + repo = demo["repo"] + await _open_stale_row(demo, monkeypatch) + + async def _history_dir(cfg: Any, **kw: Any) -> tuple[str, str]: + return cfg.git_dir, "" + + async def _merge_base(git_dir: str, a: str, b: str) -> str: + return DEMO_PARENT + + async def _names(git_dir: str, base: str, head: str, **kw: Any) -> list[str]: + return list(DEMO_FACTS["files"]) + + async def _item(org: str, ns: str, pr_number: int) -> dict[str, Any]: + return {"title": "Greet by first name", "author": "ada"} + + monkeypatch.setattr(h, "history_dir", _history_dir) + monkeypatch.setattr(gitrepo_mod, "merge_base", _merge_base) + monkeypatch.setattr(gitrepo_mod, "diff_name_only", _names) + monkeypatch.setattr(repo, "gh_pr_head", _item, raising=False) + out, notes = await _read(open=True) + assert out.source == "built" and out.stored is True and notes == [] + [(_table, [row])] = repo.inserted + assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) + assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION + + @pytest.mark.asyncio async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(demo: dict[str, Any]) -> None: """During a rolling upgrade the older build never rebuilds what the newer one stored.""" From 01405fb2e49683b570b6e38271448d7371941d73 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:51:25 +0000 Subject: [PATCH 08/26] A failed rebuild lists the build's notes as they were, and never lowers a newer build's marker The build's notes are listed in degraded (and stored in rebuild_notes) instead of folded into one cut-off cause; stale_brief_served says rebuild failed. A re-read that finds a marker of this or a newer version keeps it. _build_at builds for the miss path and the rebuild alike, so _rebuild takes the row's key and PR number explicitly. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 7 +- server/code/app/review_brief.py | 99 ++++++++++++--------- tests/unit/test_code_review_brief_mirror.py | 45 ++++++---- 3 files changed, 89 insertions(+), 62 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index f9f18ec8c66..a8dfc1d00d8 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -304,9 +304,10 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the host has no mirror of the repository; - an open PR's brief is found by its number on a merged read; - the build raised, found nothing, was not stored, or was stored under another merge - commit the mirror names for the PR. The stored row then records the version that - tried and the cause, and a later read by a build of the same or a lower version - serves it without a build. + commit the mirror names for the PR (`rebuild failed`, after the build's own notes in + `degraded`). The stored row then records the version that tried and those notes, and + a later read by a build of the same or a lower version serves it, with the same + notes, without a build. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index a6963f0e9a3..6399879fd14 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -15,7 +15,6 @@ import json import logging import time -from collections.abc import Awaitable, Callable from typing import Any, Literal from server.code.api.models_conventions import CodeSettingFactsInput @@ -267,40 +266,48 @@ async def _payload_for( if not await _stored_inside_head(repo, org, ns, payload): payload = None # stored while the head held the merge; it no longer does - async def build(sha: str) -> tuple[dict[str, Any] | None, Source]: - """The brief built afresh at `sha`: the open PR's head, or the merge commit.""" - if not is_open: - return await _build_on_miss( - repo, org, ns, pr_number=pr_number, merge_sha=sha, store=store - ) - built = ( - await _build_open(repo, org, ns, pr_number=pr_number, head_sha=sha, store=store) - if sha - else None - ) - return built, "built" if built is not None else "missing" - if payload is not None and int(payload.get("v") or 0) < rb.PAYLOAD_VERSION: - if bool(payload.get("overlay")) != is_open: + if not is_open and payload.get("overlay"): # an open PR's brief the merged read found by its number: only the open read # builds it return _stale_served(payload, "an open PR's brief read as merged") - # the stored row's key: a read by merge commit alone names no number - pr_number = int(payload.get("pr_number") or pr_number) sha = head_sha if is_open else str(payload.get("merge_sha") or "") - return await _rebuild(repo, org, ns, payload, sha, store=store, build=build) + return await _rebuild(repo, org, ns, payload, sha, is_open=is_open, store=store) if payload is not None: return payload, "precomputed" with code_span("review_brief.build") as sp: - payload, source = await build(head_sha if is_open else merge_sha) + payload, source = await _build_at( + repo, + org, + ns, + is_open=is_open, + pr_number=pr_number, + sha=head_sha if is_open else merge_sha, + store=store, + ) span_attrs(sp, results=int(payload is not None)) return payload, source +async def _build_at( + repo: CodeRepo, org: str, ns: str, *, is_open: bool, pr_number: int, sha: str, store: bool +) -> tuple[dict[str, Any] | None, Source]: + """The brief built afresh at `sha`: an open PR's head, or the merge commit.""" + if not is_open: + return await _build_on_miss(repo, org, ns, pr_number=pr_number, merge_sha=sha, store=store) + built = ( + await _build_open(repo, org, ns, pr_number=pr_number, head_sha=sha, store=store) + if sha + else None + ) + return built, "built" if built is not None else "missing" + + # What a stored brief of an older payload version records of the one build that tried to -# replace it: the version that build was of, and why its brief was not stored. +# replace it: the version that build was of, and the notes of why its brief was not stored. REBUILT_FOR = "rebuilt_for" -REBUILD_CAUSE = "rebuild_cause" +REBUILD_NOTES = "rebuild_notes" +REBUILD_FAILED = "rebuild failed" async def _rebuild( @@ -310,47 +317,54 @@ async def _rebuild( stale: dict[str, Any], sha: str, *, + is_open: bool, store: bool, - build: Callable[[str], Awaitable[tuple[dict[str, Any] | None, Source]]], ) -> tuple[dict[str, Any], Source]: - """A stored brief of an older payload version, built again at `sha` and stored in its - place, at most once per row and version; when it is served instead is in + """A stored brief of an older payload version, built again at `sha`, its row's key with + its PR number (an open PR's head, or the merge commit), and stored in its place, at + most once per row and version; when it is served instead is in docs/features/code-index/history-and-prs.md.""" from server.code.domain.index.repos import repo_for_namespace + pr_number = int(stale.get("pr_number") or 0) if int(stale.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: - return _stale_served(stale, str(stale.get(REBUILD_CAUSE) or "")) + return _stale_served(stale, REBUILD_FAILED, stale.get(REBUILD_NOTES)) if not store: return _stale_served(stale, "not stored by this read") if not await present_dir(repo_for_namespace(org, ns)): return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): try: - fresh, source = await build(sha) + fresh, _source = await _build_at( + repo, org, ns, is_open=is_open, pr_number=pr_number, sha=sha, store=True + ) except Exception as e: # noqa: BLE001 — a rebuild that raises serves the stored brief logger.warning("code.review_brief: rebuild at %s raised: %s", sha[:12], e) degradations.partial("code.review_brief", "brief_missing", e) - fresh, source = None, "missing" - notes = degradations.current() + fresh, _source = None, "missing" + if fresh is not None: + at = str(fresh.get("head_sha" if is_open else "merge_sha") or "") + if at != sha: # another key than the stored row's + degradations.partial("code.review_brief", "rebuilt_at_another_commit", at[:12]) + elif fresh.get("stored", True): + return fresh, _source + notes = degradations.current() or [ + "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") + ] span_attrs(sp, results=int(fresh is not None)) - if fresh is not None: - at = str(fresh.get("head_sha" if fresh.get("overlay") else "merge_sha") or "") - if at != sha: - notes.append(f"built at {at[:12]}") # another key than the stored row's - elif fresh.get("stored", True): - return fresh, source - cause = "; ".join(notes) or ("unstored" if fresh is not None else "missing") - pr_number = int(stale.get("pr_number") or 0) try: row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: - return _stale_served(stale, cause) # deleted while the build ran + return _stale_served(stale, REBUILD_FAILED, notes) # deleted while the build ran latest = json.loads(str(row.get("payload") or "{}")) if int(latest.get("v") or 0) >= rb.PAYLOAD_VERSION: return latest, "precomputed" # another replica stored the rebuilt brief + if int(latest.get(REBUILT_FOR) or 0) >= rb.PAYLOAD_VERSION: + # a build of this or a newer version marked it meanwhile + return _stale_served(latest, REBUILD_FAILED, latest.get(REBUILD_NOTES)) stale = latest marked = review_brief_build.brief_row( - org, ns, {**latest, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_CAUSE: cause} + org, ns, {**latest, REBUILT_FOR: rb.PAYLOAD_VERSION, REBUILD_NOTES: notes} ) # The row it replaces keeps its key and build time (an open PR's payload names no # merge commit), and its version plus one, below any build's, which is stamped with @@ -361,10 +375,15 @@ async def _rebuild( await repo.insert_rows("code_review_briefs", [marked]) except Exception as e: # noqa: BLE001 — unmarked, the next read builds it again logger.warning("code.review_brief: rebuild of PR %s not recorded: %s", pr_number, e) - return _stale_served(stale, cause) + return _stale_served(stale, REBUILD_FAILED, notes) -def _stale_served(stale: dict[str, Any], cause: str) -> tuple[dict[str, Any], Source]: +def _stale_served( + stale: dict[str, Any], cause: str, notes: Any = None +) -> tuple[dict[str, Any], Source]: + """The stored brief, served with why it was not rebuilt and the notes of the build that + tried, each listed as it was.""" + degradations.restore(list(notes or [])) degradations.partial("code.review_brief", "stale_brief_served", cause) return stale, "precomputed" diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 7d325228bf4..79e1d3fd81f 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -622,6 +622,9 @@ async def _git_run(git_dir: str, *args: str, **kw: Any) -> str: return wired +STALE = f"code.review_brief: stale_brief_served ({h.REBUILD_FAILED})" + + async def _stale_row(state: dict[str, Any], **extra: Any) -> dict[str, Any]: """The stored row of the PR's brief as an older build wrote it: payload version 2.""" out = await h.handle_code_review_brief(CodeReviewBriefInput(pr_number=42, tier="full")) @@ -711,7 +714,7 @@ async def _no_mirror_here(cfg: Any) -> str: def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> str: - """Make the mirror's diff reads fail; the notes a build then records, as one cause.""" + """Make the mirror's diff reads fail; the notes a build then records.""" import server.code.app.index.gitrepo as gitrepo_mod async def _run(git_dir: str, *args: str, **kw: Any) -> str: @@ -720,7 +723,7 @@ async def _run(git_dir: str, *args: str, **kw: Any) -> str: raise RuntimeError("git diff failed") monkeypatch.setattr(gitrepo_mod, "run", _run) - return "git_mirror: diff_unread (RuntimeError); git_mirror: drift_unread (RuntimeError)" + return ["git_mirror: diff_unread (RuntimeError)", "git_mirror: drift_unread (RuntimeError)"] @pytest.mark.asyncio @@ -732,23 +735,23 @@ async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( version builds nothing; a newer build's version tries again.""" repo = demo["repo"] repo.stored = stale = await _stale_row(demo) - cause = _diff_fails(monkeypatch) + built = _diff_fails(monkeypatch) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert notes == [*built, STALE] assert len(demo["mirror"]) == 1 [(_table, [row])] = repo.inserted assert json.loads(row["payload"]) == { **json.loads(stale["payload"]), h.REBUILT_FOR: rb.PAYLOAD_VERSION, - h.REBUILD_CAUSE: cause, + h.REBUILD_NOTES: built, } # one above the row it replaces, so a rebuild stored by another replica still wins assert row["version"] == stale["version"] + 1 repo.stored = row again, notes = await _read() assert again.source == "precomputed" and again.sections == out.sections - assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert notes == [*built, STALE] assert len(demo["mirror"]) == 1 and len(repo.inserted) == 1 monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION + 1) @@ -760,14 +763,17 @@ async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( async def test_a_failed_rebuild_writes_nothing_over_a_newer_or_a_deleted_row( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: - """Read again after the build: a brief another replica stored meanwhile is served, and - a row deleted meanwhile is not brought back.""" + """Read again after the build: a brief another replica stored meanwhile is served, a + marker a build of this or a newer version wrote meanwhile is kept, and a row deleted + meanwhile is not brought back.""" repo = demo["repo"] stale = await _stale_row(demo) fresh_payload = {**json.loads(stale["payload"]), "v": rb.PAYLOAD_VERSION} fresh = {**stale, "payload": json.dumps(fresh_payload)} - cause = _diff_fails(monkeypatch) - for after, served in ((fresh, "fresh"), (None, "stale")): + newer = {h.REBUILT_FOR: rb.PAYLOAD_VERSION + 1, h.REBUILD_NOTES: ["git_mirror: x"]} + marked = {**stale, "payload": json.dumps({**json.loads(stale["payload"]), **newer})} + built = _diff_fails(monkeypatch) + for after, served in ((fresh, "fresh"), (marked, "marked"), (None, "stale")): reads = iter([stale, after]) async def _point_read( @@ -780,8 +786,10 @@ async def _point_read( assert out.source == "precomputed" and repo.inserted == [] if served == "fresh": assert notes == [] and "brief:v2" not in out.verdict_causes + elif served == "marked": + assert notes == ["git_mirror: x", STALE] else: - assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert notes == [*built, STALE] assert "brief:v2" in out.verdict_causes @@ -798,8 +806,7 @@ async def _ledger_down(org: str, ns: str, **kw: Any) -> None: monkeypatch.setattr(repo, "pr_merge_facts", _ledger_down) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - [note] = notes - assert note.startswith("code.review_brief: stale_brief_served (code.review_brief: brief_") + assert notes == ["code.review_brief: brief_missing (TimeoutError)", STALE] [(_table, [row])] = repo.inserted assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION @@ -810,7 +817,7 @@ async def test_a_marker_that_cannot_be_written_serves_the_stored_brief_and_tries ) -> None: repo = demo["repo"] repo.stored = await _stale_row(demo) - cause = _diff_fails(monkeypatch) + built = _diff_fails(monkeypatch) async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: raise TimeoutError("insert timed out") @@ -819,7 +826,7 @@ async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: for builds in (1, 2): out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [f"code.review_brief: stale_brief_served ({cause})"] + assert notes == [*built, STALE] assert len(demo["mirror"]) == builds # unmarked, the next read builds again @@ -840,7 +847,7 @@ async def _moved(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _moved) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [f"code.review_brief: stale_brief_served (built at {other[:12]})"] + assert notes == [f"code.review_brief: rebuilt_at_another_commit ({other[:12]})", STALE] assert [r["merge_sha"] for _t, [r] in repo.inserted] == [other, DEMO_SHA] marker = repo.inserted[1][1][0] assert marker["version"] == stale["version"] + 1 @@ -872,13 +879,13 @@ async def test_an_older_build_reads_a_newer_builds_marker_without_building( """A row below both builds' versions that the newer build marked: the older build, whose version is lower than the marker's, builds nothing either.""" repo = demo["repo"] - marked = {h.REBUILT_FOR: rb.PAYLOAD_VERSION, h.REBUILD_CAUSE: "git_mirror: diff_unread"} + marked = {h.REBUILT_FOR: rb.PAYLOAD_VERSION, h.REBUILD_NOTES: ["git_mirror: diff_unread"]} repo.stored = await _stale_row(demo, v=rb.PAYLOAD_VERSION - 2, **marked) monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION - 1) monkeypatch.setattr(review_brief_build, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION) out, notes = await _read() assert out.source == "precomputed" and demo["mirror"] == [] and repo.inserted == [] - assert notes == ["code.review_brief: stale_brief_served (git_mirror: diff_unread)"] + assert notes == ["git_mirror: diff_unread", STALE] DEMO_HEAD = "c3" * 20 @@ -923,7 +930,7 @@ async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: monkeypatch.setattr(h, "_build_open", _unbuilt) out, notes = await _read(open=True) assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == ["code.review_brief: stale_brief_served (missing)"] + assert notes == ["code.review_brief: brief_missing", STALE] [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) assert row["built_at"] == repo.stored["built_at"] From 2eac5db42cc2ee9e462b69bae63a25fb6116c3c5 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:05:25 +0000 Subject: [PATCH 09/26] A read by PR number serves a rebuild placed at another merge commit; the op text names the rebuild Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 10 +++---- docs/features/code-index/history-and-prs.md | 5 ++-- server/code/api/models_review.py | 3 +- server/code/app/review_brief.py | 32 ++++++++++++++------- server/transport/mcp_descriptions.py | 4 +-- tests/unit/test_code_review_brief_mirror.py | 22 ++++++++++---- 6 files changed, 50 insertions(+), 26 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 230e5c3645d..43384e8efc6 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1665,11 +1665,11 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline a bump that adds a cause N-1 does not know ships N-1's reading of that cause first (rule 3), or N-1 can settle a brief N leaves `unsettled`. A brief N-1's ingest writes while both serve is of N-1's version, and N rebuilds it once. A build that cannot store - its brief writes the old one again with `rebuilt_for` set to its version, at the - replaced row's version plus one, so any build stored later replaces it, and neither - build tries that row again until a higher version serves. Both builds read the same - rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are ([PR - history](../features/code-index/history-and-prs.md)). No gate holds the rollout. + its brief writes the old one again with `rebuilt_for` set to its version, with the + replaced row's `version` column plus one, so any build stored later replaces it, and + neither build tries that row again until a higher version serves. Both builds read the + same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are + ([PR history](../features/code-index/history-and-prs.md)). No gate holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version gate does not check this rule. diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index a8dfc1d00d8..327886c2c6c 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -303,8 +303,9 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the read does not store (`store: false`, a measurement consumer, a posted diff); - the host has no mirror of the repository; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing, was not stored, or was stored under another merge - commit the mirror names for the PR (`rebuild failed`, after the build's own notes in +- the build raised, found nothing, was not stored, or, on a read that names the old + merge commit, was stored under another one the mirror names for the PR (a read by + number serves that new brief) (`rebuild failed`, after the build's own notes in `degraded`). The stored row then records the version that tried and those notes, and a later read by a build of the same or a lower version serves it, with the same notes, without a build. diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index bcf10278863..bc2482b5c76 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -64,7 +64,8 @@ class CodeReviewBriefInput(_CodeIdentity, _PrPostImage): touched symbols with callers and fan-in, coverage verdicts, setting facts, regression history, blame of the deleted lines, path classes, the tracker record and the calibrated risk priors (`jit_risk` and `author_revert_prior`, ranking signals, - never a gate) — or a build on the first miss. `rationale`, read on every call and + never a gate) — or a build on the first miss, or again for a brief stored at an older + payload version. `rationale`, read on every call and never stored, lists the repository's design decisions and constraints that govern the PR's files. `tier` selects sections (trivial: paths + symbols; standard: + tests, settings, history, risk, rationale; full: + blame, qa); diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 6399879fd14..0918abd2420 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -272,7 +272,16 @@ async def _payload_for( # builds it return _stale_served(payload, "an open PR's brief read as merged") sha = head_sha if is_open else str(payload.get("merge_sha") or "") - return await _rebuild(repo, org, ns, payload, sha, is_open=is_open, store=store) + return await _rebuild( + repo, + org, + ns, + payload, + sha, + is_open=is_open, + store=store, + named=is_open or bool(merge_sha), + ) if payload is not None: return payload, "precomputed" with code_span("review_brief.build") as sp: @@ -319,11 +328,13 @@ async def _rebuild( *, is_open: bool, store: bool, + named: bool, ) -> tuple[dict[str, Any], Source]: - """A stored brief of an older payload version, built again at `sha`, its row's key with - its PR number (an open PR's head, or the merge commit), and stored in its place, at - most once per row and version; when it is served instead is in - docs/features/code-index/history-and-prs.md.""" + """Build a stored brief of an older payload version again at `sha`, its row's key (an + open PR's head or the merge commit), and store it in its place, at most once per row + and version; docs/features/code-index/history-and-prs.md says when the stored one is + served instead. A read that `named` no merge commit serves a rebuild the mirror places + at another one, which is the PR's newest brief from then on.""" from server.code.domain.index.repos import repo_for_namespace pr_number = int(stale.get("pr_number") or 0) @@ -335,23 +346,24 @@ async def _rebuild( return _stale_served(stale, "no mirror on this host") with code_span("review_brief.rebuild") as sp, degradations.scoped(): try: - fresh, _source = await _build_at( + fresh, source = await _build_at( repo, org, ns, is_open=is_open, pr_number=pr_number, sha=sha, store=True ) except Exception as e: # noqa: BLE001 — a rebuild that raises serves the stored brief logger.warning("code.review_brief: rebuild at %s raised: %s", sha[:12], e) degradations.partial("code.review_brief", "brief_missing", e) - fresh, _source = None, "missing" + fresh, source = None, "missing" + span_attrs(sp, results=int(fresh is not None)) if fresh is not None: at = str(fresh.get("head_sha" if is_open else "merge_sha") or "") + stored = bool(fresh.get("stored", True)) + if stored and (at == sha or not named): + return fresh, source if at != sha: # another key than the stored row's degradations.partial("code.review_brief", "rebuilt_at_another_commit", at[:12]) - elif fresh.get("stored", True): - return fresh, _source notes = degradations.current() or [ "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") ] - span_attrs(sp, results=int(fresh is not None)) try: row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 7f2e584f886..dcf0d4944f2 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1645,8 +1645,8 @@ def revision_policy(update: str) -> str: "pack (files, callers, tests). Neither: a repo orientation map." ), "code.review_brief": ( - "A merged PR's review brief, built once at merge and read as a " - "point. `verdict` answers first: gaps (`verdict_causes` names each) " + "A merged PR's review brief, built at merge (again once its rules " + "change) and read as a point. `verdict` answers first: gaps (`verdict_causes` names each) " "| no_source_change | nothing_to_check | covered_no_gaps (never on a " "coverage claim that rests on a co-changed test alone), each only " "when every check it rests on ran in full | unsettled " diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 79e1d3fd81f..5a3794fc3c2 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -713,7 +713,7 @@ async def _no_mirror_here(cfg: Any) -> str: assert demo["mirror"] == [] and repo.inserted == [] -def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> str: +def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> list[str]: """Make the mirror's diff reads fail; the notes a build then records.""" import server.code.app.index.gitrepo as gitrepo_mod @@ -746,8 +746,12 @@ async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( h.REBUILT_FOR: rb.PAYLOAD_VERSION, h.REBUILD_NOTES: built, } - # one above the row it replaces, so a rebuild stored by another replica still wins + # one above the row it replaces, so a rebuild stored by another replica still wins; + # read again and written under the row's own key, every other column as it was assert row["version"] == stale["version"] + 1 + assert repo.reads[-1] == (42, DEMO_SHA) + kept = ("pr_number", "merge_sha", "sections", "indexed_commit", "tokens", "build_ms") + assert {k: row[k] for k in kept} == {k: stale[k] for k in kept} repo.stored = row again, notes = await _read() assert again.source == "precomputed" and again.sections == out.sections @@ -834,8 +838,9 @@ async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: async def test_a_rebuild_the_mirror_places_at_another_merge_commit_marks_the_stale_row( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: - """A build stored under another key leaves the stale row as it was: the row is marked, - so a read that names the old merge commit does not build again on every call.""" + """A build stored under another key leaves the stale row as it was. A read by the PR's + number serves it, the PR's newest brief from then on; a read that names the old merge + commit marks the old row, so it does not build again on every call.""" repo = demo["repo"] repo.stored = stale = await _stale_row(demo) other = "d4" * 20 @@ -845,7 +850,12 @@ async def _moved(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: return {**DEMO_FACTS, "merge_sha": other} monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _moved) - out, notes = await _read() + by_number, notes = await _read() + assert by_number.source == "built_from_mirror" and by_number.merge_sha == other + assert notes == [] and [r["merge_sha"] for _t, [r] in repo.inserted] == [other] + + repo.inserted.clear() + out, notes = await _read(merge_sha=DEMO_SHA) assert out.source == "precomputed" and "brief:v2" in out.verdict_causes assert notes == [f"code.review_brief: rebuilt_at_another_commit ({other[:12]})", STALE] assert [r["merge_sha"] for _t, [r] in repo.inserted] == [other, DEMO_SHA] @@ -933,7 +943,7 @@ async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: assert notes == ["code.review_brief: brief_missing", STALE] [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) - assert row["built_at"] == repo.stored["built_at"] + assert row["built_at"] == repo.stored["built_at"] and repo.reads[-1] == (42, DEMO_HEAD) assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION # read by its number as merged, an open PR's brief is not built as a merged one From ec81f93aaea1c892d0c4c684554829ff7c8509d5 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:14:07 +0000 Subject: [PATCH 10/26] The docs say a rebuild's marker holds for the version whatever the cause Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 7 ++++--- docs/features/code-index/history-and-prs.md | 16 ++++++++++------ server/code/api/models_review.py | 10 +++++----- server/code/app/index/review_brief.py | 4 ++-- server/code/app/review_brief.py | 2 +- tests/unit/test_code_review_brief_mirror.py | 12 +++++------- 6 files changed, 27 insertions(+), 24 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 43384e8efc6..d899375b397 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1667,9 +1667,10 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline while both serve is of N-1's version, and N rebuilds it once. A build that cannot store its brief writes the old one again with `rebuilt_for` set to its version, with the replaced row's `version` column plus one, so any build stored later replaces it, and - neither build tries that row again until a higher version serves. Both builds read the - same rows, so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are - ([PR history](../features/code-index/history-and-prs.md)). No gate holds the rollout. + neither build tries that row again until a higher version serves, whatever made the + build fail. Both builds read the same rows, so a rollback leaves rebuilt briefs as + newer rows N-1 serves as they are ([PR + history](../features/code-index/history-and-prs.md)). No gate holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version gate does not check this rule. diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 327886c2c6c..174f14178b4 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -303,12 +303,16 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the read does not store (`store: false`, a measurement consumer, a posted diff); - the host has no mirror of the repository; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing, was not stored, or, on a read that names the old - merge commit, was stored under another one the mirror names for the PR (a read by - number serves that new brief) (`rebuild failed`, after the build's own notes in - `degraded`). The stored row then records the version that tried and those notes, and - a later read by a build of the same or a lower version serves it, with the same - notes, without a build. +- the build raised, found nothing or was not stored, or, on a read that names the old + merge commit, was stored under another one the mirror names for the PR. A read by + number serves the brief stored under the other commit. + +In the last case `degraded` lists the build's notes, then `stale_brief_served (rebuild +failed)`. The stored row records the version that tried and those notes, and a later +read by a build of the same or a lower version serves it, with the same notes, without +a build. That holds whatever the cause, a passing failure on one host (a timed-out read, +a git call that failed) included: the cost stays at one build per stored row and +version, and the old brief answers until a build of a higher version tries again. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index bc2482b5c76..72bcbf2b8ea 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -65,11 +65,11 @@ class CodeReviewBriefInput(_CodeIdentity, _PrPostImage): regression history, blame of the deleted lines, path classes, the tracker record and the calibrated risk priors (`jit_risk` and `author_revert_prior`, ranking signals, never a gate) — or a build on the first miss, or again for a brief stored at an older - payload version. `rationale`, read on every call and - never stored, lists the repository's design decisions and constraints that govern the - PR's files. `tier` selects sections (trivial: paths + symbols; - standard: + tests, settings, history, risk, rationale; full: + blame, qa); - `sections` narrows further; a positive `token_budget` limits the returned rows.""" + payload version. `rationale`, read on every call and never stored, lists the + repository's design decisions and constraints that govern the PR's files. `tier` + selects sections (trivial: paths + symbols; standard: + tests, settings, history, + risk, rationale; full: + blame, qa); `sections` narrows further; a positive + `token_budget` limits the returned rows.""" # The PR to brief; 0 = find it by `merge_sha`. Required with `open`. A PR merged # after the commit the namespace indexes answers `missing`, as an unknown PR. diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index 1500d4c5961..10596753d04 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -76,8 +76,8 @@ # The version of the rules a brief is built and answered by. Bump it in the change that # alters what a build stores (a section, a row field, a cap, a cause) or what # `brief_verdict` answers over a stored brief: a read of a brief stored at a lower version -# builds it again (`server.code.app.review_brief._rebuild`). The build before answers a -# brief of this version by its own rules, so a new cause ships its reading there first +# builds it again (`server.code.app.review_brief._rebuild`). The previous release answers +# a brief of this version by its own rules, so a new cause ships its reading there first # (rolling-upgrades rule 101). PAYLOAD_VERSION = 3 diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 0918abd2420..3b65c81879f 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -395,7 +395,7 @@ def _stale_served( ) -> tuple[dict[str, Any], Source]: """The stored brief, served with why it was not rebuilt and the notes of the build that tried, each listed as it was.""" - degradations.restore(list(notes or [])) + degradations.restore(notes or []) degradations.partial("code.review_brief", "stale_brief_served", cause) return stale, "precomputed" diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 5a3794fc3c2..15826afeb39 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -865,21 +865,19 @@ async def _moved(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: @pytest.mark.asyncio -async def test_a_read_by_merge_commit_alone_rebuilds_under_the_stored_rows_key( - demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +async def test_a_read_by_merge_commit_alone_rebuilds_by_the_stored_rows_pr_number( + demo: dict[str, Any], ) -> None: + """A read that names only the merge commit rebuilds by the stored row's PR number + (the mirror is asked for PR 42) and stores the brief under the row's key.""" repo = demo["repo"] repo.stored = await _stale_row(demo) - - async def _by_sha(git_dir: str, sha: str, **kw: Any) -> dict[str, Any] | None: - return dict(DEMO_FACTS) if sha == DEMO_SHA else None - - monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _by_sha) out = await h.handle_code_review_brief(CodeReviewBriefInput(merge_sha=DEMO_SHA, tier="full")) assert out.source == "built_from_mirror" and out.stored is True and out.pr_number == 42 [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert repo.reads[-1] == (0, DEMO_SHA) + assert demo["mirror"] == [("/nonexistent/greeter.git", "trunk", 42)] @pytest.mark.asyncio From f0e3e7ac41bf0c7711036e210830b45f217580a7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:23:20 +0000 Subject: [PATCH 11/26] The docs name the one exception to the rebuild bound, and the MCP text says a rebuild happens on a read Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 10 +++++----- docs/features/code-index/history-and-prs.md | 3 ++- server/transport/mcp_descriptions.py | 5 +++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index d899375b397..59b0468a1d1 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1668,11 +1668,11 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline its brief writes the old one again with `rebuilt_for` set to its version, with the replaced row's `version` column plus one, so any build stored later replaces it, and neither build tries that row again until a higher version serves, whatever made the - build fail. Both builds read the same rows, so a rollback leaves rebuilt briefs as - newer rows N-1 serves as they are ([PR - history](../features/code-index/history-and-prs.md)). No gate holds the rollout. - `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version - gate does not check this rule. + build fail; a row whose marker could not be written is built again by the next read. + Both builds read the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 + serves as they are ([PR history](../features/code-index/history-and-prs.md)). No gate + holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and + the mixed-version gate does not check this rule. ## What checks them diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 174f14178b4..08003443798 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -312,7 +312,8 @@ failed)`. The stored row records the version that tried and those notes, and a l read by a build of the same or a lower version serves it, with the same notes, without a build. That holds whatever the cause, a passing failure on one host (a timed-out read, a git call that failed) included: the cost stays at one build per stored row and -version, and the old brief answers until a build of a higher version tries again. +version, and the old brief answers until a build of a higher version tries again. Only +a row whose marker could not be written is built again by the next read. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index dcf0d4944f2..1dc48fb4959 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1645,8 +1645,9 @@ def revision_policy(update: str) -> str: "pack (files, callers, tests). Neither: a repo orientation map." ), "code.review_brief": ( - "A merged PR's review brief, built at merge (again once its rules " - "change) and read as a point. `verdict` answers first: gaps (`verdict_causes` names each) " + "A merged PR's review brief, built at merge (and again on a read of " + "one stored at an older payload version) and read as a point. " + "`verdict` answers first: gaps (`verdict_causes` names each) " "| no_source_change | nothing_to_check | covered_no_gaps (never on a " "coverage claim that rests on a co-changed test alone), each only " "when every check it rests on ran in full | unsettled " From b00d5edc8c2fc5cc17f7f50546445655ada4646c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:36:31 +0000 Subject: [PATCH 12/26] A rebuild of a merged brief looks the row up by its own merge commit Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 6 +-- server/code/app/review_brief.py | 35 ++++++---------- tests/unit/test_code_review_brief_mirror.py | 45 +++++---------------- 3 files changed, 25 insertions(+), 61 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 08003443798..0b8a3c18fe8 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -294,7 +294,7 @@ older version is tried once (below). A change to what a brief stores or how its verdict reads it raises the payload version (`v` in the payload). A stored brief of the current version is served as it was built. -A read of a brief of an older version builds it again, a merged PR's from its merge +A read of a brief of an older version builds it again, a merged PR's from its own merge commit and an open PR's at the same head, and stores the new brief in its place (`source` names the build); a read after that serves it as stored. The old brief is served instead, its verdict `gaps`, or `unsettled` with `brief:v`, and `degraded` @@ -303,9 +303,7 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the read does not store (`store: false`, a measurement consumer, a posted diff); - the host has no mirror of the repository; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing or was not stored, or, on a read that names the old - merge commit, was stored under another one the mirror names for the PR. A read by - number serves the brief stored under the other commit. +- the build raised, found nothing or was not stored. In the last case `degraded` lists the build's notes, then `stale_brief_served (rebuild failed)`. The stored row records the version that tried and those notes, and a later diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 3b65c81879f..40e74f63214 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -272,16 +272,7 @@ async def _payload_for( # builds it return _stale_served(payload, "an open PR's brief read as merged") sha = head_sha if is_open else str(payload.get("merge_sha") or "") - return await _rebuild( - repo, - org, - ns, - payload, - sha, - is_open=is_open, - store=store, - named=is_open or bool(merge_sha), - ) + return await _rebuild(repo, org, ns, payload, sha, is_open=is_open, store=store) if payload is not None: return payload, "precomputed" with code_span("review_brief.build") as sp: @@ -328,13 +319,12 @@ async def _rebuild( *, is_open: bool, store: bool, - named: bool, ) -> tuple[dict[str, Any], Source]: """Build a stored brief of an older payload version again at `sha`, its row's key (an open PR's head or the merge commit), and store it in its place, at most once per row and version; docs/features/code-index/history-and-prs.md says when the stored one is - served instead. A read that `named` no merge commit serves a rebuild the mirror places - at another one, which is the PR's newest brief from then on.""" + served instead. A merged row is built from its own merge commit alone, so the build + lands on the row's key.""" from server.code.domain.index.repos import repo_for_namespace pr_number = int(stale.get("pr_number") or 0) @@ -347,20 +337,21 @@ async def _rebuild( with code_span("review_brief.rebuild") as sp, degradations.scoped(): try: fresh, source = await _build_at( - repo, org, ns, is_open=is_open, pr_number=pr_number, sha=sha, store=True + repo, + org, + ns, + is_open=is_open, + pr_number=pr_number if is_open else 0, + sha=sha, + store=True, ) except Exception as e: # noqa: BLE001 — a rebuild that raises serves the stored brief logger.warning("code.review_brief: rebuild at %s raised: %s", sha[:12], e) degradations.partial("code.review_brief", "brief_missing", e) - fresh, source = None, "missing" + fresh = None span_attrs(sp, results=int(fresh is not None)) - if fresh is not None: - at = str(fresh.get("head_sha" if is_open else "merge_sha") or "") - stored = bool(fresh.get("stored", True)) - if stored and (at == sha or not named): - return fresh, source - if at != sha: # another key than the stored row's - degradations.partial("code.review_brief", "rebuilt_at_another_commit", at[:12]) + if fresh is not None and fresh.get("stored", True): + return fresh, source notes = degradations.current() or [ "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") ] diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 15826afeb39..ee13be16221 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -609,6 +609,10 @@ async def _mirror(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: wired["mirror"].append((git_dir, branch, pr_number)) return dict(DEMO_FACTS) if pr_number == 42 else None + async def _by_sha(git_dir: str, merge_sha: str, **kw: Any) -> Any: + wired["mirror"].append((git_dir, merge_sha)) + return dict(DEMO_FACTS) if merge_sha == DEMO_SHA else None + async def _git_run(git_dir: str, *args: str, **kw: Any) -> str: if args[0] == "rev-parse": return DEMO_PARENT + "\n" @@ -617,6 +621,7 @@ async def _git_run(git_dir: str, *args: str, **kw: Any) -> str: monkeypatch.setattr(h, "resolve_code_identity", lambda o, n: (DEMO_ORG, DEMO_NS)) monkeypatch.setattr(repos_mod, "repo_for_namespace", lambda o, n: _DemoCfg()) monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _mirror) + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _by_sha) monkeypatch.setattr(h, "call_code_op", _demo_calls) monkeypatch.setattr(gitrepo_mod, "run", _git_run) return wired @@ -660,7 +665,7 @@ async def test_a_brief_stored_at_an_older_version_is_rebuilt_once_and_stored_in_ out, notes = await _read() assert out.source == "built_from_mirror" and out.stored is True and notes == [] assert not any(c.startswith("brief:") for c in out.verdict_causes) - assert demo["mirror"] == [("/nonexistent/greeter.git", "trunk", 42)] + assert demo["mirror"] == [("/nonexistent/greeter.git", DEMO_SHA)] [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION @@ -835,41 +840,11 @@ async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: @pytest.mark.asyncio -async def test_a_rebuild_the_mirror_places_at_another_merge_commit_marks_the_stale_row( - demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch -) -> None: - """A build stored under another key leaves the stale row as it was. A read by the PR's - number serves it, the PR's newest brief from then on; a read that names the old merge - commit marks the old row, so it does not build again on every call.""" - repo = demo["repo"] - repo.stored = stale = await _stale_row(demo) - other = "d4" * 20 - - async def _moved(git_dir: str, branch: str, pr_number: int, **kw: Any) -> Any: - demo["mirror"].append((git_dir, branch, pr_number)) - return {**DEMO_FACTS, "merge_sha": other} - - monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _moved) - by_number, notes = await _read() - assert by_number.source == "built_from_mirror" and by_number.merge_sha == other - assert notes == [] and [r["merge_sha"] for _t, [r] in repo.inserted] == [other] - - repo.inserted.clear() - out, notes = await _read(merge_sha=DEMO_SHA) - assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [f"code.review_brief: rebuilt_at_another_commit ({other[:12]})", STALE] - assert [r["merge_sha"] for _t, [r] in repo.inserted] == [other, DEMO_SHA] - marker = repo.inserted[1][1][0] - assert marker["version"] == stale["version"] + 1 - assert json.loads(marker["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION - - -@pytest.mark.asyncio -async def test_a_read_by_merge_commit_alone_rebuilds_by_the_stored_rows_pr_number( +async def test_a_read_by_merge_commit_alone_rebuilds_the_row_at_its_merge_commit( demo: dict[str, Any], ) -> None: - """A read that names only the merge commit rebuilds by the stored row's PR number - (the mirror is asked for PR 42) and stores the brief under the row's key.""" + """A rebuild asks the mirror for the row's own merge commit, not the PR's number, so + the brief is stored under the row's key.""" repo = demo["repo"] repo.stored = await _stale_row(demo) out = await h.handle_code_review_brief(CodeReviewBriefInput(merge_sha=DEMO_SHA, tier="full")) @@ -877,7 +852,7 @@ async def test_a_read_by_merge_commit_alone_rebuilds_by_the_stored_rows_pr_numbe [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert repo.reads[-1] == (0, DEMO_SHA) - assert demo["mirror"] == [("/nonexistent/greeter.git", "trunk", 42)] + assert demo["mirror"] == [("/nonexistent/greeter.git", DEMO_SHA)] @pytest.mark.asyncio From 184c4926fa2bde33d4ae20c0249f6954bab76206 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:45:19 +0000 Subject: [PATCH 13/26] A host whose mirror lacks the merge serves a stale brief without marking it Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 3 +- server/code/app/review_brief.py | 16 +++++++- tests/unit/test_code_review_brief_mirror.py | 45 ++++++++++++++++++--- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 0b8a3c18fe8..a2757e272fa 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -301,7 +301,8 @@ served instead, its verdict `gaps`, or `unsettled` with `brief:v`, and `degra names `code.review_brief: stale_brief_served` with the reason. That happens when: - the read does not store (`store: false`, a measurement consumer, a posted diff); -- the host has no mirror of the repository; +- the host has no mirror of the repository, or its mirror has yet to fetch the merge + commit (a later read, on this host or another, builds it); - an open PR's brief is found by its number on a merged read; - the build raised, found nothing or was not stored. diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 40e74f63214..e90ac645576 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -332,8 +332,12 @@ async def _rebuild( return _stale_served(stale, REBUILD_FAILED, stale.get(REBUILD_NOTES)) if not store: return _stale_served(stale, "not stored by this read") - if not await present_dir(repo_for_namespace(org, ns)): + git_dir = await present_dir(repo_for_namespace(org, ns)) + if not git_dir: return _stale_served(stale, "no mirror on this host") + if not is_open and not await _mirror_holds(git_dir, sha): + # a merge the mirror has yet to fetch: no build and no marker, a later read builds it + return _stale_served(stale, "merge not on this host's mirror") with code_span("review_brief.rebuild") as sp, degradations.scoped(): try: fresh, source = await _build_at( @@ -381,6 +385,16 @@ async def _rebuild( return _stale_served(stale, REBUILD_FAILED, notes) +async def _mirror_holds(git_dir: str, sha: str) -> bool: + from server.code.app.index import gitrepo + + try: + return await gitrepo.holds_commit(git_dir, sha) + except gitrepo.GitError as e: # an unreadable mirror holds nothing this read can build + logger.info("code.review_brief: mirror %s unread for %s: %s", git_dir, sha[:12], e) + return False + + def _stale_served( stale: dict[str, Any], cause: str, notes: Any = None ) -> tuple[dict[str, Any], Source]: diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index ee13be16221..2655f6dacc1 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -623,7 +623,12 @@ async def _git_run(git_dir: str, *args: str, **kw: Any) -> str: monkeypatch.setattr(review_brief_sources, "mirror_merge_facts", _mirror) monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _by_sha) monkeypatch.setattr(h, "call_code_op", _demo_calls) + + async def _holds(git_dir: str, sha: str, **kw: Any) -> bool: + return sha == DEMO_SHA + monkeypatch.setattr(gitrepo_mod, "run", _git_run) + monkeypatch.setattr(gitrepo_mod, "holds_commit", _holds) return wired @@ -695,11 +700,11 @@ async def _ledger(org: str, ns: str, **kw: Any) -> dict[str, Any]: @pytest.mark.asyncio @pytest.mark.parametrize("consumer", ["reviewer", "eval-b12"]) -async def test_a_read_that_may_not_store_or_has_no_mirror_serves_the_stale_brief_unbuilt( - demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch, consumer: str +async def test_a_read_that_may_not_store_serves_the_stale_brief_unbuilt( + demo: dict[str, Any], consumer: str ) -> None: """A rebuild nobody stores would run again on every read: a read that does not store - serves the stored brief, and so does a host whose mirror cannot read the diff.""" + serves the stored brief.""" repo = demo["repo"] repo.stored = await _stale_row(demo) store = consumer != "reviewer" # the measurement label never stores, whatever it passes @@ -708,15 +713,45 @@ async def test_a_read_that_may_not_store_or_has_no_mirror_serves_the_stale_brief assert notes == ["code.review_brief: stale_brief_served (not stored by this read)"] assert demo["mirror"] == [] and repo.inserted == [] + +@pytest.mark.asyncio +async def test_a_host_without_the_merge_serves_the_stale_brief_unbuilt_and_unmarked( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A host with no mirror, or whose mirror has yet to fetch the merge, builds nothing + and writes no marker, so a read on a host that holds the merge still builds it.""" + import server.code.app.index.gitrepo as gitrepo_mod + + repo = demo["repo"] + repo.stored = await _stale_row(demo) + async def _no_mirror_here(cfg: Any) -> str: return "" - monkeypatch.setattr(h, "present_dir", _no_mirror_here) - out, notes = await _read() + with monkeypatch.context() as m: + m.setattr(h, "present_dir", _no_mirror_here) + out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes assert notes == ["code.review_brief: stale_brief_served (no mirror on this host)"] assert demo["mirror"] == [] and repo.inserted == [] + async def _not_fetched(git_dir: str, sha: str, **kw: Any) -> bool: + return False + + async def _unreadable(git_dir: str, sha: str, **kw: Any) -> bool: + raise gitrepo_mod.GitError("fatal: not a git repository", returncode=128) + + for holds in (_not_fetched, _unreadable): + with monkeypatch.context() as m: + m.setattr(gitrepo_mod, "holds_commit", holds) + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == ["code.review_brief: stale_brief_served (merge not on this host's mirror)"] + assert demo["mirror"] == [] and repo.inserted == [] + + out, _ = await _read() # the host that holds the merge builds it + assert out.source == "built_from_mirror" and out.stored is True + def _diff_fails(monkeypatch: pytest.MonkeyPatch) -> list[str]: """Make the mirror's diff reads fail; the notes a build then records.""" From f6ad4676816cd9b9807d66faf2b47a6cf07e6103 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:59:52 +0000 Subject: [PATCH 14/26] An open rebuild left unstored by an unread items row marks the stale row Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/review_brief.py | 12 ++++++++---- tests/unit/test_code_review_brief_mirror.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 5f4c716eb7a..396c029e980 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -338,7 +338,7 @@ async def _rebuild( gap = "" if is_open else await _merge_gap(git_dir, sha) if gap: # no build and no marker: a read once a mirror holds the merge builds it return _stale_served(stale, gap) - with code_span("review_brief.rebuild") as sp, degradations.scoped(): + with code_span("review_brief.rebuild") as sp, degradations.scoped() as own: try: fresh, source = await _build_at( repo, @@ -354,11 +354,12 @@ async def _rebuild( degradations.partial("code.review_brief", "brief_missing", e) fresh = None span_attrs(sp, results=int(fresh is not None)) - if fresh is not None and fresh.get("stored", True): - return fresh, source notes = degradations.current() or [ "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") ] + if fresh is not None and fresh.get("stored", True): + degradations.restore(own) # a stored rebuild keeps its build's notes, as a miss does + return fresh, source try: row = await repo.review_brief(org, ns, pr_number=pr_number, merge_sha=sha) if row is None: @@ -581,7 +582,7 @@ async def _build_open( try: if img is None: files = await gitrepo.diff_name_only(cfg.git_dir, base, head_sha) - return await review_brief_build.build_for_open( + payload = await review_brief_build.build_for_open( repo, org, ns, @@ -597,6 +598,9 @@ async def _build_open( author=author, diff=diff, ) + if not store: # the build sets `stored` only for a store it was asked for + payload["stored"] = False + return payload except Exception as e: # noqa: BLE001 — a miss that cannot build is a miss logger.warning("code.review_brief: open build failed for PR %s: %s", pr_number, e) degradations.partial("code.review_brief", "brief_missing", e) diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 612160cdbb2..bc5077d89e8 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -976,6 +976,7 @@ async def test_an_open_rebuild_through_the_open_build_is_stored_under_its_head( repo = demo["repo"] await _open_stale_row(demo, monkeypatch) + stale = repo.stored async def _history_dir(cfg: Any, **kw: Any) -> tuple[str, str]: return cfg.git_dir, "" @@ -999,6 +1000,24 @@ async def _item(org: str, ns: str, pr_number: int) -> dict[str, Any]: assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION + # an items row that cannot be read leaves the build unstored: the row is marked, and + # the next read serves it without a build + repo.stored = stale + repo.inserted.clear() + + async def _item_unread(org: str, ns: str, pr_number: int) -> dict[str, Any]: + raise TimeoutError("items read timed out") + + monkeypatch.setattr(repo, "gh_pr_head", _item_unread, raising=False) + out, notes = await _read(open=True) + assert out.source == "precomputed" and out.stored is False and "brief:v2" in out.verdict_causes + assert notes[0].startswith("code.review_brief: pr_item_unread") and notes[-1] == STALE + [(_table, [row])] = repo.inserted + assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION + repo.stored = row + out, again = await _read(open=True) + assert out.source == "precomputed" and len(repo.inserted) == 1 and again == notes + @pytest.mark.asyncio async def test_a_brief_stored_by_a_newer_build_is_served_as_it_is(demo: dict[str, Any]) -> None: From 26ce7134de22a6b53509a9c95846dc3d5254bb08 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:06:57 +0000 Subject: [PATCH 15/26] Test the unstored open answer and a stored rebuild's notes Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- tests/unit/test_code_review_brief_mirror.py | 68 +++++++++++++++++---- 1 file changed, 57 insertions(+), 11 deletions(-) diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index bc5077d89e8..96153d74056 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -881,6 +881,27 @@ async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: assert len(demo["mirror"]) == builds # unmarked, the next read builds again +@pytest.mark.asyncio +async def test_a_stored_rebuild_keeps_the_notes_its_lookup_recorded( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A note the rebuild records before its build (here the mirror lookup) reaches the + caller's `degraded` when the rebuilt brief is stored.""" + from server.observability import degradations + + repo = demo["repo"] + repo.stored = await _stale_row(demo) + + async def _by_sha_noted(git_dir: str, merge_sha: str, **kw: Any) -> Any: + degradations.partial("git_mirror", "lookup_slow", "a test note") + return dict(DEMO_FACTS) + + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _by_sha_noted) + out, notes = await _read() + assert out.source == "built_from_mirror" and out.stored is True + assert notes == ["git_mirror: lookup_slow (a test note)"] + + @pytest.mark.asyncio async def test_a_read_by_merge_commit_alone_rebuilds_the_row_at_its_merge_commit( demo: dict[str, Any], @@ -968,16 +989,10 @@ async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: assert notes == ["code.review_brief: stale_brief_served (an open PR's brief read as merged)"] -@pytest.mark.asyncio -async def test_an_open_rebuild_through_the_open_build_is_stored_under_its_head( - demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch -) -> None: +def _wire_open_build(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None: + """The real open build over the made-up repository: its mirror, base and changed files.""" import server.code.app.index.gitrepo as gitrepo_mod - repo = demo["repo"] - await _open_stale_row(demo, monkeypatch) - stale = repo.stored - async def _history_dir(cfg: Any, **kw: Any) -> tuple[str, str]: return cfg.git_dir, "" @@ -987,12 +1002,43 @@ async def _merge_base(git_dir: str, a: str, b: str) -> str: async def _names(git_dir: str, base: str, head: str, **kw: Any) -> list[str]: return list(DEMO_FACTS["files"]) - async def _item(org: str, ns: str, pr_number: int) -> dict[str, Any]: - return {"title": "Greet by first name", "author": "ada"} - monkeypatch.setattr(h, "history_dir", _history_dir) monkeypatch.setattr(gitrepo_mod, "merge_base", _merge_base) monkeypatch.setattr(gitrepo_mod, "diff_name_only", _names) + + +@pytest.mark.asyncio +async def test_an_open_build_without_its_items_row_answers_unstored( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """An open PR with no stored brief whose items row cannot be read is built and served, + and answers `stored: false`: nothing is kept.""" + repo = demo["repo"] + await _open_stale_row(demo, monkeypatch) + repo.stored = None + + async def _item_unread(org: str, ns: str, pr_number: int) -> dict[str, Any]: + raise TimeoutError("items read timed out") + + _wire_open_build(demo, monkeypatch) + monkeypatch.setattr(repo, "gh_pr_head", _item_unread, raising=False) + out, notes = await _read(open=True) + assert out.source == "built" and out.stored is False and repo.inserted == [] + assert notes[0].startswith("code.review_brief: pr_item_unread") + + +@pytest.mark.asyncio +async def test_an_open_rebuild_through_the_open_build_is_stored_under_its_head( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + repo = demo["repo"] + await _open_stale_row(demo, monkeypatch) + stale = repo.stored + + async def _item(org: str, ns: str, pr_number: int) -> dict[str, Any]: + return {"title": "Greet by first name", "author": "ada"} + + _wire_open_build(demo, monkeypatch) monkeypatch.setattr(repo, "gh_pr_head", _item, raising=False) out, notes = await _read(open=True) assert out.source == "built" and out.stored is True and notes == [] From 7f8b7f9052b326fd38c6e82f142c0585e6b5ed97 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:14:01 +0000 Subject: [PATCH 16/26] A stale brief's note comes before its build's, so the note cap cannot drop it Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 8 +++--- server/code/app/review_brief.py | 7 +++--- tests/unit/test_code_review_brief_mirror.py | 27 ++++++++++++++------- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index c5defa25ae4..d0c52a1d1c7 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -306,10 +306,10 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - an open PR's brief is found by its number on a merged read; - the build raised, found nothing or was not stored. -In the last case `degraded` lists the build's notes, then `stale_brief_served (rebuild -failed)`. The stored row records the version that tried and those notes, and a later -read by a build of the same or a lower version serves it, with the same notes, without -a build. That holds whatever the cause, a passing failure on one host (a timed-out read, +In the last case `degraded` lists `stale_brief_served (rebuild failed)`, then the +build's notes. The stored row records the version that tried and those notes, and a +later read by a build that has this rule, of the same or a lower version, serves it with +the same notes and without a build. That holds whatever the cause, a passing failure on one host (a timed-out read, a git call that failed) included: the cost stays at one build per stored row and version, and the old brief answers until a build of a higher version tries again. Only a row whose marker could not be written is built again by the next read. diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 396c029e980..a96dc50d5d5 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -401,10 +401,11 @@ async def _merge_gap(git_dir: str, sha: str) -> str: def _stale_served( stale: dict[str, Any], cause: str, notes: Any = None ) -> tuple[dict[str, Any], Source]: - """The stored brief, served with why it was not rebuilt and the notes of the build that - tried, each listed as it was.""" - degradations.restore(notes or []) + """The stored brief, served with why it was not rebuilt and then the notes of the build + that tried, each listed as it was. The stale note goes first: notes are capped, and a + build that filled the cap must not hide that the brief is stale.""" degradations.partial("code.review_brief", "stale_brief_served", cause) + degradations.restore(notes or []) return stale, "precomputed" diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 96153d74056..db15cb8075d 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -785,7 +785,7 @@ async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( built = _diff_fails(monkeypatch) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [*built, STALE] + assert notes == [STALE, *built] assert len(demo["mirror"]) == 1 [(_table, [row])] = repo.inserted assert json.loads(row["payload"]) == { @@ -802,7 +802,7 @@ async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( repo.stored = row again, notes = await _read() assert again.source == "precomputed" and again.sections == out.sections - assert notes == [*built, STALE] + assert notes == [STALE, *built] assert len(demo["mirror"]) == 1 and len(repo.inserted) == 1 monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION + 1) @@ -838,9 +838,9 @@ async def _point_read( if served == "fresh": assert notes == [] and "brief:v2" not in out.verdict_causes elif served == "marked": - assert notes == ["git_mirror: x", STALE] + assert notes == [STALE, "git_mirror: x"] else: - assert notes == [*built, STALE] + assert notes == [STALE, *built] assert "brief:v2" in out.verdict_causes @@ -857,7 +857,7 @@ async def _ledger_down(org: str, ns: str, **kw: Any) -> None: monkeypatch.setattr(repo, "pr_merge_facts", _ledger_down) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == ["code.review_brief: brief_missing (TimeoutError)", STALE] + assert notes == [STALE, "code.review_brief: brief_missing (TimeoutError)"] [(_table, [row])] = repo.inserted assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION @@ -877,7 +877,7 @@ async def _store_down(table: str, rows: list[dict[str, Any]]) -> None: for builds in (1, 2): out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [*built, STALE] + assert notes == [STALE, *built] assert len(demo["mirror"]) == builds # unmarked, the next read builds again @@ -931,7 +931,7 @@ async def test_an_older_build_reads_a_newer_builds_marker_without_building( monkeypatch.setattr(review_brief_build, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION) out, notes = await _read() assert out.source == "precomputed" and demo["mirror"] == [] and repo.inserted == [] - assert notes == ["git_mirror: diff_unread", STALE] + assert notes == [STALE, "git_mirror: diff_unread"] DEMO_HEAD = "c3" * 20 @@ -976,7 +976,7 @@ async def _unbuilt(repo: Any, org: str, ns: str, **kw: Any) -> None: monkeypatch.setattr(h, "_build_open", _unbuilt) out, notes = await _read(open=True) assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == ["code.review_brief: brief_missing", STALE] + assert notes == [STALE, "code.review_brief: brief_missing"] [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_HEAD) assert row["built_at"] == repo.stored["built_at"] and repo.reads[-1] == (42, DEMO_HEAD) @@ -1057,7 +1057,7 @@ async def _item_unread(org: str, ns: str, pr_number: int) -> dict[str, Any]: monkeypatch.setattr(repo, "gh_pr_head", _item_unread, raising=False) out, notes = await _read(open=True) assert out.source == "precomputed" and out.stored is False and "brief:v2" in out.verdict_causes - assert notes[0].startswith("code.review_brief: pr_item_unread") and notes[-1] == STALE + assert notes[0] == STALE and notes[1].startswith("code.review_brief: pr_item_unread") [(_table, [row])] = repo.inserted assert json.loads(row["payload"])[h.REBUILT_FOR] == rb.PAYLOAD_VERSION repo.stored = row @@ -1135,3 +1135,12 @@ class _Agent: "sections": [], "store": False, } + + +def test_a_stale_brief_names_its_cause_when_the_build_filled_the_note_cap() -> None: + from server.observability import degradations + + built = [f"git_mirror: read_{i}" for i in range(16)] + with degradations.scoped(): + h._stale_served({}, h.REBUILD_FAILED, built) + assert degradations.current()[0] == STALE From 89e73f044ae3d9eb659c893e9d03d923da99aecc Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:17:05 +0000 Subject: [PATCH 17/26] A rebuild stored for another PR marks the stale row; rule 102 names the clock bound Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 13 ++++++----- docs/features/code-index/history-and-prs.md | 3 ++- server/code/app/review_brief.py | 6 ++++- tests/unit/test_code_review_brief_mirror.py | 25 +++++++++++++++++++++ 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index c0a2a29af8c..5ccd7dd7e9f 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1679,11 +1679,14 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline its brief writes the old one again with `rebuilt_for` set to its version, with the replaced row's `version` column plus one, so any build stored later replaces it, and neither build tries that row again until a higher version serves, whatever made the - build fail; a row whose marker could not be written is built again by the next read. - Both builds read the same rows, so a rollback leaves rebuilt briefs as newer rows N-1 - serves as they are ([PR history](../features/code-index/history-and-prs.md)). No gate - holds the rollout. `tests/unit/test_code_review_brief_mirror.py` checks N's side, and - the mixed-version gate does not check this rule. + build fail; a row whose marker could not be written is built again by the next read. A + rebuild's `version` is its host's clock: on a host whose clock runs behind the stale + row's writer by more than the time since that write, the stored rebuild loses to the + row, and reads build again until the clock passes it. Both builds read the same rows, + so a rollback leaves rebuilt briefs as newer rows N-1 serves as they are ([PR + history](../features/code-index/history-and-prs.md)). No gate holds the rollout. + `tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version + gate does not check this rule. ## What checks them diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index d0c52a1d1c7..4eaa6b1d873 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -304,7 +304,8 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the host has no mirror of the repository, its mirror does not hold the merge commit or git cannot read it; a later read builds the brief once a mirror holds the merge; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing or was not stored. +- the build raised, found nothing, was not stored or was stored for another PR the + merge commit names. In the last case `degraded` lists `stale_brief_served (rebuild failed)`, then the build's notes. The stored row records the version that tried and those notes, and a diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index a96dc50d5d5..c1347f2a7ac 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -354,10 +354,14 @@ async def _rebuild( degradations.partial("code.review_brief", "brief_missing", e) fresh = None span_attrs(sp, results=int(fresh is not None)) + built_pr = int((fresh or {}).get("pr_number") or 0) + other = fresh is not None and built_pr != pr_number + if other: # the commit names another PR: the stale row stays as it is, and is marked + degradations.partial("code.review_brief", "rebuilt_for_another_pr", built_pr) notes = degradations.current() or [ "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") ] - if fresh is not None and fresh.get("stored", True): + if fresh is not None and fresh.get("stored", True) and not other: degradations.restore(own) # a stored rebuild keeps its build's notes, as a miss does return fresh, source try: diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index db15cb8075d..f99946d29c8 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -902,6 +902,31 @@ async def _by_sha_noted(git_dir: str, merge_sha: str, **kw: Any) -> Any: assert notes == ["git_mirror: lookup_slow (a test note)"] +@pytest.mark.asyncio +async def test_a_merge_commit_that_names_another_pr_marks_the_stale_row( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A rebuild stored under another PR's key leaves the stale row unreplaced: it is marked, + so the next read builds nothing.""" + repo = demo["repo"] + repo.stored = stale = await _stale_row(demo) + + async def _names_43(git_dir: str, merge_sha: str, **kw: Any) -> Any: + demo["mirror"].append((git_dir, merge_sha)) + return {**DEMO_FACTS, "pr_number": 43} + + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _names_43) + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == [STALE, "code.review_brief: rebuilt_for_another_pr (43)"] + built, marker = (r for _t, [r] in repo.inserted) + assert (built["pr_number"], marker["pr_number"]) == (43, 42) + assert marker["version"] == stale["version"] + 1 + repo.stored = marker + again, _ = await _read() + assert again.source == "precomputed" and len(repo.inserted) == 2 and len(demo["mirror"]) == 1 + + @pytest.mark.asyncio async def test_a_read_by_merge_commit_alone_rebuilds_the_row_at_its_merge_commit( demo: dict[str, Any], From c3fe335fe0c798090023d47807d0ba64bc1784b4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:28:05 +0000 Subject: [PATCH 18/26] A rebuild reads a merged row by its number and commit; another PR's commit is a miss Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 13 +++---- server/code/app/review_brief.py | 30 ++++++++-------- tests/unit/test_code_review_brief_mirror.py | 40 +++++++++++++-------- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 4eaa6b1d873..e6a6acae22a 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -304,16 +304,17 @@ names `code.review_brief: stale_brief_served` with the reason. That happens when - the host has no mirror of the repository, its mirror does not hold the merge commit or git cannot read it; a later read builds the brief once a mirror holds the merge; - an open PR's brief is found by its number on a merged read; -- the build raised, found nothing, was not stored or was stored for another PR the - merge commit names. +- the build raised, found nothing (a merge commit whose subject names another PR + included) or was not stored. In the last case `degraded` lists `stale_brief_served (rebuild failed)`, then the build's notes. The stored row records the version that tried and those notes, and a later read by a build that has this rule, of the same or a lower version, serves it with -the same notes and without a build. That holds whatever the cause, a passing failure on one host (a timed-out read, -a git call that failed) included: the cost stays at one build per stored row and -version, and the old brief answers until a build of a higher version tries again. Only -a row whose marker could not be written is built again by the next read. +the same notes and without a build. That holds whatever the cause, a passing failure on +one host (a timed-out read, a git call that failed) included: the cost stays at one +build per stored row and version, and the old brief answers until a build of a higher +version tries again. Only a row whose marker could not be written is built again by the +next read. A brief stored at a newer version than the serving build's, during a rolling upgrade, is served as it is. diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index c1347f2a7ac..ab37ea2b937 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -323,8 +323,8 @@ async def _rebuild( """Build a stored brief of an older payload version again at `sha`, its row's key (an open PR's head or the merge commit), and store it in its place, at most once per row and version; docs/features/code-index/history-and-prs.md says when the stored one is - served instead. A merged row is built from its own merge commit alone, so the build - lands on the row's key.""" + served instead. A merged row is built from its PR number and its own merge commit, so + the build lands on the row's key.""" from server.code.domain.index.repos import repo_for_namespace pr_number = int(stale.get("pr_number") or 0) @@ -345,7 +345,7 @@ async def _rebuild( org, ns, is_open=is_open, - pr_number=pr_number if is_open else 0, + pr_number=pr_number, sha=sha, store=True, ) @@ -354,14 +354,10 @@ async def _rebuild( degradations.partial("code.review_brief", "brief_missing", e) fresh = None span_attrs(sp, results=int(fresh is not None)) - built_pr = int((fresh or {}).get("pr_number") or 0) - other = fresh is not None and built_pr != pr_number - if other: # the commit names another PR: the stale row stays as it is, and is marked - degradations.partial("code.review_brief", "rebuilt_for_another_pr", built_pr) notes = degradations.current() or [ "code.review_brief: " + ("brief_unstored" if fresh is not None else "brief_missing") ] - if fresh is not None and fresh.get("stored", True) and not other: + if fresh is not None and fresh.get("stored", True): degradations.restore(own) # a stored rebuild keeps its build's notes, as a miss does return fresh, source try: @@ -669,21 +665,25 @@ async def _build_on_miss( async def _mirror_facts( repo: CodeRepo, org: str, ns: str, cfg: Any, *, pr_number: int, merge_sha: str ) -> dict[str, Any] | None: - """The merge commit the mirror names for the PR (or the PR the merge - commit names); None on a miss, a merge the indexed head does not contain (the - mirror's branch runs ahead of an index of an older commit), a git failure (a miss, - logged) or no mirror here.""" + """The facts of the named merge commit, or of the merge the mirror names for the PR + when no commit is named; None on a miss, a commit whose subject names another PR than + the one asked for, a merge the indexed head does not contain (the mirror's branch runs + ahead of an index of an older commit), a git failure (a miss, logged) or no mirror + here.""" git_dir, gap = await history_dir(cfg) if gap: logger.info("code.review_brief: mirror lookup for PR %s skipped: %s", pr_number, gap) return None try: - if pr_number: + if merge_sha: # a named commit is the exact key; a PR number is looked up by subject + facts = await review_brief_sources.mirror_commit_facts(git_dir, merge_sha) + else: facts = await review_brief_sources.mirror_merge_facts( git_dir, cfg.git_branch, pr_number ) - else: - facts = await review_brief_sources.mirror_commit_facts(git_dir, merge_sha) + if facts and pr_number and int(facts.get("pr_number") or 0) != pr_number: + logger.info("code.review_brief: %s names another PR than %s", merge_sha[:12], pr_number) + return None if facts and not await history_bound.holds(repo, org, ns, git_dir, str(facts["merge_sha"])): return None return facts diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index f99946d29c8..57c62fe191c 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -906,8 +906,8 @@ async def _by_sha_noted(git_dir: str, merge_sha: str, **kw: Any) -> Any: async def test_a_merge_commit_that_names_another_pr_marks_the_stale_row( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: - """A rebuild stored under another PR's key leaves the stale row unreplaced: it is marked, - so the next read builds nothing.""" + """A merge commit whose subject names another PR is no build of this row: nothing is + built, the stale row is marked, and the next read builds nothing.""" repo = demo["repo"] repo.stored = stale = await _stale_row(demo) @@ -918,13 +918,32 @@ async def _names_43(git_dir: str, merge_sha: str, **kw: Any) -> Any: monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _names_43) out, notes = await _read() assert out.source == "precomputed" and "brief:v2" in out.verdict_causes - assert notes == [STALE, "code.review_brief: rebuilt_for_another_pr (43)"] - built, marker = (r for _t, [r] in repo.inserted) - assert (built["pr_number"], marker["pr_number"]) == (43, 42) + assert notes == [STALE, "code.review_brief: brief_missing"] + [(_table, [marker])] = repo.inserted + assert (marker["pr_number"], marker["merge_sha"]) == (42, DEMO_SHA) assert marker["version"] == stale["version"] + 1 repo.stored = marker again, _ = await _read() - assert again.source == "precomputed" and len(repo.inserted) == 2 and len(demo["mirror"]) == 1 + assert again.source == "precomputed" and len(repo.inserted) == 1 and len(demo["mirror"]) == 1 + + +@pytest.mark.asyncio +async def test_a_stale_brief_names_its_cause_when_the_build_filled_the_note_cap( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + from server.observability import degradations + + demo["repo"].stored = await _stale_row(demo) + + async def _noisy_miss(git_dir: str, merge_sha: str, **kw: Any) -> Any: + for i in range(12): + degradations.partial("git_mirror", f"read_{i}", "a test note") + return None + + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _noisy_miss) + out, notes = await _read() + assert out.source == "precomputed" and notes[0] == STALE + assert notes[1] == "git_mirror: read_0 (a test note)" @pytest.mark.asyncio @@ -1160,12 +1179,3 @@ class _Agent: "sections": [], "store": False, } - - -def test_a_stale_brief_names_its_cause_when_the_build_filled_the_note_cap() -> None: - from server.observability import degradations - - built = [f"git_mirror: read_{i}" for i in range(16)] - with degradations.scoped(): - h._stale_served({}, h.REBUILD_FAILED, built) - assert degradations.current()[0] == STALE From 1c3f133c9bc94e7df49a863c1f7611a4fe3146d6 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:39:42 +0000 Subject: [PATCH 19/26] A brief built from a named merge commit discloses it; the ledger read is pinned Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/reference/operations/code.md | 2 +- server/code/api/models_review.py | 6 +++--- server/code/app/index/review_brief_sources.py | 4 +++- server/code/app/review_brief.py | 2 ++ tests/unit/test_code_review_brief_mirror.py | 5 +++++ 5 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index 20f5c7a6d1e..fd4a02f8c35 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1461,7 +1461,7 @@ A merged PR's review brief: the point read of what the ingest built at merge — | `source` | `Literal['precomputed', 'built', 'built_from_mirror', 'missing']` | precomputed (the ingest built it) \| built (this call built it from the ledger's row) \| built_from_mirror (no ledger row; the merge commit, title and files came from the mirror's first-parent chain and the reviewers from the tracker record)… | | `ledger` | `Literal['', 'present', 'absent']` | what the ledger said: present (this build read its row) \| absent (this or the stored build came from the mirror because the ledger had no row) \| "" (not consulted: the ingest built the row) | | `stored` | `bool` | True when this call built the brief and stored it | -| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit, files, title (qa \| mirror), qa status, reviewers, author, has_test, is_backport_pr; {} for a ledger- or ingest-built brief | +| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent \| named_commit), files, title (qa \| mirror), qa status, reviewers, author, has_test, is_backport_pr; {} for a ledger- or ingest-built brief | | `overlay` | `bool` | On the wire only for `open: true`. | | `overlay_head_sha` | `str` | The open PR's head the brief was read or built at; '' when the mirror lacks it. | | `overlay_added` | `int` | Functions the open PR adds (the symbols section's `via: added` rows). | diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index 72bcbf2b8ea..93863b0527e 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -150,9 +150,9 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: ledger: Literal["", "present", "absent"] = "" # True when this call built the brief and stored it stored: bool = False - # A mirror-built brief's disclosure — source, ledger, merge_commit, files, title (qa - # | mirror), qa status, reviewers, author, has_test, is_backport_pr; {} for a - # ledger- or ingest-built brief + # A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent + # | named_commit), files, title (qa | mirror), qa status, reviewers, author, has_test, + # is_backport_pr; {} for a ledger- or ingest-built brief provenance: dict[str, Any] = Field(default_factory=dict) # On the wire only for `open: true`. `overlay` true = the brief is of the PR's head # (`overlay_head_sha`) against its merge-base (`overlay_base_sha` in the payload's diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 12216b6269b..0aed7e3af8f 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -185,7 +185,9 @@ async def mirror_provenance(org: str, ns: str, facts: dict[str, Any]) -> dict[st return { "source": BUILT_FROM_MIRROR, "ledger": LEDGER_ABSENT, - "merge_commit": "mirror_first_parent", + # a commit the read named is taken as named; a PR's number is placed on the + # mirror's first-parent chain + "merge_commit": "named_commit" if facts.get("named_commit") else "mirror_first_parent", "files": "mirror_diff", "title": title_from, "tracker": tracker_status, diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index ab37ea2b937..6cb878bfd67 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -677,6 +677,8 @@ async def _mirror_facts( try: if merge_sha: # a named commit is the exact key; a PR number is looked up by subject facts = await review_brief_sources.mirror_commit_facts(git_dir, merge_sha) + if facts: + facts["named_commit"] = True # disclosed: not placed on the first-parent chain else: facts = await review_brief_sources.mirror_merge_facts( git_dir, cfg.git_branch, pr_number diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 57c62fe191c..5cc86c8c6df 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -688,13 +688,17 @@ async def test_a_ledger_backed_brief_is_rebuilt_from_its_ledger_row( repo = demo["repo"] repo.stored = await _stale_row(demo) + asked: list[dict[str, Any]] = [] + async def _ledger(org: str, ns: str, **kw: Any) -> dict[str, Any]: + asked.append(kw) return {**DEMO_FACTS, "merge_sha": DEMO_SHA.encode("ascii")} monkeypatch.setattr(repo, "pr_merge_facts", _ledger) out, notes = await _read() assert out.source == "built" and out.ledger == "present" and out.stored is True assert notes == [] and demo["mirror"] == [] + assert asked[0] == {"pr_number": 42, "merge_sha": DEMO_SHA} # the row's own key assert json.loads(repo.inserted[0][1][0]["payload"])["v"] == rb.PAYLOAD_VERSION @@ -960,6 +964,7 @@ async def test_a_read_by_merge_commit_alone_rebuilds_the_row_at_its_merge_commit assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert repo.reads[-1] == (0, DEMO_SHA) assert demo["mirror"] == [("/nonexistent/greeter.git", DEMO_SHA)] + assert out.provenance["merge_commit"] == "named_commit" # not placed by first parent @pytest.mark.asyncio From 96635ecfbb19b1e9ba2df2f6358e57ee89b41938 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:13:01 +0000 Subject: [PATCH 20/26] Mirror-built wording names the commit a read or row names; two more tests Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/reference/operations/code.md | 4 ++-- server/code/api/models_review.py | 12 +++++++----- server/code/app/index/review_brief_sources.py | 4 ++-- server/code/app/review_brief.py | 17 +++++++++-------- tests/unit/test_code_review_brief_mirror.py | 16 ++++++++++++++++ 5 files changed, 36 insertions(+), 17 deletions(-) diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index fd4a02f8c35..ed9a20887b8 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1458,10 +1458,10 @@ A merged PR's review brief: the point read of what the ingest built at merge — | `verdict_causes` | `list[str]` | The gaps (`uncovered_symbol`, `symbol_with_regressions`, `randomized_setting`, `rationale_check`), or each check that did not run in full, decide or rest on more than a co-change, as `
:` (`tests:not_claimed:3`… | | `pr_number` | `int` | The PR the brief is of (from the stored brief when the request named only `merge_sha`). | | `merge_sha` | `str` | The PR's merge commit; '' on an open brief or when no brief was found. | -| `source` | `Literal['precomputed', 'built', 'built_from_mirror', 'missing']` | precomputed (the ingest built it) \| built (this call built it from the ledger's row) \| built_from_mirror (no ledger row; the merge commit, title and files came from the mirror's first-parent chain and the reviewers from the tracker record)… | +| `source` | `Literal['precomputed', 'built', 'built_from_mirror', 'missing']` | precomputed (the ingest built it) \| built (this call built it from the ledger's row) \| built_from_mirror (no ledger row; the title and files came from the mirror at the named merge commit, else at the first-parent merge for the PR number… | | `ledger` | `Literal['', 'present', 'absent']` | what the ledger said: present (this build read its row) \| absent (this or the stored build came from the mirror because the ledger had no row) \| "" (not consulted: the ingest built the row) | | `stored` | `bool` | True when this call built the brief and stored it | -| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent \| named_commit), files, title (qa \| mirror), qa status, reviewers, author, has_test, is_backport_pr; {} for a ledger- or ingest-built brief | +| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent: placed by PR number on the first-parent chain \| named_commit: the commit the read or the stored row named), files, title (qa \| mirror), qa status… | | `overlay` | `bool` | On the wire only for `open: true`. | | `overlay_head_sha` | `str` | The open PR's head the brief was read or built at; '' when the mirror lacks it. | | `overlay_added` | `int` | Functions the open PR adds (the symbols section's `via: added` rows). | diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index 93863b0527e..f99f4f22174 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -139,8 +139,9 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: # The PR's merge commit; '' on an open brief or when no brief was found. merge_sha: str = "" # precomputed (the ingest built it) | built (this call built it from the ledger's - # row) | built_from_mirror (no ledger row; the merge commit, title and files came - # from the mirror's first-parent chain and the reviewers from the tracker record) | + # row) | built_from_mirror (no ledger row; the title and files came from the mirror + # at the named merge commit, else at the first-parent merge for the PR number, and + # the reviewers from the tracker record) | # missing (neither the ledger nor the mirror names the PR, or no mirror to build # from) source: Literal["precomputed", "built", "built_from_mirror", "missing"] = "missing" @@ -150,9 +151,10 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: ledger: Literal["", "present", "absent"] = "" # True when this call built the brief and stored it stored: bool = False - # A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent - # | named_commit), files, title (qa | mirror), qa status, reviewers, author, has_test, - # is_backport_pr; {} for a ledger- or ingest-built brief + # A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent: + # placed by PR number on the first-parent chain | named_commit: the commit the read or + # the stored row named), files, title (qa | mirror), qa status, reviewers, author, + # has_test, is_backport_pr; {} for a ledger- or ingest-built brief provenance: dict[str, Any] = Field(default_factory=dict) # On the wire only for `open: true`. `overlay` true = the brief is of the PR's head # (`overlay_head_sha`) against its merge-base (`overlay_base_sha` in the payload's diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 0aed7e3af8f..1e5f2b8b366 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -185,8 +185,8 @@ async def mirror_provenance(org: str, ns: str, facts: dict[str, Any]) -> dict[st return { "source": BUILT_FROM_MIRROR, "ledger": LEDGER_ABSENT, - # a commit the read named is taken as named; a PR's number is placed on the - # mirror's first-parent chain + # a commit the read or the stored row names is taken as named; a PR's number is + # placed on the mirror's first-parent chain "merge_commit": "named_commit" if facts.get("named_commit") else "mirror_first_parent", "files": "mirror_diff", "title": title_from, diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 6cb878bfd67..eb485bc6ace 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -1,9 +1,9 @@ -"""code.review_brief handler: a point read of the brief the ingest step built for a merged -PR; on a miss, or for a brief stored at an older payload version (`_rebuild`), build it -from the ledger and the mirror, store it, serve it. A PR the ledger never saw is built from -the merge commit the mirror's first-parent chain names for it (`source: built_from_mirror`, -`ledger: absent`), and the on-demand store is the caller's `store` flag — never for a -measurement consumer. +"""code.review_brief handler: a point read of the brief the ingest step built for a merged PR; +on a miss, or for a brief stored at an older payload version (`_rebuild`), build it from the +ledger and the mirror, store it, serve it. A PR the ledger never saw is built from the merge +commit the read or the stored row names, else the one the mirror's first-parent chain names +for the PR number (`source: built_from_mirror`, `ledger: absent`), and the on-demand store +is the caller's `store` flag — never for a measurement consumer. A merged PR is briefed only when the namespace's indexed head contains it: the ledger and stored-brief reads carry the head bound, and a merge commit the mirror names is asked of @@ -620,8 +620,9 @@ async def _build_on_miss( """The brief for a PR the ingest never briefed (older than the feature, or merged while it was off): the ledger's title / file list / merge commit and the mirror's diff, through the same builder. Without a - ledger row (the PR predates the backfill horizon) the merge commit, title and files come - from the mirror's first-parent chain and the reviewers from the tracker record. + ledger row (the PR predates the backfill horizon) the title and files come from the + mirror at the named merge commit, else at the merge its first-parent chain names for + the PR number, and the reviewers from the tracker record. (None, "missing") when neither names the PR inside the indexed head, or the namespace has no mirror.""" from server.code.domain.index.repos import repo_for_namespace diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 5cc86c8c6df..70e5d083d47 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -671,6 +671,7 @@ async def test_a_brief_stored_at_an_older_version_is_rebuilt_once_and_stored_in_ assert out.source == "built_from_mirror" and out.stored is True and notes == [] assert not any(c.startswith("brief:") for c in out.verdict_causes) assert demo["mirror"] == [("/nonexistent/greeter.git", DEMO_SHA)] + assert out.provenance["merge_commit"] == "named_commit" # the stored row's commit [(_table, [row])] = repo.inserted assert (row["pr_number"], row["merge_sha"]) == (42, DEMO_SHA) assert json.loads(row["payload"])["v"] == rb.PAYLOAD_VERSION @@ -931,6 +932,21 @@ async def _names_43(git_dir: str, merge_sha: str, **kw: Any) -> Any: assert again.source == "precomputed" and len(repo.inserted) == 1 and len(demo["mirror"]) == 1 +@pytest.mark.asyncio +async def test_a_miss_that_names_a_commit_of_another_pr_is_missing( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A read of PR 42 at a merge commit whose subject names PR 43 builds nothing.""" + repo = demo["repo"] + + async def _names_43(git_dir: str, merge_sha: str, **kw: Any) -> Any: + return {**DEMO_FACTS, "pr_number": 43} + + monkeypatch.setattr(review_brief_sources, "mirror_commit_facts", _names_43) + out, _ = await _read(merge_sha=DEMO_SHA) + assert out.source == "missing" and repo.inserted == [] + + @pytest.mark.asyncio async def test_a_stale_brief_names_its_cause_when_the_build_filled_the_note_cap( demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch From cc473a663272b6ea3126949a1003789c570cf596 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:24:48 +0000 Subject: [PATCH 21/26] Mirror-built field comments name the tracker title and status Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/reference/operations/code.md | 4 ++-- server/code/api/models_review.py | 15 ++++++++------- server/code/app/review_brief.py | 7 ++++--- tests/unit/test_code_review_brief_mirror.py | 4 ++-- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index 7a45a9977b8..b76bbb51633 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1458,10 +1458,10 @@ A merged PR's review brief: the point read of what the ingest built at merge — | `verdict_causes` | `list[str]` | The gaps (`uncovered_symbol`, `symbol_with_regressions`, `randomized_setting`, `rationale_check`), or each check that did not run in full, decide or rest on more than a co-change, as `
:` (`tests:not_claimed:3`… | | `pr_number` | `int` | The PR the brief is of (from the stored brief when the request named only `merge_sha`). | | `merge_sha` | `str` | The PR's merge commit; '' on an open brief or when no brief was found. | -| `source` | `Literal['precomputed', 'built', 'built_from_mirror', 'missing']` | precomputed (the ingest built it) \| built (this call built it from the ledger's row) \| built_from_mirror (no ledger row; the title and files came from the mirror at the named merge commit, else at the first-parent merge for the PR number… | +| `source` | `Literal['precomputed', 'built', 'built_from_mirror', 'missing']` | precomputed (the ingest built it) \| built (this call built it from the ledger's row) \| built_from_mirror (no ledger row; the files, and the title when the tracker record has none, came from the mirror at the named merge commit, else at the… | | `ledger` | `Literal['', 'present', 'absent']` | what the ledger said: present (this build read its row) \| absent (this or the stored build came from the mirror because the ledger had no row) \| "" (not consulted: the ingest built the row) | | `stored` | `bool` | True when this call built the brief and stored it | -| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent: placed by PR number on the first-parent chain \| named_commit: the commit the read or the stored row named), files, title (qa \| mirror), qa status… | +| `provenance` | `dict[str, Any]` | A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent: placed by PR number on the first-parent chain \| named_commit: the commit the read or the stored row named), files, title (tracker \| mirror), tracker… | | `overlay` | `bool` | On the wire only for `open: true`. | | `overlay_head_sha` | `str` | The open PR's head the brief was read or built at; '' when the mirror lacks it. | | `overlay_added` | `int` | Functions the open PR adds (the symbols section's `via: added` rows). | diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index f99f4f22174..3188c7444d8 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -139,9 +139,9 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: # The PR's merge commit; '' on an open brief or when no brief was found. merge_sha: str = "" # precomputed (the ingest built it) | built (this call built it from the ledger's - # row) | built_from_mirror (no ledger row; the title and files came from the mirror - # at the named merge commit, else at the first-parent merge for the PR number, and - # the reviewers from the tracker record) | + # row) | built_from_mirror (no ledger row; the files, and the title when the tracker + # record has none, came from the mirror at the named merge commit, else at the + # first-parent merge for the PR number, and the reviewers from the tracker record) | # missing (neither the ledger nor the mirror names the PR, or no mirror to build # from) source: Literal["precomputed", "built", "built_from_mirror", "missing"] = "missing" @@ -151,10 +151,11 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: ledger: Literal["", "present", "absent"] = "" # True when this call built the brief and stored it stored: bool = False - # A mirror-built brief's disclosure — source, ledger, merge_commit (mirror_first_parent: - # placed by PR number on the first-parent chain | named_commit: the commit the read or - # the stored row named), files, title (qa | mirror), qa status, reviewers, author, - # has_test, is_backport_pr; {} for a ledger- or ingest-built brief + # A mirror-built brief's disclosure — source, ledger, merge_commit + # (mirror_first_parent: placed by PR number on the first-parent chain | named_commit: + # the commit the read or the stored row named), files, title (tracker | mirror), + # tracker status, reviewers, author, has_test, is_backport_pr; {} for a ledger- or + # ingest-built brief provenance: dict[str, Any] = Field(default_factory=dict) # On the wire only for `open: true`. `overlay` true = the brief is of the PR's head # (`overlay_head_sha`) against its merge-base (`overlay_base_sha` in the payload's diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index eb485bc6ace..d5c4029a92f 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -620,9 +620,10 @@ async def _build_on_miss( """The brief for a PR the ingest never briefed (older than the feature, or merged while it was off): the ledger's title / file list / merge commit and the mirror's diff, through the same builder. Without a - ledger row (the PR predates the backfill horizon) the title and files come from the - mirror at the named merge commit, else at the merge its first-parent chain names for - the PR number, and the reviewers from the tracker record. + ledger row (the PR predates the backfill horizon) the files, and the title when the + tracker record has none, come from the mirror at the named merge commit, else at the + merge its first-parent chain names for the PR number, and the reviewers from the + tracker record. (None, "missing") when neither names the PR inside the indexed head, or the namespace has no mirror.""" from server.code.domain.index.repos import repo_for_namespace diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 70e5d083d47..4c6fa55c408 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -1,6 +1,6 @@ """A review brief for a PR the ledger never saw. The merge -commit comes from the mirror's first-parent chain (one bounded grep per PR, -cached), the title from the tracker record or the merge commit, the files from +commit is the one the read or the stored row names, else the mirror's first-parent +merge for the PR number (one bounded grep per PR, cached), the title from the tracker record or the merge commit, the files from the merge's diff; the brief says `source: built_from_mirror`, `ledger: absent`; the on-demand store is the caller's `store` flag and never a measurement consumer's. A ledger-backed build is byte-identical to the base brief.""" From bd5f2d377308261ec77f623f7d7406d58afe8eca Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:33:30 +0000 Subject: [PATCH 22/26] The other-PR check sits with the named-commit lookup; tracker wording Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/index/review_brief_sources.py | 8 ++++---- server/code/app/review_brief.py | 8 +++++--- tests/unit/test_code_review_brief_mirror.py | 12 ++++++------ 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 1e5f2b8b366..60279455f09 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -168,11 +168,11 @@ async def tracker_pr_facts(org: str, ns: str, pr_number: int) -> tuple[str, dict async def mirror_provenance(org: str, ns: str, facts: dict[str, Any]) -> dict[str, Any]: """The disclosure a mirror-built brief carries in its payload: where the - merge commit, files and title came from, the reviewers when the QA - record has them. The QA title, when there is one, replaces the merge + merge commit, files and title came from, the reviewers when the tracker + record has them. The tracker title, when there is one, replaces the merge commit's in `facts` (the body's first line is the title as the author - typed it at merge time; QA carries the PR's current one). QA failing is - a fact on the record, never a failed brief.""" + typed it at merge time; the tracker carries the PR's current one). The + tracker failing is a fact on the record, never a failed brief.""" try: tracker_status, tracker_row = await tracker_pr_facts(org, ns, int(facts["pr_number"])) except Exception as e: # noqa: BLE001 — the brief stands without the reviewers, unstored diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index d5c4029a92f..fcbaba616b2 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -679,15 +679,17 @@ async def _mirror_facts( try: if merge_sha: # a named commit is the exact key; a PR number is looked up by subject facts = await review_brief_sources.mirror_commit_facts(git_dir, merge_sha) + if facts and pr_number and int(facts["pr_number"]) != pr_number: + logger.info( + "code.review_brief: %s names another PR than %s", merge_sha[:12], pr_number + ) + return None if facts: facts["named_commit"] = True # disclosed: not placed on the first-parent chain else: facts = await review_brief_sources.mirror_merge_facts( git_dir, cfg.git_branch, pr_number ) - if facts and pr_number and int(facts.get("pr_number") or 0) != pr_number: - logger.info("code.review_brief: %s names another PR than %s", merge_sha[:12], pr_number) - return None if facts and not await history_bound.holds(repo, org, ns, git_dir, str(facts["merge_sha"])): return None return facts diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 4c6fa55c408..13a53743d71 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -1,9 +1,9 @@ -"""A review brief for a PR the ledger never saw. The merge -commit is the one the read or the stored row names, else the mirror's first-parent -merge for the PR number (one bounded grep per PR, cached), the title from the tracker record or the merge commit, the files from -the merge's diff; the brief says `source: built_from_mirror`, `ledger: -absent`; the on-demand store is the caller's `store` flag and never a -measurement consumer's. A ledger-backed build is byte-identical to the base brief.""" +"""A review brief for a PR the ledger never saw. The merge commit is the one the read or +the stored row names, else the mirror's first-parent merge for the PR number (one +bounded grep per PR, cached), the title from the tracker record or the merge commit, the +files from the merge's diff; the brief says `source: built_from_mirror`, `ledger: +absent`; the on-demand store is the caller's `store` flag and never a measurement +consumer's. A ledger-backed build is byte-identical to the base brief.""" from __future__ import annotations From 09c4219c5d633a5a59aaea90a5463a84c98401eb Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:46:44 +0000 Subject: [PATCH 23/26] The marker reads the row's build time and version as stored; mirror_commit_facts docstring Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/index/review_brief_sources.py | 6 +++--- server/code/app/review_brief.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 0bd267e122a..6b1949eaf24 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -117,9 +117,9 @@ async def mirror_commit_facts( *, timeout_s: float = 20.0, ) -> dict[str, Any] | None: - """The same facts for a merge commit named by sha (a `merge_sha`-only - read with no ledger row): None when the mirror holds no such commit or its - subject names no PR. A mirror git cannot read raises.""" + """The same facts for a merge commit named by sha (a read or a stored row that + names the commit, when the ledger has no row): None when the mirror holds no such + commit or its subject names no PR. A mirror git cannot read raises.""" from server.code.app.index import gitrepo if not await gitrepo.holds_commit(git_dir, sha, timeout_s=timeout_s): diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index fcbaba616b2..cbe46abfa52 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -378,8 +378,8 @@ async def _rebuild( # merge commit), and its version plus one, below any build's, which is stamped with # the time it is stored: a rebuild another replica stores after this read wins. marked["merge_sha"] = sha_text(row.get("merge_sha")) - marked["built_at"] = row.get("built_at") or marked["built_at"] - marked["version"] = int(row.get("version") or 0) + 1 + marked["built_at"] = row["built_at"] + marked["version"] = int(row["version"]) + 1 await repo.insert_rows("code_review_briefs", [marked]) except Exception as e: # noqa: BLE001 — unmarked, the next read builds it again logger.warning("code.review_brief: rebuild of PR %s not recorded: %s", pr_number, e) From b3ee06916a988f0a3a8beac4b63c41419733bd8c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:56:23 +0000 Subject: [PATCH 24/26] The marker reads merge_sha as stored; the re-read test covers a same-version marker Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/review_brief.py | 2 +- tests/unit/test_code_review_brief_mirror.py | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index cbe46abfa52..99293d81e7f 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -377,7 +377,7 @@ async def _rebuild( # The row it replaces keeps its key and build time (an open PR's payload names no # merge commit), and its version plus one, below any build's, which is stamped with # the time it is stored: a rebuild another replica stores after this read wins. - marked["merge_sha"] = sha_text(row.get("merge_sha")) + marked["merge_sha"] = sha_text(row["merge_sha"]) marked["built_at"] = row["built_at"] marked["version"] = int(row["version"]) + 1 await repo.insert_rows("code_review_briefs", [marked]) diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 13a53743d71..1ff2aa8d1d5 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -826,10 +826,20 @@ async def test_a_failed_rebuild_writes_nothing_over_a_newer_or_a_deleted_row( stale = await _stale_row(demo) fresh_payload = {**json.loads(stale["payload"]), "v": rb.PAYLOAD_VERSION} fresh = {**stale, "payload": json.dumps(fresh_payload)} - newer = {h.REBUILT_FOR: rb.PAYLOAD_VERSION + 1, h.REBUILD_NOTES: ["git_mirror: x"]} - marked = {**stale, "payload": json.dumps({**json.loads(stale["payload"]), **newer})} + old = json.loads(stale["payload"]) + + def _marked(version: int) -> dict[str, Any]: + mark = {h.REBUILT_FOR: version, h.REBUILD_NOTES: ["git_mirror: x"]} + return {**stale, "payload": json.dumps({**old, **mark})} + built = _diff_fails(monkeypatch) - for after, served in ((fresh, "fresh"), (marked, "marked"), (None, "stale")): + cases = ( + (fresh, "fresh"), + (_marked(rb.PAYLOAD_VERSION), "marked"), # by a build of this version + (_marked(rb.PAYLOAD_VERSION + 1), "marked"), # by a newer build + (None, "stale"), + ) + for after, served in cases: reads = iter([stale, after]) async def _point_read( From 22342e7f67b80fd77dee9a91ca56fc1626ecca09 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 10:04:39 +0000 Subject: [PATCH 25/26] The open miss test stubs only the head; _rebuild's docstring drops a repeat Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/review_brief.py | 3 +-- tests/unit/test_code_review_brief_mirror.py | 10 +++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 99293d81e7f..e645d70881a 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -323,8 +323,7 @@ async def _rebuild( """Build a stored brief of an older payload version again at `sha`, its row's key (an open PR's head or the merge commit), and store it in its place, at most once per row and version; docs/features/code-index/history-and-prs.md says when the stored one is - served instead. A merged row is built from its PR number and its own merge commit, so - the build lands on the row's key.""" + served instead.""" from server.code.domain.index.repos import repo_for_namespace pr_number = int(stale.get("pr_number") or 0) diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 1ff2aa8d1d5..e7a6d933624 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -1019,12 +1019,17 @@ async def _open_stale_row(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) payload = {**json.loads(stale["payload"]), "overlay": True, "merge_sha": ""} payload["head_sha"] = DEMO_HEAD demo["repo"].stored = {**stale, "merge_sha": DEMO_HEAD, "payload": json.dumps(payload)} + _open_at_head(monkeypatch) + return payload + + +def _open_at_head(monkeypatch: pytest.MonkeyPatch) -> None: + """The open PR's head as the tracker names it.""" async def _head(repo: Any, org: str, ns: str, pr_number: int) -> tuple[str, str]: return DEMO_HEAD, "" monkeypatch.setattr(h, "_open_head", _head) - return payload @pytest.mark.asyncio @@ -1089,8 +1094,7 @@ async def test_an_open_build_without_its_items_row_answers_unstored( """An open PR with no stored brief whose items row cannot be read is built and served, and answers `stored: false`: nothing is kept.""" repo = demo["repo"] - await _open_stale_row(demo, monkeypatch) - repo.stored = None + _open_at_head(monkeypatch) async def _item_unread(org: str, ns: str, pr_number: int) -> dict[str, Any]: raise TimeoutError("items read timed out") From 65626a56880751459196b1e0cc13c70901740159 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 10:08:45 +0000 Subject: [PATCH 26/26] Open-row test helpers: the mirror names the head; the stale row is typed Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- tests/unit/test_code_review_brief_mirror.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index e7a6d933624..6a8d8b7be1d 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -1012,7 +1012,7 @@ async def test_an_older_build_reads_a_newer_builds_marker_without_building( DEMO_HEAD = "c3" * 20 -async def _open_stale_row(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> Any: +async def _open_stale_row(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: """An open PR's brief of payload version 2, stored under (PR, head): its payload names no merge commit.""" stale = await _stale_row(demo) @@ -1024,7 +1024,7 @@ async def _open_stale_row(demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch) def _open_at_head(monkeypatch: pytest.MonkeyPatch) -> None: - """The open PR's head as the tracker names it.""" + """The open PR's head as the mirror's refs/pull/N/head names it.""" async def _head(repo: Any, org: str, ns: str, pr_number: int) -> tuple[str, str]: return DEMO_HEAD, ""