diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-11-04 17:32:19 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-04 17:32:32 +0000 |
| commit | bde3b016a04e73b5bb0817f68c174d0d3c47f7d4 (patch) | |
| tree | a38e1720917f9671908ccc1d1394e15fe95fcc33 /plugins | |
| parent | fa4eb54397ee2faccb6940512a19c017cb1337f3 (diff) | |
security-guidance: clear net_err when a review gets through
A failed first probe, a lost race fallback or a failed dual leg left its
class (and api_error) on the row of a review that got a verdict.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 6 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 13 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 4 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_network_failure_class.py | 112 |
4 files changed, 132 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 28b189a4..91381f64 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -212,7 +212,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": [], @@ -308,7 +308,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 468d9e6d..13e16c41 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -429,7 +429,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 @@ -932,6 +934,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 @@ -1323,6 +1333,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 3efe344e..9c282c4f 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -1371,6 +1371,10 @@ def _agentic_review_with_race( else: winner, (g, v, m) = "fallback", (None, [], { "agentic": False, "review_failed": True, "api_error": _RACE_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)) |
