diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 43eab9d3836..3bb5868a892 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -41,7 +41,23 @@ jobs: MAX_CHANGES = 1000 MAX_BYTES = 1024 * 1024 MAX_FINDINGS = 20 + # The Compare API returns at most 300 files, even with commit pagination. + COMPARE_FILE_LIMIT = 300 + MAX_COMPARE_BYTES = 8 * 1024 * 1024 SEVERITIES = {"low", "moderate", "high", "critical"} + SNAPSHOT_WORKFLOWS = { + ".github/workflows/maven-dependency-graph.yml", + ".github/workflows/rust-dependency-graph.yml", + } + EXPRESSION = "$" + "{{ " + PR_EVENT = "github.event_name == 'pull_request'" + CONCURRENCY_LINES = [ + "+concurrency:", + "+ group: " + EXPRESSION + "github.workflow }}-" + EXPRESSION + + PR_EVENT + " && github.ref || github.sha }}", + "+ cancel-in-progress: " + EXPRESSION + PR_EVENT + " }}", + "+", + ] class ReviewError(ValueError): @@ -53,17 +69,20 @@ jobs: return None - def snapshot_complete(value): + def missing_head_snapshot(value, head): if not value: - return + return False + if len(value) > 8192: + raise ReviewError("Snapshot warning header exceeds its limit") try: - if len(value) > 8192: - raise ReviewError("Snapshot warning header exceeds its limit") - warnings = json.loads(base64.b64decode(value, validate=True)) - except (ValueError, binascii.Error) as error: + warning = base64.b64decode(value, validate=True) + except binascii.Error as error: raise ReviewError("Invalid dependency snapshot warning header") from error - if warnings != []: - raise ReviewError("Dependency snapshots are incomplete") + if warning == b"[]": + return False + if warning == f"No snapshots were found for the head SHA {head}.".encode(): + return True + raise ReviewError("Dependency snapshots are incomplete") def next_page(value, endpoint, canonical_endpoint, page): @@ -87,7 +106,7 @@ jobs: return True - def read_page(opener, url, token): + def read_response(opener, url, token, max_bytes=MAX_BYTES): request = urllib.request.Request( url, headers={ @@ -100,21 +119,72 @@ jobs: with opener.open(request, timeout=20) as response: if response.status != 200: raise ReviewError("Dependency review API did not return HTTP 200") - snapshot_complete( - response.headers.get("x-github-dependency-graph-snapshot-warnings", "") - ) - body = response.read(MAX_BYTES + 1) - link = response.headers.get("Link", "") + body = response.read(max_bytes + 1) + headers = response.headers except urllib.error.HTTPError as error: raise ReviewError(f"Dependency review API returned HTTP {error.code}") from error except (urllib.error.URLError, TimeoutError, http.client.HTTPException) as error: raise ReviewError("Dependency review API request failed") from error - if len(body) > MAX_BYTES: + if len(body) > max_bytes: raise ReviewError("Dependency review response exceeds its limit") - changes = json.loads(body) + return json.loads(body), headers + + + def read_page(opener, url, token, head): + changes, headers = read_response(opener, url, token) if not isinstance(changes, list): raise ReviewError("Invalid dependency review response") - return changes, link + missing = missing_head_snapshot( + headers.get("x-github-dependency-graph-snapshot-warnings", ""), head + ) + return changes, headers.get("Link", ""), missing + + + def scheduler_only(file): + if file["status"] != "modified" or file.get("deletions") != 0: + return False + patch = file.get("patch") + if not isinstance(patch, str) or file.get("additions") != len(CONCURRENCY_LINES): + return False + added = [line for line in patch.splitlines() if line.startswith("+")] + return added == CONCURRENCY_LINES and "\n".join(added + [" permissions:"]) in patch + + + def affects_snapshot(path, file): + parts = path.split("/") + if path in SNAPSHOT_WORKFLOWS: + return not scheduler_only(file) + if ".cargo" in parts or ".mvn" in parts or parts[-1] in {"Cargo.toml", "Cargo.lock", "pom.xml"}: + return True + if path.startswith("sdk/java/"): + # Maven resolves these graphs from the POMs and build configuration. + return not ("src" in parts and path.endswith(".java")) + # Python loads the Rust workflow's modules from the checkout root as well. + module = parts[0].partition(".")[0] + if module in sys.stdlib_module_names or module in {"sitecustomize", "usercustomize"}: + return True + # Rust runs the converter and its tests before publishing the resolved graph. + return path.startswith(("sdk/rust/", ".github/scripts/")) + + + def check_snapshot_inputs(repository_url, base, head, token, opener): + data, _ = read_response( + opener, f"{repository_url}/compare/{base}...{head}?per_page=1", token, MAX_COMPARE_BYTES + ) + if not isinstance(data, dict) or not isinstance(data.get("files"), list): + raise ReviewError("Cannot verify the dependency snapshot inputs") + if len(data["files"]) >= COMPARE_FILE_LIMIT: + raise ReviewError("Too many changed files to verify the dependency snapshot inputs") + merge_base = data["merge_base_commit"]["sha"] + if not isinstance(merge_base, str) or not re.fullmatch(r"[0-9a-f]{40}", merge_base): + raise ReviewError("Invalid merge base for dependency snapshot comparison") + for file in data["files"]: + paths = [file["filename"]] + if file["status"] == "renamed": + paths.append(file["previous_filename"]) + if any(affects_snapshot(path, file) for path in paths): + raise ReviewError("Dependency snapshots are incomplete and snapshot inputs changed") + return merge_base def blocked_changes(change): @@ -154,11 +224,16 @@ jobs: if not all(re.fullmatch(r"[0-9a-f]{40}", sha) for sha in (base, head)) or not token: raise ReviewError("Missing token or invalid commit identities") comparison = f"/dependency-graph/compare/{base}...{head}" - endpoint = f"https://api.github.com/repos/{repository}{comparison}" + repository_url = f"https://api.github.com/repos/{repository}" + endpoint = repository_url + comparison canonical_endpoint = f"https://api.github.com/repositories/{repository_id}{comparison}" findings, blocked, total = [], 0, 0 + head_snapshot_missing = False for page in range(1, MAX_PAGES + 1): - changes, link = read_page(opener, f"{endpoint}?per_page={PAGE_SIZE}&page={page}", token) + changes, link, missing = read_page( + opener, f"{endpoint}?per_page={PAGE_SIZE}&page={page}", token, head + ) + head_snapshot_missing = head_snapshot_missing or missing total += len(changes) if total > MAX_CHANGES: raise ReviewError( @@ -169,7 +244,13 @@ jobs: blocked += len(matches) findings.extend(matches[: MAX_FINDINGS - len(findings)]) if not next_page(link, endpoint, canonical_endpoint, page): - return {"changes": total, "blocked_advisories": blocked, "findings": findings} + result = {"changes": total, "blocked_advisories": blocked, "findings": findings} + if head_snapshot_missing: + merge_base = check_snapshot_inputs(repository_url, base, head, token, opener) + if merge_base != base: + check_snapshot_inputs(repository_url, merge_base, base, token, opener) + result["snapshot_inputs"] = "unchanged" + return result raise ReviewError("Dependency changes exceed the page limit; review is incomplete") diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 13f5aa785b1..2a41bf209f0 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -668,6 +668,9 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | `LOOM_CODE_UNIT_RISK_MAX_AGE_S` | `int` | `864000` | | Age (seconds) past which a risk row is stale and annotated live; must exceed the weekly pass interval. | | `LOOM_CODE_SEARCH_BODIES_DEFAULT` | `'auto' \| 'none'` | `'auto'` | | code.search `bodies` when the request omits it: "auto" fills bodies into the budget; "none" serves handles only. | | `LOOM_CODE_SEARCH_TOKEN_BUDGET` | `int` | `0` | | code.search response budget in tokens when the request omits token_budget; 0 = unlimited. An explicit request budget overrides this default. | +| `LOOM_CODE_SEARCH_PLACES_TOKEN_BUDGET` | `int` | `600` | | Token target for MCP search places when the request omits token_budget. A lone place or cursor page can exceed it. 0 = unlimited. | +| `LOOM_CODE_SEARCH_PLACES_SOURCE_MAX_LINES` | `int` | `30` | | Maximum lines in the full body of the leading search place. 0 = omit the full body. | +| `LOOM_CODE_SEARCH_PLACES_QUERY_MAX_WORDS` | `int` | `32` | | Maximum distinct query words used to select matching lines in search places. | | `LOOM_CODE_SEARCH_MEMO_ENABLED` | `bool` | `True` | | Memoise served code.search responses per (org, namespace, request shape) in loom.code_search_memo and replay within the TTL (route "+memo"); `fresh=true` bypasses it. | | `LOOM_CODE_SEARCH_MEMO_TTL_S` | `int` | `1800` | | Seconds a memoised response, and a cursor's stored pool, stay replayable. | | `LOOM_CODE_SEARCH_MEMO_MAX_PAYLOAD_BYTES` | `int` | `200000` | | Max bytes of a response the memo stores; a larger one is not memoised. 0 = no cap. | diff --git a/loom.example.yaml b/loom.example.yaml index e22c70a7608..8fb1164ffa6 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -2045,6 +2045,18 @@ settings: # unlimited. An explicit request budget overrides this default. [restart] # code_search_token_budget: 0 + # Token target for MCP search places when the request omits token_budget. A lone place + # or cursor page can exceed it. 0 = unlimited. [restart] + # code_search_places_token_budget: 600 + + # Maximum lines in the full body of the leading search place. 0 = omit the full body. + # [restart] + # code_search_places_source_max_lines: 30 + + # Maximum distinct query words used to select matching lines in search places. + # [restart] + # code_search_places_query_max_words: 32 + # Memoise served code.search responses per (org, namespace, request shape) in # loom.code_search_memo and replay within the TTL (route "+memo"); `fresh=true` # bypasses it. [restart] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 17251e17800..ce92f9c639e 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -2189,6 +2189,24 @@ "type": "string", "description": "code.search's listwise pick (a request's `rerank: \"builtin:pick\"`): for an issue-shaped query it reads one line for each of the first 100 ranked units and names the definitions a fix changes, with how sure it is. The provider's smallest model is the one measured. \"\" = off: such a request keeps the plain ranking." }, + "code_search_places_query_max_words": { + "default": 32, + "minimum": 1, + "type": "integer", + "description": "Maximum distinct query words used to select matching lines in search places." + }, + "code_search_places_source_max_lines": { + "default": 30, + "minimum": 0, + "type": "integer", + "description": "Maximum lines in the full body of the leading search place. 0 = omit the full body." + }, + "code_search_places_token_budget": { + "default": 600, + "minimum": 0, + "type": "integer", + "description": "Token target for MCP search places when the request omits token_budget. A lone place or cursor page can exceed it. 0 = unlimited." + }, "code_search_pr_leg": { "default": "issue", "enum": [ diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 588ab54218e..1a6928107c8 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1692,6 +1692,14 @@ def _check_git_proxy(self) -> CodeSettings: # code.search response budget in tokens when the request omits token_budget; # 0 = unlimited. An explicit request budget overrides this default. code_search_token_budget: int = Field(default=0, ge=0) + # Token target for MCP search places when the request omits token_budget. + # A lone place or cursor page can exceed it. 0 = unlimited. + code_search_places_token_budget: int = Field(default=600, ge=0) + # Maximum lines in the full body of the leading search place. + # 0 = omit the full body. + code_search_places_source_max_lines: int = Field(default=30, ge=0) + # Maximum distinct query words used to select matching lines in search places. + code_search_places_query_max_words: int = Field(default=32, ge=1) # Memoise served code.search responses per (org, namespace, request shape) # in loom.code_search_memo and replay within the TTL (route "+memo"); # `fresh=true` bypasses it. diff --git a/server/transport/code_lean.py b/server/transport/code_lean.py index 63af9f9dcf6..284fca2457f 100644 --- a/server/transport/code_lean.py +++ b/server/transport/code_lean.py @@ -631,14 +631,10 @@ def _lean_search(out: dict[str, Any]) -> None: ) PLACE_MATCHING_LINES = 2 PLACE_LINE_CHARS = 120 -# What the places of one reply may cost by `estimate_json_tokens`; a call's own -# `token_budget` replaces it (0 = no limit). -PLACES_TOKEN_BUDGET = 600 # The first place carries its source when no other result competes with it (it is # the only one, or its score is this many times the second's) and the source is # short: a body costs its lines on every later request, a missing one a read. TOP_SOURCE_LEAD = 2.0 -TOP_SOURCE_MAX_LINES = 30 _QUERY_WORD = re.compile(r"\w{3,}") # A three-letter word is common inside longer ones (`set` in `offset`, `for` in # `format`): it matches a whole word or one part of an identifier (`set_quota`, @@ -648,8 +644,6 @@ def _lean_search(out: dict[str, Any]) -> None: # A line the chunker wrote, not source: a continued piece's header, an elided body, # a window's pointer to the next, after the language's comment leader if it has one. _CHUNK_MARKER = re.compile(r"(?:\S+ )?… (?:continued |body elided )") -# A pasted issue has thousands of words: the longest are the identifiers. -_QUERY_WORDS_MAX = 32 # A leg that proposes a unit neither content leg ranked. _VIA_REASON = {"symbol": "exact name", "definition": "named in the query"} # What `_compact_as_of` keeps of a fresh index. @@ -669,7 +663,9 @@ def _source_lines(row: dict[str, Any]) -> tuple[list[str], int]: def _query_words(query: Any) -> list[str]: words = {word.lower() for word in _QUERY_WORD.findall(str(query or ""))} - return sorted(words, key=lambda word: (-len(word), word))[:_QUERY_WORDS_MAX] + return sorted(words, key=lambda word: (-len(word), word))[ + : settings.code_search_places_query_max_words + ] def _matching_lines(row: dict[str, Any], words: list[str]) -> list[str]: @@ -703,7 +699,7 @@ def _place_reason(row: dict[str, Any]) -> str: def _top_source(rows: list[dict[str, Any]]) -> bool: lines, first = _source_lines(rows[0]) - if not first or len(lines) > TOP_SOURCE_MAX_LINES: + if not first or len(lines) > settings.code_search_places_source_max_lines: return False if len(rows) == 1: return True @@ -727,7 +723,7 @@ def _places_budget(arguments: dict[str, Any]) -> int: try: return max(int(arguments["token_budget"]), 0) except (KeyError, TypeError, ValueError): - return PLACES_TOKEN_BUDGET + return settings.code_search_places_token_budget def _search_places(out: dict[str, Any], served: Any, arguments: dict[str, Any]) -> None: diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 5df88fecbf1..3c45cfa2d05 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -387,6 +387,9 @@ "code_search_memo_ttl_s": 1800, "code_search_pattern_max_files": 1500, "code_search_pick_model": "", + "code_search_places_query_max_words": 32, + "code_search_places_source_max_lines": 30, + "code_search_places_token_budget": 600, "code_search_pr_leg": "issue", "code_search_pr_leg_cap": 0.5, "code_search_pr_leg_max_files": 10, diff --git a/tests/unit/test_code_search_places.py b/tests/unit/test_code_search_places.py index 71d95b11969..22e81d1f804 100644 --- a/tests/unit/test_code_search_places.py +++ b/tests/unit/test_code_search_places.py @@ -182,7 +182,7 @@ def test_places_fit_the_budget_and_a_call_can_set_its_own() -> None: query = {"query": "quota usage limit of an account", "top_k": 25} out = lean_code("code.search", {**_reply(rows), "has_more": False}, query) places = out["results"] - assert estimate_json_tokens(places) <= code_lean.PLACES_TOKEN_BUDGET + assert estimate_json_tokens(places) <= settings.code_search_places_token_budget assert 1 < len(places) < 25 and out["has_more"] is True assert [row["path"] for row in places] == [row["path"] for row in rows[: len(places)]] assert not any("lines" in row for row in places), "lines leave before places do" @@ -244,6 +244,22 @@ def test_a_short_word_matches_a_whole_word_or_identifier_part_not_inside_a_word( assert longer["results"][0]["lines"] == ["14: free_symbols = offset"] +def test_search_places_limit_the_query_words_used_for_matching( + monkeypatch: pytest.MonkeyPatch, +) -> None: + rows = [_unit("a.py", "cache = {}\nreturn relationship\n"), _unit("b.py", "x = 1\n")] + query = {"query": "cache relationship"} + assert lean_code("code.search", _reply(rows), query)["results"][0]["lines"] == [ + "10: cache = {}", + "11: return relationship", + ] + + monkeypatch.setattr(settings, "code_search_places_query_max_words", 1) + assert lean_code("code.search", _reply(rows), query)["results"][0]["lines"] == [ + "11: return relationship", + ] + + def test_the_first_place_carries_short_source_only_when_nothing_competes() -> None: query = {"query": "save"} alone = lean_code("code.search", _reply([_unit("a.py", SAVE, via="symbol")]), query) @@ -264,7 +280,7 @@ def test_the_first_place_carries_short_source_only_when_nothing_competes() -> No first, runner_up = lean_code("code.search", _reply(rows), query)["results"] assert ("body" in first) is has_source and ("lines" in first) is not has_source assert "body" not in runner_up - long = _unit("a.py", SAVE * (code_lean.TOP_SOURCE_MAX_LINES // 5 + 1)) + long = _unit("a.py", SAVE * (settings.code_search_places_source_max_lines // 5 + 1)) assert "body" not in lean_code("code.search", _reply([long]), query)["results"][0] # two namespaces rank on separate scales: a score lead across them is no lead rows = [_unit("a.py", SAVE, namespace="code-a"), _unit("b.py", SAVE, score=0.01)] diff --git a/tests/unit/test_dependency_review_workflow.py b/tests/unit/test_dependency_review_workflow.py index dcb4731d1c3..0c93f8d0a41 100644 --- a/tests/unit/test_dependency_review_workflow.py +++ b/tests/unit/test_dependency_review_workflow.py @@ -80,6 +80,23 @@ def review(*responses): return POLICY.review(REPOSITORY, BASE, HEAD, "test-token", Opener(*responses), REPOSITORY_ID) +def missing_head(data): + warning = f"No snapshots were found for the head SHA {HEAD}.".encode() + return Response( + data, + headers={"x-github-dependency-graph-snapshot-warnings": base64.b64encode(warning).decode()}, + ) + + +def comparison(paths, *, merge_base=BASE): + return Response( + { + "merge_base_commit": {"sha": merge_base}, + "files": [{"filename": path, "status": "modified"} for path in paths], + } + ) + + class DependencyReviewTests(unittest.TestCase): def test_added_high_and_critical_fail_but_lower_and_removed_pass(self): result = review( @@ -149,6 +166,88 @@ def test_incomplete_or_malformed_snapshots_fail(self): with self.assertRaises(POLICY.ReviewError): review(Response([], headers={"x-github-dependency-graph-snapshot-warnings": "%%%"})) + def test_missing_head_snapshot_checks_advisories_when_inputs_are_unchanged(self): + opener = Opener( + missing_head([change()]), + comparison(["frontend/src/example.ts", "sdk/java/src/main/java/example.java"]), + ) + result = POLICY.review(REPOSITORY, BASE, HEAD, "test-token", opener, REPOSITORY_ID) + self.assertEqual(result["blocked_advisories"], 1) + self.assertEqual( + opener.requests[1][0].full_url, + f"https://api.github.com/repos/{REPOSITORY}/compare/{BASE}...{HEAD}?per_page=1", + ) + + def test_missing_snapshot_requires_a_complete_diff_on_both_sides(self): + with self.assertRaises(POLICY.ReviewError): + review(missing_head([]), comparison(["docs/example.md"] * 300)) + with self.assertRaises(POLICY.ReviewError): + review( + missing_head([]), + comparison(["docs/example.md"], merge_base="c" * 40), + comparison(["sdk/rust/Cargo.toml"], merge_base="c" * 40), + ) + self.assertEqual( + review( + missing_head([]), + comparison(["docs/example.md"], merge_base="c" * 40), + comparison(["README.md"], merge_base="c" * 40), + )["blocked_advisories"], + 0, + ) + + def test_missing_snapshot_refuses_modified_build_inputs(self): + for path in ( + "sdk/java/pom.xml", + ".mvn/maven.config", + ".cargo/config.toml", + "sdk/rust/src/lib.rs", + ".github/scripts/rust-dependency-snapshot.py", + ".github/scripts/test_rust_dependency_snapshot.py", + ".github/workflows/maven-dependency-graph.yml", + "unittest/__init__.py", + "pathlib.py", + "sitecustomize.py", + ): + with self.subTest(path=path), self.assertRaises(POLICY.ReviewError): + review(missing_head([]), comparison([path])) + + def test_missing_snapshot_accepts_only_the_scheduler_change_in_submission_workflows(self): + expression = "$" + "{{ " + condition = expression + "github.event_name == 'pull_request'" + patch = ( + "@@ -1,2 +1,6 @@\n+concurrency:\n" + f"+ group: {expression}github.workflow }}}}-{condition} && github.ref || github.sha }}}}\n" + f"+ cancel-in-progress: {condition} }}}}\n+\n permissions:\n contents: read" + ) + file = { + "filename": ".github/workflows/rust-dependency-graph.yml", + "status": "modified", + "additions": 4, + "deletions": 0, + "patch": patch, + } + data = {"merge_base_commit": {"sha": BASE}, "files": [file]} + self.assertEqual(review(missing_head([]), Response(data))["snapshot_inputs"], "unchanged") + for changes in ( + {"patch": None}, + {"deletions": 1}, + {"patch": patch.replace(" permissions:", " jobs:")}, + {"status": "renamed", "previous_filename": "sdk/rust/Cargo.toml"}, + ): + with self.subTest(changes=changes), self.assertRaises(POLICY.ReviewError): + review(missing_head([]), Response({**data, "files": [{**file, **changes}]})) + + def test_missing_snapshot_checks_the_old_name_of_a_renamed_input(self): + data = { + "merge_base_commit": {"sha": BASE}, + "files": [ + {"filename": "example.txt", "status": "renamed", "previous_filename": "pom.xml"} + ], + } + with self.assertRaises(POLICY.ReviewError): + review(missing_head([]), Response(data)) + def test_http_and_timeout_fail_without_retry(self): for code in (403, 404, 429, 503): opener = Opener(urllib.error.HTTPError(ENDPOINT, code, "failure", {}, None))