summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/diffstate.py
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-13 20:52:59 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:40:32 +0000
commit7e05205b41cbd5d3c8884f7effc8688c10e2cf00 (patch)
tree8bd75dc2ce0f8db6187b64630b6ad5942e5720f0 /plugins/security-guidance/hooks/diffstate.py
parent83e004a98e1fc268a94cc6a74b1b054630542696 (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/security-guidance/hooks/diffstate.py')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py188
1 files changed, 185 insertions, 3 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)
# =====================================================================