diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 8794a107f1..899a3de464 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -171,6 +171,22 @@ the PRs of its files (every file that defines a name), newest first; a `numbers` answers in one page of up to `limit` PRs and refuses `offset`. `code.symbol_history` narrows this to one function's regression history: the PRs that touched its span, their linked issues and reverts, and the review comments inside it. +Its `regression_prs` names up to three PRs behind the summary's `named_fix_prs`, +`reverts` and `caused_issues`, read from the whole window whatever `limit` serves. Each +carries its title as the one-line cause, its merge date and `kinds` (`fix`, `revert`, +`caused_issue` with the issue numbers). A fix says `fix_by`: `title` when its title says +fix, crash, regression and the like, or `linked_issue` when it is counted only for closing +an issue, which a feature or performance PR does too. A PR behind more of the counts comes +first, then every entry before a `linked_issue` fix, then a fix before a revert before a +PR issues trace back to, then the newest. When the PR changed test files, `test_gate` holds +the `code.test_gate` arguments (`org`, `namespace`, `files`) that list how to run up to +four of them in the namespace the history was read from: first those `code.test_gate` has +a run recipe for (its built-in ones and `code_test_gate_run_templates`), then files named +as tests, then fixtures that are tests only by their directory, with one file of each run +command (such as one suite's directory) before a second of it. They are the paths the +ledger lists for the PR, so one it deleted or a later PR renamed may be gone. The record +is the PR ledger's; a test file is one `code.test_gate` counts as a test (a test +directory, or a test file name in the languages it lists). `code.blame_range` takes a `path`, a line range (at most 400 lines) and a window as release versions (`from_version`, `to_version`) or commit shas. It combines the PR @@ -203,6 +219,13 @@ record by its file and name (`path:symbol`), so a name many files define, such a `path:symbol` form does not parse, such as a path without an extension or with `[`, or a name such as `(anonymous namespace)::f`, reads the bare name, as does a form past the op's 300-character name bound; a record of another file's definition is `unknown`. +A row whose counts make the section `regressions` carries that record's `regression_prs`, +so the brief names the earlier fixes, reverts and culprit PRs with their test files; a +brief stored by an earlier build has the counts without it. When a tracker namespace a +record may rest on, the one bound to the code namespace or the one the record says it +read, is restricted, the brief carries the counts without `regression_prs`, as it leaves +that tracker out of its `qa` section. When its classification cannot be read, the brief +leaves them out too and is not stored, so the next read builds it again. The answer comes first: `verdict` and `verdict_causes`, read off every section the brief holds, whatever the tier serves, and off `rationale` when this read serves it. A verdict diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index d271d54724..3a0cc5eece 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1730,6 +1730,7 @@ The regression history of one function: the merged PRs that touched it (with lin | `review_comments` | `list[dict[str, Any]]` | inline review comments inside the symbol's span, newest first (≤5) | | `open_issues_naming` | `list[dict[str, Any]]` | open issues whose text names the function (QA), most severe first (≤5) | | `summary` | `dict[str, Any]` | {prs_total, named_prs, fix_prs, named_fix_prs, reverts, caused_issues[], open_issues_naming, last_touched, oldest_in_window, authors[], note} | +| `regression_prs` | `list[dict[str, Any]]` | Up to 3 PRs behind named_fix_prs, reverts and caused_issues, strongest first, each with its title, merge date, kinds and a code.test_gate query for the tests it changed. | | `tracker_namespace` | `str` | The tracker namespace that answered the QA side; "" when none is bound or its read failed. | | `tracker_unavailable` | `bool` | True when a tracker is bound but its read failed. | | `trace_run_id` | `str` | Id of this call's trace row; pass it to `code.outcome`. | diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 11bd896deb..c1ea612b1a 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -2464,6 +2464,7 @@ type CodeSymbolHistoryOutput struct { ReviewComments *[]map[string]json.RawMessage `json:"review_comments,omitempty"` OpenIssuesNaming *[]map[string]json.RawMessage `json:"open_issues_naming,omitempty"` Summary *map[string]json.RawMessage `json:"summary,omitempty"` + RegressionPrs *[]map[string]json.RawMessage `json:"regression_prs,omitempty"` TrackerNamespace *string `json:"tracker_namespace,omitempty"` TrackerUnavailable *bool `json:"tracker_unavailable,omitempty"` TraceRunID *string `json:"trace_run_id,omitempty"` diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index fed55a178b..b46e24dd58 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -8718,6 +8718,7 @@ class CodeSymbolHistoryOutput(TypedDict, total=False): review_comments: NotRequired[list[dict[str, Any]]] open_issues_naming: NotRequired[list[dict[str, Any]]] summary: NotRequired[dict[str, Any]] + regression_prs: NotRequired[list[dict[str, Any]]] tracker_namespace: NotRequired[str] tracker_unavailable: NotRequired[bool] trace_run_id: NotRequired[str] diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index dee1f7fb44..41597946da 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -15764,6 +15764,8 @@ pub struct CodeSymbolHistoryOutput { pub open_issues_naming: Vec>, #[serde(default = "default_code_symbol_history_output_summary")] pub summary: std::collections::HashMap, + #[serde(default = "default_code_symbol_history_output_regression_prs")] + pub regression_prs: Vec>, #[serde(default = "default_code_symbol_history_output_tracker_namespace")] pub tracker_namespace: String, #[serde(default = "default_code_symbol_history_output_tracker_unavailable")] @@ -69490,6 +69492,10 @@ fn default_code_symbol_history_output_open_issues_naming( fn default_code_symbol_history_output_summary() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } +fn default_code_symbol_history_output_regression_prs( +) -> Vec> { + serde_json::from_str("[]").expect("schema default") +} fn default_code_symbol_history_output_tracker_namespace() -> String { serde_json::from_str("\"\"").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index 16f15cd3ff..364dbae8b1 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -10697,6 +10697,11 @@ fn code_symbol_history() { serde_json::from_str::("{}").unwrap(), "code.symbol_history:summary" ); + assert_eq!( + encoded["regression_prs"], + serde_json::from_str::("[]").unwrap(), + "code.symbol_history:regression_prs" + ); assert_eq!( encoded["tracker_namespace"], serde_json::from_str::("\"\"").unwrap(), diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 5ed29683ca..944f4c3f38 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -1915,6 +1915,7 @@ export interface CodeSymbolHistoryOutput { review_comments?: Array>; open_issues_naming?: Array>; summary?: Record; + regression_prs?: Array>; tracker_namespace?: string; tracker_unavailable?: boolean; trace_run_id?: string; diff --git a/server/code/api/models_history.py b/server/code/api/models_history.py index b27899132d..381ab49e5d 100644 --- a/server/code/api/models_history.py +++ b/server/code/api/models_history.py @@ -617,6 +617,9 @@ class CodeSymbolHistoryOutput(BaseModel): # {prs_total, named_prs, fix_prs, named_fix_prs, reverts, caused_issues[], # open_issues_naming, last_touched, oldest_in_window, authors[], note} summary: dict[str, Any] = Field(default_factory=dict) + # Up to 3 PRs behind named_fix_prs, reverts and caused_issues, strongest first, each + # with its title, merge date, kinds and a code.test_gate query for the tests it changed. + regression_prs: list[dict[str, Any]] = Field(default_factory=list) # The tracker namespace that answered the QA side; "" when none is bound or # its read failed. tracker_namespace: str = "" diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 56ea5fea29..e7e66eb24a 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -894,6 +894,35 @@ def _history_name(name: str, path: str) -> str: return form if carried else name +# `_tracker_gate`: a tracker the brief may carry rows of, one it may not, and an +# unread classification (closed too, and the brief is not stored, so the next read +# builds it again) +TRACKER_OPEN, TRACKER_CLOSED, TRACKER_UNREAD = "open", "closed", "unread" + + +async def _tracker_gate(org: str, ns: str, results: list[Any]) -> str: + """Whether the brief may carry the rows of the tracker namespaces the history records + may rest on: the one bound to the code namespace now (a record whose tracker side + raised names none) and each one a record says it read (the binding may have moved + since). A stored brief is read by every viewer of the code namespace, so as for the + `qa` section, a restricted tracker's rows never enter it.""" + from server.auth.directory import ClassificationUnavailable + from server.identity.app.namespace_classification import is_restricted + from server.tracker.app.binding import refresh_overrides, tracker_namespace_for + + await refresh_overrides() # the links as of the refresh interval, branches included + trackers = {tracker_namespace_for(org, ns)} | { + str(r.get("tracker_namespace") or "") for r in results if not isinstance(r, BaseException) + } + for tracker in sorted(trackers - {""}): + try: + if await is_restricted(org, tracker): + return TRACKER_CLOSED + except ClassificationUnavailable: + return TRACKER_UNREAD + return TRACKER_OPEN + + async def _history_section( call: CallOp, inp: BriefInputs, defs: list[tuple[str, str]] ) -> dict[str, Any]: @@ -922,6 +951,16 @@ async def _history_section( causes: list[str] = [] unavailable = 0 left = 0 # functions an op refused to read: a cap + # a name that resolved to another file's definition reads as unknown + results = [ + r + if isinstance(r, BaseException) + or str((r.get("symbol") or {}).get("path") or "") in ("", path) + else {"verdict": "unknown"} + for (_, path), r in zip(defs, results, strict=True) + ] + listed = any(not isinstance(r, BaseException) and r.get("regression_prs") for r in results) + gate = await _tracker_gate(inp.org, inp.ns, results) if listed else TRACKER_OPEN for (name, path), res in zip(defs, results, strict=True): if isinstance(res, BaseException): if refused(res): @@ -930,26 +969,27 @@ async def _history_section( degradations.partial("code.review_brief", "symbol_history_failed", res) causes.append(failure_cause("symbol_history", res)) continue - resolved = str((res.get("symbol") or {}).get("path") or "") - if resolved and resolved != path: - res = {"verdict": "unknown"} s = dict(res.get("summary") or {}) - rows.append( - { - "qualified_name": name, - "path": path, - "verdict": str(res.get("verdict") or "unknown"), - "prs_total": int(s.get("prs_total") or 0), - "fix_prs": int(s.get("fix_prs") or 0), - "named_fix_prs": int(s.get("named_fix_prs") or 0), - "reverts": int(s.get("reverts") or 0), - "caused_issues": len(list(s.get("caused_issues") or [])), - "open_issues_naming": int(s.get("open_issues_naming") or 0), - "last_touched": str(s.get("last_touched") or ""), - "tracker": not bool(res.get("tracker_unavailable")) - and bool(res.get("tracker_namespace")), - } - ) + row: dict[str, Any] = { + "qualified_name": name, + "path": path, + "verdict": str(res.get("verdict") or "unknown"), + "prs_total": int(s.get("prs_total") or 0), + "fix_prs": int(s.get("fix_prs") or 0), + "named_fix_prs": int(s.get("named_fix_prs") or 0), + "reverts": int(s.get("reverts") or 0), + "caused_issues": len(list(s.get("caused_issues") or [])), + "open_issues_naming": int(s.get("open_issues_naming") or 0), + "last_touched": str(s.get("last_touched") or ""), + "tracker": not bool(res.get("tracker_unavailable")) + and bool(res.get("tracker_namespace")), + } + prs = list(res.get("regression_prs") or []) if gate == TRACKER_OPEN else [] + if prs: + # the PRs behind the counts that make `regressions` (the op names none on a + # row without them), each with its title and the test files it changed + row["regression_prs"] = prs + rows.append(row) # the tracker is bound and its read failed: the issues it traces are unread unavailable += bool(res.get("tracker_unavailable")) rows.sort( @@ -966,7 +1006,9 @@ async def _history_section( epistemic="lower_bound", causes=causes, rows=rows, - failed=causes, # every cause here is a read that raised + # every cause here is a read that raised; an unread tracker classification decides + # no verdict, so it keeps the brief unstored without being a cause + failed=[*causes, *(["tracker_classification_unread"] if gate == TRACKER_UNREAD else [])], note="touch is file-level unless `qa` is true on the row; every count is a floor", ) _cut(out, NOT_READ, left) diff --git a/server/code/app/symbol_history.py b/server/code/app/symbol_history.py index 4d66356e0c..abcfd69c5a 100644 --- a/server/code/app/symbol_history.py +++ b/server/code/app/symbol_history.py @@ -28,6 +28,7 @@ from server.code.store.index import CodeRepo from server.core.errors import ValidationError from server.observability import degradations +from server.settings import settings from server.tracker.domain import bisect as bi logger = logging.getLogger(__name__) @@ -218,6 +219,9 @@ async def handle_code_symbol_history(input: Any) -> Any: review_comments=span_comments, open_issues_naming=[_open_issue_view(r) for r in open_issues[:5]], summary=summary, + regression_prs=sh.regression_prs( + rows, org=org, namespace=ns, run_templates=str(settings.code_test_gate_run_templates) + ), tracker_namespace=tracker_ns, tracker_unavailable=tracker_unavailable, trace_run_id=trace_run_id, diff --git a/server/code/domain/index/symbol_history.py b/server/code/domain/index/symbol_history.py index 0b69a8fcd0..ac2ee11aaa 100644 --- a/server/code/domain/index/symbol_history.py +++ b/server/code/domain/index/symbol_history.py @@ -17,6 +17,7 @@ from typing import Any from server.code.domain.index.blame_range import sha_text +from server.code.domain.index.test_gate import is_test_named, is_test_path, run_command_for HISTORY = "history" NO_HISTORY = "no_history" @@ -25,6 +26,9 @@ # counts those among them that touch the definition, and `limit` serves up to all. # not a setting: the op's `limit` bound on the wire is derived from it PR_WINDOW = 120 +# not a setting: bounds on `regression_prs`, the evidence behind the summary's counts +EVIDENCE_PRS = 3 +EVIDENCE_TEST_FILES = 4 _FIX_RE = re.compile( r"(?i)\b(fix|fixes|fixed|fixing|bug|crash|regression|logical error|segfault|" @@ -49,6 +53,8 @@ class PrRow: # false (QA diff does not) | unknown touches_symbol: str = "unknown" tracker: dict[str, Any] = field(default_factory=dict) + # the PR's changed files, as the ledger lists them + files: list[str] = field(default_factory=list) def as_dict(self) -> dict[str, Any]: out: dict[str, Any] = { @@ -150,6 +156,7 @@ def build_rows( is_backport=bool(_BACKPORT_RE.match(title)), linked_issues=linked, comments_on_symbol=by_pr_comments.get(n, 0), + files=[str(f) for f in r.get("files") or []], ) # loom's own function-level hint: the PR's title or description # names the function (a review comment inside the span counts too) @@ -194,9 +201,11 @@ def summarize( touching = [r for r in rows if r.touches_symbol != "false"] named = [r for r in touching if r.touches_symbol in ("true", "named")] fixes = [r for r in touching if r.is_fix and not r.is_revert] - named_fixes = [r for r in named if r.is_fix and not r.is_revert] - reverts = [r for r in touching if r.is_revert] - caused = sorted({i for r in touching for i in (r.tracker.get("caused") or [])}) + # the counts that make `regressions`, by the rule `regression_prs` names them with + kinds = [(r, _evidence_kinds(r)) for r in touching] + named_fixes = [r for r, k in kinds if "fix" in k] + reverts = [r for r, k in kinds if "revert" in k] + caused = sorted({i for r, k in kinds if "caused_issue" in k for i in r.tracker["caused"]}) authors: dict[str, int] = {} for r in touching: if r.author and not r.author.endswith("[bot]") and not r.author.startswith("robot-"): @@ -245,6 +254,86 @@ def summarize( } +_KIND_ORDER = {"fix": 0, "revert": 1, "caused_issue": 2} + + +def _evidence_kinds(row: PrRow) -> list[str]: + """Which of the summary's regression counts the row adds to: `fix` (a named fix), + `revert`, `caused_issue` (an issue the tracker traces back to it).""" + if row.touches_symbol == "false": + return [] + kinds: list[str] = [] + if row.is_fix and not row.is_revert and row.touches_symbol in ("true", "named"): + kinds.append("fix") + if row.is_revert: + kinds.append("revert") + if row.tracker.get("caused"): + kinds.append("caused_issue") + return kinds + + +def _fix_by(row: PrRow, kinds: list[str]) -> str: + """How a named fix was recognized: `title` (its title says fix, crash, regression and the + like) or `linked_issue` (it closes an issue, which a feature PR may do too); '' when + the row is no named fix.""" + if "fix" not in kinds: + return "" + return "title" if _FIX_RE.search(row.title) else "linked_issue" + + +def _test_files(row: PrRow, run_templates: str) -> list[str]: + """The PR's test files, those code.test_gate has a run recipe for first, then those + named as tests before fixtures that are tests only by their directory; within that + order one file of each run command (a suite's directory) before a second of it, so the + files of one suite cannot crowd out another the PR changed.""" + runs = {p: run_command_for(p, run_templates) for p in row.files if is_test_path(p)} + tests = sorted(runs, key=lambda p: (runs[p][1], not is_test_named(p))) + seen: set[str] = set() + repeat: dict[str, bool] = {} + for p in tests: + run = runs[p][0] or p # a file with no recipe is its own run command + repeat[p] = run in seen + seen.add(run) + tests.sort(key=lambda p: repeat[p]) + return tests[:EVIDENCE_TEST_FILES] + + +def regression_prs( + rows: list[PrRow], *, org: str, namespace: str, run_templates: str = "" +) -> list[dict[str, Any]]: + """The PRs behind `named_fix_prs`, `reverts` and `caused_issues`, strongest first: a + PR behind more of the counts, then any of them before a fix counted only for closing + an issue (`_fix_by`), then a named fix before a revert before a PR issues trace back + to, then the newest. Each carries its title as the one-line cause and, when it + changed test files (`_test_files`), the `code.test_gate` arguments that list how to + run them in this namespace. `run_templates` is the deployment's run recipes, as + code.test_gate reads them.""" + + def strength(entry: tuple[PrRow, list[str], str]) -> tuple[int, bool, int]: + _, kinds, fix_by = entry + return -len(kinds), fix_by == "linked_issue", _KIND_ORDER[kinds[0]] + + picked = [(r, k, _fix_by(r, k)) for r in rows if (k := _evidence_kinds(r))] + picked.sort(key=lambda entry: entry[0].merged_at, reverse=True) # ties: the newest + picked.sort(key=strength) + out: list[dict[str, Any]] = [] + for row, kinds, fix_by in picked[:EVIDENCE_PRS]: + item: dict[str, Any] = { + "pr_number": row.pr_number, + "title": row.title[:160], + "merged_at": row.merged_at[:10], + "kinds": kinds, + } + if fix_by: + item["fix_by"] = fix_by + if "caused_issue" in kinds: + item["caused_issues"] = list(row.tracker["caused"]) + if tests := _test_files(row, run_templates): + item["test_gate"] = {"org": org, "namespace": namespace, "files": tests} + out.append(item) + return out + + def verdict_of(rows: list[PrRow], *, resolved: bool) -> tuple[str, list[str]]: if not resolved: return UNKNOWN, ["symbol_unresolved"] @@ -259,6 +348,7 @@ def verdict_of(rows: list[PrRow], *, resolved: bool) -> tuple[str, list[str]]: "build_rows", "in_span", "is_fix_title", + "regression_prs", "summarize", "verdict_of", ] diff --git a/server/code/domain/index/test_gate.py b/server/code/domain/index/test_gate.py index 75c7247227..8598e15026 100644 --- a/server/code/domain/index/test_gate.py +++ b/server/code/domain/index/test_gate.py @@ -102,9 +102,13 @@ def is_test_path(path: str) -> bool: tests/, test/ or spec/, or a test-named file. Fixture and data files under tests/ count too — a changed fixture is still something to re-run against.""" p = (path or "").strip().lstrip("./") - if not p: - return False - return bool(_TEST_DIR_RE.search(p) or _TEST_FILE_RE.search(p)) + return bool(p) and (bool(_TEST_DIR_RE.search(p)) or is_test_named(p)) + + +def is_test_named(path: str) -> bool: + """A file whose own name marks it a test (test_x.py, x_test.go, XTest.java, + gtest_x.cpp), as against a fixture that is a test path only by its directory.""" + return bool(_TEST_FILE_RE.search((path or "").strip().lstrip("./"))) def _stem(path: str) -> str: @@ -186,8 +190,8 @@ def run_command_for(test_path: str, overrides_json: str = "") -> tuple[str, bool groups = {f"g{i}": g or "" for i, g in enumerate(m.groups(), start=1)} try: return tpl.format(**ctx, **groups), False - except (KeyError, IndexError): - continue + except (KeyError, IndexError, ValueError, AttributeError, TypeError): + continue # a template that does not format (a field it lacks, a stray brace) return "", True diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index ca28bdc2b5..dd92a0b40a 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -618,6 +618,7 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: "open_issues_naming": 0, "last_touched": "2026-09-01", }, + "regression_prs": [{"pr_number": 117000, "kinds": ["fix"]}] if named else [], "tracker_namespace": "", "tracker_unavailable": False, } @@ -813,6 +814,9 @@ async def test_build_assembles_every_section_with_verdicts_and_decisions() -> No assert secs["history"]["verdict"] == "regressions" assert secs["history"]["rows"][0]["qualified_name"] == "DB::MergeTreeData::loadDataParts" assert secs["history"]["rows"][0]["named_fix_prs"] == 1 + # the row that makes `regressions` names the PRs behind its counts; a clean one does not + assert secs["history"]["rows"][0]["regression_prs"] == [{"pr_number": 117000, "kinds": ["fix"]}] + assert "regression_prs" not in secs["history"]["rows"][1] assert {r["qualified_name"] for r in secs["history"]["rows"]} == { "DB::MergeTreeData::loadDataParts", "DB::Settings::dump", @@ -3613,3 +3617,104 @@ async def down(*a: Any) -> Any: assert degradations.current() == ["code.review_brief: reviewers_unread (TimeoutError)"] assert payload["provenance"]["tracker"] == rb.FAILED assert payload["stored"] is False and repo.inserted == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("bound", "read", "closed"), + [ + ("open", "", False), + ("restricted", "", True), # the record's tracker side raised: the binding decides + ("unclassified", "", True), + ("open", "restricted", True), # the binding moved off the tracker the record read + ("restricted", "open", True), + ("open", "open", False), + ], +) +async def test_history_rows_name_no_pr_a_restricted_tracker_read( + monkeypatch: pytest.MonkeyPatch, bound: str, read: str, closed: bool +) -> None: + """A stored brief is read by every viewer of the code namespace, so a record that may + rest on a restricted tracker (or one whose classification is unread), the bound one + or the one the record says it read, names no PR in it, as that tracker stays out of + its `qa` section.""" + import server.identity.app.namespace_classification as nc + import server.tracker.app.binding as binding_mod + from server.auth.directory import ClassificationUnavailable + + async def is_restricted(org: str, ns: str) -> bool: + if ns == "unclassified": + raise ClassificationUnavailable("directory unread") + return ns == "restricted" + + async def refresh() -> None: + return None + + monkeypatch.setattr(nc, "is_restricted", is_restricted) + monkeypatch.setattr(binding_mod, "refresh_overrides", refresh) + monkeypatch.setattr(binding_mod, "tracker_namespace_for", lambda org, ns: bound) + evidence = [ + {"pr_number": 3, "kinds": ["fix", "caused_issue"], "caused_issues": [9]}, + {"pr_number": 2, "kinds": ["revert"]}, + ] + + async def call(op: str, body: dict[str, Any]) -> dict[str, Any]: + return { + "verdict": "history", + "symbol": {"path": "app/counter.py"}, + "summary": {"named_fix_prs": 1, "reverts": 1, "caused_issues": [9]}, + "regression_prs": evidence, + "tracker_namespace": read, + } + + hist = await review_brief_build._history_section( + call, _inputs(), [("app.counter::bump", "app/counter.py")] + ) + # the counts and the verdict stand either way + assert hist["verdict"] == "regressions" and hist["rows"][0]["named_fix_prs"] == 1 + if closed: + # a tracker match or link may be all a fix entry rests on: none is copied + assert "regression_prs" not in hist["rows"][0] + else: + assert hist["rows"][0]["regression_prs"] == evidence + # an unread classification keeps the brief unstored, deciding no verdict + unread = "unclassified" in (bound, read) + assert rb.failed_reads({"history": hist}) == ( + ["history:tracker_classification_unread"] if unread else [] + ) + assert hist["causes"] == [] + + +@pytest.mark.asyncio +async def test_a_record_of_another_file_reads_no_tracker(monkeypatch: pytest.MonkeyPatch) -> None: + """A record whose symbol is another file's is discarded, so its tracker does not keep + the brief unstored.""" + import server.identity.app.namespace_classification as nc + import server.tracker.app.binding as binding_mod + from server.auth.directory import ClassificationUnavailable + + async def is_restricted(org: str, ns: str) -> bool: + raise ClassificationUnavailable("directory unread") + + async def refresh() -> None: + return None + + monkeypatch.setattr(nc, "is_restricted", is_restricted) + monkeypatch.setattr(binding_mod, "refresh_overrides", refresh) + monkeypatch.setattr(binding_mod, "tracker_namespace_for", lambda org, ns: "qa") + + async def call(op: str, body: dict[str, Any]) -> dict[str, Any]: + return { + "verdict": "history", + "symbol": {"path": "app/other.py"}, + "summary": {"named_fix_prs": 1}, + "regression_prs": [{"pr_number": 3, "kinds": ["fix"]}], + "tracker_namespace": "qa", + } + + hist = await review_brief_build._history_section( + call, _inputs(), [("app.counter::bump", "app/counter.py")] + ) + assert hist["rows"][0]["verdict"] == "unknown" + assert "regression_prs" not in hist["rows"][0] + assert rb.failed_reads({"history": hist}) == [] diff --git a/tests/unit/test_code_symbol_history.py b/tests/unit/test_code_symbol_history.py index 37a80a42e3..52148373df 100644 --- a/tests/unit/test_code_symbol_history.py +++ b/tests/unit/test_code_symbol_history.py @@ -6,6 +6,7 @@ from __future__ import annotations +import json from datetime import datetime from typing import Any @@ -39,7 +40,7 @@ "merged_at": datetime(2026, 9, 1), "linked_issues": [100], "is_revert": False, - "files": [PATH], + "files": [PATH, "tests/test_parts_loading.py"], }, { "pr_number": 850, @@ -167,6 +168,168 @@ def test_build_rows_marks_touch_from_tracker_and_summarises() -> None: assert "2 open issues name it today" in summary["note"] +def _evidence(rows: list[sh.PrRow], **kw: Any) -> list[dict[str, Any]]: + return sh.regression_prs(rows, org="acme", namespace="code-shop", **kw) + + +def test_regression_prs_name_the_rows_behind_the_counts_strongest_first() -> None: + def row(n: int, title: str, at: str, **kw: Any) -> sh.PrRow: + return sh.PrRow(pr_number=n, title=title, merged_at=f"{at}T10:00:00", **kw) + + rows = [ + # a named fix counted only for closing an issue, newest + row(60, "Speed up the loader", "2026-09-05", is_fix=True, touches_symbol="named"), + # a fix whose diff misses the function adds to no count + row(50, "Fix crash", "2026-09-04", is_fix=True, touches_symbol="false"), + row( + 40, + "Fix crash in load_items", + "2026-09-03", + is_fix=True, + touches_symbol="true", + files=["app/items.py", "tests/fixtures/items.json", "tests/test_items.py"], + ), + row(30, 'Revert "Load items"', "2026-09-02", is_revert=True, is_fix=True), + row(20, "Load items in parallel", "2026-09-01", tracker={"caused": [100, 101]}), + # a fix that also caused an issue backs two counts: strongest + row( + 10, + "Fix race", + "2026-08-01", + is_fix=True, + touches_symbol="true", + tracker={"caused": [102]}, + ), + ] + out = _evidence(rows) + assert [e["pr_number"] for e in out] == [10, 40, 30] + assert out[0]["kinds"] == ["fix", "caused_issue"] and out[0]["caused_issues"] == [102] + assert out[0]["fix_by"] == "title" and "test_gate" not in out[0] + assert out[0]["merged_at"] == "2026-08-01" + # the runnable test before its fixture, as code.test_gate arguments in this namespace + assert out[1]["test_gate"] == { + "org": "acme", + "namespace": "code-shop", + "files": ["tests/test_items.py", "tests/fixtures/items.json"], + } + assert out[2]["kinds"] == ["revert"] and "fix_by" not in out[2] + # past the cap: the PR issues trace back to before a fix counted only for an issue + rest = _evidence([r for r in rows if r.pr_number in (60, 20)]) + assert [(e["pr_number"], e.get("fix_by")) for e in rest] == [(20, None), (60, "linked_issue")] + assert rest[0]["caused_issues"] == [100, 101] + # more counts first: a fix counted only for an issue that also caused one leads + both = sh.PrRow( + pr_number=5, + title="Speed up the loader", + merged_at="2026-01-01T00:00:00", + is_fix=True, + touches_symbol="named", + tracker={"caused": [103]}, + ) + lead = _evidence([both, *[r for r in rows if r.pr_number in (40, 30)]]) + assert [(e["pr_number"], e.get("fix_by")) for e in lead] == [ + (5, "linked_issue"), + (40, "title"), + (30, None), + ] + # the entries and the counts come from one rule + summary = sh.summarize(rows, window_prs=10, open_issues=0, qa_ok=True) + assert summary["named_fix_prs"] == 3 and summary["reverts"] == 1 + assert summary["caused_issues"] == [100, 101, 102] + + +def test_regression_test_files_follow_the_deployments_run_recipes() -> None: + # a layout no built-in recipe knows: ledger order until a run template names the cases + row = sh.PrRow( + pr_number=7, + title="Fix overflow in tally", + merged_at="2026-09-01T00:00:00", + is_fix=True, + touches_symbol="true", + files=["spec/tally.expected", "spec/tally.case"], + ) + plain = _evidence([row]) + assert plain[0]["test_gate"]["files"] == ["spec/tally.expected", "spec/tally.case"] + recipes = '[{"pattern": "^spec/.+\\\\.case$", "run": "./run-case {path}"}]' + ordered = _evidence([row], run_templates=recipes) + assert ordered[0]["test_gate"]["files"] == ["spec/tally.case", "spec/tally.expected"] + + +def test_regression_prs_keep_four_test_files_runnable_first() -> None: + fixtures = [f"tests/fixtures/case{i}.json" for i in range(4)] + row = sh.PrRow( + pr_number=8, + title="Fix leak in pool", + merged_at="2026-09-01T00:00:00", + is_fix=True, + touches_symbol="true", + files=[*fixtures, "tests/test_pool.py", "tests/test_pool_reuse.py"], + ) + out = _evidence([row])[0] + assert out["test_gate"]["files"] == [ + "tests/test_pool.py", + "tests/test_pool_reuse.py", + "tests/fixtures/case0.json", + "tests/fixtures/case1.json", + ] + + +def test_a_layout_without_a_run_recipe_keeps_its_named_tests_before_fixtures() -> None: + # a C++ and a Java layout no built-in recipe runs: the file named as a test survives the cap + def fix(n: int, files: list[str]) -> sh.PrRow: + return sh.PrRow( + pr_number=n, + title="Fix overflow", + merged_at=f"2026-09-0{n}T00:00:00", + is_fix=True, + touches_symbol="true", + files=files, + ) + + data = [f"lib/tests/data/{c}.txt" for c in "abcd"] + java = [f"core/src/test/fixtures/{c}.json" for c in "abcd"] + out = _evidence( + [ + fix(2, [*data, "lib/tests/gtest_counter.cpp"]), + fix(1, [*java, "core/src/test/java/app/CounterTest.java"]), + ] + ) + assert out[0]["test_gate"]["files"][0] == "lib/tests/gtest_counter.cpp" + assert out[1]["test_gate"]["files"][0] == "core/src/test/java/app/CounterTest.java" + assert all(len(e["test_gate"]["files"]) == 4 for e in out) + + +def test_regression_prs_break_ties_on_the_newest_and_match_the_counts() -> None: + def row(n: int, at: str, touch: str) -> sh.PrRow: + return sh.PrRow( + pr_number=n, title="Fix leak", merged_at=at, is_fix=True, touches_symbol=touch + ) + + rows = [ + row(1, "2026-07-01T00:00:00", "true"), + row(2, "2026-09-01T00:00:00", "named"), + # a fix that touched only the file is no named fix: neither counted nor named + row(3, "2026-10-01T00:00:00", "unknown"), + ] + assert [e["pr_number"] for e in _evidence(rows)] == [2, 1] + summary = sh.summarize(rows, window_prs=10, open_issues=0, qa_ok=True) + assert summary["named_fix_prs"] == 2 and summary["fix_prs"] == 3 + + +def test_build_rows_keep_the_files_a_pr_changed() -> None: + rows = sh.build_rows( + [{"pr_number": 1, "title": "t", "files": ["app/items.py", "tests/test_items.py"]}], + issue_facts={}, + comments=[], + span=(1, 2), + tracker_facts={}, + tracker_edges=[], + frames=[], + qa_ok=False, + ) + assert rows[0].files == ["app/items.py", "tests/test_items.py"] + + def test_without_tracker_rows_stay_file_level_and_the_note_says_so() -> None: rows = sh.build_rows( PRS, @@ -311,6 +474,23 @@ async def test_handler_assembles_loom_and_tracker(wired) -> None: ] assert out.open_issues_naming[0]["number"] == 300 and out.summary["open_issues_naming"] == 1 assert out.summary["reverts"] == 1 and out.summary["last_touched"] == "2026-09-01" + assert [(e["pr_number"], e["kinds"]) for e in out.regression_prs] == [ + (900, ["fix"]), + (850, ["revert"]), + ] + # replayable on the namespace the history was read from + assert out.regression_prs[0]["test_gate"] == { + "org": ORG, + "namespace": NS, + "files": ["tests/test_parts_loading.py"], + } + # the evidence reads the whole window, not the `limit` rows served + one = await h.handle_code_symbol_history( + CodeSymbolHistoryInput( + org=ORG, namespace=NS, name="DB::MergeTreeData::loadDataParts", limit=1 + ) + ) + assert len(one.prs) == 1 and one.regression_prs == out.regression_prs @pytest.mark.asyncio @@ -394,3 +574,47 @@ async def _no_items(self, org, ns, numbers): "code_index: issue_facts_unread (TimeoutError)", "tracker: symbol_facts_unread (RuntimeError)", ] + + +@pytest.mark.asyncio +async def test_handler_orders_test_files_by_the_deployments_run_templates( + wired, monkeypatch: pytest.MonkeyPatch +) -> None: + # the ledger lists the fixture first; only the deployment's template runs the case + monkeypatch.setitem(PRS[0], "files", [PATH, "spec/parts.expected", "spec/parts.case"]) + recipes = '[{"pattern": "^spec/.+[.]case$", "run": "./run-case {path}"}]' + monkeypatch.setattr(h.settings, "code_test_gate_run_templates", recipes) + out = await h.handle_code_symbol_history( + CodeSymbolHistoryInput(org=ORG, namespace=NS, name="DB::MergeTreeData::loadDataParts") + ) + assert out.regression_prs[0]["test_gate"]["files"] == ["spec/parts.case", "spec/parts.expected"] + + +def test_one_suites_files_do_not_crowd_out_another_suite() -> None: + suite_a = [f"spec/alpha/{c}.case" for c in "abcd"] + row = sh.PrRow( + pr_number=4, + title="Fix reconnect", + merged_at="2026-09-01T00:00:00", + is_fix=True, + touches_symbol="true", + files=[*suite_a, "spec/beta/a.case"], + ) + recipes = '[{"pattern": "^spec/([^/]+)/", "run": "./run-suite {g1}"}]' + files = _evidence([row], run_templates=recipes)[0]["test_gate"]["files"] + assert files[:2] == [suite_a[0], "spec/beta/a.case"] + assert len(files) == 4 + + +def test_a_template_that_does_not_format_counts_as_no_recipe() -> None: + row = sh.PrRow( + pr_number=9, + title="Fix overflow", + merged_at="2026-09-01T00:00:00", + is_fix=True, + touches_symbol="true", + files=["spec/a.case"], + ) + for run in ("./run {path", "./run {path.x}", "./run {path[x]}"): + recipes = json.dumps([{"pattern": "^spec/", "run": run}]) + assert _evidence([row], run_templates=recipes)[0]["test_gate"]["files"] == ["spec/a.case"]