diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-13 20:52:59 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-15 22:40:32 +0000 |
| commit | 7e05205b41cbd5d3c8884f7effc8688c10e2cf00 (patch) | |
| tree | 8bd75dc2ce0f8db6187b64630b6ad5942e5720f0 /plugins | |
| parent | 83e004a98e1fc268a94cc6a74b1b054630542696 (diff) | |
security-guidance: do not review a commit twice while its first review is runningmhegazy/sg-inflight-reviews
A commit review records its commits only once it has a verdict. A push
(or the next commit's reflog scan) that started before then reviewed the
same diff again. A running review now holds a lock file per commit in the
git dir; a push review waits for it and skips what it recorded, and the
reflog scan leaves those commits to it.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 188 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 45 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_inflight_reviews.py | 248 |
3 files changed, 473 insertions, 8 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 74870c15..7c5853ec 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -280,14 +280,19 @@ def capture_git_baseline(cwd): _REVIEWED_SHAS_BASENAME = "sg-reviewed-shas" _REVIEWED_SHAS_CAP = 500 +def _is_full_sha(sha): + return len(sha) == 40 and all(c in "0123456789abcdef" for c in sha) + + def _reviewed_shas_path(repo_root): gd = _git_dir(repo_root) return os.path.join(gd, _REVIEWED_SHAS_BASENAME) if gd else None -def _load_reviewed_shas(repo_root): +def _load_reviewed_shas(repo_root, _gd=None): """Set of full 40-hex shas previously reviewed in this clone.""" - p = _reviewed_shas_path(repo_root) + p = (os.path.join(_gd, _REVIEWED_SHAS_BASENAME) if _gd + else _reviewed_shas_path(repo_root)) if not p or not os.path.exists(p): return set() out = set() @@ -295,7 +300,7 @@ def _load_reviewed_shas(repo_root): with open(p, "r") as f: for line in f: sha = line.split("\t", 1)[0].strip() - if len(sha) == 40 and all(c in "0123456789abcdef" for c in sha): + if _is_full_sha(sha): out.add(sha) except OSError: pass @@ -347,6 +352,183 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): pass +# ─── in-flight review markers ─────────────────────────────────────────────── +# +# A commit or push review records its shas only once it has a verdict, which +# is minutes after it starts. A review that starts in between (the push right +# after a commit, the next commit's reflog scan) would send the same commits +# through a second full review. So a review first takes an exclusive flock on +# `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its +# process ends; other reviews leave a locked commit to it. The kernel drops +# the lock however the holder dies, so a killed review blocks nobody. Without +# flock (native Windows Python, some network filesystems) there are no +# markers and nothing changes. + +_INFLIGHT_PREFIX = "sg-inflight-" +# A marker file nobody holds (a killed review's) is removed once this old. +_INFLIGHT_GC_AGE_S = 3600 +_inflight_held = {} + + +def _full_shas(repo_root, shas): + """Resolve abbreviated commit refs to full 40-hex shas; drops unresolved.""" + out = [] + for s in shas: + try: + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", s], + cwd=repo_root, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + continue + if r.returncode == 0: + out.append(r.stdout.decode("utf-8", errors="replace").strip()) + return out + + +def _flock_nb(fd, exclusive): + """True when the lock was taken, False when another process holds it. + Raises OSError when the file cannot be locked at all.""" + import errno + import fcntl + try: + fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB) + return True + except OSError as e: + if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN): + return False + raise + + +def _release_inflight(): + for p, fd in list(_inflight_held.items()): + try: + os.unlink(p) + except OSError: + pass + try: + os.close(fd) + except OSError: + pass + _inflight_held.clear() + + +def _sweep_inflight(gd): + """Remove old marker files no review holds.""" + import time as _time + cutoff = _time.time() - _INFLIGHT_GC_AGE_S + for name in os.listdir(gd): + p = os.path.join(gd, name) + if not name.startswith(_INFLIGHT_PREFIX) or p in _inflight_held: + continue + try: + if os.path.getmtime(p) > cutoff: + continue + fd = os.open(p, os.O_RDWR) + except OSError: + continue + try: + if _flock_nb(fd, exclusive=True): + os.unlink(p) + except OSError: + pass + os.close(fd) + + +def _mark_inflight(repo_root, shas): + """Claim `shas` (full 40-hex) for the review this process is about to + run, until the process ends. Best-effort; never raises. A commit another + live review holds stays with that review.""" + try: + import fcntl # noqa: F401 + gd = _git_dir(repo_root) + if not gd: + return + _sweep_inflight(gd) + for sha in shas: + p = os.path.join(gd, _INFLIGHT_PREFIX + sha) + if not _is_full_sha(sha) or p in _inflight_held: + continue + fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600) + try: + # The inode check: a holder unlinks its marker when it ends, + # and a lock on that unlinked file would claim nothing. + held = (_flock_nb(fd, exclusive=True) + and os.fstat(fd).st_ino == os.stat(p).st_ino) + except OSError: + # Cannot lock here at all: leave no file that reads as held. + os.close(fd) + os.unlink(p) + return + if not held: + os.close(fd) + continue + if not _inflight_held: + import atexit + atexit.register(_release_inflight) + _inflight_held[p] = fd + os.utime(p) + except Exception: + pass + + +def _load_inflight_shas(repo_root, shas, _gd=None): + """Which of `shas` another live review in this clone holds right now.""" + out = set() + try: + import fcntl # noqa: F401 + except ImportError: + return out + gd = _gd or _git_dir(repo_root) + if not gd: + return out + for sha in shas: + p = os.path.join(gd, _INFLIGHT_PREFIX + sha) + if not _is_full_sha(sha) or p in _inflight_held: + continue + try: + fd = os.open(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) + return out + + +def _reviewed_after_inflight(repo_root, push_range, max_wait_s, poll_s=1.0): + """The reviewed-sha set for a push of `push_range` (oldest first), read + once no other review is still running on the commit the push review + would start from, or after `max_wait_s`. Returns (reviewed, waited_s).""" + import time as _time + gd = _git_dir(repo_root) + start = _time.monotonic() + waited = False + reviewed = _load_reviewed_shas(repo_root, _gd=gd) + while gd: + # Only the first unreviewed commit matters: if nobody is reviewing + # it, the push review covers everything from there on anyway. + first = next((s for s in push_range if s not in reviewed), None) + if first is None: + break + # In-flight before reviewed: a review that ends between the two + # reads then shows up as reviewed rather than as neither. + busy = _load_inflight_shas(repo_root, [first], _gd=gd) + reviewed = _load_reviewed_shas(repo_root, _gd=gd) + if first in reviewed: + continue + if not busy or _time.monotonic() - start >= max_wait_s: + break + waited = True + _time.sleep(poll_s) + return reviewed, (_time.monotonic() - start) if waited else 0.0 + + # ===================================================================== # v2 review-set computation (Stop hook) # ===================================================================== diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3608ec1d..bcd22e36 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -117,6 +117,7 @@ from diffstate import ( # noqa: E402,F401 get_baseline_file_content, capture_git_baseline, _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP, _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, + _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, ) from reporesolve import ( # noqa: E402,F401 @@ -755,6 +756,13 @@ _PUSH_RANGE_RE = re.compile( MAX_PUSH_SWEEP_FILES = int(os.environ.get("SG_PUSH_SWEEP_MAX_FILES", "30")) MAX_PUSH_SWEEP_RANGE = int(os.environ.get("SG_PUSH_SWEEP_MAX_RANGE", "50")) PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3")) +# How long a push review waits for a commit review that is still running on +# the pushed commits, before reviewing them itself. Longer than the agentic +# race delay, so a commit review that fell back to single-shot can finish. +try: + INFLIGHT_WAIT_S = int(os.environ.get("SG_INFLIGHT_WAIT_S", "") or 240) +except ValueError: + INFLIGHT_WAIT_S = 240 def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. @@ -1235,8 +1243,13 @@ def handle_commit_review_posttooluse(input_data): _root = repo_root _fresh, _stale = _git_reflog_recent_commits(_root) if _fresh: + # Commits an earlier call's review is still working on are that + # review's: it records them when it has a verdict. (Read before + # the reviewed set, so one that ends in between counts as reviewed.) + _inflight = _load_inflight_shas(_root, _fresh) _already = _load_reviewed_shas(_root) - _reflog_shas = [s for s in _fresh if s not in _already] + _reflog_shas = [s for s in _fresh + if s not in _already and s not in _inflight] if _reflog_shas: commit_succeeded = True debug_log( @@ -1248,8 +1261,9 @@ def handle_commit_review_posttooluse(input_data): # Fresh commit(s) in reflog but all already in # sg-reviewed-shas — likely a Bash retry or the commit was # reviewed via a prior fire. Correct to skip; sub=2 lets telemetry - # split this from genuine fails. - _skip_21_sub = 2 + # split this from genuine fails. sub=5: at least one is still + # being reviewed by an earlier call. + _skip_21_sub = 5 if any(s not in _already for s in _fresh) else 2 elif _stale: _skip_21_sub = 3 # commit entries exist but all >120s old else: @@ -1509,6 +1523,10 @@ def handle_commit_review_posttooluse(input_data): previous_findings = with_locked_state(session_id, _read_previous) or [] + # Tell a push review (or the next commit's reflog scan) that these commits + # are being reviewed, so it does not start a second review of them. + _mark_inflight(repo_root, _full_shas(repo_root, shas)) + review_start = _time.time() agentic_metrics: Dict[str, Any] = {} @@ -1862,13 +1880,27 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) - reviewed = _load_reviewed_shas(repo_root) + # 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) + _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) if base is None: debug_log("Push sweep: every pushed commit already reviewed") emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, - "prefix_advanced": prefix_advanced}) + "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. + debug_log("Push sweep: HEAD moved while waiting, skipping") + emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m}) sys.exit(0) debug_log(f"Push sweep: range={len(push_range)} prefix_advanced=" @@ -1921,6 +1953,8 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 23, **_base}) sys.exit(0) + _mark_inflight(repo_root, tail) + import time as _time now = _time.time() previous_findings = with_locked_state( @@ -1983,6 +2017,7 @@ def handle_push_sweep_posttooluse(input_data): "prefix_advanced": prefix_advanced, "vulns_found": len(new_vulns), "files_reviewed": len(diff_files), "review_ms": review_ms, **({"deduped": n_deduped} if n_deduped else {}), + **_wait_m, } _push_rewake_summary = _format_vulns_summary(new_vulns, prefix="Push security review found") diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py new file mode 100644 index 00000000..4e00c608 --- /dev/null +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -0,0 +1,248 @@ +"""A commit still under review is not sent through a second review.""" +import contextlib +import json +import os +import subprocess +import sys +import time + +import pytest + +from conftest import ( + HOOK_SCRIPT, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, +) + +import diffstate + +pytest.importorskip("fcntl") + +_HOLD = ( + "import fcntl, os, sys, time\n" + "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n" + "fcntl.flock(fd, fcntl.LOCK_EX)\n" + "print('held', flush=True)\n" + "time.sleep(float(sys.argv[2]))\n" +) + + +@contextlib.contextmanager +def _held_by_another_review(repo, sha, seconds=60): + """A marker on `sha` that a live process holds, as a running review does.""" + marker = repo / ".git" / f"sg-inflight-{sha}" + p = subprocess.Popen([sys.executable, "-c", _HOLD, str(marker), str(seconds)], + stdout=subprocess.PIPE, text=True) + try: + assert p.stdout.readline().strip() == "held" + yield marker + finally: + p.kill() + p.wait() + p.stdout.close() + + +@contextlib.contextmanager +def _hook_in_background(payload, env): + p = subprocess.Popen( + [sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, env=env, + ) + try: + p.stdin.write(json.dumps(payload)) + p.stdin.close() + yield p + finally: + if p.poll() is None: + p.kill() + p.wait() + p.stdout.close() + + +def _repo_with_remote(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + remote = tmp_path / "remote.git" + git(tmp_path, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + return repo, remote + + +def _markers(repo): + return [n for n in os.listdir(repo / ".git") if n.startswith("sg-inflight-")] + + +def _wait_until(cond, what, timeout=20): + end = time.time() + timeout + while time.time() < end: + if cond(): + return + time.sleep(0.05) + raise AssertionError(f"timed out waiting for {what}") + + +def _reviews(stub_api): + return [c for c in stub_api.calls if c.endswith("/v1/messages")] + + +def _commit_and_push(repo, remote): + base = git(repo, "rev-parse", "HEAD").strip() + sha, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + git(repo, "push", "-q", "origin", "main") + push_out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + return base, sha, commit_out, push_out + + +def test_push_right_after_commit_runs_one_review(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, commit_out, push_out = _commit_and_push(repo, remote) + stub_api.delay = 6 + with _hook_in_background(bash_payload(repo, "git commit -m change", commit_out), + hook_env) as commit: + _wait_until(lambda: _markers(repo), "the commit review's marker") + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + commit.wait(timeout=60) + + m = metrics_of(so) + assert rc == 0 and m["push_sweep"] is True + assert m["pushed"] == 1 and m["unreviewed"] == 0 + assert m.get("inflight_wait_s", 0) >= 1 + assert len(_reviews(stub_api)) == 1 + assert sha in diffstate._load_reviewed_shas(str(repo)) + assert _markers(repo) == [] + + +def test_push_reviews_commit_whose_review_died(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + with _held_by_another_review(repo, sha): + pass # killed: its marker file stays, its lock does not + assert _markers(repo) == [f"sg-inflight-{sha}"] + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 and "inflight_wait_s" not in m + assert len(_reviews(stub_api)) == 1 + assert _markers(repo) == [] + + +def test_push_reviews_commit_whose_review_ended_without_a_verdict(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + with _held_by_another_review(repo, sha, seconds=3): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 + assert m["files_reviewed"] == 1 and len(_reviews(stub_api)) == 1 + assert sha in diffstate._load_reviewed_shas(str(repo)) + + +def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "2"} + with _held_by_another_review(repo, sha): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 and m["inflight_wait_s"] >= 2 + assert len(_reviews(stub_api)) == 1 + + +def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base = git(repo, "rev-parse", "HEAD").strip() + commit_file(repo, "outside.py", "def o(x):\n return x\n") + sha, _ = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + git(repo, "push", "-q", "origin", "main") + push_out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + with _held_by_another_review(repo, sha): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["pushed"] == 2 and m["unreviewed"] == 2 and "inflight_wait_s" not in m + assert m["files_reviewed"] == 2 + + +def test_push_does_not_record_the_range_when_head_moves_during_the_wait(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "10"} + with _held_by_another_review(repo, sha): + with _hook_in_background(bash_payload(repo, "git push origin main", push_out), + env) as push: + time.sleep(5) + git(repo, "checkout", "-q", "-b", "elsewhere", base) + so = push.stdout.read() + push.wait(timeout=60) + + m = metrics_of(so) + assert m["skip_reason"] == 44 and m.get("inflight_wait_s", 0) >= 1 + assert _reviews(stub_api) == [] + assert sha not in diffstate._load_reviewed_shas(str(repo)) + + +def test_next_quiet_commit_leaves_a_running_review_its_commit(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + commit_file(repo, "a.py", "def a(x):\n return x\n") + stub_api.delay = 6 + with _hook_in_background(bash_payload(repo, "git commit -q -m a"), hook_env) as first: + _wait_until(lambda: _markers(repo), "the first review's marker") + commit_file(repo, "b.py", "def b(x):\n return x\n") + rc, so, _ = run_hook(bash_payload(repo, "git commit -q -m b"), hook_env) + first.wait(timeout=60) + + m = metrics_of(so) + assert m["sha_via_reflog"] is True and m["reflog_shas_n"] == 1 + assert m["files_reviewed"] == 1 + assert _markers(repo) == [] + + +def test_marker_is_not_taken_from_a_live_review(tmp_path): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + with _held_by_another_review(repo, sha) as marker: + diffstate._mark_inflight(str(repo), [sha]) + assert diffstate._inflight_held == {} + assert diffstate._load_inflight_shas(str(repo), [sha]) == {sha} + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + assert marker.exists() # fresh leftovers stay; old ones are removed + old = time.time() - diffstate._INFLIGHT_GC_AGE_S - 5 + os.utime(marker, (old, old)) + diffstate._mark_inflight(str(repo), []) + assert not marker.exists() + + +def test_no_marker_is_left_where_files_cannot_be_locked(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + + def no_locks(fd, exclusive): + raise OSError(37, "No locks available") + monkeypatch.setattr(diffstate, "_flock_nb", no_locks) + diffstate._mark_inflight(str(repo), [sha]) + assert _markers(repo) == [] and diffstate._inflight_held == {} + (repo / ".git" / f"sg-inflight-{sha}").write_text("") + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + + +def test_own_marker_is_held_until_released(tmp_path): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + diffstate._mark_inflight(str(repo), [sha, "not-a-sha"]) + marker = repo / ".git" / f"sg-inflight-{sha}" + try: + assert _markers(repo) == [marker.name] + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + probe = ( + "import sys; sys.path.insert(0, sys.argv[1]); import diffstate; " + "print(sorted(diffstate._load_inflight_shas(sys.argv[2], [sys.argv[3]])))" + ) + seen = subprocess.run( + [sys.executable, "-c", probe, os.path.dirname(diffstate.__file__), str(repo), sha], + capture_output=True, text=True).stdout.strip() + assert seen == str([sha]) + reviewed, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 5) + assert reviewed == set() and waited == 0.0 + finally: + diffstate._release_inflight() + assert not marker.exists() |
