diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 9c4fae5ab3..c447765e46 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -303,17 +303,17 @@ stores its first 200 changed paths as rows; its `rows_total`, verdict and causes every changed path. The `rationale` section is never stored, so a read that does not serve it (the trivial tier, or `sections` without it) answers `gaps`, `unsettled` with `rationale:not_requested`, or `no_source_change`: `covered_no_gaps` needs `rationale` in -`sections` (or `sections` empty) on the standard or full tier. A brief one of whose -reads raised is served and not stored, and the next read builds it again (the test home -is advice: a read of it that raised or was refused decides no verdict, though one that -raised still keeps the brief unstored); so is an open PR's brief built without its diff, -or from an overlay that was off (`overlay:error` when git could not read its diff), left -a changed file unreached when its parse time was spent or its parse could not run here, -or parsed another head. A parse of a file that raised or ran past its limits does the -same on every build of that file, at an open PR's head and at a merged PR's parent -alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for -the file, and an open PR's `overlay_note` counts it. A build that replaces a brief of an -older version is tried once (below). +`sections` (or `sections` empty) on the standard or full tier. A brief one of whose reads +raised is served and not stored, and the next read builds it again (the test home and the +tests to run first are advice: a read of one that raised or was refused decides no verdict, +though one that raised still keeps the brief unstored); so is an open PR's brief built +without its diff, or from an overlay that was off (`overlay:error` when git could not read +its diff), left a changed file unreached when its parse time was spent or its parse could +not run here, or parsed another head. A parse of a file that raised or ran past its limits +does the same on every build of that file, at an open PR's head and at a merged PR's parent +alike, so that brief is stored, `unsettled`: `code.impact` names `new_side_unread` for the +file, and an open PR's `overlay_note` counts it. A build that replaces a brief of an older +version is tried once (below). A change to what a brief stores or how its verdict reads it raises the payload version (`v` in the payload). A stored brief of the current version is served as it was built. @@ -459,6 +459,36 @@ at most eight sites, outside the methods of its own class (the its head's, which the index rows are not at, so its brief collapses nothing. The section's `note` gives both counts. +The first `tests` row, `kind: "run_first"`, names the tests to run first: the first five +tests `code.test_gate` lists for the PR's diff, in its order, so every test that says +`must_run` comes before a lead and the strongest evidence comes first. Files that share a +run command are one test, and a file with no run command joins the first test that holds a +file of its directory and name up to the first dot (a case's expected output beside its +script; a dotfile's whole name); files with different run commands are never one test. A +test of several files names its first five in `test_paths` and counts them in +`test_paths_total`. Each test carries its run command (`run`, with `run_unknown: true` when +the gate knows none) and the gate's `why`, `evidence` and `must_run` for its first file. The +brief reads the gate's first 200 rows. `left_out` counts the test files the gate holds under +none of the five, and `must_run_left_out` how many of them say `must_run`. A file past those +200 rows and a lead the gate cut are counted whatever their run command, and the gate's +count of cut leads is a lower bound. The row says `cut: true` when the gate did not read the +whole change, or read a changed source file on another revision: a changed file is missing +from the gate's `changed_files` (the files it read), the diff is longer than 200,000 +characters, the gate's causes say `truncated` (its call-graph walk or coverage read was +cut), or a changed source file is drifted (the index holds it at another revision than the +diff's old side, so its lines may map onto other definitions) or the drift read failed, or +the brief was built with no diff (from its changed paths alone), when its list may name a +file the PR deletes. Its list and counts are then of what it read. The gate reads test links +at the revision the index holds, as the claim rows do, so the brief of a merged PR built +after the index moved past it can name a test added since. A test file the PR deletes or +renames away is no test to run: with the diff, its row among those the brief reads is +neither listed nor counted. The row is advice no verdict rests on: a read of the gate that +raised keeps the brief unstored, and a refused read, or a gate that lists and counts no +test, leaves the row out. A gate that names no test, or only deleted ones, but counts other +tests or the leads it cut gives a row with no tests and their count in `left_out`. A brief +stored with no `run_first` row says nothing of the tests to run first: `code.test_gate` +lists them. + Each `tests` row of a symbol or setting carries the coverage claim's `verdict`, its `strongest_tier` (`code.coverage_claim`'s evidence tiers), up to two `tests` of that tier by repository path, and `tests_at_tier`, how many tests of that tier the claim listed (it diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index 8b9d512440..daaa9a4259 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -771,6 +771,10 @@ the nested one), or an override or a subclass, as a test double is. The other `s rows, and the `test_map` and `file_neighbor` rows, say `false` too. Those rows may not run the changed code, and a caller with a budget can leave them out. +A review brief names the first five tests of this list, one per test, in its `tests` +section's `run_first` row, with the count of the test files it leaves out ([review +briefs](history-and-prs.md#review-briefs-and-conventions)). + The gate reads a test file (one under a test directory such as `tests/`, `test/` or `spec/`, or a test-named file such as `foo_test.go`) as a test, except a definition there that other tests call or take as a fixture (a `conftest.py` fixture, a builder): that is a helper. A diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index b76bbb5163..063632b6a8 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1473,7 +1473,7 @@ A merged PR's review brief: the point read of what the ingest built at merge — | `tokens_used` | `int` | Estimated tokens of the sections served. | | `token_budget` | `int` | The budget the sections were cut to: the request's, else the tier's. | | `decisions` | `dict[str, bool]` | one-bit answers read off the section verdicts: test_only, symbol_with_regressions, uncovered_symbol, randomized_setting, deleted_lines_blamed | -| `sections` | `dict[str, dict[str, Any]]` | name -> {status, verdict, epistemic, causes, rows, rows_total, tokens, truncated}; `rows_total` counts every row, of which `paths` stores the first 200; `failed` names the reads of a section that raised, among its causes; `symbols` adds… | +| `sections` | `dict[str, dict[str, Any]]` | name -> {status, verdict, epistemic, causes, rows, rows_total, tokens, truncated}; `rows_total` counts every row, of which `paths` stores the first 200; `failed` names the reads of a section that raised, among its causes except the advice… | | `trace_run_id` | `str` | Id of this call's trace row; pass it to `code.outcome`. | ## `code.scip_ingest` diff --git a/server/code/api/models_review.py b/server/code/api/models_review.py index 3188c7444d..a96b1a6da9 100644 --- a/server/code/api/models_review.py +++ b/server/code/api/models_review.py @@ -191,10 +191,10 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: decisions: dict[str, bool] = Field(default_factory=dict) # name -> {status, verdict, epistemic, causes, rows, rows_total, tokens, truncated}; # `rows_total` counts every row, of which `paths` stores the first 200; `failed` names - # the reads of a section that raised, among its causes; `symbols` adds `collapsed` - # ({registration | factory | constructor | one_line: count}) for the wiring the PR - # adds that it lists as counts, not rows, and marks a function an open PR's overlay - # adds `via: added`. + # the reads of a section that raised, among its causes except the advice reads + # (`code.test_home`, `code.test_gate`); `symbols` adds `collapsed` ({registration | + # factory | constructor | one_line: count}) for the wiring the PR adds that it lists as + # counts, not rows, and marks a function an open PR's overlay adds `via: added`. sections: dict[str, dict[str, Any]] = Field(default_factory=dict) # Id of this call's trace row; pass it to `code.outcome`. trace_run_id: str = "" diff --git a/server/code/app/index/review_brief.py b/server/code/app/index/review_brief.py index ef07616d5e..c9fca74a91 100644 --- a/server/code/app/index/review_brief.py +++ b/server/code/app/index/review_brief.py @@ -24,9 +24,11 @@ weekly fan-in; the wiring the PR adds that nothing but a registry or its own class reaches (`WIRING_KINDS`) is a count per kind in `collapsed`, not a row, and is claimed like any other row; -- `tests` — a coverage claim per touched function and setting, with the - claim's strongest evidence tier and only the tests of that tier, - and the test file this PR's fingerprint belongs in; +- `tests` — the first tests code.test_gate lists for the diff, one per test + with the reason it is there and how many were left out; a coverage + claim per touched function and setting, with the claim's strongest + evidence tier and only the tests of that tier; and the test file this + PR's fingerprint belongs in; - `settings` — the facts of every setting the diff declares, changes in the history file or uses in a new stateless test; - `history` — each touched function's regression record; @@ -79,7 +81,7 @@ # 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 +PAYLOAD_VERSION = 4 SECTION_ORDER: tuple[str, ...] = ( "paths", @@ -131,10 +133,13 @@ MAX_SETTINGS = 8 MAX_COVERAGE_SETTINGS = 4 MAX_BLAME_RANGES = 5 -MAX_DIFF_CHARS = 200_000 # CodeImpactInput.diff's cap -# The changed files the brief's impact read seeds from. -# not a setting: CodeImpactInput.files' max_length -IMPACT_SEED_FILES = 50 +MAX_DIFF_CHARS = 200_000 # CodeImpactInput.diff's and CodeTestGateInput.diff's cap +# The changed files the brief's impact and test-gate reads seed from. +# not a setting: CodeImpactInput.files' and CodeTestGateInput.files' max_length +SEED_FILES = 50 +# The rows of code.test_gate the tests to run first are picked from. +# not a setting: CodeTestGateInput.limit's maximum +GATE_ROWS = 200 # The paths section stores the first this many changed paths as rows (impact's # `paths_seen` cut); `rows_total` counts them all, and its verdict and causes read all. # not a setting: it bounds a stored row list @@ -553,8 +558,8 @@ def section( failed: list[str] | None = None, ) -> dict[str, Any]: """One section. `failed` names the reads of it that raised (`failure_cause`), which are - among its `causes` too unless no verdict rests on the read (`code.test_home`); the key - rides only when there are any.""" + among its `causes` too unless no verdict rests on the read (`code.test_home`, + `code.test_gate`); the key rides only when there are any.""" rows = rows or [] out: dict[str, Any] = { "status": status if rows or status != SERVED else EMPTY, @@ -859,6 +864,24 @@ def wiring_kind(qualified_name: str, *, lines: int, path: str) -> str: return WIRING_ONE_LINE if lines == 1 else "" +def deleted_paths(diff: str) -> set[str]: + """The paths of the files a git diff deletes or moves away: a `+++ /dev/null` side + (`whole_files`), a `deleted file mode` line for a deletion git prints with no sides (a + binary or an empty file), or a rename's `rename from` path.""" + marked: set[str] = set() + header = "" + for line in diff.split("\n"): + line = line.removesuffix("\r") + if line.startswith("diff --git "): + header = line + elif line.startswith("deleted file mode") and header: + marked.add(_git_header_paths(header)[0]) + elif line.startswith("rename from "): + marked.add(line[len("rename from ") :]) + marked.discard("") + return marked | set(whole_files(diff)) + + def whole_files(diff: str, *, added: bool = False) -> dict[str, list[str]]: """The lines of each file the diff deletes (`+++ /dev/null`), by its old path, or with `added` of each file it adds (`--- /dev/null`), by its new path.""" @@ -1194,7 +1217,7 @@ def serve( "DRIFTED", "EMPTY", "FAILED", - "IMPACT_SEED_FILES", + "GATE_ROWS", "INDEX_ERROR", "NOT_BOUND", "NOT_BUILT", @@ -1205,6 +1228,7 @@ def serve( "RATIONALE", "RESTRICTED", "SECTION_ORDER", + "SEED_FILES", "SERVED", "SERVED_ORDER", "TIERS", @@ -1220,6 +1244,7 @@ def serve( "checked_names", "class_member", "decisions_of", + "deleted_paths", "deleted_ranges", "failed_reads", "failure_cause", diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 70f937c3ab..e65dd128e2 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -15,7 +15,7 @@ DRIFTED, EMPTY, FAILED, - IMPACT_SEED_FILES, + GATE_ROWS, INDEX_ERROR, MAX_COVERAGE_SETTINGS, MAX_COVERAGE_SYMBOLS, @@ -29,6 +29,7 @@ PATHS_ROWS, PAYLOAD_VERSION, SECTION_ORDER, + SEED_FILES, SERVED, UNDECIDED, UNGRAPHED, @@ -44,6 +45,7 @@ canonical, class_member, decisions_of, + deleted_paths, deleted_ranges, failed_reads, failed_section, @@ -63,8 +65,12 @@ ) from server.code.app.symbol.diff import _parse_unified_diff_full, is_blank from server.code.app.symbol.resolve import _parse_file_symbol -from server.code.domain.index.epistemic import CAUSE_NEW_SIDE_FAILED, CAUSE_UNMAPPED -from server.code.domain.index.test_gate import is_test_path +from server.code.domain.index.epistemic import ( + CAUSE_NEW_SIDE_FAILED, + CAUSE_TRUNCATED, + CAUSE_UNMAPPED, +) +from server.code.domain.index.test_gate import is_test_path, run_first from server.observability import degradations logger = logging.getLogger(__name__) @@ -98,7 +104,7 @@ async def build_brief( { "org": inp.org, "namespace": inp.ns, - "files": paths[:IMPACT_SEED_FILES], + "files": paths[:SEED_FILES], "diff": diff[:MAX_DIFF_CHARS], "depth": 1, "per_hop_limit": 200, @@ -149,7 +155,19 @@ async def build_brief( ranges = deleted_ranges(facts, src_only=is_graphed_path) - tests_t = _tests_section(call, inp, names[:MAX_COVERAGE_SYMBOLS], setting_names, stems) + # a changed source file the index holds at another revision, or a drift read that + # failed: the gate may have mapped the diff's lines onto other definitions + moved = bool(inp.drift_failed) or any(kinds.get(p) for p in inp.drifted) + tests_t = _tests_section( + call, + inp, + names[:MAX_COVERAGE_SYMBOLS], + setting_names, + stems, + paths=paths, + diff=diff, + moved=moved, + ) settings_t = _settings_section(call, inp, facts.settings[:MAX_SETTINGS]) defs = list(dict.fromkeys((str(r["qualified_name"]), str(r["path"])) for r in ranked)) history_t = _history_section(call, inp, defs[:MAX_HISTORY_SYMBOLS]) @@ -730,6 +748,10 @@ async def _tests_section( names: list[str], setting_names: list[str], stems: list[str], + *, + paths: list[str], + diff: str, + moved: bool, ) -> dict[str, Any]: base = {"org": inp.org, "namespace": inp.ns} subjects = [("symbol", n) for n in names] + [ @@ -754,8 +776,13 @@ async def _tests_section( }, ) ) - results = await asyncio.gather(*tasks, return_exceptions=True) - rows: list[dict[str, Any]] = [] + (results, (first, advice_failed)) = await asyncio.gather( + asyncio.gather(*tasks, return_exceptions=True), + _run_first_row(call, inp, paths, diff, moved=moved), + ) + # The tests to run first are advice no verdict rests on, first so a token budget trims + # them last + rows: list[dict[str, Any]] = [first] if first else [] causes: list[str] = [] left = 0 # claims an op refused to read: a cap epistemic = "lower_bound" @@ -785,13 +812,12 @@ async def _tests_section( ) # The home is advice no verdict rests on: a read of it that raised only keeps the # brief unstored, and a refused one leaves the row out - home_failed: list[str] = [] if home_wanted: res = results[-1] if isinstance(res, BaseException): if not refused(res): degradations.partial("code.review_brief", "test_home_failed", res) - home_failed.append(failure_cause("test_home", res)) + advice_failed.append(failure_cause("test_home", res)) else: rows.append( { @@ -805,7 +831,12 @@ async def _tests_section( "next_free_stateless_number": int(res.get("next_free_stateless_number") or 0), } ) - if rows and all(r.get("epistemic") == "exact" for r in rows if r.get("kind") != "home"): + # the tests to run first say nothing of what the claims read: a section of the home + # alone is exact, one of the tests to run first alone is not + claims = [r for r in rows if r.get("kind") in ("symbol", "setting")] + if any(r.get("kind") != "run_first" for r in rows) and all( + r.get("epistemic") == "exact" for r in claims + ): epistemic = "exact" out = section( SERVED, @@ -813,12 +844,72 @@ async def _tests_section( epistemic=epistemic, causes=causes, rows=rows, - failed=[*causes, *home_failed], # every cause here is a read that raised + failed=[*causes, *advice_failed], # every cause here is a read that raised ) _cut(out, NOT_CLAIMED, left) return out +async def _run_first_row( + call: CallOp, inp: BriefInputs, paths: list[str], diff: str, *, moved: bool +) -> tuple[dict[str, Any] | None, list[str]]: + """(the `run_first` row of the tests section, the read of it that raised): the first + tests code.test_gate lists for the PR's diff (`run_first`), None when it lists and + counts none. The gate reads a diff's old side as the revision the index holds, so `diff` + is the one code.impact reads: a merged PR's reversed, an open PR's as written; `moved` + says it may have mapped a source file's lines onto rows of another revision. A test file + the PR deletes or renames away is no test to run, and its row is neither listed nor + counted. A read that raised only keeps the brief unstored, and a refused one leaves the + row out.""" + if not (paths or diff): + return None, [] + try: + gate = await call( + "code.test_gate", + { + "org": inp.org, + "namespace": inp.ns, + "files": paths[:SEED_FILES], + "diff": diff[:MAX_DIFF_CHARS], + "limit": GATE_ROWS, + }, + ) + except Exception as e: # noqa: BLE001 — the tests to run first are advice + if refused(e): + return None, [] + degradations.partial("code.review_brief", "test_gate_failed", e) + return None, [failure_cause("test_gate", e)] + deleted = deleted_paths(inp.diff) + every = list(gate.get("tests") or []) + tests = [t for t in every if t.get("test_path") not in deleted] + gone = [t for t in every if t.get("test_path") in deleted] + total = int(gate.get("tests_total") or 0) - len(gone) + # a gate can list none (or only deleted files) and still count tests past its rows or + # the leads it cut: the row then names no test and counts them + unnamed = int(gate.get("tests_unnamed") or 0) + if not (tests or unnamed or total): + return None, [] + picked = run_first( + tests, + tests_total=total, + must_run_total=int(gate.get("must_run_total") or 0) + - sum(1 for t in gone if t.get("must_run")), + tests_unnamed=unnamed, + ) + # the gate read a cut change (a changed file it did not read), cut its own walk or + # coverage read, or may have mapped a source file's lines onto rows of another revision + # (`moved`), or the brief has no diff to tell the files the PR deletes: the list and + # counts are of what it read + cut = ( + bool(set(paths) - set(gate.get("changed_files") or [])) + or len(diff) > MAX_DIFF_CHARS + or CAUSE_TRUNCATED in (gate.get("causes") or []) + or moved + or not inp.diff + ) + return {"kind": "run_first", **picked, **({"cut": True} if cut else {})}, [] + + async def _settings_section( call: CallOp, inp: BriefInputs, diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index e645d70881..0d625eef8a 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -21,7 +21,11 @@ from server.code.api.models_history import CodeBlameRangeInput, CodeSymbolHistoryInput from server.code.api.models_review import CodeReviewBriefOutput from server.code.api.models_symbol import CodeImpactInput -from server.code.api.models_testing import CodeCoverageClaimInput, CodeTestHomeInput +from server.code.api.models_testing import ( + CodeCoverageClaimInput, + CodeTestGateInput, + CodeTestHomeInput, +) from server.code.app.common import ( new_trace_run_id, require_code_intel, @@ -53,12 +57,14 @@ async def call_code_op(op: str, body: dict[str, Any]) -> dict[str, Any]: from server.code.app.coverage import handle_code_coverage_claim, handle_code_test_home from server.code.app.settings import handle_code_setting_facts from server.code.app.symbol import handle_code_impact + from server.code.app.symbol.gate import handle_code_test_gate from server.code.app.symbol_history import handle_code_symbol_history table: dict[str, tuple[Any, Any]] = { "code.impact": (CodeImpactInput, handle_code_impact), "code.coverage_claim": (CodeCoverageClaimInput, handle_code_coverage_claim), "code.test_home": (CodeTestHomeInput, handle_code_test_home), + "code.test_gate": (CodeTestGateInput, handle_code_test_gate), "code.setting_facts": (CodeSettingFactsInput, handle_code_setting_facts), "code.symbol_history": (CodeSymbolHistoryInput, handle_code_symbol_history), "code.blame_range": (CodeBlameRangeInput, handle_code_blame_range), @@ -473,7 +479,7 @@ async def _rationale_section( # the stored rows are the first `PATHS_ROWS` of `rows_total`; a brief of payload # version 1 stored impact's list, which may stop at its seed files paths_maybe_cut=len(rows) < int(paths_sec.get("rows_total") or 0) - or (int(payload.get("v") or 0) < 2 and len(rows) >= rb.IMPACT_SEED_FILES), + or (int(payload.get("v") or 0) < 2 and len(rows) >= rb.SEED_FILES), # a brief stored without a diff or a file list says nothing of the PR's paths no_paths=not rows, budget_tokens=settings.code_review_brief_rationale_tokens, diff --git a/server/code/domain/index/test_gate.py b/server/code/domain/index/test_gate.py index 8598e15026..fb6af11fce 100644 --- a/server/code/domain/index/test_gate.py +++ b/server/code/domain/index/test_gate.py @@ -251,6 +251,89 @@ def _links_to(roots: set[str], names: dict[str, str]) -> list[str]: return sorted(names[r] for r in roots if r in names)[:_LINKS_SHOWN] +# Tests a brief names to run first (`run_first`). +# not a setting: a list short enough to run before the rest +RUN_FIRST = 5 + + +def _stem_key(path: str) -> str: + """A test file's directory and its name up to the first dot (`a.sql`, `a.expected`), a + dotfile's whole name (`.env`).""" + p = PurePosixPath(path) + return f"{p.parent}/{p.name.split('.', 1)[0] or p.name}" + + +def _test_groups(tests: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: + """The gate's rows as tests, each in the gate's order and the tests in the order of + their first rows: rows that share a run command are one test, and a row with none joins + the first test that holds a file of its directory and name (`_stem_key`, a case's + expected output beside its script), else the test of the command-less rows of that name. + Rows with different commands are never one test.""" + by_run: dict[str, list[int]] = {} + for i, r in enumerate(tests): + if r.get("run"): + by_run.setdefault(str(r["run"]), []).append(i) + groups = list(by_run.values()) + stems = [{_stem_key(str(tests[i]["test_path"])) for i in g} for g in groups] + for i, r in enumerate(tests): + if r.get("run"): + continue + stem = _stem_key(str(r["test_path"])) + at = next((k for k, held in enumerate(stems) if stem in held), None) + if at is None: + groups.append([i]) + stems.append({stem}) + else: + groups[at].append(i) + return [[tests[i] for i in sorted(g)] for g in sorted(groups, key=min)] + + +# Paths a listed test names in `test_paths`: one run command can hold a whole directory. +_PATHS_SHOWN = 5 + + +def run_first( + tests: list[dict[str, Any]], + *, + tests_total: int, + must_run_total: int, + tests_unnamed: int, +) -> dict[str, Any]: + """The first `RUN_FIRST` tests of a gate's `tests` rows (`_test_groups`), in the gate's + order: every `must_run` row first, the strongest evidence first. A test carries its + first row's path, `why`, `evidence` and `must_run`, and its run command; a test of + several files names the first `_PATHS_SHOWN` and counts them all. `left_out` counts the + gate's test files under no listed test, and `must_run_left_out` those of them that say + `must_run`; `tests_total`, `must_run_total` and `tests_unnamed` are the gate's counts of + the rows `tests` was cut from. A row past `tests` and a lead the gate cut are counted + whatever their run command, and the cut leads are a lower bound.""" + listed = _test_groups(tests)[:RUN_FIRST] + shown = [r for rows in listed for r in rows] + return { + "tests": [ + { + "test_path": rows[0]["test_path"], + "run": next((str(r["run"]) for r in rows if r.get("run")), ""), + "run_unknown": not any(r.get("run") for r in rows), + "why": rows[0]["why"], + "evidence": rows[0].get("evidence") or "", + "must_run": bool(rows[0].get("must_run")), + **( + { + "test_paths": [r["test_path"] for r in rows[:_PATHS_SHOWN]], + "test_paths_total": len(rows), + } + if len(rows) > 1 + else {} + ), + } + for rows in listed + ], + "left_out": tests_total + tests_unnamed - len(shown), + "must_run_left_out": must_run_total - sum(1 for r in shown if r.get("must_run")), + } + + def link_state(run: dict[str, Any] | None, linked: bool) -> str: """What the index knows of one definition's tests: what a verified coverage run measured of it when there is one (`executed`, `unexecuted`), else whether a call diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 5067e2482b..6599dbc314 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1661,7 +1661,16 @@ def revision_policy(update: str) -> str: "callers and fan-in; the registrations, factories, constructors and " "one-line definitions the PR adds that nothing else calls are counts " "in `collapsed`), " - "tests (coverage_claim per function and setting, its strongest tier " + "tests (first a run_first row: the first five tests code.test_gate " + "lists for the diff, must_run ones first, one per test with its why and " + "evidence, and `left_out` / `must_run_left_out` counting the test " + "files under none of them (code.test_gate lists up to 200 and counts " + "the leads it cuts), and `cut: true` when the gate did not read the " + "whole change, read a source file the index holds at another " + "revision, the drift read failed or the brief had no diff (it then " + "cannot tell deleted tests), its list and counts then of what it " + "read; a brief with no run_first row says nothing of them; then " + "coverage_claim per function and setting, its strongest tier " "and that tier's test paths — verdict uncovered | covered | " "partly_covered | unknown — " "plus the test file this change belongs in), settings (facts of " diff --git a/tests/unit/test_code_review_brief_no_groups.py b/tests/unit/test_code_review_brief_no_groups.py index 99222f2b0e..d1f3c6b435 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 = "779d8ac5bcd771bc0c1ef7ab9ae18e3446abfc2e436aabacf95ea1dfe5a420ef" +PAYLOAD_DIGEST = "aa4ad326558f0961437a8f966c423eec7d6c454b093aa4e637eedd26c616331d" ORG, NS = "clickhouse", "code-clickhouse" SHA = "1e93c0a25f177d3a971668e058745a6e8bfe3e2c" PARENT = "b41b780feecc85780bebca041acda03358719a79" @@ -225,6 +225,8 @@ async def _call(op: str, body: dict[str, Any]) -> dict[str, Any]: "tests_total": 2 if covered else 0, "epistemic": "lower_bound", } + if op == "code.test_gate": + return {"tests": [], "tests_total": 0, "must_run_total": 0, "tests_unnamed": 0} if op == "code.test_home": return { "verdict": "add_case_to", diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index bf1d7e6f2e..7c22f85d74 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -9,6 +9,7 @@ import asyncio import dataclasses import json +import re from datetime import UTC, datetime from typing import Any, ClassVar @@ -583,6 +584,50 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: "tests_total": 4523 if covered else 0, "epistemic": "lower_bound", } + if op == "code.test_gate": + # the gate's shape: the must_run row first, four leads, six more cut + lead = {"why": "test_map", "evidence": "test map", "run_unknown": False} + return { + "tests": [ + { + "test_path": "tests/integration/test_parts/test.py", + "why": "static_call", + "evidence": "test_load reaches the change in 1 hop(s)", + "run": "pytest tests/integration/test_parts", + "run_unknown": False, + "must_run": True, + }, + { + **lead, + "test_path": "tests/integration/test_parts/configs/parts.xml", + "run": "pytest tests/integration/test_parts", + "must_run": False, + }, + *( + { + **lead, + "test_path": f"tests/unit/test_{n}.py", + "run": f"pytest tests/unit/test_{n}.py", + "must_run": False, + } + for n in ("a", "b", "c") + ), + ], + "tests_total": 5, + "must_run_total": 1, + "tests_unnamed": 6, + "tests_capped": False, + # as the gate reads them: the files sent, then the files the diff changes on + # its new side (a deleted file has none) + "changed_files": list( + dict.fromkeys( + [ + *body["files"], + *re.findall(r"^\+\+\+ b/(\S+)$", body["diff"], flags=re.M), + ] + ) + )[:200], + } if op == "code.test_home": return { "verdict": "add_case_to", @@ -782,8 +827,39 @@ async def test_build_assembles_every_section_with_verdicts_and_decisions() -> No assert secs["symbols"]["verdict"] == "touched" and secs["symbols"]["causes"] == [ "treesitter_only" ] - # tests: a claim per symbol and per setting, then the home; Settings::dump is uncovered - kinds = [(r["kind"], r["subject"]) for r in secs["tests"]["rows"]] + # tests: the tests to run first, a claim per symbol and per setting, then the home; + # Settings::dump is uncovered + first = secs["tests"]["rows"][0] + assert first["kind"] == "run_first" and "cut" not in first + # the integration test's config is under its test: four tests, the six cut leads are + # left out + assert [t["test_path"] for t in first["tests"]] == [ + "tests/integration/test_parts/test.py", + "tests/unit/test_a.py", + "tests/unit/test_b.py", + "tests/unit/test_c.py", + ] + assert first["tests"][0] == { + "test_path": "tests/integration/test_parts/test.py", + "run": "pytest tests/integration/test_parts", + "run_unknown": False, + "why": "static_call", + "evidence": "test_load reaches the change in 1 hop(s)", + "must_run": True, + "test_paths": [ + "tests/integration/test_parts/test.py", + "tests/integration/test_parts/configs/parts.xml", + ], + "test_paths_total": 2, + } + assert first["left_out"] == 6 and first["must_run_left_out"] == 0 + gate_body = next(b for op, b in calls.calls if op == "code.test_gate") + # read from the merge commit, which the index holds, as impact reads it + assert ( + gate_body["diff"] == rb.reversed_diff(DIFF) + and "src/Core/Settings.cpp" in gate_body["files"] + ) + kinds = [(r["kind"], r.get("subject")) for r in secs["tests"]["rows"][1:]] assert ("symbol", "DB::MergeTreeData::loadDataParts") in kinds and ( "setting", "new_flag", @@ -792,7 +868,7 @@ async def test_build_assembles_every_section_with_verdicts_and_decisions() -> No assert secs["tests"]["verdict"] == "uncovered" # a claim row keeps its strongest tier and that tier's tests by path; the grep total # of every tier is not carried - claim = secs["tests"]["rows"][kinds.index(("symbol", "DB::MergeTreeData::loadDataParts"))] + claim = secs["tests"]["rows"][1:][kinds.index(("symbol", "DB::MergeTreeData::loadDataParts"))] assert claim["strongest_tier"] == "exact_scoped" and claim["tests_at_tier"] == 2 assert claim["tests"] == [ "tests/queries/0_stateless/02994_parts.sql", @@ -1008,9 +1084,15 @@ async def test_a_failing_op_fails_its_section_open_and_the_rest_stand() -> None: @pytest.mark.asyncio -async def test_the_test_home_decides_no_verdict() -> None: - """The test home is advice: a read of it that raised or was refused leaves a settled - brief settled, and one that raised keeps the brief unstored.""" +@pytest.mark.parametrize( + ("op", "kind", "cause"), + [("code.test_home", "home", "test_home"), ("code.test_gate", "run_first", "test_gate")], +) +async def test_the_test_home_and_the_tests_to_run_first_decide_no_verdict( + op: str, kind: str, cause: str +) -> None: + """The test home and the tests to run first are advice: a read of one that raised or was + refused leaves a settled brief settled, and one that raised keeps the brief unstored.""" from server.core.errors import ValidationError async def build(fail: set[str], error: type[Exception] = RuntimeError) -> dict[str, Any]: @@ -1024,12 +1106,196 @@ async def build(fail: set[str], error: type[Exception] = RuntimeError) -> dict[s base = await build(set()) assert rb.brief_verdict(base) == ("covered_no_gaps", []) - assert any(r["kind"] == "home" for r in base["tests"]["rows"]) - for error, failed in ((RuntimeError, ["tests:test_home:RuntimeError"]), (ValidationError, [])): - secs = await build({"code.test_home"}, error) + assert any(r["kind"] == kind for r in base["tests"]["rows"]) + for error, failed in ((RuntimeError, [f"tests:{cause}:RuntimeError"]), (ValidationError, [])): + secs = await build({op}, error) assert rb.brief_verdict(secs) == ("covered_no_gaps", []) assert rb.failed_reads(secs) == failed - assert not any(r["kind"] == "home" for r in secs["tests"]["rows"]) + assert not any(r["kind"] == kind for r in secs["tests"]["rows"]) + + +@pytest.mark.asyncio +async def test_a_drifted_source_file_or_a_failed_drift_read_marks_the_run_first_row_cut() -> None: + """The gate maps the diff's lines onto the rows the index holds: a changed source file + the index holds at another revision, or a drift read that failed, makes its list a cut + one; a drifted file of no source kind maps no line.""" + + async def first(inp: rb.BriefInputs) -> dict[str, Any]: + payload = await review_brief_build.build_brief( + inp, call=_Calls(), repo=_Repo(), tracker_rows=_tracker_served, now=_fixed_now + ) + return payload["sections"]["tests"]["rows"][0] + + assert "cut" not in await first(_inputs()) + src = dataclasses.replace(_inputs(), drifted=("src/Core/Settings.cpp",)) + assert (await first(src))["cut"] is True + failed = dataclasses.replace(_inputs(), drift_failed="drift:TimeoutError") + assert (await first(failed))["cut"] is True + doc = dataclasses.replace( + _inputs(), changed_paths=[*PATHS, "src/README.md"], drifted=("src/README.md",) + ) + assert "cut" not in await first(doc) + + +_OPEN = dataclasses.replace(_inputs(), open=True, head_sha="a" * 40) +_TEST_DIFF = "--- a/tests/unit/test_x.py\n+++ b/tests/unit/test_x.py\n@@ -1 +1 @@\n-a\n+b\n" +_DELETING = "--- a/tests/unit/test_x.py\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n" +_DELETED_ROW = {"test_path": "tests/unit/test_x.py", "why": "changed_test", "must_run": True} + + +async def _run_first_of( + call: Any, + inp: rb.BriefInputs = _OPEN, + *, + paths: list[str] | None = None, + diff: str = _TEST_DIFF, + moved: bool = False, +) -> dict[str, Any]: + """The `run_first` row of a tests section with no claim and no home.""" + sec = await review_brief_build._tests_section( + call, inp, [], [], [], paths=paths or [], diff=diff, moved=moved + ) + return dict(sec["rows"][0]) + + +def _answering(*, ahead: tuple[dict[str, Any], ...] = (), **gate: Any) -> Any: + """`_Calls` whose code.test_gate answer puts the rows `ahead` before its own `tests` + and then carries the fields `gate`.""" + calls = _Calls() + + async def answer(op: str, body: dict[str, Any]) -> Any: + out = await calls(op, body) + if op != "code.test_gate": + return out + return {**out, "tests": [*ahead, *out["tests"]], **gate} + + return answer + + +@pytest.mark.asyncio +async def test_the_tests_to_run_first_alone_leave_the_section_a_lower_bound() -> None: + """A PR with no claim and no home still names its tests to run first; the row says + nothing of what a claim read, so the section stays `lower_bound` with no verdict.""" + calls = _Calls() + out = await review_brief_build._tests_section( + calls, _OPEN, [], [], [], paths=["tests/unit/test_x.py"], diff=_TEST_DIFF, moved=False + ) + assert [r["kind"] for r in out["rows"]] == ["run_first"] + assert out["epistemic"] == "lower_bound" and out["verdict"] == "no_subjects" + assert "cut" not in out["rows"][0] + # the gate reads the diff it is handed and all its rows + body = next(b for op, b in calls.calls if op == "code.test_gate") + assert body["diff"] == _TEST_DIFF and body["limit"] == 200 + + +@pytest.mark.asyncio +async def test_an_open_prs_diff_reaches_the_gate_as_written() -> None: + """The index holds an open PR's base, the diff's old side: the gate reads the diff as + written, where a merged PR's is reversed.""" + calls = _Calls() + await review_brief_build.build_brief( + _OPEN, call=calls, repo=_Repo(), tracker_rows=_tracker_served, now=_fixed_now + ) + assert next(b for op, b in calls.calls if op == "code.test_gate")["diff"] == DIFF + + +@pytest.mark.asyncio +async def test_the_tests_to_run_first_say_cut_when_the_gate_read_a_cut_change() -> None: + """A changed file the gate did not read (past its file cap and outside the diff, a file + the diff deletes there, or past the 200 paths it reads), a diff past its cap, a gate + that cut its own walk, and a changed source file read on another revision each say the + list and counts are of a cut read. A gate that held more rows than it returned is no + cut read, and a file past the cap whose hunks the diff carries is read.""" + calls = _Calls() + wide = [f"tests/unit/test_{i}.py" for i in range(51)] + gone = "--- a/src/a.py\n+++ /dev/null\n@@ -1 +0,0 @@\n-x\n" + many = [f"tests/unit/test_{i}.py" for i in range(201)] + every = "".join(f"--- a/{p}\n+++ b/{p}\n@@ -1 +1 @@\n-a\n+b\n" for p in many) + for paths, diff in ( + (wide, _TEST_DIFF), + (many, every), + ([*wide[:50], "src/a.py"], _TEST_DIFF + gone), + ([], _TEST_DIFF + "+" * rb.MAX_DIFF_CHARS), + ): + assert (await _run_first_of(calls, paths=paths, diff=diff))["cut"] is True + assert (await _run_first_of(_answering(causes=["truncated"])))["cut"] is True + assert (await _run_first_of(calls, moved=True))["cut"] is True + # a brief built from its changed paths alone cannot tell the files the PR deletes + unread = dataclasses.replace(_inputs(), diff="") + assert (await _run_first_of(calls, unread, paths=["src/a.py"], diff=""))["cut"] is True + assert "cut" not in await _run_first_of(_answering(tests_capped=True)) + read = await _run_first_of(calls, paths=[*wide[:50], "tests/unit/test_x.py"]) + assert "cut" not in read + + +@pytest.mark.asyncio +async def test_a_test_file_the_pr_deletes_is_neither_listed_nor_counted() -> None: + """Whether git prints the deletion with a `+++ /dev/null` side, with only `deleted file + mode` (a binary or an empty file), or as a rename away from the path; a gate whose rows + are all deleted files still counts its other tests.""" + bare = "diff --git a/tests/unit/test_x.py b/tests/unit/test_x.py\ndeleted file mode 100644\n" + renamed = ( + "diff --git a/tests/unit/test_x.py b/tests/unit/test_y.py\nsimilarity index 100%\n" + "rename from tests/unit/test_x.py\nrename to tests/unit/test_y.py\n" + ) + with_deleted = _answering(ahead=(_DELETED_ROW,), tests_total=6, must_run_total=2) + for deletion in (_DELETING, bare, renamed): + row = await _run_first_of(with_deleted, dataclasses.replace(_OPEN, diff=deletion)) + assert "tests/unit/test_x.py" not in [t["test_path"] for t in row["tests"]] + assert row["left_out"] == 6 and row["must_run_left_out"] == 0 + only_deleted = _answering( + tests=[_DELETED_ROW], tests_total=4, must_run_total=2, tests_unnamed=0 + ) + row = await _run_first_of(only_deleted, dataclasses.replace(_OPEN, diff=_DELETING)) + assert row["tests"] == [] and row["left_out"] == 3 and row["must_run_left_out"] == 1 + + +@pytest.mark.asyncio +async def test_a_merged_prs_deleted_tests_are_read_off_its_own_diff() -> None: + """A merged PR's gate reads the reversed diff, where a deletion git printed with no + `deleted file mode` line reads as a change: the deleted files come from the PR's own + diff, so its deleted test is neither listed nor counted.""" + merged = dataclasses.replace(_inputs(), diff=_DELETING) + row = await _run_first_of( + _answering(ahead=(_DELETED_ROW,), tests_total=6, must_run_total=2), + merged, + diff=rb.reversed_diff(_DELETING), + ) + assert "tests/unit/test_x.py" not in [t["test_path"] for t in row["tests"]] + assert row["left_out"] == 6 and row["must_run_left_out"] == 0 + + +@pytest.mark.asyncio +async def test_a_gate_that_names_no_test_but_counts_cut_leads_gives_a_row_of_the_count() -> None: + row = await _run_first_of( + _answering(tests=[], tests_total=0, must_run_total=0, tests_unnamed=7) + ) + assert row["tests"] == [] and row["left_out"] == 7 + + +@pytest.mark.asyncio +async def test_a_gate_that_lists_and_counts_no_test_leaves_the_row_out() -> None: + """Nor does a gate whose only rows are files the PR deletes and that counts no other.""" + empty = _answering(tests=[], tests_total=0, must_run_total=0, tests_unnamed=0) + only_gone = _answering(tests=[_DELETED_ROW], tests_total=1, must_run_total=1, tests_unnamed=0) + for call, inp in ((empty, _OPEN), (only_gone, dataclasses.replace(_OPEN, diff=_DELETING))): + sec = await review_brief_build._tests_section( + call, inp, [], [], [], paths=[], diff=_TEST_DIFF, moved=False + ) + assert [r for r in sec["rows"] if r.get("kind") == "run_first"] == [] + + +@pytest.mark.asyncio +async def test_a_token_budget_trims_the_tests_to_run_first_last() -> None: + """`apply_budget` drops a section's rows from its end, so the first row goes last.""" + calls = _Calls() + sec = await review_brief_build._tests_section( + calls, _OPEN, ["DB::f", "DB::g"], [], [], paths=[], diff=_TEST_DIFF, moved=False + ) + assert sec["rows"][0]["kind"] == "run_first" and len(sec["rows"]) > 1 + first = rb.estimate_tokens(sec["rows"][:1]) + trimmed, _ = rb.apply_budget({"tests": sec}, ["tests"], first) + assert [r["kind"] for r in trimmed["tests"]["rows"]] == ["run_first"] @pytest.mark.asyncio @@ -1093,7 +1359,7 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: return {"verdict": "covered_by", "strongest_tier": "exact", "tests": []} if op != "code.impact": return await super().__call__(op, body) - assert len(body["files"]) == rb.IMPACT_SEED_FILES + assert len(body["files"]) == rb.SEED_FILES assert len(body["diff"]) == rb.MAX_DIFF_CHARS return { "touched_symbols": [], @@ -3552,6 +3818,7 @@ async def run(git_dir: str, *args: str) -> str: ("symbol_stats", "code_index: fan_in_unread (TimeoutError)"), ("code.coverage_claim", "code.review_brief: coverage_claim_failed (RuntimeError)"), ("code.test_home", "code.review_brief: test_home_failed (RuntimeError)"), + ("code.test_gate", "code.review_brief: test_gate_failed (RuntimeError)"), ("code.setting_facts", "code.review_brief: setting_facts_failed (RuntimeError)"), ("code.symbol_history", "code.review_brief: symbol_history_failed (RuntimeError)"), ("code.blame_range", "code.review_brief: blame_range_failed (RuntimeError)"), diff --git a/tests/unit/test_code_test_gate.py b/tests/unit/test_code_test_gate.py index ae9031cc42..c7fbd39077 100644 --- a/tests/unit/test_code_test_gate.py +++ b/tests/unit/test_code_test_gate.py @@ -219,6 +219,119 @@ def test_each_row_says_whether_its_test_is_tied_to_the_change_or_to_its_file() - assert [(r["why"], r["must_run"]) for r in few.tests] == [("file_neighbor", False)] +def _gate_row(path: str, why: str, must_run: bool) -> dict[str, Any]: + run, unknown = tg.run_command_for(path) + return { + "test_path": path, + "why": why, + "evidence": f"{why} evidence", + "run": run, + "run_unknown": unknown, + "must_run": must_run, + } + + +def test_run_first_lists_one_entry_per_test_in_the_gates_order() -> None: + """A case's script and its expected output are one test, as are the files of one run + command, under the stronger row; the list stops at `RUN_FIRST` and counts the test + files it leaves out, the gate's cut leads and the rows it did not return among them.""" + rows = [ + _gate_row("tests/cases/a.expected", "changed_test", True), + {**_gate_row("tests/cases/a.sh", "changed_test", True), "run": "sh tests/cases/a.sh"}, + _gate_row("src/x/tests/check_x.cpp", "static_call", True), + _gate_row("pkg/store/store_test.go", "coverage", True), + _gate_row("pkg/store/load_test.go", "test_map", False), + _gate_row("tests/unit/test_b.py", "stem_partner", False), + _gate_row("tests/unit/test_c.py", "test_map", False), + _gate_row("tests/unit/test_d.py", "test_map", False), + _gate_row("tests/unit/test_e.py", "test_map", False), + ] + out = tg.run_first(rows, tests_total=9, must_run_total=4, tests_unnamed=3) + assert [(t["test_path"], t["why"], t["must_run"]) for t in out["tests"]] == [ + ("tests/cases/a.expected", "changed_test", True), + ("src/x/tests/check_x.cpp", "static_call", True), + ("pkg/store/store_test.go", "coverage", True), + ("tests/unit/test_b.py", "stem_partner", False), + ("tests/unit/test_c.py", "test_map", False), + ] + # the expected output's test is run by its script's command + assert out["tests"][0]["test_paths"] == ["tests/cases/a.expected", "tests/cases/a.sh"] + assert out["tests"][0]["test_paths_total"] == 2 + assert out["tests"][0]["run"] == "sh tests/cases/a.sh" and not out["tests"][0]["run_unknown"] + assert out["tests"][2]["run"] == "go test ./pkg/store/" and out["tests"][2]["test_paths"] == [ + "pkg/store/store_test.go", + "pkg/store/load_test.go", + ] + # a test of one file names no `test_paths` + assert "test_paths" not in out["tests"][1] and out["tests"][1]["run_unknown"] + # 7 of the 9 rows are listed; the 3 cut leads are left out too + assert out["left_out"] == 5 and out["must_run_left_out"] == 0 + # with more must-run tests than the list holds, the rest are counted + must = [_gate_row(f"pkg/m{i}/m_test.go", "coverage", True) for i in range(7)] + many = tg.run_first(must, tests_total=7, must_run_total=7, tests_unnamed=0) + assert many["left_out"] == 2 and many["must_run_left_out"] == 2 + # a gate cut by its own limit: the rows it did not return are left out too + cut = tg.run_first(rows[:2], tests_total=9, must_run_total=4, tests_unnamed=3) + assert len(cut["tests"]) == 1 and cut["left_out"] == 10 and cut["must_run_left_out"] == 2 + + +def test_run_first_joins_a_command_less_file_to_the_test_of_its_name() -> None: + """A command-less row joins the test that runs a file of its name, wherever that file + stands, and a row joins the test of its run command before one of its name; + command-less files of one name with no test of a command are one test of their own.""" + order = [ + _gate_row("tests/cases/a.expected", "changed_test", True), + {**_gate_row("tests/cases/b.sh", "coverage", True), "run": "run-cases tests/cases"}, + {**_gate_row("tests/cases/a.sh", "static_call", True), "run": "run-cases tests/cases"}, + ] + grouped = tg.run_first(order, tests_total=3, must_run_total=3, tests_unnamed=0)["tests"] + assert [(t["test_paths"], t["run"], t["why"]) for t in grouped] == [ + ( + ["tests/cases/a.expected", "tests/cases/b.sh", "tests/cases/a.sh"], + "run-cases tests/cases", + "changed_test", + ) + ] + pair = [ + _gate_row("tests/cases/c.in", "test_map", False), + _gate_row("tests/cases/c.out", "test_map", False), + ] + alone = tg.run_first(pair, tests_total=2, must_run_total=0, tests_unnamed=0)["tests"] + assert [(t["test_paths"], t["run_unknown"]) for t in alone] == [ + (["tests/cases/c.in", "tests/cases/c.out"], True) + ] + + +def test_run_first_counts_a_row_past_the_gates_tests_whatever_its_command() -> None: + """The gate's counts are all the brief has of a row it did not return.""" + pkg = [_gate_row(f"pkg/a/f{i}_test.go", "changed_test", True) for i in range(3)] + past = tg.run_first(pkg, tests_total=5, must_run_total=5, tests_unnamed=0) + assert len(past["tests"]) == 1 and past["left_out"] == 2 and past["must_run_left_out"] == 2 + + +def test_run_first_names_five_paths_of_a_test_and_counts_all() -> None: + many = [_gate_row(f"pkg/b/f{i}_test.go", "coverage", True) for i in range(7)] + one_test = tg.run_first(many, tests_total=7, must_run_total=7, tests_unnamed=0)["tests"] + assert len(one_test[0]["test_paths"]) == 5 and one_test[0]["test_paths_total"] == 7 + + +def test_run_first_keeps_tests_of_one_name_with_different_commands_apart() -> None: + pair = [ + _gate_row("web/a.test.ts", "coverage", True), + _gate_row("web/a.spec.ts", "coverage", True), + ] + assert len(tg.run_first(pair, tests_total=2, must_run_total=2, tests_unnamed=0)["tests"]) == 2 + + +def test_run_first_keeps_dotfiles_of_one_directory_apart() -> None: + """A dotfile's name is its whole name, so `.env` and `.npmrc` share none.""" + dots = [ + {"test_path": "fixtures/.env", "why": "changed_test", "must_run": True, "run": ""}, + {"test_path": "fixtures/.npmrc", "why": "changed_test", "must_run": True, "run": ""}, + ] + assert len(tg.run_first(dots, tests_total=2, must_run_total=2, tests_unnamed=0)["tests"]) == 2 + + def test_a_one_hop_row_whose_test_uses_no_touched_definition_is_a_lead() -> None: """A test double that overrides the change and a call of the function a touched nested function is defined in are one hop away and not `direct`: they come after the direct diff --git a/tests/unit/test_review_brief_rationale.py b/tests/unit/test_review_brief_rationale.py index 61a250a476..9e062109fd 100644 --- a/tests/unit/test_review_brief_rationale.py +++ b/tests/unit/test_review_brief_rationale.py @@ -764,15 +764,20 @@ async def _failing_git(*args: Any, **kw: Any) -> Any: assert await gitrepo.run_bounded("/m.git", "diff", max_bytes=100) == ("+partial", False) -def test_the_impact_seed_count_is_code_impacts_own_file_cap() -> None: +def test_the_seed_and_gate_caps_are_code_impacts_and_code_test_gates_own() -> None: + """The brief cuts what it sends to the reads' own input caps: past one, the read is + refused and the brief loses what it would have named.""" from server.code.api.models_symbol import CodeImpactInput + from server.code.api.models_testing import CodeTestGateInput - caps = [ - m.max_length - for m in CodeImpactInput.model_fields["files"].metadata - if hasattr(m, "max_length") - ] - assert caps == [rb.IMPACT_SEED_FILES] + def bound(model: Any, field: str, attr: str) -> list[Any]: + return [getattr(m, attr) for m in model.model_fields[field].metadata if hasattr(m, attr)] + + assert bound(CodeImpactInput, "files", "max_length") == [rb.SEED_FILES] + assert bound(CodeImpactInput, "diff", "max_length") == [rb.MAX_DIFF_CHARS] + assert bound(CodeTestGateInput, "files", "max_length") == [rb.SEED_FILES] + assert bound(CodeTestGateInput, "diff", "max_length") == [rb.MAX_DIFF_CHARS] + assert bound(CodeTestGateInput, "limit", "le") == [rb.GATE_ROWS] @pytest.mark.asyncio