diff options
| author | Octavian Guzu <oct@anthropic.com> | 2026-10-14 13:16:03 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-14 13:16:03 +0100 |
| commit | 641d925db5a662e72f8650cb1b7670a59dab1abc (patch) | |
| tree | 1376fdeed086888c0a775e8d628a27afdda74c00 /plugins | |
| parent | 41f32e407b450055044f167db7ded5e8ff67d203 (diff) | |
| parent | c45209fd0c089108e0468ed282bd4dc0dae361a4 (diff) | |
Merge pull request #6536 from anthropics/mhegazy/sg-review-telemetry
security-guidance: report gateway routing and inner CLI stderr in review telemetry
Diffstat (limited to 'plugins')
4 files changed, 78 insertions, 4 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index e021c495..3f7607c6 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -28,6 +28,7 @@ import tempfile import threading import time import traceback +import urllib.parse import urllib.request from typing import Optional, Tuple, Dict, Any, List @@ -320,6 +321,24 @@ def _custom_headers() -> List[Tuple[str, str]]: return pairs +def gateway_cfg() -> int: + """How the plugin's own API calls are routed, for telemetry: bit 1 when + ANTHROPIC_BASE_URL names a host other than api.anthropic.com, bit 2 when + at least one ANTHROPIC_CUSTOM_HEADERS line is sent. 0 when neither. A + number only: no host, header name or value.""" + cfg = 0 + base = _anthropic_base_url() + try: + host = (urllib.parse.urlsplit(base).hostname or "").lower() + except ValueError: + host = "" + if base and host != "api.anthropic.com": + cfg |= 1 + if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()): + cfg |= 2 + return cfg + + def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)): betas = list(betas) headers = { @@ -1572,8 +1591,12 @@ def agentic_review( # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] + def _child_stderr_metric() -> Dict[str, int]: + return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} + def _on_child_stderr(line: str) -> None: child_stderr_lines[0] += 1 + metrics["child_stderr"] = child_stderr_lines[0] if child_stderr_lines[0] <= 20: debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") elif child_stderr_lines[0] == 21: @@ -1687,12 +1710,14 @@ def agentic_review( f"{json.dumps(inv, indent=2) if inv else '<none>'}") except Exception as e: debug_log(f"agentic_review: investigate failed ({e}); falling back") - return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}"} + return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}", + **_child_stderr_metric()} metrics["investigate_ms"] = int((_t.time() - t0) * 1000) metrics["investigate_turns"] = inv_turns if inv is None: reason = inv_subtype or "no_structured_output" - return None, [], {"agentic_fallback": f"investigate:{reason}"} + return None, [], {"agentic_fallback": f"investigate:{reason}", + **_child_stderr_metric()} # Keep medium-severity candidates through self-refute — that pass is the # real precision gate, and the model's investigate-stage severity rating # is conservative (it defaults to "medium"). Filtering to high/critical diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index d280e9e1..580bb8a3 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -199,6 +199,10 @@ CONTINUATION_SUFFIX = ( "response." ) +# Extra keys emit_metrics appends to every row this invocation emits. +_TAIL_METRICS: Dict[str, Any] = {} + + def emit_metrics( metrics, rewake_summary=None, @@ -262,9 +266,21 @@ def emit_metrics( head = {} if _PV and "pv" not in metrics: head["pv"] = _PV - head.update(_usage_metrics()) + usage = _usage_metrics() + head.update(usage) if head: metrics = {**head, **metrics} + # Diagnostic keys go last, so they are the first dropped when a row is + # over CC's key cap and never displace an existing key. + tail = {} + if usage or "review_ms" in metrics or metrics.get("review_failed"): + # Review rows say whether the plugin's calls went through a gateway, + # so the error rate behind gateways can be read per plugin version. + cfg = llm.gateway_cfg() + if cfg: + tail["gateway_cfg"] = cfg + tail.update(_TAIL_METRICS) + metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: out["rewakeSummary"] = rewake_summary @@ -1502,6 +1518,11 @@ def handle_commit_review_posttooluse(input_data): repo_root, diff_files, rel_touched, previous_findings ) agentic_metrics.update(_am) + if _am.get("child_stderr"): + # Lines the inner CLI wrote to stderr during the review: how often + # the condition that used to replace the findings body occurs. Not + # counted when the single-shot fallback wins the race. + _TAIL_METRICS["child_stderr"] = _am["child_stderr"] review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") # Fall back to single-shot only on agentic FAILURE (SDK/investigate @@ -1915,6 +1936,8 @@ def handle_push_sweep_posttooluse(input_data): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( repo_root, diff_files, rel_touched, previous_findings ) + if agentic_metrics.get("child_stderr"): + _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): diff --git a/plugins/security-guidance/tests/test_custom_headers.py b/plugins/security-guidance/tests/test_custom_headers.py index 2d9fa3ef..fe019d52 100644 --- a/plugins/security-guidance/tests/test_custom_headers.py +++ b/plugins/security-guidance/tests/test_custom_headers.py @@ -1,6 +1,6 @@ """ANTHROPIC_CUSTOM_HEADERS reach every call the plugin makes.""" from conftest import ( - STUB_VULN, VULN_PY, edit_payload, run_hook, stop_payload, ups_payload, + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, ) import llm @@ -63,8 +63,33 @@ class TestCustomHeaders: rc, so, se = run_hook(stop_payload(repo), e) assert rc == 2, (so, se) assert "command_injection" in se + assert metrics_of(so)["gateway_cfg"] == 3 # custom base URL and custom headers calls = [(m, p.split("?")[0]) for m, p, _ in gateway.requests] assert ("GET", "/v1/models") in calls and ("POST", "/v1/messages") in calls for method, path, headers in gateway.requests: if path.startswith("/v1/"): assert headers.get(GATEWAY_KEY[0]) == GATEWAY_KEY[1], (method, path) + + def test_gateway_cfg_is_a_number_with_no_names_or_values(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + assert llm.gateway_cfg() == 0 + for same_host in ("https://api.anthropic.com/", "https://API.anthropic.com:443"): + monkeypatch.setenv("ANTHROPIC_BASE_URL", same_host) + assert llm.gateway_cfg() == 0 + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://gw.example.com") + assert llm.gateway_cfg() == 1 + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "anthropic-beta: extra-1") + assert llm.gateway_cfg() == 1 # beta lines are not sent + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "X-Ok: 1") + assert llm.gateway_cfg() == 3 + monkeypatch.delenv("ANTHROPIC_BASE_URL") + assert llm.gateway_cfg() == 2 + + def test_gateway_cfg_is_left_out_when_no_api_call_was_made(self, env, gateway, workspace): + """Only rows that made API calls carry gateway_cfg.""" + _, repo = workspace + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0, (so, se) + row = metrics_of(so) + assert row["skipped"] is True and "gateway_cfg" not in row diff --git a/plugins/security-guidance/tests/test_findings_delivery.py b/plugins/security-guidance/tests/test_findings_delivery.py index b71fc8d6..0989ed4b 100644 --- a/plugins/security-guidance/tests/test_findings_delivery.py +++ b/plugins/security-guidance/tests/test_findings_delivery.py @@ -32,6 +32,7 @@ class TestAgenticReviewerOn: sha, rc, so, se = _commit(repo, agentic_env) assert rc == 2, (so, se) assert metrics_of(so)["agentic_fallback"] == 2 + assert metrics_of(so)["child_stderr"] >= 1 # the warning was counted, not shown body = _rewake_body(so, se) assert "command_injection" in body assert "connectors are disabled" not in body |
