summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-11-04 17:29:19 +0000
committerClaude <noreply@anthropic.com>2026-11-04 17:29:19 +0000
commit18750c0f8aeea95d5c53ab41bb5e427b79582e65 (patch)
tree23e91e40e0d1d681a19b50d92deaa9cd5944f083 /plugins
parent9d796f8636954cece459f45ff7386eaee912de5c (diff)
security-guidance: count a push review's wait against the hook's time limit
Diffstat (limited to 'plugins')
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py20
-rw-r--r--plugins/security-guidance/tests/test_inflight_reviews.py58
2 files changed, 71 insertions, 7 deletions
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 6897ea66..f67c181c 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -1266,9 +1266,9 @@ def is_commit_review_enabled():
COMMIT_REVIEW_ENABLED = is_commit_review_enabled()
-# Seconds from the start of a commit or push review's race after which
-# neither side waits for the other any longer; well inside Claude Code's
-# 10-minute hook timeout.
+# Seconds into a commit or push review after which neither side of its race
+# waits for the other any longer; well inside Claude Code's 10-minute hook
+# timeout. Time the hook spent before the race counts.
_RACE_MAX_WAIT_S = 480
# Seconds after which the review ends even if a side is still waiting on a
# request that does not answer, with time left to tell the session before
@@ -1282,6 +1282,7 @@ def _agentic_review_with_race(
diff_files: List[Tuple[str, str]],
rel_touched: List[str],
previous_findings: List[Dict[str, Any]],
+ spent_s: float = 0.0,
) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
"""Race the agentic reviewer against a delayed single-shot fallback.
@@ -1293,6 +1294,9 @@ def _agentic_review_with_race(
verdict) is returned so the caller never starts another review. If agentic
finishes before the delay, the fallback never runs.
+ `spent_s`, the time the hook already waited, comes off the delay and both
+ limits: the hook's time limit does not restart with the race.
+
Metrics added:
race_winner : 1 = agentic won, 2 = fallback won (CC accepts only
bool/finite-number metric values — strings would discard the dict)
@@ -1310,13 +1314,15 @@ def _agentic_review_with_race(
if os.environ.get("SG_AGENTIC_NO_RACE") == "1":
return agentic_review(repo_root, diff_files, rel_touched)
- delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180"))
+ delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s))
+ if spent_s:
+ debug_log(f"Review race: {spent_s:.0f}s already spent, fallback starts after {delay_s}s")
q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1)
fallback_started = _th.Event()
fallback_done = _th.Event()
agentic_done = _th.Event()
fallback_result: Dict[str, Any] = {}
- deadline = _t.monotonic() + _RACE_MAX_WAIT_S
+ deadline = _t.monotonic() + max(0.0, _RACE_MAX_WAIT_S - spent_s)
timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT})
def _agentic() -> None:
@@ -1362,7 +1368,7 @@ def _agentic_review_with_race(
_th.Thread(target=_fallback, daemon=True).start()
try:
- winner, (g, v, m) = q.get(timeout=_RACE_END_S)
+ winner, (g, v, m) = q.get(timeout=max(0.0, _RACE_END_S - spent_s))
except _queue.Empty:
debug_log("review race: nothing returned in time")
winner, (g, v, m) = "fallback", timed_out
@@ -2294,7 +2300,7 @@ def handle_push_sweep_posttooluse(input_data):
rel_touched = [fp for fp, _ in diff_files]
if _agentic_commit_review_enabled():
concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race(
- repo_root, diff_files, rel_touched, previous_findings
+ repo_root, diff_files, rel_touched, previous_findings, spent_s=_waited,
)
if agentic_metrics.get("child_stderr"):
_TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"]
diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py
index 4c339a5f..570f9bd6 100644
--- a/plugins/security-guidance/tests/test_inflight_reviews.py
+++ b/plugins/security-guidance/tests/test_inflight_reviews.py
@@ -4,6 +4,7 @@ import json
import os
import subprocess
import sys
+import threading
import time
import pytest
@@ -152,6 +153,63 @@ def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api):
assert len(_reviews(stub_api)) == 1
+def test_a_push_that_waited_ends_within_the_hook_limit(tmp_path, monkeypatch):
+ """The wait for a commit review and the race share one limit; a race that
+ restarts it runs the hook past Claude Code's timeout, with no notice."""
+ import security_reminder_hook as hook
+
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, _ = _commit_and_push(repo, remote)
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1.0)
+ monkeypatch.setattr(hook, "_RACE_END_S", 1.5)
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(20))
+
+ started = time.monotonic()
+ try:
+ with _held_by_another_review(repo, sha):
+ _, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 1.0, poll_s=0.05)
+ _, _, m = hook._agentic_review_with_race(
+ str(repo), [], [], [], spent_s=waited)
+ finally:
+ release.set()
+ assert 1.0 <= waited < 1.5
+ assert 1.5 <= time.monotonic() - started < 2.4
+ assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT
+
+
+def test_the_push_handler_counts_its_wait(tmp_path, agentic_env, stub_api):
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, push_out = _commit_and_push(repo, remote)
+ log = tmp_path / "race.log"
+ env = {**agentic_env, "SG_INFLIGHT_WAIT_S": "2", "SG_AGENTIC_RACE_DELAY_S": "60",
+ "SECURITY_GUIDANCE_DEBUG_LOG": str(log)}
+ with _held_by_another_review(repo, sha):
+ _, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env)
+ assert metrics_of(so)["inflight_wait_s"] >= 2
+ assert "already spent, fallback starts after 5" in log.read_text()
+
+
+def test_the_fallback_starts_sooner_after_a_wait(tmp_path, monkeypatch):
+ import security_reminder_hook as hook
+
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "180")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: ("guidance", []))
+ monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False)
+ try:
+ g, _, m = hook._agentic_review_with_race(str(tmp_path), [], [], [], spent_s=240.0)
+ finally:
+ release.set()
+ assert g == "guidance"
+ assert (m["race_winner"], m["race_delay_s"], m["race_started"]) == (2, 0, 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()