diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ab30a1ad78..2ea5d856b5 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1690,6 +1690,26 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline migration's file name and the read of a row N-1 wrote, and the mixed-version gate does not check this rule. +103. **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 (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, 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. 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 `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 899a3de464..9c4fae5ab3 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -265,7 +265,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, 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, @@ -311,9 +312,35 @@ 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: one of an older payload version (`v` in the payload) records no cap or failed -read, so its verdict is `gaps` or `unsettled`. +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. +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` +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, 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 (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. + +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/docs/reference/operations/code.md b/docs/reference/operations/code.md index fcff916b3b..b76bbb5163 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 | @@ -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 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, 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 (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 eb56c773ad..3188c7444d 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -64,11 +64,12 @@ 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 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.""" + 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.""" # 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. @@ -98,8 +99,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, @@ -137,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 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" @@ -148,9 +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, 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/index/review_brief.py b/server/code/app/index/review_brief.py index dee741e831..ef07616d5e 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 read of a brief stored at a lower version +# 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 103). +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/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 12216b6269..6b1949eaf2 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): @@ -168,15 +168,15 @@ 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 - logger.info("review_brief: qa facts for PR %s failed: %s", facts.get("pr_number"), e) + logger.info("review_brief: tracker facts for PR %s failed: %s", facts.get("pr_number"), e) degradations.partial("code.review_brief", "reviewers_unread", e) tracker_status, tracker_row = FAILED, {} title_from = "tracker" if tracker_row.get("title") else "mirror" @@ -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 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, "tracker": tracker_status, diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 6b67757091..e645d70881 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -1,8 +1,9 @@ -"""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 -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 @@ -239,7 +240,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: @@ -263,34 +265,147 @@ 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 + + if payload is not None and int(payload.get("v") or 0) < rb.PAYLOAD_VERSION: + 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") + 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) if payload is not None: 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( + 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 the notes of why its brief was not stored. +REBUILT_FOR = "rebuilt_for" +REBUILD_NOTES = "rebuild_notes" +REBUILD_FAILED = "rebuild failed" + + +async def _rebuild( + repo: CodeRepo, + org: str, + ns: str, + stale: dict[str, Any], + sha: str, + *, + is_open: bool, + store: 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.""" + 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, REBUILD_FAILED, stale.get(REBUILD_NOTES)) + if not store: + return _stale_served(stale, "not stored by this read") + git_dir = await present_dir(repo_for_namespace(org, ns)) + if not git_dir: + return _stale_served(stale, "no mirror on this host") + 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() as own: + try: + fresh, source = await _build_at( repo, org, ns, + is_open=is_open, pr_number=pr_number, - merge_sha=merge_sha, - store=store, + sha=sha, + store=True, ) - span_attrs(sp, results=int(payload is not None)) - return payload, source + 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 = None + span_attrs(sp, results=int(fresh is not None)) + 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: + 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_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 + # the time it is stored: a rebuild another replica stores after this read wins. + 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]) + 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, REBUILD_FAILED, notes) + + +async def _merge_gap(git_dir: str, sha: str) -> str: + """Why this host's mirror cannot build at merge commit `sha`; "" when it holds it.""" + from server.code.app.index import gitrepo + + try: + held = await gitrepo.holds_commit(git_dir, sha) + except (gitrepo.GitError, OSError) as e: # git unreadable or unstarted: the stored brief + logger.info("code.review_brief: mirror %s unread for %s: %s", git_dir, sha[:12], e) + return "mirror unreadable" + return "" if held else "merge not on this host's mirror" + + +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 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" async def _stored_inside_head(repo: CodeRepo, org: str, ns: str, payload: dict[str, Any]) -> bool: @@ -467,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, @@ -483,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) @@ -501,8 +619,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 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 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 @@ -546,21 +666,29 @@ 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) + 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 ) - else: - facts = await review_brief_sources.mirror_commit_facts(git_dir, merge_sha) if facts and not await history_bound.holds(repo, org, ns, git_dir, str(facts["merge_sha"])): return None return facts diff --git a/server/code/store/index/reviews.py b/server/code/store/index/reviews.py index e64e1feba7..0175d02c04 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/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 165c9cba66..5067e2482b 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1648,8 +1648,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 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 (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 " diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 11f7d92426..8098a0773c 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 @@ -521,7 +522,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 ? @@ -607,7 +607,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 @@ -909,7 +908,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 @@ -1695,6 +1693,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 @@ -2256,6 +2255,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 f0fb156b95..6a8d8b7be1 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -1,13 +1,14 @@ -"""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 -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 import asyncio +import json import subprocess from pathlib import Path from typing import Any @@ -544,6 +545,617 @@ async def _no_mirror_here(cfg: Any) -> str: assert kept.source == "precomputed" +# ---- 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"} + + +@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 + + 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 _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" + 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(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 + + +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")) + 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)} + + +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=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( + demo: dict[str, Any], +) -> None: + repo = demo["repo"] + repo.stored = await _stale_row(demo) + stale, _ = await _read(store=False) + 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 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 + # 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 +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) + + 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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("consumer", ["reviewer", "eval-b12"]) +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.""" + 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" 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 == [] + + +@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 "" + + 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) + + async def _unstarted(git_dir: str, sha: str, **kw: Any) -> bool: + raise OSError(24, "Too many open files") + + for holds, cause in ( + (_not_fetched, "merge not on this host's mirror"), + (_unreadable, "mirror unreadable"), + (_unstarted, "mirror 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 == [f"code.review_brief: stale_brief_served ({cause})"] + 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.""" + 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)", "git_mirror: drift_unread (RuntimeError)"] + + +@pytest.mark.asyncio +async def test_a_rebuild_that_is_not_stored_is_tried_once_per_version( + 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.""" + repo = demo["repo"] + repo.stored = stale = await _stale_row(demo) + built = _diff_fails(monkeypatch) + out, notes = await _read() + assert out.source == "precomputed" and "brief:v2" in out.verdict_causes + assert notes == [STALE, *built] + 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_NOTES: built, + } + # 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 + assert notes == [STALE, *built] + assert len(demo["mirror"]) == 1 and len(repo.inserted) == 1 + + monkeypatch.setattr(rb, "PAYLOAD_VERSION", rb.PAYLOAD_VERSION + 1) + await _read() + assert len(demo["mirror"]) == 2 and len(repo.inserted) == 2 + + +@pytest.mark.asyncio +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, 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)} + 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) + 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( + 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 + elif served == "marked": + assert notes == [STALE, "git_mirror: x"] + else: + assert notes == [STALE, *built] + 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 + assert notes == [STALE, "code.review_brief: brief_missing (TimeoutError)"] + [(_table, [row])] = repo.inserted + 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) + built = _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 == [STALE, *built] + 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_merge_commit_that_names_another_pr_marks_the_stale_row( + demo: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """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) + + 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: 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) == 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 +) -> 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 +async def test_a_read_by_merge_commit_alone_rebuilds_the_row_at_its_merge_commit( + demo: dict[str, Any], +) -> None: + """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")) + 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", DEMO_SHA)] + assert out.provenance["merge_commit"] == "named_commit" # not placed by first parent + + +@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_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 == [STALE, "git_mirror: diff_unread"] + + +DEMO_HEAD = "c3" * 20 + + +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) + 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 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, "" + + monkeypatch.setattr(h, "_open_head", _head) + + +@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 == [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) + 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)"] + + +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 + + 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"]) + + 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"] + _open_at_head(monkeypatch) + + 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 == [] + [(_table, [row])] = repo.inserted + 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] == 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 + 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: + """During a rolling upgrade the older build never rebuilds what the newer one stored.""" + 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() + 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 9a6095f76b..99222f2b0e 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 dd92a0b40a..bf1d7e6f2e 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -3133,6 +3133,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)}, @@ -3255,7 +3256,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 []) @@ -3293,6 +3296,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=[])},