From 4a6d4660e40e0c976a9a79bd0dac7db48bba61e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 23:45:23 +0000 Subject: security-guidance: review a commit-and-push again when the commit review gave no verdict When one command commits and pushes, the push review left the new commit to the commit review and ended at once. A commit review that then failed, was killed or skipped the commit left it pushed and unreviewed, and no later push covers it. The push review now waits for the commit review's process to end, and reviews the pushed range itself when there is no verdict. Both choose the commit through one helper, so they cannot pick differently. Co-authored-by: mhegazy --- plugins/security-guidance/hooks/diffstate.py | 79 +++++- .../hooks/security_reminder_hook.py | 210 +++++++++++----- plugins/security-guidance/tests/conftest.py | 9 +- .../tests/test_chained_commit_push.py | 275 ++++++++++++++++++++- 4 files changed, 495 insertions(+), 78 deletions(-) (limited to 'plugins') diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index cd3205e6..3315e84b 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -1228,6 +1228,71 @@ def _mark_inflight(repo_root, shas): pass +def hold_until_exit(path): + """Lock the file at `path` until this process ends, so that others can + see it `is_held`. Best-effort; never raises.""" + import time as _time + try: + fd = _open_own_file(path, os.O_RDWR) + except (OSError, TypeError): + return + try: + for _ in range(10): # another process may be looking at this moment + if _flock_nb(fd, exclusive=True): + return # left open: the lock goes when the process does + _time.sleep(0.01) + except OSError: + pass + os.close(fd) + + +def is_held(path): + """Whether a live process holds the file at `path`; None when that cannot + be told (no such file, or no locks here).""" + try: + fd = _open_own_file(path, os.O_RDONLY) + except (OSError, TypeError): + return None + try: + # Shared, so two processes looking at once do not look like a holder + # to each other. + return not _flock_nb(fd, exclusive=False) + except OSError: + return None + finally: + os.close(fd) + + +def becomes_held(path, max_wait_s, poll_s=0.1): + """Whether a live process holds the file at `path` or does so soon.""" + import time as _time + end = _time.monotonic() + max_wait_s + while not is_held(path): + if _time.monotonic() >= end: + return False + _time.sleep(poll_s) + return True + + +def wait_for_holder(path, max_wait_s, poll_s=0.5): + """Wait for the process holding the file at `path` to end. Returns + (ended, waited_s); `ended` is False when it still runs after `max_wait_s`, + or when that cannot be told.""" + import time as _time + start = _time.monotonic() + waited, looks_free = False, 0 + while True: + held = is_held(path) + # Free twice in a row: a holder creates the file a moment before it + # locks it. + looks_free = 0 if held else looks_free + 1 + spent = _time.monotonic() - start + if held is None or looks_free == 2 or (held and spent >= max_wait_s): + return looks_free == 2 and held is False, spent if waited else 0.0 + waited = waited or held + _time.sleep(poll_s) + + def _load_inflight_shas(repo_root, shas, _gd=None): """Which of `shas` another live review in this clone holds right now.""" out = set() @@ -1238,18 +1303,8 @@ def _load_inflight_shas(repo_root, shas, _gd=None): p = os.path.join(gd, _INFLIGHT_PREFIX + sha) if not _is_full_sha(sha) or p in _inflight_held: continue - try: - fd = _open_own_file(p, os.O_RDONLY) - except OSError: - continue - try: - # Shared, so two reviews asking at once do not look like a - # holder to each other. - if not _flock_nb(fd, exclusive=False): - out.add(sha) - except OSError: - pass - os.close(fd) + if is_held(p): + out.add(sha) return out diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index fcd20a7f..15578cc3 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -1221,6 +1221,35 @@ def _unmatched_bash_sampled(input_data): return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0 +_bash_hook_git_dir = {} + + +def _bash_hook_sentinel(input_data, route="once"): + """The file one spawn of this Bash call's hook creates to claim `route`, + or None when there is nothing to tell the spawns apart by.""" + tuid = input_data.get("tool_use_id") + cwd = input_data.get("cwd") + if not tuid or not cwd: + return None + command = (input_data.get("tool_input") or {}).get("command", "") or "" + call = (tuid, cwd, command) + if call not in _bash_hook_git_dir: + _bash_hook_git_dir[call] = _git_dir( + _git_toplevel(cwd) + or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS) + or cwd + ) + gd = _bash_hook_git_dir[call] + if not gd: + return None + # Sanitize tuid into a filesystem-safe basename — defensive, the value is + # CC-generated (toolu_), but it ends up in a path. + safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80] + # A second route ("push") lets the other spawn of a commit-and-push run + # its own review, once. + return os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}")) + + def _claim_bash_hook_once(input_data, route="once"): """De-dupe across hooks.json `if` matchers firing for the same Bash call. @@ -1236,20 +1265,12 @@ def _claim_bash_hook_once(input_data, route="once"): Sentinel is per-clone (`.git/sg-hook-once-`), not /tmp, so concurrent CC sessions in *different* repos don't collide. Stale - sentinels (>5min) are GC'd opportunistically. + sentinels (older than a hook can run) are GC'd opportunistically. """ - tuid = input_data.get("tool_use_id") - cwd = input_data.get("cwd") - if not tuid or not cwd: - return True - command = (input_data.get("tool_input") or {}).get("command", "") or "" - gd = _git_dir( - _git_toplevel(cwd) - or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS) - or cwd - ) - if not gd: + sentinel = _bash_hook_sentinel(input_data, route) + if not sentinel: return True + gd = os.path.dirname(sentinel) # GC: best-effort sweep of stale sentinels so they don't accumulate. import time as _time now = _time.time() @@ -1258,21 +1279,20 @@ def _claim_bash_hook_once(input_data, route="once"): if name.startswith("sg-hook-once-"): p = os.path.join(gd, name) try: - if now - os.path.getmtime(p) > 300: + if now - os.path.getmtime(p) > 900: os.unlink(p) except OSError: pass except OSError: pass - # Sanitize tuid into a filesystem-safe basename — defensive, the value is - # CC-generated (toolu_), but it ends up in a path. - safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80] - # A second route ("push") lets the other spawn of a commit-and-push run - # its own review, once. - sentinel = os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}")) try: fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY) os.close(fd) + command = (input_data.get("tool_input") or {}).get("command", "") or "" + if (route == "once" and _GIT_COMMIT_RE.search(command) + and _GIT_PUSH_RE.search(command)): + # The push spawn of this command waits for this one to end. + diffstate.hold_until_exit(sentinel) return True except FileExistsError: return False @@ -1718,12 +1738,25 @@ def _left_out_files_notice(session_id, repo_root, untracked, diff_output): f"in {DEBUG_LOG_FILE}.") +def _push_review_takes_over(input_data, rate_n): + """True when the push spawn of this commit-and-push call waits to review + what this commit review, the `rate_n`th within the cap, has no verdict on.""" + command = input_data["tool_input"]["command"] + sentinel = _bash_hook_sentinel(input_data, "push") + return bool( + PUSH_SWEEP_ENABLED and sentinel and _GIT_PUSH_RE.search(command) + and rate_n < MAX_COMMIT_REVIEWS_PER_HOUR + # It may still be on its way to the wait when a review fails at once. + and diffstate.becomes_held(sentinel, 3)) + + def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): """End a commit ("Commit") or push ("Push") review that got no verdict. Never reports the code as clean. Tells Claude once per session for each kind of review and failure; repeats are only logged. `pushed` ("yes", - "maybe" or "no"): whether the commit's own command also pushed it. Exits. + "maybe" or "no"): whether the commit's own command also pushed it; + "taken_over" when that command's push review takes it from here. Exits. """ failure, reason, cause = _review_failure_reason(status) debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed") @@ -1733,7 +1766,8 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): # A commit its own command pushed gets its own notice: no later push # re-checks it. told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "") - if not atomic_check_and_mark_warning(session_id, told_key): + # With a push review waiting to take over, that one reports. + if pushed == "taken_over" or not atomic_check_and_mark_warning(session_id, told_key): emit_metrics(metrics) sys.exit(0) subject = "this push" if kind == "Push" else "this commit" @@ -1762,6 +1796,37 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): f"Log: {DEBUG_LOG_FILE}")) sys.exit(2) +def _commit_in_output(bash_output): + """The commit that a successful `git commit` printed, or None.""" + # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat + # signal before treating the tool call as a successful commit. The old + # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks + # emitting labels like `[pre-commit abc1234]`, and on (b) chained + # `git commit || git log --stat` where `N files changed` appears in output + # even though the commit itself failed. + # + # Take only the LAST match: pre-commit/husky hooks can print bracketed + # labels like `[pre-commit abc1234]` that precede the real `[branch sha]` + # line; chained commands like `git commit && git commit` produce multiple + # real SHAs and we want the most recent. The real commit line is always + # last in git's own output — the earlier matches are either decoys or + # superseded commits. + all_shas = _COMMIT_SHA_RE.findall(bash_output) + if all_shas and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS): + return all_shas[-1] + return None + + +def _commit_review_candidates(bash_output, repo_root): + """(shas, stale): the commits the commit review of a Bash call that was + not interrupted takes, newest first, before it leaves out those already + reviewed or under review: the one its output names, else the fresh ones in + the reflog, with the count of entries too old. Both the commit review and + the push review of the same call choose by this.""" + named = _commit_in_output(bash_output) + return ([named], 0) if named else _git_reflog_recent_commits(repo_root) + + def handle_commit_review_posttooluse(input_data): """PostToolUse handler for Bash — reviews git commits for security issues. @@ -1798,19 +1863,10 @@ def handle_commit_review_posttooluse(input_data): bash_output = stdout + "\n" + stderr interrupted = bool(tool_response.get("interrupted")) - # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat - # signal before treating the tool call as a successful commit. The old - # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks - # emitting labels like `[pre-commit abc1234]`, and on (b) chained - # `git commit || git log --stat` where `N files changed` appears in output - # even though the commit itself failed. all_shas = _COMMIT_SHA_RE.findall(bash_output) diffstate.note_seen_commits(session_id, all_shas) - commit_succeeded = ( - not interrupted - and bool(all_shas) - and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS) - ) + named = None if interrupted else _commit_in_output(bash_output) + commit_succeeded = bool(named) # commit_review_on emitted on every path so telemetry can filter on # commit_review and group by commit_review_on. @@ -1851,7 +1907,7 @@ def handle_commit_review_posttooluse(input_data): repo_res = RES_HINT _base["repo_resolution"] = repo_res _root = repo_root - _fresh, _stale = _git_reflog_recent_commits(_root) + _fresh, _stale = _commit_review_candidates(bash_output, _root) diffstate.note_seen_commits(session_id, _fresh) if _fresh: # Commits an earlier call's review is still working on are that @@ -1909,8 +1965,8 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 25, **_base}) sys.exit(0) - if not repo_root and all_shas and not _reflog_shas: - repo_root = repo_containing_commit(all_shas[-1], scan_roots(cwd)) + if not repo_root and named: + repo_root = repo_containing_commit(named, scan_roots(cwd)) if repo_root: repo_res = RES_SHA_SCAN if not repo_root: @@ -1936,13 +1992,6 @@ def handle_commit_review_posttooluse(input_data): # fallback above is the narrow exception: it only fires when output gave # us nothing AND the cwd repo's own reflog confirms a `commit:` just # happened there, which rules out the cross-repo case. - # - # Take only the LAST match: pre-commit/husky hooks can print bracketed - # labels like `[pre-commit abc1234]` that precede the real `[branch sha]` - # line; chained commands like `git commit && git commit` produce multiple - # real SHAs and we want the most recent. The real commit line is always - # last in git's own output — the earlier matches are either decoys or - # superseded commits. if _reflog_shas: # Output-based detection already failed above; the reflog SHAs are the # authoritative ones. Don't re-parse bash_output here — any bracketed @@ -1953,7 +2002,7 @@ def handle_commit_review_posttooluse(input_data): # all are reviewed. shas = _reflog_shas else: - shas = [all_shas[-1]] if all_shas else [] + shas = [named] if named else [] if not shas: debug_log("Commit review: no SHA in commit output") emit_metrics({"skipped": True, "skip_reason": 33, **_base}) @@ -2079,6 +2128,11 @@ def handle_commit_review_posttooluse(input_data): # skip_reason=28 correctly. if pre_amend_sha and not diff_files: debug_log("Commit review: --amend produced empty delta (message-only?), skipping") + # Same content under a new sha: as reviewed as the original is or, + # with its review still running, will be. + if (pre_amend_sha in _load_inflight_shas(repo_root, [pre_amend_sha]) + or pre_amend_sha in _load_reviewed_shas(repo_root)): + _append_reviewed_shas(repo_root, _full_shas(repo_root, shas)) emit_metrics({"skipped": True, "skip_reason": 35, **_base, "files_reviewed": 0}) sys.exit(0) @@ -2219,7 +2273,8 @@ def handle_commit_review_posttooluse(input_data): **_base, **_agentic_m, "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status, pushed=( - "yes" if _push_in_output(bash_output) + "taken_over" if _push_review_takes_over(input_data, _rate_n) + else "yes" if _push_in_output(bash_output) else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command) else "no")) @@ -2325,12 +2380,17 @@ def _pushed_beyond_commit_review(repo_root, push_range, bash_output): """ covered = [] if COMMIT_REVIEW_ENABLED: - named = _COMMIT_SHA_RE.findall(bash_output) - covered = named[-1:] or _git_reflog_recent_commits(repo_root)[0] + covered = _commit_review_candidates(bash_output, repo_root)[0] rest = [s for s in push_range if not any(s.startswith(c) for c in covered)] + return _without_review(repo_root, rest) + + +def _without_review(repo_root, shas): + """True when one of `shas` is neither reviewed nor under review.""" + # In that order: a review that ends in between then counts as reviewed. + held = _load_inflight_shas(repo_root, shas) reviewed = _load_reviewed_shas(repo_root) - held = _load_inflight_shas(repo_root, rest) - return any(s not in reviewed and s not in held for s in rest) + return any(s not in reviewed and s not in held for s in shas) def handle_push_sweep_posttooluse(input_data): @@ -2501,7 +2561,9 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 41, **_base}) sys.exit(0) - push_range = _git_rev_list_range(repo_root, prev_upstream, "HEAD") + # The tip that was pushed, checked above. HEAD itself may move meanwhile. + tip = head or "HEAD" + push_range = _git_rev_list_range(repo_root, prev_upstream, tip) if not push_range: emit_metrics({"skipped": True, "skip_reason": 42, **_base, "pushed": 0}) sys.exit(0) @@ -2511,24 +2573,44 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) + _spawn_wait, _take_over = 0.0, False if _GIT_COMMIT_RE.search(command) and not _pushed_beyond_commit_review( repo_root, push_range, bash_output): - emit_metrics({"skipped": True, "skip_reason": 47, **_base, - "pushed": len(push_range)}) - sys.exit(0) + # All of it is the other spawn's to review. Once pushed, no later push + # covers it, so see that review end and take over what got no verdict. + # One that outlasts the wait, or cannot be watched, is left to it. + reviewed = _load_reviewed_shas(repo_root) + if any(s not in reviewed for s in push_range): + diffstate.hold_until_exit(_bash_hook_sentinel(input_data, "push")) + _ended, _spawn_wait = diffstate.wait_for_holder( + _bash_hook_sentinel(input_data), INFLIGHT_WAIT_S) + _take_over = _ended and _without_review(repo_root, push_range) + # A commit the hourly cap kept out stays out. + _skip = (47 if not _take_over + else 23 if atomic_check_rate_limit( + session_id, "CommitReview", 0, COMMIT_REVIEW_RATE_WINDOW_S + )[1] >= MAX_COMMIT_REVIEWS_PER_HOUR + else 24 if not ensure_anthropic_reachable() else 0) + if _skip: + emit_metrics({"skipped": True, "skip_reason": _skip, **_base, + "pushed": len(push_range), + **({"inflight_wait_s": max(1, int(round(_spawn_wait)))} + if _spawn_wait else {})}) + sys.exit(0) # A commit review that is still running on these commits records them # once it has a verdict. Wait for it instead of reviewing the same diff a # second time; if it ends without one, they are reviewed here. reviewed, _waited = _reviewed_after_inflight( - repo_root, push_range, INFLIGHT_WAIT_S) + repo_root, push_range, max(0.0, INFLIGHT_WAIT_S - _spawn_wait)) + _waited += _spawn_wait _wait_m = {} if _waited: _wait_m = {"inflight_wait_s": max(1, int(round(_waited)))} debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review") base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed) prefix_advanced = len(push_range) - len(tail) - _parents = _git_range_parents(repo_root, prev_upstream, "HEAD") if base else {} + _parents = _git_range_parents(repo_root, prev_upstream, tip) if base else {} _settled = [] if any(len(p) > 1 for p in _parents.values()): base, _settled = _push_sweep_base_with_merges( @@ -2546,9 +2628,11 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, "prefix_advanced": prefix_advanced, **_wait_m}) sys.exit(0) - if _waited and head and _git_rev_parse_head(repo_root) != head: - # Same guard as above: the diff and the reviewer's file reads are - # both taken at HEAD, and HEAD left the pushed tip during the wait. + _head_moved = bool(_waited and head and _git_rev_parse_head(repo_root) != head) + if _head_moved and not _take_over: + # Same guard as above: the agentic reviewer reads files at HEAD, and + # HEAD left the pushed tip during the wait. A take-over goes on without + # that reviewer, on the diff of the pushed tip. debug_log("Push sweep: HEAD moved while waiting, skipping") emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m}) sys.exit(0) @@ -2556,7 +2640,7 @@ def handle_push_sweep_posttooluse(input_data): debug_log(f"Push sweep: range={len(push_range)} prefix_advanced=" f"{prefix_advanced} base={base[:12]} tail={len(tail)}") - diff_text = _git_diff_range(repo_root, base, "HEAD") + diff_text = _git_diff_range(repo_root, base, tip) if diff_text is None: # Diff failed (non-zero exit / 30s timeout / git missing). Do NOT # mark `tail` reviewed — we did not actually review it. Marking @@ -2598,6 +2682,8 @@ def handle_push_sweep_posttooluse(input_data): if _dropped: _base = {**_base, "diff_files_dropped": _dropped} + if _take_over: + _base["commit_no_verdict"] = True _allowed, _rate_n = atomic_check_rate_limit( session_id, "PushSweep", MAX_COMMIT_REVIEWS_PER_HOUR, COMMIT_REVIEW_RATE_WINDOW_S) @@ -2608,7 +2694,7 @@ def handle_push_sweep_posttooluse(input_data): _mark_inflight(repo_root, tail) _diff_token, _seen_m = _diff_review_started( - repo_root, _cap_files_for_prompt(diff_files)) + repo_root, _cap_files_for_prompt(diff_files), tip=tip) _TAIL_METRICS.update(_seen_m) import time as _time @@ -2622,7 +2708,7 @@ def handle_push_sweep_posttooluse(input_data): review_start = _time.time() rel_touched = [fp for fp, _ in diff_files] - if _agentic_commit_review_enabled(): + if _agentic_commit_review_enabled() and not _head_moved: concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(), ) @@ -3364,8 +3450,8 @@ def main(): # # The push-matcher spawn then claims the "push" route and runs the push # sweep, which reviews only when the command pushed a commit that - # commit-review will not see: once behind the upstream, no later push - # would cover it. + # commit-review will not see or gave no verdict on: once behind the + # upstream, no later push would cover it. if tool_name == "Bash" and hook_event_name == "PostToolUse": cmd = (input_data.get("tool_input") or {}).get("command", "") or "" if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)): diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index b0df08de..3987e1de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -96,7 +96,11 @@ class _Stub(http.server.BaseHTTPRequestHandler): self.server.calls.append(self.path) if self.server.delay: time.sleep(self.server.delay) - if self.server.status == 200: + status = self.server.status + reviews = [c for c in self.server.calls if c.endswith("/v1/messages")] + if self.path.endswith("/v1/messages") and len(reviews) <= getattr(self.server, "fail_first", 0): + status = 400 + if status == 200: vulns = list(self.server.vulns) body = json.dumps({ "id": "msg_stub", "type": "message", "role": "assistant", @@ -107,7 +111,7 @@ class _Stub(http.server.BaseHTTPRequestHandler): }).encode() else: body = b'{"type":"error","error":{"type":"invalid_request_error","message":"stub"}}' - self.send_response(self.server.status) + self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() @@ -126,6 +130,7 @@ def stub_api(): srv.bodies = [] srv.status = 200 srv.delay = 0 + srv.fail_first = 0 # the first N review requests are answered with 400 srv.vulns = [] t = threading.Thread(target=srv.serve_forever, daemon=True) t.start() diff --git a/plugins/security-guidance/tests/test_chained_commit_push.py b/plugins/security-guidance/tests/test_chained_commit_push.py index 8518ed5f..5d702371 100644 --- a/plugins/security-guidance/tests/test_chained_commit_push.py +++ b/plugins/security-guidance/tests/test_chained_commit_push.py @@ -4,15 +4,23 @@ The commit review sees only the commit the command made, and no later push covers what is already behind the upstream, so the second start of the hook for such a command runs the push review when something else went out. """ +import contextlib +import errno +import json import os import subprocess +import sys +import time import pytest -from conftest import GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook +from conftest import ( + GIT_ENV, HOOK_SCRIPT, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, +) +import diffstate import security_reminder_hook as hook -from diffstate import _append_reviewed_shas +from diffstate import _append_reviewed_shas, _load_reviewed_shas CMD = "git add -A && git commit -m new && git push" @@ -110,3 +118,266 @@ def test_plain_commit_second_start_is_deduped(repo, env): first, second, _ = _three_starts(repo, env, "git commit -m x", out, err) assert first.get("commit_review") is True assert second.get("bash_hook_dedup") is True + + +# The push spawn waits for the commit spawn, and takes over what it gave no +# verdict on. + +@contextlib.contextmanager +def _spawn(payload, env): + p = subprocess.Popen([sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env) + try: + p.stdin.write(json.dumps(payload)) + p.stdin.close() + p.stdin = None + yield p + finally: + if p.poll() is None: + p.kill() + p.communicate() + + +def _until(cond, what, timeout=30): + end = time.time() + timeout + while not cond(): + assert time.time() < end, f"timed out waiting for {what}" + time.sleep(0.05) + + +def _both_spawns(repo, env, out, err, meanwhile=lambda commit: None, command=CMD): + """The two spawns of one call, the commit spawn first. Returns the commit + spawn's (exit code, metrics, stderr), then the push spawn's.""" + payload = bash_payload(str(repo), command, stdout=out, stderr=err, tool_use_id="t1") + with _spawn(payload, env) as commit: + _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim") + with _spawn(payload, env) as push: + _until(lambda: (repo / ".git" / "sg-hook-once-t1-push").exists(), + "the push spawn's claim") + meanwhile(commit) + ends = [] + for p in (commit, push): + so, se = p.communicate(timeout=90) + ends.append((p.returncode, metrics_of(so), se)) + return ends + + +def _reviews(stub_api): + return len([c for c in stub_api.calls if c.endswith("/v1/messages")]) + + +def _head(repo): + return git(repo, "rev-parse", "HEAD").strip() + + +def test_one_review_while_the_push_spawn_waits(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.delay = 4 + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["commit_review"] is True and "skip_reason" not in commit[1] + assert push[1]["skip_reason"] == 47 and push[1]["inflight_wait_s"] >= 1 + assert "commit_no_verdict" not in push[1] + assert _reviews(stub_api) == 1 + + +def test_failed_commit_review_is_taken_over(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.fail_first, stub_api.delay = 2, 1 # the review and its retry + commit, push = _both_spawns(repo, hook_env, out, err) + # The push review reports, so the commit review does not. + assert commit[0] == 0 and commit[1]["review_failed"] is True and not commit[2] + assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1 + assert "skip_reason" not in push[1] and _reviews(stub_api) == 3 + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def test_killed_commit_review_is_taken_over(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.delay = 6 + + def kill(commit): + _until(lambda: _reviews(stub_api) == 1, "the commit review's request") + commit.kill() + + _, push = _both_spawns(repo, hook_env, out, err, kill) + assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1 + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def test_take_over_keeps_to_the_commit_review_cap(repo, hook_env, stub_api): + hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "1" + _, first = commit_file(repo, "first.py", "print('first')\n", "first") + run_hook(bash_payload(str(repo), "git commit -m first", first), hook_env) + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["skip_reason"] == 23 + assert push[1]["skip_reason"] == 23 + assert _reviews(stub_api) == 1 + + +def test_commit_without_reviewable_files_sends_nothing(repo, hook_env, stub_api): + out, err = _commit_and_push(repo, "notes.png") + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["skip_reason"] == 30 and push[1]["skip_reason"] == 30 + assert _reviews(stub_api) == 0 + + +def test_message_only_amend_is_not_reviewed_again(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env) + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_nothing_is_held_where_files_cannot_be_locked(repo, monkeypatch): + def no_locks(fd, exclusive): + raise OSError(errno.ENOLCK, "no locks here") + + path = str(repo / ".git" / "sg-hook-once-t1") + open(path, "w").close() + monkeypatch.setattr(diffstate, "_flock_nb", no_locks) + for p in (path, path + "-missing", None): + diffstate.hold_until_exit(p) + assert diffstate.is_held(p) is None + assert diffstate.wait_for_holder(p, 5) == (False, 0.0) + assert diffstate.becomes_held(p, 0) is False + + +def test_wait_for_holder_stops_at_the_limit(tmp_path): + path = tmp_path / "held" + path.write_text("") + script = ("import sys, time\nsys.path.insert(0, sys.argv[2])\nimport diffstate\n" + "diffstate.hold_until_exit(sys.argv[1])\n" + "print('held', flush=True)\ntime.sleep(60)\n") + p = subprocess.Popen([sys.executable, "-c", script, str(path), os.path.dirname(diffstate.__file__)], + stdout=subprocess.PIPE, text=True) + try: + assert p.stdout.readline().strip() == "held" + ended, waited = diffstate.wait_for_holder(str(path), 1) + assert ended is False and waited >= 1 + assert diffstate.is_held(str(path)) is True + p.kill() + p.wait() + assert diffstate.wait_for_holder(str(path), 20) == (True, 0.0) + finally: + p.kill() + p.communicate() + + +def test_both_reviews_pick_the_same_commits(repo): + """The output names a commit but has no diffstat: both go by the reflog.""" + (repo / "quiet.py").write_text("print('quiet')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "quiet") + out, err = _run(repo, "commit", "--allow-empty", "-m", "marker") + pout, perr = _run(repo, "push") + output = out + pout + err + perr + assert hook._COMMIT_SHA_RE.findall(output) and not hook._commit_in_output(output) + both = git(repo, "rev-list", "@{u}@{1}..HEAD").split() + assert hook._commit_review_candidates(output, str(repo))[0][:2] == both + assert not _beyond(repo, output) + + +def test_quiet_commit_then_empty_commit_runs_one_review(repo, hook_env, stub_api): + (repo / "quiet.py").write_text("print('quiet')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "quiet") + out, err = _run(repo, "commit", "--allow-empty", "-m", "marker") + pout, perr = _run(repo, "push") + stub_api.delay = 2 + commit, push = _both_spawns( + repo, hook_env, out + pout, err + perr, + command="git commit -q -m quiet && git commit --allow-empty -m marker && git push") + assert commit[1]["sha_via_reflog"] is True and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_slow_commit_review_is_left_alone(repo, hook_env, stub_api): + """It outlasts the wait: skipped as before, not reviewed twice.""" + out, err = _commit_and_push(repo) + stub_api.delay = 4 + commit, push = _both_spawns(repo, {**hook_env, "SG_INFLIGHT_WAIT_S": "1"}, out, err) + assert "skip_reason" not in commit[1] and push[1]["skip_reason"] == 47 + assert "commit_no_verdict" not in push[1] + assert _reviews(stub_api) == 1 + + +def test_take_over_after_head_moved(repo, hook_env, stub_api): + """Another commit landed meanwhile: still reviewed, as it was pushed.""" + out, err = _commit_and_push(repo) + pushed = _head(repo) + stub_api.fail_first, stub_api.delay = 2, 2 + + def move_head(commit): + _until(lambda: diffstate.is_held(str(repo / ".git" / "sg-hook-once-t1-push")), + "the push spawn's wait") + commit_file(repo, "later.py", "print('later')\n", "later") + + _, push = _both_spawns(repo, hook_env, out, err, move_head) + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + assert "new.py" in stub_api.bodies[-1] and "later.py" not in stub_api.bodies[-1] + assert _load_reviewed_shas(str(repo)) == {pushed} + + +def test_no_promise_of_a_push_review_that_ended(repo, hook_env, stub_api): + """Two branches pushed: that push review skips, and nothing takes over.""" + git(repo, "branch", "side") + git(repo, "push", "-q", "origin", "side") + git(repo, "checkout", "-q", "side") + commit_file(repo, "side.py", "print('side')\n", "side") + git(repo, "checkout", "-q", "main") + (repo / "new.py").write_text("print('new')\n") + git(repo, "add", "-A") + out, err = _run(repo, "commit", "-m", "new") + pout, perr = _run(repo, "push", "--all", "origin") + stub_api.fail_first, stub_api.delay = 2, 2 + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit -m new && git push --all origin") + assert push[1]["skip_reason"] == 44 and commit[1]["review_failed"] is True + assert "a later push will not re-check it" in commit[2] + + +def test_message_only_amend_while_the_original_is_under_review(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 5 + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_failed_review_at_the_cap_still_reports(repo, hook_env, stub_api): + """The cap leaves the push review no turn, so the commit review reports.""" + out, err = _commit_and_push(repo) + stub_api.fail_first, stub_api.delay = 2, 1 + commit, push = _both_spawns(repo, {**hook_env, "MAX_COMMIT_REVIEWS_PER_HOUR": "1"}, out, err) + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + assert push[1]["skip_reason"] == 23 + + +def test_both_reviews_fail(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.status = 400 + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[0] == 0 and commit[1]["review_failed"] is True + assert push[0] == 2 and "a later push will not re-check them" in push[2] + + +def test_older_commit_under_another_review_is_left_to_it(repo, hook_env, stub_api): + _, made = commit_file(repo, "older.py", "print('older')\n", "older") + stub_api.delay = 4 + with _spawn(bash_payload(str(repo), "git commit -m older", made), hook_env) as older: + _until(lambda: _reviews(stub_api) == 1, "the older commit's review") + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + older.communicate(timeout=60) + assert push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 2 -- cgit From 8c431861e8bb8f77f23601c8d6b9fdc5c1fadc90 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:31:00 +0000 Subject: security-guidance: wait for the original review on a message-only amend, and report a failure the push review did not A message-only amend made while the first review was running counted as reviewed at once. When that review then failed, a later push reviewed nothing. The amend now waits for that review. A failed commit review stayed quiet for the push review of its own command, which can itself end quietly (a cap, no network, killed). It now waits for the push review, and reports unless that one got a verdict or told of its own failure. Co-authored-by: mhegazy --- plugins/security-guidance/hooks/diffstate.py | 18 ++- .../hooks/security_reminder_hook.py | 65 ++++++++--- .../tests/test_chained_commit_push.py | 130 +++++++++++++++++++++ 3 files changed, 196 insertions(+), 17 deletions(-) (limited to 'plugins') diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 3315e84b..a94363f4 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -1228,9 +1228,13 @@ def _mark_inflight(repo_root, shas): pass +_holds = {} + + def hold_until_exit(path): - """Lock the file at `path` until this process ends, so that others can - see it `is_held`. Best-effort; never raises.""" + """Lock the file at `path` until this process ends or calls + `release_hold`, so that others can see it `is_held`. Best-effort; never + raises.""" import time as _time try: fd = _open_own_file(path, os.O_RDWR) @@ -1239,13 +1243,21 @@ def hold_until_exit(path): try: for _ in range(10): # another process may be looking at this moment if _flock_nb(fd, exclusive=True): - return # left open: the lock goes when the process does + _holds[path] = fd # left open: the lock goes when the process does + return _time.sleep(0.01) except OSError: pass os.close(fd) +def release_hold(path): + """Give up the lock `hold_until_exit` took. Never raises.""" + fd = _holds.pop(path, None) + if fd is not None: + _drop_marker(path, fd, unlink=False) + + def is_held(path): """Whether a live process holds the file at `path`; None when that cannot be told (no such file, or no locks here).""" diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 15578cc3..fd7c9caf 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -1508,6 +1508,9 @@ _RACE_MAX_WAIT_S = 480 # Claude Code kills the hook. The inner CLI exits with the hook. The same limit # holds for a commit or push review's single-shot review outside a race. _RACE_END_S = 570 +# Seconds after which a failed commit review stops waiting for the push review +# of its own command, which may run to the limit above on a later clock. +_HOOK_LAST_WAIT_S = 580 # api_error for a race that hit that deadline with no verdict. _RACE_TIMED_OUT = -2 @@ -1738,25 +1741,37 @@ def _left_out_files_notice(session_id, repo_root, untracked, diff_output): f"in {DEBUG_LOG_FILE}.") -def _push_review_takes_over(input_data, rate_n): +def _push_review_takes_over(input_data): """True when the push spawn of this commit-and-push call waits to review - what this commit review, the `rate_n`th within the cap, has no verdict on.""" + what this commit review has no verdict on.""" command = input_data["tool_input"]["command"] sentinel = _bash_hook_sentinel(input_data, "push") return bool( PUSH_SWEEP_ENABLED and sentinel and _GIT_PUSH_RE.search(command) - and rate_n < MAX_COMMIT_REVIEWS_PER_HOUR # It may still be on its way to the wait when a review fails at once. and diffstate.becomes_held(sentinel, 3)) -def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): +def _push_review_settled_it(input_data): + """Let the push review that waits for this commit review go on, and wait + for its end. False when it ended without a verdict and told nobody (a cap, + no network, killed): that is for the commit review to report.""" + debug_log("Commit review: got no verdict; waiting for the push review of the same command") + diffstate._release_inflight() + diffstate.release_hold(_bash_hook_sentinel(input_data)) + diffstate.wait_for_holder(_bash_hook_sentinel(input_data, "push"), + max(0.0, _HOOK_LAST_WAIT_S - _hook_spent_s())) + return os.path.exists(_bash_hook_sentinel(input_data, "settled")) + + +def _exit_review_failed(kind, session_id, metrics, status, pushed="no", told=None): """End a commit ("Commit") or push ("Push") review that got no verdict. Never reports the code as clean. Tells Claude once per session for each kind of review and failure; repeats are only logged. `pushed` ("yes", "maybe" or "no"): whether the commit's own command also pushed it; - "taken_over" when that command's push review takes it from here. Exits. + "taken_over" when that command's push review dealt with it. `told` is + called when Claude is told. Exits. """ failure, reason, cause = _review_failure_reason(status) debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed") @@ -1766,7 +1781,6 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): # A commit its own command pushed gets its own notice: no later push # re-checks it. told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "") - # With a push review waiting to take over, that one reports. if pushed == "taken_over" or not atomic_check_and_mark_warning(session_id, told_key): emit_metrics(metrics) sys.exit(0) @@ -1794,6 +1808,8 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): emit_metrics(metrics, rewake_summary=(f"{kind} security review did not complete: {reason}. " f"Log: {DEBUG_LOG_FILE}")) + if told: + told() sys.exit(2) def _commit_in_output(bash_output): @@ -2128,13 +2144,19 @@ def handle_commit_review_posttooluse(input_data): # skip_reason=28 correctly. if pre_amend_sha and not diff_files: debug_log("Commit review: --amend produced empty delta (message-only?), skipping") - # Same content under a new sha: as reviewed as the original is or, - # with its review still running, will be. - if (pre_amend_sha in _load_inflight_shas(repo_root, [pre_amend_sha]) - or pre_amend_sha in _load_reviewed_shas(repo_root)): - _append_reviewed_shas(repo_root, _full_shas(repo_root, shas)) + # Same content under a new sha: as reviewed as the original is. With + # its review still running, see that end first. A push review of the + # new sha waits for this process meanwhile: wait less than it does, so + # that it can still review what has no verdict by then. + _new = _full_shas(repo_root, shas) + _mark_inflight(repo_root, _new) + reviewed, _waited = _reviewed_after_inflight( + repo_root, [pre_amend_sha], max(0.0, INFLIGHT_WAIT_S * 0.9 - _hook_spent_s())) + if pre_amend_sha in reviewed: + _append_reviewed_shas(repo_root, _new) emit_metrics({"skipped": True, "skip_reason": 35, **_base, - "files_reviewed": 0}) + "files_reviewed": 0, + **({"inflight_wait_s": max(1, int(round(_waited)))} if _waited else {})}) sys.exit(0) debug_log(f"Commit review: {resolved}/{len(shas)} sha(s) resolved, " @@ -2273,7 +2295,8 @@ def handle_commit_review_posttooluse(input_data): **_base, **_agentic_m, "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status, pushed=( - "taken_over" if _push_review_takes_over(input_data, _rate_n) + "taken_over" if _push_review_takes_over(input_data) + and _push_review_settled_it(input_data) else "yes" if _push_in_output(bash_output) else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command) else "no")) @@ -2573,6 +2596,13 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) + def _note_settled(): + # Tells the commit spawn of this call that it has nothing to report. + if (_GIT_COMMIT_RE.search(command) and any( + s.startswith(c) for s in push_range + for c in _commit_review_candidates(bash_output, repo_root)[0])): + _claim_bash_hook_once(input_data, "settled") + _spawn_wait, _take_over = 0.0, False if _GIT_COMMIT_RE.search(command) and not _pushed_beyond_commit_review( repo_root, push_range, bash_output): @@ -2585,6 +2615,10 @@ def handle_push_sweep_posttooluse(input_data): _ended, _spawn_wait = diffstate.wait_for_holder( _bash_hook_sentinel(input_data), INFLIGHT_WAIT_S) _take_over = _ended and _without_review(repo_root, push_range) + if _ended and not _take_over: + reviewed = _load_reviewed_shas(repo_root) + if all(s in reviewed for s in push_range): + _note_settled() # A commit the hourly cap kept out stays out. _skip = (47 if not _take_over else 23 if atomic_check_rate_limit( @@ -2625,6 +2659,7 @@ def handle_push_sweep_posttooluse(input_data): prefix_advanced = 0 if base is None: debug_log("Push sweep: every pushed commit already reviewed") + _note_settled() emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, "prefix_advanced": prefix_advanced, **_wait_m}) sys.exit(0) @@ -2662,6 +2697,7 @@ def handle_push_sweep_posttooluse(input_data): "unreviewed": len(tail), "skip_reason": 30}) # Still mark tail reviewed — there's nothing to review. _append_reviewed_shas(repo_root, tail, vulns_found=0) + _note_settled() sys.exit(0) # Same prioritize-don't-bail logic as commit-review (see comment there). # push-sweep ranges are net diffs over many commits so they hit the cap @@ -2733,10 +2769,11 @@ def handle_push_sweep_posttooluse(input_data): _exit_review_failed("Push", session_id, { **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), "files_reviewed": len(diff_files), "review_ms": review_ms, - }, api_status) + }, api_status, told=_note_settled) # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) + _note_settled() _diff_review_done(_diff_token) new_vulns, n_deduped = _dedup_against_state( diff --git a/plugins/security-guidance/tests/test_chained_commit_push.py b/plugins/security-guidance/tests/test_chained_commit_push.py index 5d702371..9b105362 100644 --- a/plugins/security-guidance/tests/test_chained_commit_push.py +++ b/plugins/security-guidance/tests/test_chained_commit_push.py @@ -381,3 +381,133 @@ def test_older_commit_under_another_review_is_left_to_it(repo, hook_env, stub_ap older.communicate(timeout=60) assert push[1]["skip_reason"] == 47 assert _reviews(stub_api) == 2 + + +@pytest.mark.parametrize("chained", [False, True]) +def test_message_only_amend_of_a_commit_whose_review_fails(repo, hook_env, stub_api, chained): + """The amended commit is not recorded on the word of a review that then + gives no verdict: the push review covers it.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay, stub_api.fail_first = 5, 2 + amend = "git commit --amend -m better" + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env) as orig: + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + if chained: + pout, perr = _run(repo, "push") + _, (_, push, _) = _both_spawns(repo, hook_env, out + pout, err + perr, + command=amend + " && git push") + else: + run_hook(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env) + pout, perr = _run(repo, "push") + push = metrics_of(run_hook(bash_payload( + str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1]) + orig.communicate(timeout=60) + assert "skip_reason" not in push and push["unreviewed"] == 1 + assert _reviews(stub_api) == 3 # the review, its retry, the push review + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def _push_only(repo, env, tool_use_id, name): + commit_file(repo, name, "print('outside')\n", name) + out, err = _run(repo, "push") + return run_hook(bash_payload(str(repo), "git push", out, stderr=err, + tool_use_id=tool_use_id), env) + + +def test_failure_is_told_when_the_push_review_is_at_its_cap(repo, hook_env, stub_api): + hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "2" + for n in ("p1", "p2"): + assert "skip_reason" not in metrics_of(_push_only(repo, hook_env, n, n + ".py")[1]) + out, err = _commit_and_push(repo) + stub_api.status, stub_api.delay = 400, 1 + commit, push = _both_spawns(repo, hook_env, out, err) + assert push[1]["skip_reason"] == 23 and not push[2] + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + + +def test_failure_is_told_when_the_push_review_told_of_one_before(repo, hook_env, stub_api): + stub_api.status = 400 + assert "did not complete" in _push_only(repo, hook_env, "p1", "p1.py")[2] + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + assert push[0] == 0 and push[1]["review_failed"] is True + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + + +def test_failure_is_told_when_the_push_review_is_killed(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + payload = bash_payload(str(repo), CMD, stdout=out, stderr=err, tool_use_id="t1") + stub_api.fail_first, stub_api.delay = 2, 4 + with _spawn(payload, hook_env) as commit: + _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim") + with _spawn(payload, hook_env) as push: + _until(lambda: _reviews(stub_api) == 3, "the push review's request") + push.kill() + _, told = commit.communicate(timeout=60) + assert commit.returncode == 2 and "a later push will not re-check it" in told + + +def test_other_commits_of_the_command_do_not_bring_a_failure_notice(repo, hook_env, stub_api): + """Only what was pushed is for the push review: the commit that was then + amended is not, and the review of the rest succeeded.""" + (repo / "new.py").write_text("print('new')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "wip") + git(repo, "commit", "-q", "--amend", "-m", "done") + out, err = _run(repo, "push") + stub_api.fail_first, stub_api.delay = 2, 1 + commit, push = _both_spawns( + repo, hook_env, out, err, + command="git commit -q -m wip && git commit -q --amend -m done && git push") + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + assert commit[0] == 0 and not commit[2] + + +def test_separate_push_waits_for_a_message_only_amend(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 6 + amend = "git commit --amend -m better" + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + with _spawn(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env) as p: + marker = repo / ".git" / ("sg-inflight-" + _head(repo)) + _until(lambda: diffstate.is_held(str(marker)), "the amend's claim") + pout, perr = _run(repo, "push") + push = metrics_of(run_hook(bash_payload( + str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1]) + p.communicate(timeout=60) + assert push["unreviewed"] == 0 and push["inflight_wait_s"] >= 1 + assert _reviews(stub_api) == 1 + + +def test_amend_waits_less_than_its_push_review(repo, hook_env, stub_api): + """The original outlasts both waits: the push review still gets its turn.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 25 + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "15"} + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and commit[1]["inflight_wait_s"] >= 1 + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + + +def test_failure_of_a_commit_elsewhere_is_told(repo, hook_env, stub_api, tmp_path): + """The push is of another repository, whose commits are all reviewed.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env) + lib = make_repo(tmp_path / "lib") + (lib / "x.py").write_text("print('x')\n") + git(lib, "add", "-A") + out, err = _run(lib, "commit", "-m", "x") + pout, perr = _run(repo, "push") + stub_api.status, stub_api.delay = 400, 1 + commit, _ = _both_spawns( + repo, hook_env, out + pout, err + perr, + command=f"git -C {lib} commit -m x && git push") + assert commit[0] == 2 and "did not complete" in commit[2] -- cgit