summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/_base.py
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-05-31 08:34:35 -0700
committerMohamed Hegazy <mhegazy@anthropic.com>2026-05-31 08:34:35 -0700
commit475038edfce3b736fba6648af7d8c1bd627c2464 (patch)
treeffda9f5698f4e4bf8597e212b1f61135a1c19958 /plugins/security-guidance/hooks/_base.py
parent3d368d2972d9af8f52e96ae7d86d2686967af31f (diff)
security-guidance: emit HTTP error codes + fix sdk_bootstrap phase/err encodingtelemetry-failure-signals
Fills two failure-visibility gaps in plugin telemetry. ## Gap 1: HTTP errors from _call_claude invisible Before: a 4xx/5xx response from the LLM API caused `_call_claude` to return None and produce ZERO fingerprint in tengu_hook_plugin_metrics. A failed call looked identical to "no review needed". The recent deprecation-400 outage (PR #2105, output_format → output_config.format, #2098) was invisible in aggregate dashboards until a user manually reported errors from their debug log. Cohort-specific or partial outages would never show up in BQ. Fix: add `http_err_last` (most recent status) and `http_err_count` to the existing `_USAGE` accumulator in `_base.py`. `_usage_metrics()` snapshots them whenever count > 0 (skip-path no-pollute contract preserved when count == 0). All `_call_claude` error sites now call the new `_record_http_error()` helper alongside the existing `_last_call_claude_http_error` module-state assignment. Now any future API failure category is queryable in BQ in real time: SELECT DATE(server_timestamp, "America/Los_Angeles") AS d, CAST(JSON_VALUE(additional_metadata, "$.http_err_last") AS INT64) AS code, COUNT(*) AS n FROM ... WHERE event_name = "tengu_hook_plugin_metrics" AND JSON_VALUE(additional_metadata, "$.pluginId") LIKE "%security-guidance%" AND JSON_VALUE(additional_metadata, "$.http_err_count") IS NOT NULL GROUP BY d, code ORDER BY d, n DESC ## Gap 2: sdk_bootstrap_phase / sdk_bootstrap_err always NULL in BQ Before: ensure_agent_sdk.py emitted these as strings (e.g. "pip", "dns_fail"). CC's plugin-metrics pipeline silently drops plugin-emitted string values — only bool|finite-number plugin metrics reach BigQuery. (CC-core fields like `subscription_type` are exempt because they're injected downstream of plugin validation.) Confirmed empirically: ~185K BUILD_FAILED rows in BQ over the past 2 days had `sdk_bootstrap_phase` = NULL and `sdk_bootstrap_err` = NULL despite the Python code emitting them. ~28K BUILD_FAILED sessions/day had no diagnostic split — flying blind on whether the failures are pip-no-match vs dns-fail vs ssl-verify vs proxy-auth etc. Fix: encode phase + err_kind as stable integers via SDK_BOOTSTRAP_PHASE_CODES and SDK_BOOTSTRAP_ERR_CODES. Phase: 1=pre, 2=venv, 3=pip, 4=main. Err: 10 known categories (1-10), 11-98 reserved, 99 = uncategorized catch-all (covers "exc:<X>", "other:<X>", and unmapped strings). APPEND-ONLY for telemetry stability. Also corrects the misleading "CC accepts string metric values" comment in ensure_agent_sdk.py that led to the bug originally. Verified locally on macOS Python 3.13: - py_compile clean. - 32 new tests in test_telemetry_failure_signals.py (added to internal test suite at sg-staging/tests/, not in this PR): * 4 HTTP-error tracking unit tests: _record_http_error increments count + tracks most-recent; handles None/invalid; -1 for network/timeout. * 4 _usage_metrics emission tests: empty when no activity; successful call has no http_err fields; failure-only has http_err and no api_calls; mixed has both. * 1 contract test: every emitted value is bool|finite-number (catches future regression of the string-dropping bug class). * 13 sdk_bootstrap encoding tests (parametrized over the 10 known err_kind categories + 5 catch-all shapes): each maps to the right integer; unknown phase = 0; unknown err = 99. * 1 static-shape regression catcher: every `err_kind = "..."` string in ensure_agent_sdk.main() must be in SDK_BOOTSTRAP_ERR_CODES (otherwise new err_kinds silently collapse to 99). * 2 emit-shape regression catchers: the assignments in main() go through _encode_phase / _encode_err_kind helpers (no raw strings); no literal string values for sdk_bootstrap_phase/err. * 1 comment-accuracy: the misleading "CC accepts string metric values" comment is gone. - Full suite: 437/437 pass + 2 skipped (live API tests, opt-in). NOT verified end-to-end against BQ — would require shipping + observing in production for 24h to confirm the http_err and sdk_bootstrap_phase/err fields actually appear in tengu_hook_plugin_metrics rows. The unit tests pin the contract; if the wire shape is broken, BQ will show NULL for the new fields and we revisit (with the same diagnostic the BUILD_FAILED bug gave us). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'plugins/security-guidance/hooks/_base.py')
-rw-r--r--plugins/security-guidance/hooks/_base.py71
1 files changed, 59 insertions, 12 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 9adbcff4..ce051753 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -116,7 +116,18 @@ _PV = _read_plugin_version_int()
# Emitted via _usage_metrics() into the existing emit_metrics() channel so
# hook metrics rows carry per-invocation token/cost totals
# alongside the existing skip_reason / vulns_found fields.
-_USAGE = {"in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0}
+_USAGE = {
+ "in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0,
+ # HTTP error visibility (#2098 visibility gap — see emit comment in
+ # _usage_metrics). Without this, API failures from `_call_claude` left
+ # zero fingerprint in telemetry: the call returns None, the caller's
+ # emit_metrics carries no api_calls field, and the failure is
+ # indistinguishable from "no review needed". The deprecation outage
+ # that broke every commit-review LLM call was invisible until users
+ # reported it manually.
+ "http_err_last": 0, # most recent HTTP error code this invocation
+ "http_err_count": 0, # total HTTP errors (4xx + 5xx + network)
+}
_USAGE_LOCK = threading.Lock()
# $/Mtok (input, output). Used only for the raw-HTTP path; the SDK path
@@ -166,19 +177,55 @@ def _record_usage(usage, model, cost_usd=None):
_USAGE["n"] += 1
+def _record_http_error(status):
+ """Record an HTTP error from an LLM API call. `status` is the HTTP
+ status code (integer 400–599) or -1 for network/timeout errors. Stored
+ in `_USAGE["http_err_last"]` (most recent) and counted in
+ `_USAGE["http_err_count"]`. Snapshot via `_usage_metrics()` so every
+ subsequent `emit_metrics` includes the failure fingerprint.
+
+ Background: without this, the most recent example was the #2098
+ deprecation 400. Every hook fire's LLM call returned HTTP 400; the
+ plugin caught it and returned None; the emit_metrics carried no
+ api_calls field; aggregate dashboards looked normal. The failure
+ only became visible when a user manually reported errors out of
+ their debug log. With this field, a category-of-failure spike (4xx,
+ 5xx, or -1 network) is queryable from BQ in real time.
+ """
+ try:
+ s = int(status)
+ except (TypeError, ValueError):
+ return
+ with _USAGE_LOCK:
+ _USAGE["http_err_last"] = s
+ _USAGE["http_err_count"] += 1
+
+
def _usage_metrics():
"""Snapshot the accumulator as metric keys. Returns {} when no API calls
- were made so skip-path emits don't burn key budget. cost_usd rounded to
- 1e-6 to keep the float finite/short for the zod schema."""
+ AND no HTTP errors were made so skip-path emits don't burn key budget.
+ cost_usd rounded to 1e-6 to keep the float finite/short for the zod
+ schema.
+
+ HTTP errors (`http_err_last`, `http_err_count`) emitted ONLY when
+ `http_err_count > 0` so successful calls don't pad every metrics row
+ with two zero fields.
+ """
with _USAGE_LOCK:
- if _USAGE["n"] == 0:
+ if _USAGE["n"] == 0 and _USAGE["http_err_count"] == 0:
return {}
- return {
- "tok_in": _USAGE["in"],
- "tok_out": _USAGE["out"],
- "tok_cache_r": _USAGE["cr"],
- "tok_cache_w": _USAGE["cw"],
- "cost_usd": round(_USAGE["cost"], 6),
- "api_calls": _USAGE["n"],
- }
+ out = {}
+ if _USAGE["n"] > 0:
+ out.update({
+ "tok_in": _USAGE["in"],
+ "tok_out": _USAGE["out"],
+ "tok_cache_r": _USAGE["cr"],
+ "tok_cache_w": _USAGE["cw"],
+ "cost_usd": round(_USAGE["cost"], 6),
+ "api_calls": _USAGE["n"],
+ })
+ if _USAGE["http_err_count"] > 0:
+ out["http_err_last"] = _USAGE["http_err_last"]
+ out["http_err_count"] = _USAGE["http_err_count"]
+ return out