diff --git a/README.md b/README.md index 31c1d13..2fd1ea5 100644 --- a/README.md +++ b/README.md @@ -192,12 +192,32 @@ 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 pull request's title, description and changed files with their patches, as +GitHub lists them. The service counts size and tests itself, asks a fixed nine-question checklist +about the diff (sign-in and access, billing, stored data, releases, dependency and platform versions, +public interfaces, calls to other services), has a model decide each answer and a second pass drop +the false alarms, with a sentence and the changed line behind each risk it keeps. With your own +provider key it sends the same provider headers as the guide: your model makes the decision and the +review, and the checklist's classifier, which only CodeBoarding's key can reach, is skipped. With +`closed_features_source: false` it sends neither patches nor the description, only each file's +path, additions and deletions; a diff too large to send with its patches goes the same way. Without patches the +checklist cannot run: the answer comes back `partial` with size and tests only, the run logs a +notice, and the web platform shows the level as not assessed 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 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 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 @@ -409,8 +429,8 @@ 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. | -| `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. | +| `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. 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/action.yml b/action.yml index 1524ae6..50b6dfd 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 title, description and 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/' @@ -157,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: @@ -809,6 +812,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 }} + # 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 96743a6..dbd3016 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_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. # Keep it one line, `key=value` pairs, values without spaces, so a regex over it stays trivial. diff --git a/scripts/remote_features.py b/scripts/remote_features.py index e06e711..bcee2af 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -1,11 +1,15 @@ #!/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. It sends +only the pull request's title, description and changed files with their patches, never the +analysis, and neither patches nor description when the workflow turns source off, in which case the service answers with size and tests +alone and says its checklist did not run. What a request sends -------------------- @@ -42,7 +46,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. @@ -57,7 +62,7 @@ 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_OUTPUT, and optionally LICENSE_KEY, CLOSED_FEATURES_SOURCE, LLM, MODEL, AGENT_MODEL, _API_KEY, _BASE_URL, ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN. """ @@ -113,6 +118,18 @@ 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. +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 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): @@ -513,9 +530,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 @@ -629,13 +651,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)) @@ -666,7 +688,7 @@ def _no_architecture(ctx: dict, status: str, reason: str) -> dict: """Preserve the architecture envelope even when the request cannot complete.""" return { "feature": "architecture", - "schema": 1, + "schema": 2, "status": status, "repo": ctx["repo"], "pr": ctx["pr"], @@ -719,6 +741,137 @@ 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_files(ctx: dict) -> tuple[str, str, list[dict]]: + """The pull request's title, description and 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 + pull = _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}") + if pull["head"]["sha"] != ctx["head"]: + raise Skip("the pull request moved on to a newer head") + return pull.get("title") or "", pull.get("body") or "", files + + +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 (no `>`, so no `-->`) or match the + status line's `key=value` reader; a JSON parser reads the escapes back. It carries what the level + needs (the checklist's sensitive yeses, size, the reasons' codes) and leaves the explanations to + the artifact. None when it would be over MAX_MARKER_CHARS, since a comment has room for 65,536 + characters in all.""" + compact = { + "v": 2, + "head": result["headSha"], + "checked": result["checklist"] is not None, + "sensitive": result["sensitive"], + "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"] + ], + } + text = json.dumps(compact, separators=(",", ":")) + for char in "<>=": + text = text.replace(char, f"\\u{ord(char):04x}") + line = f"" + return line if len(line) <= MAX_MARKER_CHARS else None + + +def merge_risk_request(ctx: dict, title: str, description: str, 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"], + "title": title, + "description": description, + "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: + title, description, files = merge_risk_files(ctx) + # With source off the description stays on the runner too: it can quote code. + data = merge_risk_request(ctx, title, description if source_allowed(env) else "", files, source_allowed(env)) + # The run's own provider, as for the guide: its model decides, and its code reaches no other + # model. Headers that cannot be built fail merge risk rather than fall back to ours. + answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, {**headers, **model_headers(env)}, timeout=120) + if not isinstance(answer, dict) or not isinstance(answer.get("facts"), dict): + raise ValueError("the service returned no merge-risk facts") + checklist = answer.get("checklist") + result = { + "feature": "merge-risk", + "schema": 2, + "repo": ctx["repo"], + "pr": ctx["pr"], + "headSha": ctx["head"], + "status": answer.get("status") or "ok", + "facts": answer["facts"], + "checklist": checklist if isinstance(checklist, dict) else None, + "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], + "sensitive": [str(question) for question in answer.get("sensitive") or [] if isinstance(question, str)], + } + for step in ("unchecked", "unhinted", "undecided", "unreviewed"): + if isinstance(answer.get(step), str): + result[step] = answer[step] + if "unchecked" in result: + why = "source is off for this workflow" if not source_allowed(env) else result["unchecked"] + print(f"::notice::merge-risk checklist did not run ({why}): the level reads as not assessed") + elif result["facts"].get("patches", "all") != "all": + print("::notice::merge-risk read some of the patches: GitHub or the size limit left some out") + # 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(stored) + 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: + 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: @@ -729,21 +882,17 @@ def main(env: dict | None = None) -> int: 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}" + 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=2) as pool: - 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() + 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) + 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 ac949b6..09398f3 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -4,10 +4,12 @@ import json import lzma import os +import re import subprocess import sys import tempfile import threading +import time import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from importlib import metadata @@ -25,7 +27,7 @@ GUIDE = {"version": 1, "changes": [{"id": "u1"}]} ENVELOPE = { "feature": "architecture", - "schema": 1, + "schema": 2, "status": "partial", "repo": "o/r", "pr": 7, @@ -428,6 +430,8 @@ def setUp(self): ("_contents", {"return_value": "base"}), ("call_graph", {"return_value": {"nodes": {}, "edges": []}}), ("read_analysis", {"return_value": (_analysis([]), {})}), + # 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() @@ -578,6 +582,310 @@ 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_CHECKLIST = { + "model": "typesafe/jev-1.14-20261014", + "version": 1, + "probabilities": {"signin": 0.1, "contract": 0.95}, + "cut": False, + "yes": ["contract"], + "decided": True, + "reviewed": True, +} +RISK_ANSWER = { + "status": "ok", + "facts": {"files": 1, "sourceFiles": 1, "srcLines": 60, "tests": 0, "patches": "all"}, + "checklist": RISK_CHECKLIST, + "reasons": [ + { + "level": "medium", + "code": "checklist", + "params": {"question": "contract"}, + "file": "app.py", + "line": 1, + "side": "RIGHT", + "explanation": "Adds a public route.", + }, + {"level": "low", "code": "no_tests", "params": {"srcLines": 60}}, + ], + "sensitive": [], + "usage": {"checklist": {"inputTokens": 900, "cost": 0.00004}}, +} +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 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=("Add a route", "Adds GET /items.", 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 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({"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, + "title": "Add a route", + "description": "Adds GET /items.", + "files": RISK_FILES, + }, + ) + stored = {key: value for key, value in RISK_ANSWER.items() if key != "usage"} + expected = {"feature": "merge-risk", "schema": 2, "repo": "o/r", "pr": 7, "headSha": "H", **stored} + 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_merge_risk_carries_the_runs_own_provider_as_the_guide_does(self): + self.env.update({"LLM": "openai", "OPENAI_API_KEY": "sk-their", "AGENT_MODEL": "gpt-5.5"}) + service = self.run_service(_answer) + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + sent = {name.lower(): value for name, value in request["headers"].items()} + self.assertEqual( + (sent.get("x-llm-provider"), sent.get("x-llm-api-key"), sent.get("x-llm-model")), + ("openai", "sk-their", "gpt-5.5"), + ) + self.env["LLM"] = "hosted" + [request] = [sent for sent in self.run_service(_answer).requests if sent["path"] == "/v1/merge-risk"] + self.assertNotIn("x-llm-provider", {name.lower() for name in request["headers"]}) + + def test_a_failed_merge_risk_writes_nothing_and_leaves_the_others_alone(self): + 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 = 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([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): + self.files.return_value = ("Add a route", "", [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}]) + with mock.patch.object(remote_features, "MAX_COMPRESSED_BYTES", 2000): + 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}]) + + def sent_description(self, service): + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + return json.loads(lzma.decompress(request["body"]))["description"] + + 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.sent_description(service), "") + 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_checklist_that_did_not_run_is_logged_stored_and_rides_on_the_line(self): + unchecked = { + **RISK_ANSWER, + "status": "partial", + "unchecked": "no_patches", + "checklist": None, + "facts": {**RISK_ANSWER["facts"], "patches": "none"}, + "reasons": [RISK_ANSWER["reasons"][1]], + } + self.env["CLOSED_FEATURES_SOURCE"] = "false" + _, printed = self.run_logged( + lambda path, body: (200, unchecked) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIn( + "::notice::merge-risk checklist did not run (source is off for this workflow): " + "the level reads as not assessed", + printed, + ) + self.assertEqual((self.result()["status"], self.result()["unchecked"]), ("partial", "no_patches")) + self.assertIn('"checked":false', self.output()) + self.env["CLOSED_FEATURES_SOURCE"] = "true" + _, printed = self.run_logged(_answer) + self.assertFalse([line for line in printed if "merge-risk" 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) + 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}, "t", "", 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.""" + + 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"}, "title": "Add files", "body": "Why."} + return pages[path.rsplit("&", 1)[1]] + + with mock.patch.object(remote_features, "_github_json", side_effect=github): + title, description, files = remote_features.merge_risk_files({"repo": "o/r", "pr": 7, "head": "H"}) + self.assertEqual((title, description, len(files)), ("Add files", "Why.", 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_a_negative_number_reads_back_and_an_oversized_line_is_left_out(self): + result = { + "headSha": "abc123", + "sensitive": [], + "checklist": None, + "facts": {"srcLines": 3, "sourceFiles": 1}, + "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": "checklist", + "params": {"question": "a-->b=d"}, + "file": "x", + "line": 3, + "explanation": "Calls --> the service.", + } + result = { + "headSha": "abc123", + "sensitive": ["signin"], + "checklist": RISK_CHECKLIST, + "facts": {"srcLines": 1815, "sourceFiles": 31, "tests": 0}, + "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": 2, + "head": "abc123", + "checked": True, + "sensitive": ["signin"], + "srcLines": 1815, + "sourceFiles": 31, + "patches": "all", + "reasons": [{"level": "medium", "code": "checklist", "params": reason["params"]}], + }, + ) + + 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 709f693..b3b7541 100644 --- a/tests/test_review_comment.py +++ b/tests/test_review_comment.py @@ -81,6 +81,17 @@ 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_before_the_last(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + line = '' + lines = _build(Path(tmp), MERGE_RISK_LINE=line).rstrip("\n").splitlines() + self.assertEqual(lines[-2], line) + self.assertTrue(lines[-1].startswith("