summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-06 11:42:19 -0800
committerGitHub <noreply@github.com>2026-11-06 11:42:19 -0800
commitb4720bd2ea255d57666fbf3aa6fbe5a40435089e (patch)
tree48542187ecab7b3a111ffdefa0c1f5d1d86016c9 /plugins
parent385e32d91174c6955f5cc52f9a84da314fddb3a0 (diff)
parenta7ae8adaac24a60a6ec0c030f3333d288811db45 (diff)
Merge pull request #6997 from anthropics/mhegazy/sg-net-err-on-verdict
security-guidance: clear net_err when a review gets through
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/_base.py6
-rw-r--r--plugins/security-guidance/hooks/llm.py13
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py4
-rw-r--r--plugins/security-guidance/tests/test_network_failure_class.py112
4 files changed, 132 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 523049c1..99607e4a 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -240,7 +240,7 @@ _USAGE = {
# reported it manually.
"http_err_last": 0, # most recent HTTP error code this invocation
"http_err_count": 0, # total HTTP errors (4xx + 5xx + network)
- "net_err": 0, # why the last call got no HTTP response, 0 if it got one
+ "net_err": 0, # why the deciding call got no HTTP response, 0 if it got one
# For the usage log line only: model ids as recorded (the requested alias
# on the Agent SDK path), and whether any call had no price-table entry.
"models": [],
@@ -336,7 +336,9 @@ def _record_net_error(code):
raises outside its own error type (a default TLS context that cannot be
built, a connection closed before the reply) has no `api_error` at all.
Emitted as `net_err` on the row of a hook whose last call failed this
- way; a later call clears it."""
+ way; a later call clears it, and so does a call that gets through beside
+ it (a second probe, the other leg of a dual review, the agentic run that
+ wins a race)."""
try:
c = int(code)
except (TypeError, ValueError):
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index c0a878f4..ee9ad2be 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -437,7 +437,9 @@ def ensure_anthropic_reachable() -> bool:
debug_log("Remote env: api.anthropic.com unreachable, stripping anthropic.com from NO_PROXY")
_strip_anthropic_from_no_proxy()
_anthropic_reachable = _probe_anthropic()
- if not _anthropic_reachable:
+ if _anthropic_reachable:
+ _clear_net_error() # the first probe's failure; this one got through
+ else:
debug_log("Remote env: api.anthropic.com still unreachable after NO_PROXY scrub")
return _anthropic_reachable
@@ -994,6 +996,14 @@ def can_review(session_id) -> bool:
return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None
+def _forget_failed_call():
+ """A review got its answer from another call running beside the one that
+ failed, so the row should not report that failure."""
+ global _last_call_claude_http_error
+ _last_call_claude_http_error = None
+ _clear_net_error()
+
+
def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None,
cli_path=None):
"""Single-turn SDK call as a substitute for the HTTP _call_claude path on
@@ -1384,6 +1394,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str,
merged.append(item)
elif item not in merged:
merged.append(item)
+ _forget_failed_call() # one leg got through; the other may have failed
return {bool_key: bool(merged) or bool((ra or {}).get(bool_key)) or bool((rb or {}).get(bool_key)),
list_key: merged}
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 7c84357f..47a992aa 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -1472,6 +1472,10 @@ def _agentic_review_with_race(
winner, (g, v, m) = "fallback", fallback_result["r"]
else:
winner, (g, v, m) = "fallback", timed_out
+ if winner == "agentic" and not m.get("agentic_fallback"):
+ # The agentic run reached the model; any failure on record is the
+ # fallback's, which lost.
+ llm._forget_failed_call()
m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict
m["race_winner"] = 1 if winner == "agentic" else 2
m["race_delay_s"] = delay_s
diff --git a/plugins/security-guidance/tests/test_network_failure_class.py b/plugins/security-guidance/tests/test_network_failure_class.py
index 896a251f..7a2229ad 100644
--- a/plugins/security-guidance/tests/test_network_failure_class.py
+++ b/plugins/security-guidance/tests/test_network_failure_class.py
@@ -5,6 +5,7 @@ import http.client
import socket
import ssl
import sys
+import threading
import types
import urllib.error
@@ -326,6 +327,117 @@ class TestEmittedRow:
assert "net_err" not in self._row(capsys)
+class TestClearedOnALaterResponse:
+ """`net_err` says why the last call got no response, so a failed call
+ followed by one that got through leaves nothing on the review's row."""
+
+ @pytest.fixture(autouse=True)
+ def _clean(self, monkeypatch):
+ monkeypatch.setitem(_base._USAGE, "net_err", 0)
+ monkeypatch.setattr(llm, "_last_call_claude_http_error", None)
+
+ @pytest.fixture
+ def remote(self, direct, monkeypatch):
+ monkeypatch.setenv("CLAUDE_CODE_REMOTE", "1")
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
+ monkeypatch.setattr(llm, "_anthropic_reachable", None)
+
+ def _probes(self, monkeypatch, *outcomes):
+ def urlopen(request, timeout):
+ outcome = outcomes[len(calls)]
+ calls.append(request)
+ if isinstance(outcome, BaseException):
+ raise outcome
+ return _Reply("")
+ calls = []
+ monkeypatch.setattr(llm, "_urlopen", urlopen)
+ return calls
+
+ def _status(self, code):
+ return urllib.error.HTTPError("https://api.anthropic.com/", code, "x", {}, None)
+
+ @pytest.mark.parametrize("second", ["reply", "status"])
+ def test_second_probe_that_gets_through(self, remote, monkeypatch, second):
+ calls = self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()),
+ None if second == "reply" else self._status(404))
+ assert llm.ensure_anthropic_reachable() is True
+ assert len(calls) == 2
+ assert _base._net_error_metric() == 0
+
+ def test_second_probe_that_fails_keeps_its_class(self, remote, monkeypatch):
+ self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()),
+ urllib.error.URLError(socket.gaierror(-2, "x")))
+ assert llm.ensure_anthropic_reachable() is False
+ assert _base._net_error_metric() == llm.NET_ERR_DNS
+
+ def _race(self, monkeypatch, agentic_result):
+ """A fallback that records a refused connection and has no verdict,
+ then an agentic run that ends with `agentic_result`."""
+ tried = threading.Event()
+
+ def fallback(diff_files, is_diff, previous_findings):
+ _base._record_net_error(llm.NET_ERR_CONNECT)
+ llm._last_call_claude_http_error = -1
+ tried.set()
+ return None, []
+
+ def agentic(repo_root, diff_files, rel_touched):
+ assert tried.wait(10)
+ return agentic_result
+
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setattr(hook, "analyze_code_security", fallback)
+ monkeypatch.setattr(hook, "agentic_review", agentic)
+ monkeypatch.setattr(hook.llm, "last_review_failed", lambda: True)
+ monkeypatch.setattr(hook.llm, "last_review_status", lambda: -1)
+ return hook._agentic_review_with_race(".", [], [], [])
+
+ @pytest.mark.parametrize("guidance", ["findings", None])
+ def test_agentic_verdict_after_a_failed_fallback(self, monkeypatch, guidance):
+ _, _, m = self._race(monkeypatch, (guidance, [], {"agentic": True}))
+ assert (m["race_winner"], m["race_started"]) == (1, 1)
+ assert _base._net_error_metric() == 0
+ assert llm._last_call_claude_http_error is None
+
+ def test_no_verdict_from_either_side_keeps_the_class(self, monkeypatch):
+ _, _, m = self._race(monkeypatch, (None, [], {"agentic_fallback": "investigate:x"}))
+ assert m["race_winner"] == 2 and m["review_failed"]
+ assert _base._net_error_metric() == llm.NET_ERR_CONNECT
+
+ def _dual_legs(self, monkeypatch, *replies):
+ """The first leg records a refused connection before the second ends."""
+ lock, failed = threading.Lock(), threading.Event()
+ pending = list(replies)
+
+ def call(*a, **k):
+ with lock:
+ reply = pending.pop(0)
+ if reply is None:
+ _base._record_net_error(llm.NET_ERR_CONNECT)
+ llm._last_call_claude_http_error = -1
+ failed.set()
+ else:
+ assert failed.wait(10)
+ return reply
+
+ monkeypatch.setenv("SG_DUAL_OR", "on")
+ monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-opus-5-5")
+ monkeypatch.setattr(llm, "_call_claude", call)
+ return llm._call_claude_dual_or("p", {}, bool_key="found", list_key="items")
+
+ def test_dual_review_with_one_leg_that_gets_through(self, monkeypatch):
+ merged = self._dual_legs(monkeypatch, None, {"found": False, "items": []})
+ assert merged["found"] is False
+ assert _base._net_error_metric() == 0
+ assert llm._last_call_claude_http_error is None
+
+ def test_dual_review_with_no_leg_through_keeps_the_class(self, monkeypatch):
+ assert self._dual_legs(monkeypatch, None, None) is None
+ assert _base._net_error_metric() == llm.NET_ERR_CONNECT
+
+
def _free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))