From 8ce80d7f8df3407b8caaa29651884d05d799e0f4 Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Thu, 26 Nov 2026 22:27:09 +0100 Subject: [PATCH 1/6] Ask for merge risk in the run and keep it in the artifact and the comment A third request beside the review guide and architecture, POST /v1/merge-risk, sends the files changed between the merge base and the head with their patches. They come from git in the checkout, not the compare API, which stops at 300 files; the checkout is one commit deep, so the merge base is fetched by sha with the run's token passed through the environment. A patch over 300 KB is left out, and the patches go when the request would be over the service's limit. The answer is written to closed/merge_risk.json in the review artifact with the head and base it describes, and summed up in one hidden line of the review comment, , for the web platform's dashboard. The JSON escapes <, >, - and = so nothing in it can end the comment or match the status line's reader. It runs from the start, whatever happens to the analysis inputs or the guide, and a failure is one notice that writes nothing. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- action.yml | 12 +- scripts/action/build-review-comment.sh | 5 + scripts/action/merge_risk_marker.py | 58 ++++++++ scripts/remote_features.py | 177 ++++++++++++++++++++++--- tests/test_remote_features.py | 137 +++++++++++++++++++ tests/test_review_comment.py | 62 +++++++++ 7 files changed, 440 insertions(+), 22 deletions(-) create mode 100755 scripts/action/merge_risk_marker.py diff --git a/README.md b/README.md index 31c1d136..8ac93f8f 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,15 @@ The guide's request body, the same xz-compressed bytes the service receives, is `closed/bundle.json.xz`, so the guide can be generated again later from the same inputs. It never carries `source.json`, and it is left out when no guide request goes out. +A third request, `POST /v1/merge-risk`, goes to the same base URL at the same time and sends +no analysis: only the files changed between the merge base and the head, with their patches, +read with `git diff` in the checkout (the merge base is fetched by sha, one commit deep). A +patch over 300 KB is left out. The answer, the diff's merge-risk facts and the reasons they +give, is saved as `closed/merge_risk.json` with the head and base it describes, and summed up +in one hidden line of the review comment, ``, which +the web platform's dashboard reads. When the request fails, neither is written and the run +logs one notice. + Only architecture receives optional `source.json`: tracked Python, JavaScript/TypeScript and C# files (`.py`, `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.cs`, `.csproj`), excluding dependency/build directories, docs/public/fixtures, minified JS and TypeScript declarations. @@ -409,7 +418,7 @@ The update runs after the baseline is saved, stops itself after 10 minutes and n | `github_token` | both | `${{ github.token }}` | Token for comments and sync delivery. | | `codeboarding_analysis_location` | both | `codeboarding_branch` | Where the synced branch's analysis is stored: `codeboarding_branch` (on `codeboarding/baseline`, for the default branch; the code is never written) or `in_place` (committed as `.codeboarding/` on the synced branch). Sync saves it there and review reads it from there. | | `warmstart_retention_days` | review | `1` | Days to keep the reusable analysis. Only the next run reads it. | -| `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide` and `/v1/architecture`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json`, `closed/architecture.json` and the guide's request (`closed/bundle.json.xz`) in the review artifact. Set to `''` to disable all three. Never fails the run. | +| `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide`, `/v1/architecture` and `/v1/merge-risk`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json`, `closed/architecture.json`, `closed/merge_risk.json` and the guide's request (`closed/bundle.json.xz`) in the review artifact. Set to `''` to disable them all. Never fails the run. | | `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so. | | `problem_history` | sync | `false` | Opt-in. With `'true'`, each sync sends this repository's issues and merged pull requests to `review_guide_url` and commits the returned problem list as `problems.json` on the orphan branch `codeboarding/briefing`. Needs `contents: write`, `issues: read`, `pull-requests: read`, `actions: read` and `id-token: write` on the sync job. See [Problem history](#problem-history). Never fails the run. | diff --git a/action.yml b/action.yml index 1524ae6b..2f50a087 100644 --- a/action.yml +++ b/action.yml @@ -145,10 +145,12 @@ inputs: default: '2' review_guide_url: description: >- - Experimental. Service base URL for POST /v1/review-guide and POST /v1/architecture. - Defaults to production. Both receive this run's analysis independently; results are stored - as review_guide.json and closed/architecture.json, and the guide's request as sent as - closed/bundle.json.xz. Set to an empty string to disable both. + Experimental. Service base URL for POST /v1/review-guide, POST /v1/architecture and + POST /v1/merge-risk. Defaults to production. The first two receive this run's analysis and + the third its changed files, independently; results are stored as review_guide.json, + closed/architecture.json and closed/merge_risk.json, and the guide's request as sent as + closed/bundle.json.xz. Merge risk is also summed up in a hidden line of the review comment. + Set to an empty string to disable all three. Sync's opt-in problem_history calls POST /v1/briefing on the same URL. required: false default: 'https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/' @@ -809,6 +811,8 @@ runs: HEAD_SHA: ${{ steps.guard.outputs.head_sha }} # Analysed files whose content hash differs between base and head, from the render step. ANALYSED_FILES_CHANGED: ${{ steps.review_render.outputs.analysed_files_changed }} + # Written by the remote features step when the service answered; absent otherwise. + MERGE_RISK_FILE: ${{ steps.review_artifact.outputs.artifact_dir }}/closed/merge_risk.json run: "$GITHUB_ACTION_PATH/scripts/action/build-review-comment.sh" - name: Post review comment diff --git a/scripts/action/build-review-comment.sh b/scripts/action/build-review-comment.sh index 96743a6e..c97f4751 100755 --- a/scripts/action/build-review-comment.sh +++ b/scripts/action/build-review-comment.sh @@ -53,6 +53,11 @@ fi printf '[download artifacts](%s) ยท ' "$ARTIFACT_URL" fi printf 'run [%s](%s)\n' "$GITHUB_RUN_ID" "$RUN_URL" + # Merge risk at this head, for the web platform's dashboard: one more hidden line, only when the + # service answered (see merge_risk_marker.py). Before the line below, which stays last. + if [ -n "${MERGE_RISK_FILE:-}" ]; then + python3 "$(dirname "$0")/merge_risk_marker.py" "$MERGE_RISK_FILE" + fi # The machine-readable line: what a reader of the comment (the web platform's dashboard, an # agent) needs without parsing the prose or the diagram. An HTML comment renders as nothing. # Keep it one line, `key=value` pairs, values without spaces, so a regex over it stays trivial. diff --git a/scripts/action/merge_risk_marker.py b/scripts/action/merge_risk_marker.py new file mode 100755 index 00000000..a8d25c3a --- /dev/null +++ b/scripts/action/merge_risk_marker.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Print the review comment's merge-risk line from closed/merge_risk.json, or nothing without one. + +The web platform's dashboard reads merge risk for every open pull request from this line rather than +from each run's artifact. It is one HTML comment, ``, so it +renders as nothing. The JSON is compact and escapes `<`, `>`, `-` and `=`: none of them can end the +comment, and the status line's `key=value` reader cannot match inside it. A JSON parser reads the +escapes back as the characters they stand for. + +Usage: merge_risk_marker.py +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +# The most dependency names the line carries; the copy shows four and the count. +MAX_DEPS = 20 + + +def marker(result: dict) -> str: + facts = result["facts"] + critical = [area["name"] for area in facts.get("areas") or [] if area.get("critical")] + compact = { + "v": 1, + "head": result["headSha"], + "sensitive": bool(result.get("sensitive")), + "areas": critical, + "deps": (facts.get("deps") or [])[:MAX_DEPS], + "srcLines": facts.get("srcLines", 0), + "sourceFiles": facts.get("sourceFiles", 0), + "tests": facts.get("tests", 0), + "dirs": facts.get("dirs", 0), + "reasons": [ + {"level": reason["level"], "code": reason["code"], "params": reason.get("params") or {}} + for reason in result.get("reasons") or [] + ], + } + text = json.dumps(compact, separators=(",", ":"), ensure_ascii=True) + for char, escape in (("<", "\\u003c"), (">", "\\u003e"), ("-", "\\u002d"), ("=", "\\u003d")): + text = text.replace(char, escape) + return f"" + + +def main(argv: list[str]) -> int: + try: + result = json.loads(Path(argv[1]).read_text()) + print(marker(result)) + except Exception as error: # no file, or one we cannot read: the comment goes without the line + if not isinstance(error, (FileNotFoundError, IndexError)): + print(f"::notice::merge-risk line left out: {type(error).__name__}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/remote_features.py b/scripts/remote_features.py index e06e7117..0eeeb3b0 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -1,11 +1,16 @@ #!/usr/bin/env python3 -"""Ask the CodeBoarding service for a pull request's review guide and architecture checks. +"""Ask the CodeBoarding service for a pull request's review guide, architecture checks and merge risk. -Runs after the review analysis. The two requests go out in parallel and independently: either one -failing leaves the other alone, and nothing here fails the run. The guide is stored as +Runs after the review analysis. The three requests go out in parallel and independently: any one +failing leaves the others alone, and nothing here fails the run. The guide is stored as review_guide.json and the architecture envelope as closed/architecture.json in the review artifact, including partial, skipped and failed results. The guide's request, exactly as sent, is stored as -closed/bundle.json.xz, so a guide can be generated again from the same inputs. +closed/bundle.json.xz, so a guide can be generated again from the same inputs. Merge risk is stored as +closed/merge_risk.json when the service answered, and nothing is written when it did not. + +Merge risk sends only the changed files with their patches, read with git between the merge base and +the head (see merge_risk_files), never the analysis. The compare API stops at 300 files, so it is not +used here. What a request sends -------------------- @@ -57,13 +62,14 @@ hosted proxy gets), or the run's GITHUB_TOKEN when the workflow cannot mint one. Environment: CLOSED_FUNCTIONS_URL, REPOSITORY, PR_NUMBER, ARTIFACT_DIR, HEAD_ANALYSIS_PATH, -BASE_ANALYSIS_PATH, CHECKOUT_DIR, GITHUB_TOKEN, GITHUB_API_URL, and optionally LICENSE_KEY, +BASE_ANALYSIS_PATH, CHECKOUT_DIR, GITHUB_TOKEN, GITHUB_API_URL, GITHUB_SERVER_URL, and optionally LICENSE_KEY, CLOSED_FEATURES_SOURCE, LLM, MODEL, AGENT_MODEL, _API_KEY, _BASE_URL, ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN. """ from __future__ import annotations +import base64 import importlib.util import json import lzma @@ -72,6 +78,7 @@ import re import subprocess import sys +import threading from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path @@ -113,6 +120,11 @@ MAX_SOURCE_BYTES = 16_000_000 # The review guide's request as sent, kept in the review artifact's closed/ directory (see keep_bundle). BUNDLE_NAME = "bundle.json.xz" +# The service refuses a merge-risk request over 64 MiB of JSON: MAX_MERGE_RISK_BYTES in licensing-aws +# remote_analysis/handler.py. A file's patch over MAX_FILE_BYTES is left out, as GitHub leaves out the +# patch of a very large file. +MAX_MERGE_RISK_JSON_BYTES = 64 * 1024 * 1024 +MERGE_RISK_NAME = "merge_risk.json" class Skip(Exception): @@ -538,6 +550,81 @@ def collect_source(env: dict) -> tuple[str | None, str | None]: return json.dumps(files), None +# --- Merge risk's file list ----------------------------------------------------------------------- + + +def _git(checkout: Path, *args: str, token: str | None = None) -> bytes: + """git in the checkout. A token goes in through the environment, never the arguments, so a failure's + message cannot carry it; the message is the command's first word and git's own error.""" + env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"} + if token: + auth = base64.b64encode(f"x-access-token:{token}".encode()).decode() + env.update(GIT_CONFIG_COUNT="1", GIT_CONFIG_KEY_0="http.extraheader") + env["GIT_CONFIG_VALUE_0"] = f"AUTHORIZATION: basic {auth}" + done = subprocess.run(["git", "-C", str(checkout), *args], capture_output=True, env=env) + if done.returncode != 0: + error = done.stderr.decode("utf-8", "replace").strip().splitlines() + raise RuntimeError(f"git {args[0]} failed: {error[-1] if error else done.returncode}") + return done.stdout + + +def _ensure_commit(env: dict, checkout: Path, sha: str) -> None: + """The commit in the checkout, fetched by sha from the repository when the shallow checkout lacks it. + The checkout keeps no credentials, so the run's token is passed for this one fetch.""" + try: + _git(checkout, "cat-file", "-e", f"{sha}^{{commit}}") + return + except RuntimeError: + pass + server = env.get("GITHUB_SERVER_URL", "https://github.com").rstrip("/") + url = f"{server}/{env['REPOSITORY']}.git" + _git(checkout, "fetch", "-q", "--no-tags", "--depth=1", url, sha, token=env.get("GITHUB_TOKEN")) + + +def _numstat(raw: bytes) -> list[tuple[str, int, int]]: + """`git diff --numstat -z` as (path, additions, deletions); a rename by its new path, a binary file + as no lines, as GitHub counts it.""" + fields = raw.decode("utf-8", "replace").split("\0") + out: list[tuple[str, int, int]] = [] + position = 0 + while position < len(fields) and fields[position]: + added, deleted, path = fields[position].split("\t", 2) + position += 1 + if not path: # a rename: the old path and the new one follow as their own fields + path = fields[position + 1] + position += 2 + out.append((path, int(added) if added.isdigit() else 0, int(deleted) if deleted.isdigit() else 0)) + return out + + +def _patches(raw: bytes) -> list[str | None]: + """The patch of each file in a `git diff`, in its order: the hunks alone, as GitHub gives them, or + None for a file with no hunk (binary, a mode change) or a patch over MAX_FILE_BYTES.""" + out: list[str | None] = [] + for section in re.split(rb"^diff --git ", raw, flags=re.M)[1:]: + hunk = re.search(rb"^@@", section, flags=re.M) + patch = section[hunk.start() :].decode("utf-8", "replace").rstrip("\n") if hunk else None + out.append(patch if patch is None or len(patch.encode()) <= MAX_FILE_BYTES else None) + return out + + +def merge_risk_files(env: dict, base_sha: str, head_sha: str) -> list[dict]: + """Every file changed between the merge base and the head as {filename, additions, deletions, + patch}, read with git in the checkout, which is fetched one commit deep.""" + checkout = Path(env["CHECKOUT_DIR"]) + for sha in (head_sha, base_sha): + _ensure_commit(env, checkout, sha) + options = ("--no-color", "--no-ext-diff", "-M", base_sha, head_sha) + stats = _numstat(_git(checkout, "diff", "--numstat", "-z", *options)) + patches = _patches(_git(checkout, "diff", "--no-textconv", *options)) + if len(patches) != len(stats): # both list the files in one order; if not, send no patch at all + patches = [None] * len(stats) + return [ + {"filename": path, "additions": added, "deletions": deleted, "patch": patch} + for (path, added, deleted), patch in zip(stats, patches) + ] + + # --- Credentials ---------------------------------------------------------------------------------- @@ -588,7 +675,16 @@ def model_headers(env: dict) -> dict[str, str]: return headers +# Merge risk asks for its own bearer while the guide asks for one; both write the license to one file. +_BEARER_LOCK = threading.Lock() + + def _bearer(env: dict) -> dict[str, str]: + with _BEARER_LOCK: + return _bearer_unlocked(env) + + +def _bearer_unlocked(env: dict) -> dict[str, str]: url, token = env.get("ACTIONS_ID_TOKEN_REQUEST_URL", ""), env.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") if not url or not token: # Without `id-token: write` the run's own token proves the same thing: it can read this @@ -719,6 +815,50 @@ def run_architecture(service_url: str, ctx: dict, data: bytes, headers: dict) -> return _no_architecture(ctx, "skipped" if isinstance(error, Skip) else "failed", str(error)) +def _merge_risk_request(ctx: dict, files: list[dict]) -> bytes: + """The merge-risk request, xz-compressed. Without patches when it is over a limit with them, so the + sizes and paths still count; TooLarge when not even that fits.""" + body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} + for attempt in (body, {**body, "files": [{**f, "patch": None} for f in files]}): + text = json.dumps(attempt).encode() + if len(text) > MAX_MERGE_RISK_JSON_BYTES: + continue + data = lzma.compress(text) + if len(data) <= MAX_COMPRESSED_BYTES: + return data + raise TooLarge(f"its {len(files)} changed files are over the service's limit even without patches") + + +def run_merge_risk(service_url: str, ctx: dict, env: dict, artifact: Path) -> None: + """Merge risk at this head, written to closed/merge_risk.json. It needs neither the analysis nor the + guide, so it runs whatever happens to them, and a failure is one line in the log.""" + try: + metadata = json.loads((artifact / "metadata.json").read_text()) + base_sha = metadata.get("merge_base_sha") or metadata.get("base_sha") + if not base_sha or not ctx["head"]: + raise Skip("the analysed commits are unknown") + data = _merge_risk_request(ctx, merge_risk_files(env, base_sha, ctx["head"])) + answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, _bearer(env), timeout=120) + if not isinstance(answer, dict) or not isinstance(answer.get("facts"), dict): + raise ValueError("the service returned no merge-risk facts") + result = { + "feature": "merge-risk", + "schema": 1, + "repo": ctx["repo"], + "pr": ctx["pr"], + "headSha": ctx["head"], + "baseSha": base_sha, + "facts": answer["facts"], + "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], + "sensitive": bool(answer.get("sensitive")), + } + path = artifact / "closed" / MERGE_RISK_NAME + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(result, ensure_ascii=False, indent=1)) + except Exception as error: + print(f"::notice::merge-risk {'skipped' if isinstance(error, Skip) else 'failed'}: {error}") + + def main(env: dict | None = None) -> int: env = dict(os.environ if env is None else env) try: @@ -728,22 +868,25 @@ def main(env: dict | None = None) -> int: service_url = env["CLOSED_FUNCTIONS_URL"] if not service_url.strip(): return 0 - try: - headers = {**_bearer(env), **model_headers(env)} - guide_request, architecture_request = _requests(ctx, collect(env), env) - except TooLarge as error: - print(f"::notice::review-guide skipped: {error}") - architecture = _no_architecture(ctx, "skipped", str(error)) - except Exception as error: - reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}" - print(f"::notice::review-guide failed: {reason}") - architecture = _no_architecture(ctx, "failed", reason) - else: - with ThreadPoolExecutor(max_workers=2) as pool: + with ThreadPoolExecutor(max_workers=3) as pool: + # First and on its own: it reads only git, so collecting the analysis cannot hold it up. + merge_risk = pool.submit(run_merge_risk, service_url, ctx, env, artifact) + try: + headers = {**_bearer(env), **model_headers(env)} + guide_request, architecture_request = _requests(ctx, collect(env), env) + except TooLarge as error: + print(f"::notice::review-guide skipped: {error}") + architecture = _no_architecture(ctx, "skipped", str(error)) + except Exception as error: + reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}" + print(f"::notice::review-guide failed: {reason}") + architecture = _no_architecture(ctx, "failed", reason) + else: guide = pool.submit(run_review_guide, service_url, guide_request, headers, artifact) result = pool.submit(run_architecture, service_url, ctx, architecture_request, headers) architecture = result.result() guide.result() + merge_risk.result() path = artifact / "closed" / "architecture.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(architecture, ensure_ascii=False, indent=1)) diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index ac949b63..f464eb65 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -428,6 +428,8 @@ def setUp(self): ("_contents", {"return_value": "base"}), ("call_graph", {"return_value": {"nodes": {}, "edges": []}}), ("read_analysis", {"return_value": (_analysis([]), {})}), + # The stub checkout has no commits; MergeRiskTests gives it some. + ("merge_risk_files", {"side_effect": remote_features.Skip("no commits in this checkout")}), ): patch = mock.patch.object(remote_features, name, **kwargs) patch.start() @@ -578,6 +580,141 @@ def test_either_limit_omits_source_then_skips_if_required_inputs_too_large(self) self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "skipped") +RISK_ANSWER = { + "facts": {"files": 1, "sourceFiles": 1, "srcLines": 60, "tests": 0, "dirs": 1, "areas": [], "deps": []}, + "reasons": [{"level": "low", "code": "no_tests", "params": {"srcLines": 60}}], + "sensitive": False, +} +RISK_FILES = [{"filename": "app.py", "additions": 60, "deletions": 0, "patch": "@@ -0,0 +1 @@\n+x"}] + + +def _answer(path, body): + if path == "/v1/merge-risk": + return 200, RISK_ANSWER + return 200, {"guide": GUIDE, "envelope": ENVELOPE} + + +class MergeRiskTests(_ServiceCase): + """Merge risk is a third request beside the guide and architecture, from git rather than the + analysis, and no failure of one reaches another.""" + + def setUp(self): + super().setUp() + patch = mock.patch.object(remote_features, "merge_risk_files", return_value=RISK_FILES) + self.files = patch.start() + self.addCleanup(patch.stop) + + def result(self): + path = Path(self.env["ARTIFACT_DIR"]) / "closed" / "merge_risk.json" + return json.loads(path.read_text()) if path.exists() else None + + def test_sends_the_file_list_and_keeps_the_answer_with_the_commits_it_describes(self): + service = self.run_service(_answer) + self.files.assert_called_once_with(self.env, "B", "H") + [request] = [r for r in service.requests if r["path"] == "/v1/merge-risk"] + self.assertEqual(request["headers"]["Authorization"], "Bearer ghs_run") + self.assertEqual( + json.loads(lzma.decompress(request["body"])), {"version": 1, "repo": "o/r", "pr": 7, "files": RISK_FILES} + ) + self.assertEqual( + self.result(), + { + "feature": "merge-risk", + "schema": 1, + "repo": "o/r", + "pr": 7, + "headSha": "H", + "baseSha": "B", + **RISK_ANSWER, + }, + ) + self.assertEqual(_read(self.env, "review_guide.json"), GUIDE) + self.assertEqual(_read(self.env, "closed/architecture.json"), ENVELOPE) + + def test_a_failed_merge_risk_writes_nothing_and_leaves_the_others_alone(self): + self.run_service(lambda p, b: (500, {}) if p == "/v1/merge-risk" else _answer(p, b)) + self.assertIsNone(self.result()) + self.assertEqual(_read(self.env, "review_guide.json"), GUIDE) + self.assertEqual(_read(self.env, "closed/architecture.json"), ENVELOPE) + self.files.side_effect = RuntimeError("git fetch failed") + self.run_service(_answer) + self.assertIsNone(self.result()) + + def test_merge_risk_does_not_need_the_analysis_or_the_guide(self): + (Path(self.env["HEAD_ANALYSIS_PATH"]).parent / "static_analysis.pkl").unlink() + service = self.run_service(_answer) + self.assertEqual([r["path"] for r in service.requests], ["/v1/merge-risk"]) + self.assertEqual(self.result()["reasons"], RISK_ANSWER["reasons"]) + self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") + + def test_without_room_for_patches_it_sends_the_files_without_them(self): + big = [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}] + with mock.patch.object(remote_features, "MAX_COMPRESSED_BYTES", 2000): + body = json.loads(lzma.decompress(remote_features._merge_risk_request({"repo": "o/r", "pr": 7}, big))) + self.assertEqual(body["files"], [{**RISK_FILES[0], "patch": None}]) + with mock.patch.object(remote_features, "MAX_MERGE_RISK_JSON_BYTES", 10): + with self.assertRaises(remote_features.TooLarge): + remote_features._merge_risk_request({"repo": "o/r", "pr": 7}, big) + + +def _commit(repo: Path, message: str) -> str: + subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True) + subprocess.run( + ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", message], check=True + ) + return subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() + + +class MergeRiskFilesTests(unittest.TestCase): + """The file list comes from git in a checkout one commit deep, with the merge base fetched by sha.""" + + def test_every_change_between_the_commits_in_the_shape_github_gives(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + origin = root / "server" / "o" / "r.git" + work = root / "work" + subprocess.run(["git", "init", "-q", "-b", "main", str(work)], check=True) + (work / "app.py").write_text("one\ntwo\n") + (work / "old name.py").write_text("".join(f"line {n}\n" for n in range(20))) + (work / "gone.py").write_text("bye\n") + (work / "logo.png").write_bytes(b"\x89PNG\x00\x01") + base = _commit(work, "base") + (work / "app.py").write_text("one\n2\nthree\n") + (work / "old name.py").rename(work / "new name.py") + (work / "gone.py").unlink() + (work / "logo.png").write_bytes(b"\x89PNG\x00\x02") + (work / "package.json").write_text('{\n "zod": "^3"\n}\n') + head = _commit(work, "head") + subprocess.run(["git", "clone", "-q", "--bare", str(work), str(origin)], check=True) + checkout = root / "checkout" + subprocess.run(["git", "clone", "-q", "--depth=1", f"file://{origin}", str(checkout)], check=True) + env = { + "CHECKOUT_DIR": str(checkout), + "REPOSITORY": "o/r", + "GITHUB_SERVER_URL": f"file://{root / 'server'}", + "GITHUB_TOKEN": "ghs_run", + } + files = {f["filename"]: f for f in remote_features.merge_risk_files(env, base, head)} + self.assertEqual(set(files), {"app.py", "new name.py", "gone.py", "logo.png", "package.json"}) + self.assertEqual((files["app.py"]["additions"], files["app.py"]["deletions"]), (2, 1)) + self.assertTrue(files["app.py"]["patch"].startswith("@@ ")) + self.assertIn("+three", files["app.py"]["patch"]) + self.assertNotIn("+++", files["app.py"]["patch"]) + self.assertEqual((files["new name.py"]["additions"], files["new name.py"]["deletions"]), (0, 0)) + self.assertEqual(files["gone.py"]["deletions"], 1) + self.assertEqual((files["logo.png"]["additions"], files["logo.png"]["patch"]), (0, None)) + self.assertIn('+ "zod": "^3"', files["package.json"]["patch"]) + + def test_a_failed_fetch_never_shows_the_token(self): + with tempfile.TemporaryDirectory() as tmp: + subprocess.run(["git", "init", "-q", tmp], check=True) + env = {"CHECKOUT_DIR": tmp, "REPOSITORY": "o/r", "GITHUB_SERVER_URL": f"file://{tmp}/none"} + with self.assertRaises(RuntimeError) as raised: + remote_features.merge_risk_files({**env, "GITHUB_TOKEN": "ghs_secret"}, "a" * 40, "b" * 40) + self.assertNotIn("ghs_secret", str(raised.exception)) + self.assertNotIn("Z2hz", str(raised.exception)) # nor its base64 + + class KeptBundleTests(_ServiceCase): """The review guide's request is kept in the review artifact as closed/bundle.json.xz, byte for byte, so a guide can be generated again from the same inputs. Keeping it never fails or changes the run.""" diff --git a/tests/test_review_comment.py b/tests/test_review_comment.py index 709f6939..69c47db3 100644 --- a/tests/test_review_comment.py +++ b/tests/test_review_comment.py @@ -1,5 +1,6 @@ """The review comment's shape: the status line the web platform reads, and the machine-readable line.""" +import json import os import re import subprocess @@ -81,6 +82,67 @@ def test_a_changed_analysed_file_gets_no_verdict_even_at_zero_components(self) - self.assertIn("**Status:** 0 changed components\n", body) self.assertIn("changed=0 analysed_files_changed=2 head=abc123", body) + def test_merge_risk_rides_on_its_own_hidden_line_that_nothing_in_it_can_end(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + result = { + "headSha": "abc123", + "sensitive": True, + "facts": { + "srcLines": 1815, + "sourceFiles": 31, + "tests": 0, + "dirs": 2, + "deps": ["zod"], + "areas": [ + {"id": "signin", "name": "Sign-in and access", "critical": True}, + {"id": "review", "name": "Review", "critical": False}, + ], + }, + "reasons": [ + { + "level": "medium", + "code": "area_changed", + "params": { + "area": "signin", + "name": "Sign-in and access", + "files": ["a-->b=.ts"], + "count": 1, + }, + "file": "a-->b=.ts", + } + ], + } + (root / "merge_risk.json").write_text(json.dumps(result), encoding="utf-8") + lines = _build(root, MERGE_RISK_FILE=str(root / "merge_risk.json")).rstrip("\n").splitlines() + self.assertTrue(lines[-1].startswith("", line) + self.assertIsNotNone(match) + payload = match.group(1) if match else "" + for char in "<>-=": + self.assertNotIn(char, payload) + self.assertEqual( + json.loads(payload), + { + "v": 1, + "head": "abc123", + "sensitive": True, + "areas": ["Sign-in and access"], + "deps": ["zod"], + "srcLines": 1815, + "sourceFiles": 31, + "tests": 0, + "dirs": 2, + "reasons": [{"level": "medium", "code": "area_changed", "params": result["reasons"][0]["params"]}], + }, + ) + + def test_no_merge_risk_answer_means_no_line(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + body = _build(Path(tmp), MERGE_RISK_FILE=str(Path(tmp) / "missing.json")) + self.assertNotIn("merge_risk", body) + if __name__ == "__main__": unittest.main() From 3a6b234fb7fd957f92fdb60b8f4e9b802fef382c Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Thu, 26 Nov 2026 22:56:13 +0100 Subject: [PATCH 2/6] Read merge risk's files from the pull request and trim the request The file list now comes from GitHub's pull request files, page by page, instead of fetching the merge base by sha and parsing `git diff` in the checkout; a run whose head moved on during it sends nothing, since a newer run answers for that head. The bearer is asked for once and shared, so the lock around it goes, and the comment's hidden line is built in remote_features.py and handed to the comment step as an output, so merge_risk_marker.py goes too. The line no longer carries tests and dirs, which nothing reads. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +- action.yml | 4 +- scripts/action/build-review-comment.sh | 6 +- scripts/action/merge_risk_marker.py | 58 -------- scripts/remote_features.py | 180 +++++++++---------------- tests/test_remote_features.py | 166 +++++++++++------------ tests/test_review_comment.py | 61 +-------- 7 files changed, 159 insertions(+), 329 deletions(-) delete mode 100755 scripts/action/merge_risk_marker.py diff --git a/README.md b/README.md index 8ac93f8f..8a449e2a 100644 --- a/README.md +++ b/README.md @@ -193,13 +193,12 @@ The guide's request body, the same xz-compressed bytes the service receives, is never carries `source.json`, and it is left out when no guide request goes out. A third request, `POST /v1/merge-risk`, goes to the same base URL at the same time and sends -no analysis: only the files changed between the merge base and the head, with their patches, -read with `git diff` in the checkout (the merge base is fetched by sha, one commit deep). A -patch over 300 KB is left out. The answer, the diff's merge-risk facts and the reasons they -give, is saved as `closed/merge_risk.json` with the head and base it describes, and summed up -in one hidden line of the review comment, ``, which -the web platform's dashboard reads. When the request fails, neither is written and the run -logs one notice. +no analysis: only the pull request's changed files with their patches, as GitHub lists them. +The answer, the diff's merge-risk facts and the reasons they give, is saved as +`closed/merge_risk.json` with the head it describes, and summed up in one hidden line of the +review comment, ``, which the web platform's dashboard +reads. When the request fails, or the pull request moved on to a newer head during the run, +neither is written and the run logs one notice. Only architecture receives optional `source.json`: tracked Python, JavaScript/TypeScript and C# files (`.py`, `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.cs`, `.csproj`), excluding diff --git a/action.yml b/action.yml index 2f50a087..1d86c0c7 100644 --- a/action.yml +++ b/action.yml @@ -811,8 +811,8 @@ runs: HEAD_SHA: ${{ steps.guard.outputs.head_sha }} # Analysed files whose content hash differs between base and head, from the render step. ANALYSED_FILES_CHANGED: ${{ steps.review_render.outputs.analysed_files_changed }} - # Written by the remote features step when the service answered; absent otherwise. - MERGE_RISK_FILE: ${{ steps.review_artifact.outputs.artifact_dir }}/closed/merge_risk.json + # Set by the remote features step when the service answered merge risk; empty otherwise. + MERGE_RISK_LINE: ${{ steps.remote_features.outputs.merge_risk_line }} run: "$GITHUB_ACTION_PATH/scripts/action/build-review-comment.sh" - name: Post review comment diff --git a/scripts/action/build-review-comment.sh b/scripts/action/build-review-comment.sh index c97f4751..dbd3016f 100755 --- a/scripts/action/build-review-comment.sh +++ b/scripts/action/build-review-comment.sh @@ -54,9 +54,9 @@ fi fi printf 'run [%s](%s)\n' "$GITHUB_RUN_ID" "$RUN_URL" # Merge risk at this head, for the web platform's dashboard: one more hidden line, only when the - # service answered (see merge_risk_marker.py). Before the line below, which stays last. - if [ -n "${MERGE_RISK_FILE:-}" ]; then - python3 "$(dirname "$0")/merge_risk_marker.py" "$MERGE_RISK_FILE" + # service answered (see merge_risk_line in remote_features.py). Before the line below, which stays last. + if [ -n "${MERGE_RISK_LINE:-}" ]; then + printf '%s\n' "$MERGE_RISK_LINE" fi # The machine-readable line: what a reader of the comment (the web platform's dashboard, an # agent) needs without parsing the prose or the diagram. An HTML comment renders as nothing. diff --git a/scripts/action/merge_risk_marker.py b/scripts/action/merge_risk_marker.py deleted file mode 100755 index a8d25c3a..00000000 --- a/scripts/action/merge_risk_marker.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python3 -"""Print the review comment's merge-risk line from closed/merge_risk.json, or nothing without one. - -The web platform's dashboard reads merge risk for every open pull request from this line rather than -from each run's artifact. It is one HTML comment, ``, so it -renders as nothing. The JSON is compact and escapes `<`, `>`, `-` and `=`: none of them can end the -comment, and the status line's `key=value` reader cannot match inside it. A JSON parser reads the -escapes back as the characters they stand for. - -Usage: merge_risk_marker.py -""" - -from __future__ import annotations - -import json -import sys -from pathlib import Path - -# The most dependency names the line carries; the copy shows four and the count. -MAX_DEPS = 20 - - -def marker(result: dict) -> str: - facts = result["facts"] - critical = [area["name"] for area in facts.get("areas") or [] if area.get("critical")] - compact = { - "v": 1, - "head": result["headSha"], - "sensitive": bool(result.get("sensitive")), - "areas": critical, - "deps": (facts.get("deps") or [])[:MAX_DEPS], - "srcLines": facts.get("srcLines", 0), - "sourceFiles": facts.get("sourceFiles", 0), - "tests": facts.get("tests", 0), - "dirs": facts.get("dirs", 0), - "reasons": [ - {"level": reason["level"], "code": reason["code"], "params": reason.get("params") or {}} - for reason in result.get("reasons") or [] - ], - } - text = json.dumps(compact, separators=(",", ":"), ensure_ascii=True) - for char, escape in (("<", "\\u003c"), (">", "\\u003e"), ("-", "\\u002d"), ("=", "\\u003d")): - text = text.replace(char, escape) - return f"" - - -def main(argv: list[str]) -> int: - try: - result = json.loads(Path(argv[1]).read_text()) - print(marker(result)) - except Exception as error: # no file, or one we cannot read: the comment goes without the line - if not isinstance(error, (FileNotFoundError, IndexError)): - print(f"::notice::merge-risk line left out: {type(error).__name__}", file=sys.stderr) - return 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv)) diff --git a/scripts/remote_features.py b/scripts/remote_features.py index 0eeeb3b0..99e566c0 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -6,11 +6,8 @@ review_guide.json and the architecture envelope as closed/architecture.json in the review artifact, including partial, skipped and failed results. The guide's request, exactly as sent, is stored as closed/bundle.json.xz, so a guide can be generated again from the same inputs. Merge risk is stored as -closed/merge_risk.json when the service answered, and nothing is written when it did not. - -Merge risk sends only the changed files with their patches, read with git between the merge base and -the head (see merge_risk_files), never the analysis. The compare API stops at 300 files, so it is not -used here. +closed/merge_risk.json when the service answered, and nothing is written when it did not. It sends +only the pull request's changed files with their patches, never the analysis. What a request sends -------------------- @@ -62,14 +59,13 @@ hosted proxy gets), or the run's GITHUB_TOKEN when the workflow cannot mint one. Environment: CLOSED_FUNCTIONS_URL, REPOSITORY, PR_NUMBER, ARTIFACT_DIR, HEAD_ANALYSIS_PATH, -BASE_ANALYSIS_PATH, CHECKOUT_DIR, GITHUB_TOKEN, GITHUB_API_URL, GITHUB_SERVER_URL, and optionally LICENSE_KEY, +BASE_ANALYSIS_PATH, CHECKOUT_DIR, GITHUB_TOKEN, GITHUB_API_URL, GITHUB_OUTPUT, and optionally LICENSE_KEY, CLOSED_FEATURES_SOURCE, LLM, MODEL, AGENT_MODEL, _API_KEY, _BASE_URL, ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN. """ from __future__ import annotations -import base64 import importlib.util import json import lzma @@ -78,7 +74,6 @@ import re import subprocess import sys -import threading from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path @@ -121,10 +116,12 @@ # The review guide's request as sent, kept in the review artifact's closed/ directory (see keep_bundle). BUNDLE_NAME = "bundle.json.xz" # The service refuses a merge-risk request over 64 MiB of JSON: MAX_MERGE_RISK_BYTES in licensing-aws -# remote_analysis/handler.py. A file's patch over MAX_FILE_BYTES is left out, as GitHub leaves out the -# patch of a very large file. +# remote_analysis/handler.py. MAX_MERGE_RISK_JSON_BYTES = 64 * 1024 * 1024 MERGE_RISK_NAME = "merge_risk.json" +MERGE_RISK_FIELDS = ("filename", "additions", "deletions", "patch") +# The most dependency names the review comment's merge-risk line carries; the dashboard shows four. +MAX_MARKER_DEPS = 20 class Skip(Exception): @@ -550,81 +547,6 @@ def collect_source(env: dict) -> tuple[str | None, str | None]: return json.dumps(files), None -# --- Merge risk's file list ----------------------------------------------------------------------- - - -def _git(checkout: Path, *args: str, token: str | None = None) -> bytes: - """git in the checkout. A token goes in through the environment, never the arguments, so a failure's - message cannot carry it; the message is the command's first word and git's own error.""" - env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"} - if token: - auth = base64.b64encode(f"x-access-token:{token}".encode()).decode() - env.update(GIT_CONFIG_COUNT="1", GIT_CONFIG_KEY_0="http.extraheader") - env["GIT_CONFIG_VALUE_0"] = f"AUTHORIZATION: basic {auth}" - done = subprocess.run(["git", "-C", str(checkout), *args], capture_output=True, env=env) - if done.returncode != 0: - error = done.stderr.decode("utf-8", "replace").strip().splitlines() - raise RuntimeError(f"git {args[0]} failed: {error[-1] if error else done.returncode}") - return done.stdout - - -def _ensure_commit(env: dict, checkout: Path, sha: str) -> None: - """The commit in the checkout, fetched by sha from the repository when the shallow checkout lacks it. - The checkout keeps no credentials, so the run's token is passed for this one fetch.""" - try: - _git(checkout, "cat-file", "-e", f"{sha}^{{commit}}") - return - except RuntimeError: - pass - server = env.get("GITHUB_SERVER_URL", "https://github.com").rstrip("/") - url = f"{server}/{env['REPOSITORY']}.git" - _git(checkout, "fetch", "-q", "--no-tags", "--depth=1", url, sha, token=env.get("GITHUB_TOKEN")) - - -def _numstat(raw: bytes) -> list[tuple[str, int, int]]: - """`git diff --numstat -z` as (path, additions, deletions); a rename by its new path, a binary file - as no lines, as GitHub counts it.""" - fields = raw.decode("utf-8", "replace").split("\0") - out: list[tuple[str, int, int]] = [] - position = 0 - while position < len(fields) and fields[position]: - added, deleted, path = fields[position].split("\t", 2) - position += 1 - if not path: # a rename: the old path and the new one follow as their own fields - path = fields[position + 1] - position += 2 - out.append((path, int(added) if added.isdigit() else 0, int(deleted) if deleted.isdigit() else 0)) - return out - - -def _patches(raw: bytes) -> list[str | None]: - """The patch of each file in a `git diff`, in its order: the hunks alone, as GitHub gives them, or - None for a file with no hunk (binary, a mode change) or a patch over MAX_FILE_BYTES.""" - out: list[str | None] = [] - for section in re.split(rb"^diff --git ", raw, flags=re.M)[1:]: - hunk = re.search(rb"^@@", section, flags=re.M) - patch = section[hunk.start() :].decode("utf-8", "replace").rstrip("\n") if hunk else None - out.append(patch if patch is None or len(patch.encode()) <= MAX_FILE_BYTES else None) - return out - - -def merge_risk_files(env: dict, base_sha: str, head_sha: str) -> list[dict]: - """Every file changed between the merge base and the head as {filename, additions, deletions, - patch}, read with git in the checkout, which is fetched one commit deep.""" - checkout = Path(env["CHECKOUT_DIR"]) - for sha in (head_sha, base_sha): - _ensure_commit(env, checkout, sha) - options = ("--no-color", "--no-ext-diff", "-M", base_sha, head_sha) - stats = _numstat(_git(checkout, "diff", "--numstat", "-z", *options)) - patches = _patches(_git(checkout, "diff", "--no-textconv", *options)) - if len(patches) != len(stats): # both list the files in one order; if not, send no patch at all - patches = [None] * len(stats) - return [ - {"filename": path, "additions": added, "deletions": deleted, "patch": patch} - for (path, added, deleted), patch in zip(stats, patches) - ] - - # --- Credentials ---------------------------------------------------------------------------------- @@ -675,16 +597,7 @@ def model_headers(env: dict) -> dict[str, str]: return headers -# Merge risk asks for its own bearer while the guide asks for one; both write the license to one file. -_BEARER_LOCK = threading.Lock() - - def _bearer(env: dict) -> dict[str, str]: - with _BEARER_LOCK: - return _bearer_unlocked(env) - - -def _bearer_unlocked(env: dict) -> dict[str, str]: url, token = env.get("ACTIONS_ID_TOKEN_REQUEST_URL", ""), env.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") if not url or not token: # Without `id-token: write` the run's own token proves the same thing: it can read this @@ -815,30 +728,55 @@ def run_architecture(service_url: str, ctx: dict, data: bytes, headers: dict) -> return _no_architecture(ctx, "skipped" if isinstance(error, Skip) else "failed", str(error)) -def _merge_risk_request(ctx: dict, files: list[dict]) -> bytes: - """The merge-risk request, xz-compressed. Without patches when it is over a limit with them, so the - sizes and paths still count; TooLarge when not even that fits.""" - body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} - for attempt in (body, {**body, "files": [{**f, "patch": None} for f in files]}): - text = json.dumps(attempt).encode() - if len(text) > MAX_MERGE_RISK_JSON_BYTES: - continue - data = lzma.compress(text) - if len(data) <= MAX_COMPRESSED_BYTES: - return data - raise TooLarge(f"its {len(files)} changed files are over the service's limit even without patches") +def merge_risk_files(ctx: dict) -> list[dict]: + """The pull request's changed files as GitHub lists them (at most 3,000, a very large file without + its patch), or Skip when the head moved on, since a newer run answers for that head.""" + files: list[dict] = [] + for page in range(1, 31): + listed = _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}/files?per_page=100&page={page}") + files += [{field: changed.get(field) for field in MERGE_RISK_FIELDS} for changed in listed] + if len(listed) < 100: + break + if _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}")["head"]["sha"] != ctx["head"]: + raise Skip("the pull request moved on to a newer head") + return files + + +def merge_risk_line(result: dict) -> str: + """The review comment's hidden merge-risk line, for the web platform's dashboard. Compact JSON with + `<`, `>`, `-` and `=` escaped, so nothing in it can end the comment or match the status line's + `key=value` reader; a JSON parser reads the escapes back.""" + compact = { + "v": 1, + "head": result["headSha"], + "sensitive": result["sensitive"], + "areas": [area["name"] for area in result["facts"].get("areas") or [] if area.get("critical")], + "deps": (result["facts"].get("deps") or [])[:MAX_MARKER_DEPS], + "srcLines": result["facts"].get("srcLines", 0), + "sourceFiles": result["facts"].get("sourceFiles", 0), + "reasons": [ + {"level": reason["level"], "code": reason["code"], "params": reason.get("params") or {}} + for reason in result["reasons"] + ], + } + text = json.dumps(compact, separators=(",", ":")) + for char in "<>-=": + text = text.replace(char, f"\\u{ord(char):04x}") + return f"" -def run_merge_risk(service_url: str, ctx: dict, env: dict, artifact: Path) -> None: - """Merge risk at this head, written to closed/merge_risk.json. It needs neither the analysis nor the - guide, so it runs whatever happens to them, and a failure is one line in the log.""" +def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifact: Path) -> None: + """Merge risk at this head, written to closed/merge_risk.json and handed to the review comment as + the step's `merge_risk_line` output. It needs neither the analysis nor the guide, so it runs whatever + happens to them, and a failure is one line in the log.""" try: - metadata = json.loads((artifact / "metadata.json").read_text()) - base_sha = metadata.get("merge_base_sha") or metadata.get("base_sha") - if not base_sha or not ctx["head"]: - raise Skip("the analysed commits are unknown") - data = _merge_risk_request(ctx, merge_risk_files(env, base_sha, ctx["head"])) - answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, _bearer(env), timeout=120) + files = merge_risk_files(ctx) + body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} + try: + data = _encode(body, MAX_MERGE_RISK_JSON_BYTES, "file list") + except TooLarge: # the sizes and paths still count without the patches + data = _encode({**body, "files": [{**file, "patch": None} for file in files]}, MAX_MERGE_RISK_JSON_BYTES) + answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, headers, timeout=120) if not isinstance(answer, dict) or not isinstance(answer.get("facts"), dict): raise ValueError("the service returned no merge-risk facts") result = { @@ -847,7 +785,6 @@ def run_merge_risk(service_url: str, ctx: dict, env: dict, artifact: Path) -> No "repo": ctx["repo"], "pr": ctx["pr"], "headSha": ctx["head"], - "baseSha": base_sha, "facts": answer["facts"], "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], "sensitive": bool(answer.get("sensitive")), @@ -855,6 +792,9 @@ def run_merge_risk(service_url: str, ctx: dict, env: dict, artifact: Path) -> No path = artifact / "closed" / MERGE_RISK_NAME path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(result, ensure_ascii=False, indent=1)) + if env.get("GITHUB_OUTPUT"): + with open(env["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"merge_risk_line={merge_risk_line(result)}\n") except Exception as error: print(f"::notice::merge-risk {'skipped' if isinstance(error, Skip) else 'failed'}: {error}") @@ -869,10 +809,11 @@ def main(env: dict | None = None) -> int: if not service_url.strip(): return 0 with ThreadPoolExecutor(max_workers=3) as pool: - # First and on its own: it reads only git, so collecting the analysis cannot hold it up. - merge_risk = pool.submit(run_merge_risk, service_url, ctx, env, artifact) try: - headers = {**_bearer(env), **model_headers(env)} + bearer = _bearer(env) + # Before collecting the analysis, which merge risk does not need. + pool.submit(run_merge_risk, service_url, ctx, bearer, env, artifact) + headers = {**bearer, **model_headers(env)} guide_request, architecture_request = _requests(ctx, collect(env), env) except TooLarge as error: print(f"::notice::review-guide skipped: {error}") @@ -886,7 +827,6 @@ def main(env: dict | None = None) -> int: result = pool.submit(run_architecture, service_url, ctx, architecture_request, headers) architecture = result.result() guide.result() - merge_risk.result() path = artifact / "closed" / "architecture.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(architecture, ensure_ascii=False, indent=1)) diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index f464eb65..e27caa72 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -4,6 +4,7 @@ import json import lzma import os +import re import subprocess import sys import tempfile @@ -428,8 +429,8 @@ def setUp(self): ("_contents", {"return_value": "base"}), ("call_graph", {"return_value": {"nodes": {}, "edges": []}}), ("read_analysis", {"return_value": (_analysis([]), {})}), - # The stub checkout has no commits; MergeRiskTests gives it some. - ("merge_risk_files", {"side_effect": remote_features.Skip("no commits in this checkout")}), + # MergeRiskTests gives the pull request some files. + ("merge_risk_files", {"side_effect": remote_features.Skip("no files in this stub")}), ): patch = mock.patch.object(remote_features, name, **kwargs) patch.start() @@ -595,124 +596,123 @@ def _answer(path, body): class MergeRiskTests(_ServiceCase): - """Merge risk is a third request beside the guide and architecture, from git rather than the - analysis, and no failure of one reaches another.""" + """Merge risk is a third request beside the guide and architecture, from the pull request's files + rather than the analysis, and no failure of one reaches another.""" def setUp(self): super().setUp() patch = mock.patch.object(remote_features, "merge_risk_files", return_value=RISK_FILES) self.files = patch.start() self.addCleanup(patch.stop) + self.env["GITHUB_OUTPUT"] = str(Path(self.env["ARTIFACT_DIR"]).parent / "github_output") def result(self): path = Path(self.env["ARTIFACT_DIR"]) / "closed" / "merge_risk.json" return json.loads(path.read_text()) if path.exists() else None - def test_sends_the_file_list_and_keeps_the_answer_with_the_commits_it_describes(self): + def output(self): + path = Path(self.env["GITHUB_OUTPUT"]) + return path.read_text() if path.exists() else "" + + def test_sends_the_file_list_and_keeps_the_answer_with_the_head_it_describes(self): service = self.run_service(_answer) - self.files.assert_called_once_with(self.env, "B", "H") - [request] = [r for r in service.requests if r["path"] == "/v1/merge-risk"] + self.files.assert_called_once_with({"repo": "o/r", "pr": 7, "head": "H"}) + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] self.assertEqual(request["headers"]["Authorization"], "Bearer ghs_run") self.assertEqual( json.loads(lzma.decompress(request["body"])), {"version": 1, "repo": "o/r", "pr": 7, "files": RISK_FILES} ) - self.assertEqual( - self.result(), - { - "feature": "merge-risk", - "schema": 1, - "repo": "o/r", - "pr": 7, - "headSha": "H", - "baseSha": "B", - **RISK_ANSWER, - }, - ) + expected = {"feature": "merge-risk", "schema": 1, "repo": "o/r", "pr": 7, "headSha": "H", **RISK_ANSWER} + self.assertEqual(self.result(), expected) + self.assertEqual(self.output(), f"merge_risk_line={remote_features.merge_risk_line(expected)}\n") self.assertEqual(_read(self.env, "review_guide.json"), GUIDE) self.assertEqual(_read(self.env, "closed/architecture.json"), ENVELOPE) def test_a_failed_merge_risk_writes_nothing_and_leaves_the_others_alone(self): - self.run_service(lambda p, b: (500, {}) if p == "/v1/merge-risk" else _answer(p, b)) + self.run_service(lambda path, body: (500, {}) if path == "/v1/merge-risk" else _answer(path, body)) self.assertIsNone(self.result()) + self.assertEqual(self.output(), "") self.assertEqual(_read(self.env, "review_guide.json"), GUIDE) self.assertEqual(_read(self.env, "closed/architecture.json"), ENVELOPE) - self.files.side_effect = RuntimeError("git fetch failed") + self.files.side_effect = remote_features.Skip("the pull request moved on to a newer head") self.run_service(_answer) self.assertIsNone(self.result()) def test_merge_risk_does_not_need_the_analysis_or_the_guide(self): (Path(self.env["HEAD_ANALYSIS_PATH"]).parent / "static_analysis.pkl").unlink() service = self.run_service(_answer) - self.assertEqual([r["path"] for r in service.requests], ["/v1/merge-risk"]) + self.assertEqual([sent["path"] for sent in service.requests], ["/v1/merge-risk"]) self.assertEqual(self.result()["reasons"], RISK_ANSWER["reasons"]) self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") def test_without_room_for_patches_it_sends_the_files_without_them(self): - big = [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}] + self.files.return_value = [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}] with mock.patch.object(remote_features, "MAX_COMPRESSED_BYTES", 2000): - body = json.loads(lzma.decompress(remote_features._merge_risk_request({"repo": "o/r", "pr": 7}, big))) - self.assertEqual(body["files"], [{**RISK_FILES[0], "patch": None}]) - with mock.patch.object(remote_features, "MAX_MERGE_RISK_JSON_BYTES", 10): - with self.assertRaises(remote_features.TooLarge): - remote_features._merge_risk_request({"repo": "o/r", "pr": 7}, big) - - -def _commit(repo: Path, message: str) -> str: - subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True) - subprocess.run( - ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", message], check=True - ) - return subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() + service = self.run_service(_answer) + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + self.assertEqual(json.loads(lzma.decompress(request["body"]))["files"], [{**RISK_FILES[0], "patch": None}]) class MergeRiskFilesTests(unittest.TestCase): - """The file list comes from git in a checkout one commit deep, with the merge base fetched by sha.""" - - def test_every_change_between_the_commits_in_the_shape_github_gives(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - origin = root / "server" / "o" / "r.git" - work = root / "work" - subprocess.run(["git", "init", "-q", "-b", "main", str(work)], check=True) - (work / "app.py").write_text("one\ntwo\n") - (work / "old name.py").write_text("".join(f"line {n}\n" for n in range(20))) - (work / "gone.py").write_text("bye\n") - (work / "logo.png").write_bytes(b"\x89PNG\x00\x01") - base = _commit(work, "base") - (work / "app.py").write_text("one\n2\nthree\n") - (work / "old name.py").rename(work / "new name.py") - (work / "gone.py").unlink() - (work / "logo.png").write_bytes(b"\x89PNG\x00\x02") - (work / "package.json").write_text('{\n "zod": "^3"\n}\n') - head = _commit(work, "head") - subprocess.run(["git", "clone", "-q", "--bare", str(work), str(origin)], check=True) - checkout = root / "checkout" - subprocess.run(["git", "clone", "-q", "--depth=1", f"file://{origin}", str(checkout)], check=True) - env = { - "CHECKOUT_DIR": str(checkout), - "REPOSITORY": "o/r", - "GITHUB_SERVER_URL": f"file://{root / 'server'}", - "GITHUB_TOKEN": "ghs_run", - } - files = {f["filename"]: f for f in remote_features.merge_risk_files(env, base, head)} - self.assertEqual(set(files), {"app.py", "new name.py", "gone.py", "logo.png", "package.json"}) - self.assertEqual((files["app.py"]["additions"], files["app.py"]["deletions"]), (2, 1)) - self.assertTrue(files["app.py"]["patch"].startswith("@@ ")) - self.assertIn("+three", files["app.py"]["patch"]) - self.assertNotIn("+++", files["app.py"]["patch"]) - self.assertEqual((files["new name.py"]["additions"], files["new name.py"]["deletions"]), (0, 0)) - self.assertEqual(files["gone.py"]["deletions"], 1) - self.assertEqual((files["logo.png"]["additions"], files["logo.png"]["patch"]), (0, None)) - self.assertIn('+ "zod": "^3"', files["package.json"]["patch"]) - - def test_a_failed_fetch_never_shows_the_token(self): - with tempfile.TemporaryDirectory() as tmp: - subprocess.run(["git", "init", "-q", tmp], check=True) - env = {"CHECKOUT_DIR": tmp, "REPOSITORY": "o/r", "GITHUB_SERVER_URL": f"file://{tmp}/none"} - with self.assertRaises(RuntimeError) as raised: - remote_features.merge_risk_files({**env, "GITHUB_TOKEN": "ghs_secret"}, "a" * 40, "b" * 40) - self.assertNotIn("ghs_secret", str(raised.exception)) - self.assertNotIn("Z2hz", str(raised.exception)) # nor its base64 + """The file list is the pull request's, page by page, and only while its head is the run's.""" + + def test_reads_every_page_and_keeps_the_fields_the_service_reads(self): + changed = [ + {"filename": f"f{index}.py", "status": "added", "additions": index, "deletions": 0} for index in range(130) + ] + pages = {"page=1": changed[:100], "page=2": changed[100:]} + + def github(path): + if path.endswith("/pulls/7"): + return {"head": {"sha": "H"}} + return pages[path.rsplit("&", 1)[1]] + + with mock.patch.object(remote_features, "_github_json", side_effect=github): + files = remote_features.merge_risk_files({"repo": "o/r", "pr": 7, "head": "H"}) + self.assertEqual(len(files), 130) + self.assertEqual(files[129], {"filename": "f129.py", "additions": 129, "deletions": 0, "patch": None}) + + def test_a_head_that_moved_on_is_skipped(self): + def github(path): + return {"head": {"sha": "newer"}} if path.endswith("/pulls/7") else [] + + with mock.patch.object(remote_features, "_github_json", side_effect=github): + with self.assertRaises(remote_features.Skip): + remote_features.merge_risk_files({"repo": "o/r", "pr": 7, "head": "H"}) + + +class MergeRiskLineTests(unittest.TestCase): + def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): + reason = {"level": "medium", "code": "area_changed", "params": {"files": ["a-->b=.ts"]}, "file": "x"} + result = { + "headSha": "abc123", + "sensitive": True, + "facts": { + "srcLines": 1815, + "sourceFiles": 31, + "tests": 0, + "deps": ["zod"], + "areas": [{"name": "Sign-in and access", "critical": True}, {"name": "Review", "critical": False}], + }, + "reasons": [reason], + } + match = re.fullmatch(r"", remote_features.merge_risk_line(result)) + payload = match.group(1) if match else "" + for char in "<>-=": + self.assertNotIn(char, payload) + self.assertEqual( + json.loads(payload), + { + "v": 1, + "head": "abc123", + "sensitive": True, + "areas": ["Sign-in and access"], + "deps": ["zod"], + "srcLines": 1815, + "sourceFiles": 31, + "reasons": [{"level": "medium", "code": "area_changed", "params": reason["params"]}], + }, + ) class KeptBundleTests(_ServiceCase): diff --git a/tests/test_review_comment.py b/tests/test_review_comment.py index 69c47db3..b3b7541a 100644 --- a/tests/test_review_comment.py +++ b/tests/test_review_comment.py @@ -1,6 +1,5 @@ """The review comment's shape: the status line the web platform reads, and the machine-readable line.""" -import json import os import re import subprocess @@ -82,66 +81,16 @@ def test_a_changed_analysed_file_gets_no_verdict_even_at_zero_components(self) - self.assertIn("**Status:** 0 changed components\n", body) self.assertIn("changed=0 analysed_files_changed=2 head=abc123", body) - def test_merge_risk_rides_on_its_own_hidden_line_that_nothing_in_it_can_end(self) -> None: + def test_merge_risk_rides_on_its_own_hidden_line_before_the_last(self) -> None: with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - result = { - "headSha": "abc123", - "sensitive": True, - "facts": { - "srcLines": 1815, - "sourceFiles": 31, - "tests": 0, - "dirs": 2, - "deps": ["zod"], - "areas": [ - {"id": "signin", "name": "Sign-in and access", "critical": True}, - {"id": "review", "name": "Review", "critical": False}, - ], - }, - "reasons": [ - { - "level": "medium", - "code": "area_changed", - "params": { - "area": "signin", - "name": "Sign-in and access", - "files": ["a-->b=.ts"], - "count": 1, - }, - "file": "a-->b=.ts", - } - ], - } - (root / "merge_risk.json").write_text(json.dumps(result), encoding="utf-8") - lines = _build(root, MERGE_RISK_FILE=str(root / "merge_risk.json")).rstrip("\n").splitlines() + line = '' + lines = _build(Path(tmp), MERGE_RISK_LINE=line).rstrip("\n").splitlines() + self.assertEqual(lines[-2], line) self.assertTrue(lines[-1].startswith("", line) - self.assertIsNotNone(match) - payload = match.group(1) if match else "" - for char in "<>-=": - self.assertNotIn(char, payload) - self.assertEqual( - json.loads(payload), - { - "v": 1, - "head": "abc123", - "sensitive": True, - "areas": ["Sign-in and access"], - "deps": ["zod"], - "srcLines": 1815, - "sourceFiles": 31, - "tests": 0, - "dirs": 2, - "reasons": [{"level": "medium", "code": "area_changed", "params": result["reasons"][0]["params"]}], - }, - ) def test_no_merge_risk_answer_means_no_line(self) -> None: with tempfile.TemporaryDirectory() as tmp: - body = _build(Path(tmp), MERGE_RISK_FILE=str(Path(tmp) / "missing.json")) - self.assertNotIn("merge_risk", body) + self.assertNotIn("merge_risk", _build(Path(tmp), MERGE_RISK_LINE="")) if __name__ == "__main__": From 50541f48a4602e89df323a0ba0c0645af823eacc Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Fri, 27 Nov 2026 01:10:23 +0100 Subject: [PATCH 3/6] Keep merge risk's patches home when source is off, and fix three review findings - closed_features_source: false now reaches merge risk: it sends each changed file's path, additions and deletions with patch null, read through the same source_allowed check that collect_source uses. README and the input description say so. - A credentials failure logs its own merge-risk notice beside the guide's; before, merge risk was never submitted and said nothing. - The comment line and the stored JSON are both built before either is written, so an answer the line cannot carry leaves neither behind. - Merge risk compresses at xz preset 1 instead of 9e, and a file list over ten times the compressed limit drops its patches before compressing. The guide's and architecture's requests are unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++- action.yml | 3 +- scripts/remote_features.py | 96 ++++++++++++++++++++++++----------- tests/test_remote_features.py | 79 ++++++++++++++++++++++++++++ 4 files changed, 153 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 8a449e2a..a8a6157e 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,9 @@ never carries `source.json`, and it is left out when no guide request goes out. A third request, `POST /v1/merge-risk`, goes to the same base URL at the same time and sends no analysis: only the pull request's changed files with their patches, as GitHub lists them. +With `closed_features_source: false` it sends no patches, only each file's path, additions and +deletions, so the diff's size and the areas its paths fall in still count. A diff too large to +send with its patches goes the same way. The answer, the diff's merge-risk facts and the reasons they give, is saved as `closed/merge_risk.json` with the head it describes, and summed up in one hidden line of the review comment, ``, which the web platform's dashboard @@ -205,7 +208,8 @@ and C# files (`.py`, `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.cs`, `.cspr dependency/build directories, docs/public/fixtures, minified JS and TypeScript declarations. Symlinks are not read. Individual files are capped at 300 KB and source at 16 MB. If adding source exceeds the 4.3 MB compressed request limit, it is omitted with a reason; architecture -still runs with the required inputs. `closed_features_source: false` also omits source. +still runs with the required inputs. `closed_features_source: false` also omits source, and +merge risk then sends its file list without patches. An unsupported provider skips the guide, but architecture can still return measured findings. ### Providers @@ -418,7 +422,7 @@ The update runs after the baseline is saved, stops itself after 10 minutes and n | `codeboarding_analysis_location` | both | `codeboarding_branch` | Where the synced branch's analysis is stored: `codeboarding_branch` (on `codeboarding/baseline`, for the default branch; the code is never written) or `in_place` (committed as `.codeboarding/` on the synced branch). Sync saves it there and review reads it from there. | | `warmstart_retention_days` | review | `1` | Days to keep the reusable analysis. Only the next run reads it. | | `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide`, `/v1/architecture` and `/v1/merge-risk`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json`, `closed/architecture.json`, `closed/merge_risk.json` and the guide's request (`closed/bundle.json.xz`) in the review artifact. Set to `''` to disable them all. Never fails the run. | -| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so. | +| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so; merge risk sends the changed files' paths and line counts without their patches. | | `problem_history` | sync | `false` | Opt-in. With `'true'`, each sync sends this repository's issues and merged pull requests to `review_guide_url` and commits the returned problem list as `problems.json` on the orphan branch `codeboarding/briefing`. Needs `contents: write`, `issues: read`, `pull-requests: read`, `actions: read` and `id-token: write` on the sync job. See [Problem history](#problem-history). Never fails the run. | `target_branch` and `sync_strategy` are deprecated, and read as the `codeboarding_analysis_location` they stand for, with a warning: `sync_strategy: push` as `in_place`, `sync_strategy: pull_request` as `codeboarding_branch`. `target_branch` is accepted only when it names the branch the run is on: the push trigger picks the branch. `force_full: true` is ignored with a warning. Anything the new input cannot express fails, linking to [moving an existing setup](#moving-an-existing-setup). diff --git a/action.yml b/action.yml index 1d86c0c7..682314f8 100644 --- a/action.yml +++ b/action.yml @@ -159,7 +159,8 @@ inputs: Whether architecture checks may read this repository's source, for checks that need the whole tree and to verify a finding. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees the code around a finding, never the tree. - With 'false' those checks and the model review do not run, and the result says so. + With 'false' those checks and the model review do not run, and the result says so. Merge + risk then sends the changed files' paths and line counts without their patches. required: false default: 'true' problem_history: diff --git a/scripts/remote_features.py b/scripts/remote_features.py index 99e566c0..5d1ac02a 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -7,7 +7,8 @@ including partial, skipped and failed results. The guide's request, exactly as sent, is stored as closed/bundle.json.xz, so a guide can be generated again from the same inputs. Merge risk is stored as closed/merge_risk.json when the service answered, and nothing is written when it did not. It sends -only the pull request's changed files with their patches, never the analysis. +only the pull request's changed files with their patches, never the analysis, and no patches when the +workflow turns source off. What a request sends -------------------- @@ -44,7 +45,8 @@ These bundles compress about 10:1, but no tighter cut-off holds for every request. - xz at this preset takes about 700 MB and seconds per 10 MB, so a run compresses one body at a time and each at most once: the body without source, which both features send, and architecture's with source - when there is source. When that one does not fit, architecture sends the shared one. + when there is source. When that one does not fit, architecture sends the shared one. Merge risk's + request compresses beside them at MERGE_RISK_PRESET, which needs a few MB of memory. - MAX_FILES: how many changed files have their contents sent; past it a feature reads diffs only. - MAX_FILE_BYTES: a larger file is sent neither in files.json nor in source.json. - MAX_SOURCE_BYTES: the most source.json holds; past it source is not sent. @@ -120,6 +122,11 @@ MAX_MERGE_RISK_JSON_BYTES = 64 * 1024 * 1024 MERGE_RISK_NAME = "merge_risk.json" MERGE_RISK_FIELDS = ("filename", "additions", "deletions", "patch") +# Merge risk keeps no request, so it compresses at xz's fast preset (about 60 MB/s, where 9e is 3 MB/s). +# A file list over this many times the compressed limit needs a better ratio than patches get at that +# preset, so its patches go before compressing rather than after. +MERGE_RISK_PRESET = 1 +MERGE_RISK_PATCH_RATIO = 10 # The most dependency names the review comment's merge-risk line carries; the dashboard shows four. MAX_MARKER_DEPS = 20 @@ -522,9 +529,14 @@ def _checkout_file(checkout: Path, name: str) -> Path: return path +def source_allowed(env: dict) -> bool: + """Whether the workflow lets the service read this repository's source (`closed_features_source`).""" + return env.get("CLOSED_FEATURES_SOURCE", "true").strip().lower() != "false" + + def collect_source(env: dict) -> tuple[str | None, str | None]: """Tracked architecture source, within fixed size and extension limits, or an omission reason.""" - if env.get("CLOSED_FEATURES_SOURCE", "true").strip().lower() == "false": + if not source_allowed(env): return None, "turned off by the workflow" checkout = Path(env["CHECKOUT_DIR"]) listed = subprocess.run(["git", "-C", str(checkout), "ls-files", "-z"], capture_output=True, check=True).stdout @@ -638,13 +650,13 @@ def _post(url: str, body: bytes, headers: dict[str, str], timeout: int = 600) -> raise RuntimeError(reason) from error -def _encode(body: dict, max_json_bytes: int, what: str = "bundle") -> bytes: +def _encode(body: dict, max_json_bytes: int, what: str = "bundle", preset: int = 9 | lzma.PRESET_EXTREME) -> bytes: """The request as sent, xz-compressed JSON, or TooLarge when it is over either of the service's limits. The JSON is measured before compressing it, which is the slow part, and it is compressed once.""" text = json.dumps(body).encode() if len(text) > max_json_bytes: raise TooLarge(f"its {what} is {len(text) / 1e6:.0f} MB of JSON, over the service's limit") - data = lzma.compress(text, preset=9 | lzma.PRESET_EXTREME) + data = lzma.compress(text, preset=preset) if len(data) > MAX_COMPRESSED_BYTES: message = f"its {what} is {len(data) / 1e6:.1f} MB compressed, over the service's limit" raise TooLarge(message, fits=len(text) * MAX_COMPRESSED_BYTES // len(data)) @@ -765,17 +777,27 @@ def merge_risk_line(result: dict) -> str: return f"" +def merge_risk_request(ctx: dict, files: list[dict], with_patches: bool) -> bytes: + """The merge-risk request, compressed at MERGE_RISK_PRESET. Its patches go when the workflow turns + source off, or when the file list is over either limit with them: before compressing when the JSON + alone is over MERGE_RISK_PATCH_RATIO times the compressed limit. Sizes and paths count without them.""" + body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} + if with_patches: + clearly_over = MERGE_RISK_PATCH_RATIO * MAX_COMPRESSED_BYTES + try: + return _encode(body, min(MAX_MERGE_RISK_JSON_BYTES, clearly_over), "file list", MERGE_RISK_PRESET) + except TooLarge: + pass + without_patches = [{**file, "patch": None} for file in files] + return _encode({**body, "files": without_patches}, MAX_MERGE_RISK_JSON_BYTES, "file list", MERGE_RISK_PRESET) + + def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifact: Path) -> None: """Merge risk at this head, written to closed/merge_risk.json and handed to the review comment as the step's `merge_risk_line` output. It needs neither the analysis nor the guide, so it runs whatever happens to them, and a failure is one line in the log.""" try: - files = merge_risk_files(ctx) - body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} - try: - data = _encode(body, MAX_MERGE_RISK_JSON_BYTES, "file list") - except TooLarge: # the sizes and paths still count without the patches - data = _encode({**body, "files": [{**file, "patch": None} for file in files]}, MAX_MERGE_RISK_JSON_BYTES) + data = merge_risk_request(ctx, merge_risk_files(ctx), source_allowed(env)) answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, headers, timeout=120) if not isinstance(answer, dict) or not isinstance(answer.get("facts"), dict): raise ValueError("the service returned no merge-risk facts") @@ -789,16 +811,37 @@ def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifa "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], "sensitive": bool(answer.get("sensitive")), } + # Both are built before either is written, so the artifact and the comment never disagree. + line, stored = merge_risk_line(result), json.dumps(result, ensure_ascii=False, indent=1) path = artifact / "closed" / MERGE_RISK_NAME path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(result, ensure_ascii=False, indent=1)) + path.write_text(stored) if env.get("GITHUB_OUTPUT"): with open(env["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - output.write(f"merge_risk_line={merge_risk_line(result)}\n") + output.write(f"merge_risk_line={line}\n") except Exception as error: print(f"::notice::merge-risk {'skipped' if isinstance(error, Skip) else 'failed'}: {error}") +def _guide_and_architecture(pool, service_url: str, ctx: dict, bearer: dict, env: dict, artifact: Path) -> dict: + """Collect the analysis once, ask for the guide and architecture side by side, and return + architecture's envelope, which records why when neither request went out.""" + try: + headers = {**bearer, **model_headers(env)} + guide_request, architecture_request = _requests(ctx, collect(env), env) + except TooLarge as error: + print(f"::notice::review-guide skipped: {error}") + return _no_architecture(ctx, "skipped", str(error)) + except Exception as error: + reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}" + print(f"::notice::review-guide failed: {reason}") + return _no_architecture(ctx, "failed", reason) + guide = pool.submit(run_review_guide, service_url, guide_request, headers, artifact) + architecture = pool.submit(run_architecture, service_url, ctx, architecture_request, headers) + guide.result() + return architecture.result() + + def main(env: dict | None = None) -> int: env = dict(os.environ if env is None else env) try: @@ -808,25 +851,18 @@ def main(env: dict | None = None) -> int: service_url = env["CLOSED_FUNCTIONS_URL"] if not service_url.strip(): return 0 - with ThreadPoolExecutor(max_workers=3) as pool: - try: - bearer = _bearer(env) + try: + bearer = _bearer(env) + except Exception as error: # every request needs it, so each feature says it did not run + reason = f"getting credentials failed: {type(error).__name__}: {error}" + print(f"::notice::merge-risk failed: {reason}") + print(f"::notice::review-guide failed: {reason}") + architecture = _no_architecture(ctx, "failed", reason) + else: + with ThreadPoolExecutor(max_workers=3) as pool: # Before collecting the analysis, which merge risk does not need. pool.submit(run_merge_risk, service_url, ctx, bearer, env, artifact) - headers = {**bearer, **model_headers(env)} - guide_request, architecture_request = _requests(ctx, collect(env), env) - except TooLarge as error: - print(f"::notice::review-guide skipped: {error}") - architecture = _no_architecture(ctx, "skipped", str(error)) - except Exception as error: - reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}" - print(f"::notice::review-guide failed: {reason}") - architecture = _no_architecture(ctx, "failed", reason) - else: - guide = pool.submit(run_review_guide, service_url, guide_request, headers, artifact) - result = pool.submit(run_architecture, service_url, ctx, architecture_request, headers) - architecture = result.result() - guide.result() + architecture = _guide_and_architecture(pool, service_url, ctx, bearer, env, artifact) path = artifact / "closed" / "architecture.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(architecture, ensure_ascii=False, indent=1)) diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index e27caa72..91f5c7fe 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -9,6 +9,7 @@ import sys import tempfile import threading +import time import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from importlib import metadata @@ -652,6 +653,84 @@ def test_without_room_for_patches_it_sends_the_files_without_them(self): [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] self.assertEqual(json.loads(lzma.decompress(request["body"]))["files"], [{**RISK_FILES[0], "patch": None}]) + def sent_files(self, service): + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + return json.loads(lzma.decompress(request["body"]))["files"] + + def test_with_source_turned_off_it_sends_the_files_without_patches(self): + for setting in ("false", " False\n"): + self.env["CLOSED_FEATURES_SOURCE"] = setting + service = self.run_service(_answer) + self.assertEqual(self.sent_files(service), [{**RISK_FILES[0], "patch": None}]) + self.assertEqual(self.result()["facts"], RISK_ANSWER["facts"]) + self.env["CLOSED_FEATURES_SOURCE"] = "true" + self.assertEqual(self.sent_files(self.run_service(_answer)), RISK_FILES) + + def run_logged(self, respond): + """run_service, and the lines it printed.""" + service = _Server(respond) + self.addCleanup(service.close) + self.env["CLOSED_FUNCTIONS_URL"] = service.url + with mock.patch("builtins.print") as log: + self.assertEqual(remote_features.main(self.env), 0) + return service, [call.args[0] for call in log.call_args_list] + + def test_a_credentials_failure_is_logged_for_merge_risk_too(self): + with mock.patch.object(remote_features, "_bearer", side_effect=RuntimeError("no OIDC token")): + service, printed = self.run_logged(_answer) + reason = "getting credentials failed: RuntimeError: no OIDC token" + self.assertIn(f"::notice::merge-risk failed: {reason}", printed) + self.assertIn(f"::notice::review-guide failed: {reason}", printed) + self.assertEqual(service.requests, []) + self.assertIsNone(self.result()) + self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") + + def test_an_answer_the_line_cannot_carry_writes_neither_file_nor_line(self): + unreadable = {**RISK_ANSWER, "reasons": [{"code": "no_tests"}]} # no level + _, printed = self.run_logged( + lambda path, body: (200, unreadable) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIsNone(self.result()) + self.assertEqual(self.output(), "") + self.assertIn("::notice::merge-risk failed: 'level'", printed) + + def test_merge_risk_compresses_fast_and_the_guide_as_before(self): + presets = {} + compress = lzma.compress + + def recording(data, preset): + presets[json.loads(data).get("files").__class__.__name__] = preset + return compress(data, preset=preset) + + with mock.patch.object(lzma, "compress", side_effect=recording): + self.run_service(_answer) + # Merge risk sends a list of files; the guide and architecture a dict of named files. + self.assertEqual(presets, {"list": remote_features.MERGE_RISK_PRESET, "dict": 9 | lzma.PRESET_EXTREME}) + + def test_a_huge_diff_goes_without_patches_compressed_once_and_quickly(self): + clearly_over = remote_features.MERGE_RISK_PATCH_RATIO * remote_features.MAX_COMPRESSED_BYTES + patch_bytes = 1_000_000 + files = [ + {"filename": f"gen/f{index}.py", "additions": 20_000, "deletions": 0, "patch": "+" * patch_bytes} + for index in range(clearly_over // patch_bytes + 1) + ] + compressed = [] + compress = lzma.compress + + def recording(data, preset): + compressed.append(len(data)) + return compress(data, preset=preset) + + started = time.monotonic() + with mock.patch.object(lzma, "compress", side_effect=recording): + data = remote_features.merge_risk_request({"repo": "o/r", "pr": 7}, files, with_patches=True) + elapsed = time.monotonic() - started + sent = json.loads(lzma.decompress(data))["files"] + self.assertEqual(sent, [{**file, "patch": None} for file in files]) + self.assertEqual(len(compressed), 1) # only the list without patches + self.assertLess(compressed[0], 10_000) + self.assertLess(elapsed, 5) + class MergeRiskFilesTests(unittest.TestCase): """The file list is the pull request's, page by page, and only while its head is the run's.""" From 0e3216e9e0282c8f8036a2bf5ed4003f2c462faa Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Fri, 27 Nov 2026 02:31:47 +0100 Subject: [PATCH 4/6] Log when merge risk could not read the patches, and carry it on the line With source off or a diff too large, the request goes without patches and licensing's mention and dependency checks cannot run. The answer now says so (`facts.patches`), the run logs a notice, and the comment line carries `patches` for the web platform. The README says the input does not keep code from the review guide's request. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +++++-- scripts/remote_features.py | 11 +++++++++++ tests/test_remote_features.py | 17 +++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a8a6157e..192e9809 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,10 @@ A third request, `POST /v1/merge-risk`, goes to the same base URL at the same ti no analysis: only the pull request's changed files with their patches, as GitHub lists them. With `closed_features_source: false` it sends no patches, only each file's path, additions and deletions, so the diff's size and the areas its paths fall in still count. A diff too large to -send with its patches goes the same way. +send with its patches goes the same way. Without patches the checks that read added code (areas it +mentions, new dependencies) cannot run: the answer says so in `facts.patches`, the run logs a +notice, and the web platform shows it rather than reading the silence as clean. This input does not +keep code from the review guide, whose request carries the changed files at both commits. The answer, the diff's merge-risk facts and the reasons they give, is saved as `closed/merge_risk.json` with the head it describes, and summed up in one hidden line of the review comment, ``, which the web platform's dashboard @@ -422,7 +425,7 @@ The update runs after the baseline is saved, stops itself after 10 minutes and n | `codeboarding_analysis_location` | both | `codeboarding_branch` | Where the synced branch's analysis is stored: `codeboarding_branch` (on `codeboarding/baseline`, for the default branch; the code is never written) or `in_place` (committed as `.codeboarding/` on the synced branch). Sync saves it there and review reads it from there. | | `warmstart_retention_days` | review | `1` | Days to keep the reusable analysis. Only the next run reads it. | | `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide`, `/v1/architecture` and `/v1/merge-risk`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json`, `closed/architecture.json`, `closed/merge_risk.json` and the guide's request (`closed/bundle.json.xz`) in the review artifact. Set to `''` to disable them all. Never fails the run. | -| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so; merge risk sends the changed files' paths and line counts without their patches. | +| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so; merge risk sends the changed files' paths and line counts without their patches. It does not change what the review guide's request carries. | | `problem_history` | sync | `false` | Opt-in. With `'true'`, each sync sends this repository's issues and merged pull requests to `review_guide_url` and commits the returned problem list as `problems.json` on the orphan branch `codeboarding/briefing`. Needs `contents: write`, `issues: read`, `pull-requests: read`, `actions: read` and `id-token: write` on the sync job. See [Problem history](#problem-history). Never fails the run. | `target_branch` and `sync_strategy` are deprecated, and read as the `codeboarding_analysis_location` they stand for, with a warning: `sync_strategy: push` as `in_place`, `sync_strategy: pull_request` as `codeboarding_branch`. `target_branch` is accepted only when it names the branch the run is on: the push trigger picks the branch. `force_full: true` is ignored with a warning. Anything the new input cannot express fails, linking to [moving an existing setup](#moving-an-existing-setup). diff --git a/scripts/remote_features.py b/scripts/remote_features.py index 5d1ac02a..04beb191 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -766,6 +766,7 @@ def merge_risk_line(result: dict) -> str: "deps": (result["facts"].get("deps") or [])[:MAX_MARKER_DEPS], "srcLines": result["facts"].get("srcLines", 0), "sourceFiles": result["facts"].get("sourceFiles", 0), + "patches": result["facts"].get("patches", "all"), "reasons": [ {"level": reason["level"], "code": reason["code"], "params": reason.get("params") or {}} for reason in result["reasons"] @@ -811,6 +812,16 @@ def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifa "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], "sensitive": bool(answer.get("sensitive")), } + patches = answer["facts"].get("patches", "all") + if patches != "all": + why = ( + "source is off for this workflow" + if not source_allowed(env) + else "the diff was too large" if patches == "none" else "GitHub left some out" + ) + print( + f"::notice::merge-risk read {patches} of the patches ({why}): mentions and new dependencies not checked" + ) # Both are built before either is written, so the artifact and the comment never disagree. line, stored = merge_risk_line(result), json.dumps(result, ensure_ascii=False, indent=1) path = artifact / "closed" / MERGE_RISK_NAME diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index 91f5c7fe..9e5a1d92 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -675,6 +675,22 @@ def run_logged(self, respond): self.assertEqual(remote_features.main(self.env), 0) return service, [call.args[0] for call in log.call_args_list] + def test_withheld_patches_are_logged_and_ride_on_the_line(self): + withheld = {**RISK_ANSWER, "facts": {**RISK_ANSWER["facts"], "patches": "none"}} + self.env["CLOSED_FEATURES_SOURCE"] = "false" + _, printed = self.run_logged( + lambda path, body: (200, withheld) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIn( + "::notice::merge-risk read none of the patches (source is off for this workflow): " + "mentions and new dependencies not checked", + printed, + ) + self.assertIn('"patches":"none"', self.output()) + self.env["CLOSED_FEATURES_SOURCE"] = "true" + _, printed = self.run_logged(_answer) + self.assertFalse([line for line in printed if "read none" in line or "read some" in line]) + def test_a_credentials_failure_is_logged_for_merge_risk_too(self): with mock.patch.object(remote_features, "_bearer", side_effect=RuntimeError("no OIDC token")): service, printed = self.run_logged(_answer) @@ -789,6 +805,7 @@ def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): "deps": ["zod"], "srcLines": 1815, "sourceFiles": 31, + "patches": "all", "reasons": [{"level": "medium", "code": "area_changed", "params": reason["params"]}], }, ) From a3dd37b4d97032a69b20deab4b37a949dd854718 Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Fri, 27 Nov 2026 02:48:27 +0100 Subject: [PATCH 5/6] Keep hyphens in the merge-risk line, and cap its size Escaping `-` would turn a negative number into invalid JSON; escaping `>` already keeps `-->` out. The line is now left out, with a notice, when it would take more than 8,000 characters of a comment GitHub caps at 65,536; the artifact still carries the result. Co-Authored-By: Claude Opus 5.5 --- scripts/remote_features.py | 18 ++++++++++++------ tests/test_remote_features.py | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/scripts/remote_features.py b/scripts/remote_features.py index 04beb191..4226b449 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -129,6 +129,8 @@ MERGE_RISK_PATCH_RATIO = 10 # The most dependency names the review comment's merge-risk line carries; the dashboard shows four. MAX_MARKER_DEPS = 20 +# The most the hidden line may take of the review comment, whose body GitHub caps at 65,536 characters. +MAX_MARKER_CHARS = 8_000 class Skip(Exception): @@ -754,10 +756,11 @@ def merge_risk_files(ctx: dict) -> list[dict]: return files -def merge_risk_line(result: dict) -> str: +def merge_risk_line(result: dict) -> str | None: """The review comment's hidden merge-risk line, for the web platform's dashboard. Compact JSON with - `<`, `>`, `-` and `=` escaped, so nothing in it can end the comment or match the status line's - `key=value` reader; a JSON parser reads the escapes back.""" + `<`, `>` and `=` escaped, so nothing in it can end the comment (no `>`, so no `-->`) or match the + status line's `key=value` reader; a JSON parser reads the escapes back. None when it would be over + MAX_MARKER_CHARS, since a comment has room for 65,536 characters in all.""" compact = { "v": 1, "head": result["headSha"], @@ -773,9 +776,10 @@ def merge_risk_line(result: dict) -> str: ], } text = json.dumps(compact, separators=(",", ":")) - for char in "<>-=": + for char in "<>=": text = text.replace(char, f"\\u{ord(char):04x}") - return f"" + line = f"" + return line if len(line) <= MAX_MARKER_CHARS else None def merge_risk_request(ctx: dict, files: list[dict], with_patches: bool) -> bytes: @@ -827,7 +831,9 @@ def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifa path = artifact / "closed" / MERGE_RISK_NAME path.parent.mkdir(parents=True, exist_ok=True) path.write_text(stored) - if env.get("GITHUB_OUTPUT"): + if line is None: + print(f"::notice::merge-risk line left out of the comment: over {MAX_MARKER_CHARS} characters") + elif env.get("GITHUB_OUTPUT"): with open(env["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: output.write(f"merge_risk_line={line}\n") except Exception as error: diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index 9e5a1d92..ef8f3f98 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -777,6 +777,19 @@ def github(path): class MergeRiskLineTests(unittest.TestCase): + def test_a_negative_number_reads_back_and_an_oversized_line_is_left_out(self): + result = { + "headSha": "abc123", + "sensitive": False, + "facts": {"srcLines": 3, "sourceFiles": 1, "deps": [], "areas": []}, + "reasons": [{"level": "low", "code": "future_rule", "params": {"delta": -4}}], + } + line = remote_features.merge_risk_line(result) + payload = re.fullmatch(r"", line).group(1) + self.assertEqual(json.loads(payload)["reasons"][0]["params"], {"delta": -4}) + huge = {**result, "reasons": [{"level": "low", "code": "x" * 9000, "params": {}}]} + self.assertIsNone(remote_features.merge_risk_line(huge)) + def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): reason = {"level": "medium", "code": "area_changed", "params": {"files": ["a-->b=.ts"]}, "file": "x"} result = { @@ -793,7 +806,7 @@ def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): } match = re.fullmatch(r"", remote_features.merge_risk_line(result)) payload = match.group(1) if match else "" - for char in "<>-=": + for char in "<>=": self.assertNotIn(char, payload) self.assertEqual( json.loads(payload), From 9c9564e0c3c15889507676a4a66b057ef2ed4439 Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Fri, 27 Nov 2026 03:15:36 +0100 Subject: [PATCH 6/6] Say what the line's dependency names are for Co-Authored-By: Claude Opus 5.5 --- scripts/remote_features.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/remote_features.py b/scripts/remote_features.py index 4226b449..eaa7e95e 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -127,7 +127,8 @@ # preset, so its patches go before compressing rather than after. MERGE_RISK_PRESET = 1 MERGE_RISK_PATCH_RATIO = 10 -# The most dependency names the review comment's merge-risk line carries; the dashboard shows four. +# The most dependency names the review comment's merge-risk line carries. The dashboard reads only +# whether there are any; the four it names come from the reason's own params. MAX_MARKER_DEPS = 20 # The most the hidden line may take of the review comment, whose body GitHub caps at 65,536 characters. MAX_MARKER_CHARS = 8_000