summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-26 16:57:07 -0700
committerGitHub <noreply@github.com>2026-10-26 16:57:07 -0700
commitda54ddb82e1e5c89ca2669bb866f5ab4fdb21cac (patch)
treef05f16b3dc3417f572467bb9dfff1d17780d10c3 /plugins
parent1da406f428c285c701a1033a3aef368a9ab865dc (diff)
parentf4174b901f6c4579186587b63e7658946f18b644 (diff)
Merge pull request #6903 from anthropics/mhegazy/sg-reviewer-stage-metrics
security-guidance: report turns and model time of a commit review (measure only)
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/llm.py15
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py28
-rw-r--r--plugins/security-guidance/tests/test_reviewer_context_metrics.py94
3 files changed, 126 insertions, 11 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index cc867700..468d9e6d 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -1908,11 +1908,15 @@ def agentic_review(
before the review, 2 = it went missing during it
rv_tool_err Read/Grep/Glob calls that came back as errors
rv_tool_calls Read/Grep/Glob calls made
+ rv_turns turns the reviewer took, as the CLI counts them
+ rv_api_ms time the reviewer spent waiting on the model, in ms
- The counts cover all stages of the review. Keys are left out when 0."""
+ The counts cover all stages of the review. Keys are left out when 0.
+ rv_turns and rv_api_ms come from each stage's result message, so a stage
+ that ends without one (the CLI exits early) adds nothing to them."""
context_dir = _agentic_context_dir(repo_dir)
gone = 0 if os.path.isdir(context_dir) else 1
- ctx = {"rv_tool_err": 0, "rv_tool_calls": 0}
+ ctx = {"rv_tool_err": 0, "rv_tool_calls": 0, "rv_turns": 0, "rv_api_ms": 0}
guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx)
if not gone and not os.path.isdir(context_dir):
gone = 2
@@ -2129,6 +2133,13 @@ def _agentic_review(
# the price-table estimate. getattr guards older SDK builds.
_record_usage(getattr(msg, "usage", None) or {}, model,
cost_usd=getattr(msg, "total_cost_usd", None))
+ for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")):
+ value = getattr(msg, attr, None)
+ # Counting must never fail the review: anything that
+ # is not a positive finite number adds nothing.
+ if (isinstance(value, (int, float)) and not isinstance(value, bool)
+ and 0 < value < float("inf")):
+ ctx[key] += int(value)
else:
# Tool results come back as user messages.
content = getattr(msg, "content", None)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index cb08d1c6..3efe344e 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -226,18 +226,34 @@ _TAIL_METRICS: Dict[str, Any] = {}
# keys below come later; those are also on every smaller row of the session.
_LAST_METRIC_KEYS = ("diff_seen",)
-# The launcher's slow interpreter probes, if any. After everything else.
+# The launcher's slow interpreter probes, if any. After the keys above.
_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics()
# Reviewer context diagnostics from llm.agentic_review, most useful first.
_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls")
+# How much work the agentic reviewer did, from llm.agentic_review: turns, and
+# time waiting on the model. They tell more turns from slower turns when
+# review_ms moves.
+_REVIEWER_EFFORT_KEYS = ("rv_turns", "rv_api_ms")
+# A clean commit review row has one free key under CC's key cap once
+# rv_tool_calls is on it, so the two are sent as one number:
+# rv_effort = rv_turns * _EFFORT_TURNS_UNIT + rv_api_ms (capped below the unit)
+_EFFORT_TURNS_UNIT = 10_000_000
+# The packed value queued for this row. Emitted after every other key, the
+# launcher's included, so it never displaces one at the cap.
+_REVIEWER_EFFORT_METRICS: Dict[str, Any] = {}
def _note_reviewer_context(agentic_metrics):
- """Queue the agentic reviewer's context diagnostics for this row."""
+ """Queue the agentic reviewer's context and effort diagnostics for this row."""
for key in _REVIEWER_CONTEXT_KEYS:
if agentic_metrics.get(key):
_TAIL_METRICS[key] = agentic_metrics[key]
+ turns = agentic_metrics.get("rv_turns") or 0
+ api_ms = agentic_metrics.get("rv_api_ms") or 0
+ if turns or api_ms:
+ _REVIEWER_EFFORT_METRICS["rv_effort"] = (
+ turns * _EFFORT_TURNS_UNIT + min(api_ms, _EFFORT_TURNS_UNIT - 1))
def emit_metrics(
@@ -340,6 +356,7 @@ def emit_metrics(
if k in tail:
tail[k] = tail.pop(k)
tail.update(_LAUNCHER_METRICS)
+ tail.update(_REVIEWER_EFFORT_METRICS)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
if rewake_summary:
@@ -1340,10 +1357,11 @@ def _agentic_review_with_race(
_th.Thread(target=_fallback, daemon=True).start()
winner, (g, v, m) = q.get()
- # What the agentic run saw of its directory is kept when the fallback's
- # result replaces it below.
+ # What the agentic run saw of its directory, and how much work it did,
+ # is kept when the fallback's result replaces it below.
reviewer_context = (
- {k: m[k] for k in _REVIEWER_CONTEXT_KEYS if k in m} if winner == "agentic" else {}
+ {k: m[k] for k in _REVIEWER_CONTEXT_KEYS + _REVIEWER_EFFORT_KEYS if k in m}
+ if winner == "agentic" else {}
)
if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set():
# The caller would rerun the single-shot review the fallback has
diff --git a/plugins/security-guidance/tests/test_reviewer_context_metrics.py b/plugins/security-guidance/tests/test_reviewer_context_metrics.py
index c0dfb491..99e94dc7 100644
--- a/plugins/security-guidance/tests/test_reviewer_context_metrics.py
+++ b/plugins/security-guidance/tests/test_reviewer_context_metrics.py
@@ -1,5 +1,6 @@
"""The agentic reviewer reports, as counts only, how its Read/Grep/Glob calls
-went and whether the directory it ran in was still there."""
+went, whether the directory it ran in was still there, and how many turns and
+how much model time the review took."""
import json
import os
import shutil
@@ -27,7 +28,7 @@ def sdk(monkeypatch, tmp_path):
"""Stand-in for claude_agent_sdk whose reviewer replays `script.messages`
and then returns no findings. Like the SDK, it cannot start in a
directory that does not exist."""
- script = types.SimpleNamespace(messages=[], before_result=lambda: None)
+ script = types.SimpleNamespace(messages=[], before_result=lambda: None, result={})
class ClaudeAgentOptions:
def __init__(self, **kwargs):
@@ -51,7 +52,10 @@ def sdk(monkeypatch, tmp_path):
for m in script.messages:
yield m
script.before_result()
- yield ResultMessage()
+ result = ResultMessage()
+ for name, value in script.result.items():
+ setattr(result, name, value)
+ yield result
mod = types.ModuleType("claude_agent_sdk")
mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query
@@ -122,12 +126,48 @@ class TestAgenticReview:
m = _review(tmp_path)
assert m["agentic_fallback"].startswith("investigate:")
assert (m["rv_tool_calls"], m["rv_tool_err"]) == (1, 1)
+ assert "rv_turns" not in m and "rv_api_ms" not in m
+
+ def test_turns_and_model_time_come_from_the_result_message(self, sdk, tmp_path):
+ # One assistant message per content block: three messages, two turns.
+ sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), sdk.assistant(_ToolUse("t2", "Grep")),
+ sdk.user([_ToolResult("t1"), _ToolResult("t2")]), sdk.assistant()]
+ sdk.result = {"num_turns": 2, "duration_api_ms": 4100, "duration_ms": 9000}
+ m = _review(tmp_path)
+ assert (m["rv_turns"], m["rv_api_ms"]) == (2, 4100)
+
+ def test_turns_and_model_time_are_summed_over_stages(self, sdk, tmp_path, monkeypatch):
+ finding = {"severity": "high", "filePath": "a.py", "category": "xss", "vulnerableCode": "x = 1"}
+ monkeypatch.setattr(sys.modules["claude_agent_sdk"].ResultMessage, "structured_output",
+ {"findings": [finding], "verdicts": []})
+ sdk.result = {"num_turns": 3, "duration_api_ms": 1000}
+ m = _review(tmp_path)
+ # Investigate, the second investigate pass, and refute.
+ assert (m["rv_turns"], m["rv_api_ms"]) == (9, 3000)
+
+ def test_stage_that_ran_out_of_turns_is_counted(self, sdk, tmp_path):
+ sdk.result = {"num_turns": 18, "duration_api_ms": 60000,
+ "subtype": "error_max_turns", "structured_output": None}
+ m = _review(tmp_path)
+ assert m["agentic_fallback"] == "investigate:error_max_turns"
+ assert (m["rv_turns"], m["rv_api_ms"]) == (18, 60000)
+
+ @pytest.mark.parametrize("result", [{}, {"num_turns": None, "duration_api_ms": None},
+ {"num_turns": "3", "duration_api_ms": True},
+ {"num_turns": -1, "duration_api_ms": 0},
+ {"num_turns": float("nan"), "duration_api_ms": float("inf")}])
+ def test_missing_or_unusable_result_fields_leave_the_keys_out(self, sdk, tmp_path, result):
+ sdk.result = result
+ m = _review(tmp_path)
+ assert "agentic_fallback" not in m
+ assert "rv_turns" not in m and "rv_api_ms" not in m
class TestEmittedRow:
@pytest.fixture(autouse=True)
def _clean_tail(self, monkeypatch):
monkeypatch.setattr(hook, "_TAIL_METRICS", {})
+ monkeypatch.setattr(hook, "_REVIEWER_EFFORT_METRICS", {})
def _row(self, capsys):
return json.loads(capsys.readouterr().out)["metrics"]
@@ -139,6 +179,50 @@ class TestEmittedRow:
keys = list(self._row(capsys))
assert keys[-5:] == ["vulns_found", "review_ms", "rv_cwd_gone", "rv_tool_err", "rv_tool_calls"]
+ def test_effort_is_one_key_after_every_other_key(self, capsys, monkeypatch):
+ monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {"launcher_probe_ms": 7000})
+ hook._note_reviewer_context({"rv_api_ms": 9100, "rv_turns": 5, "rv_tool_calls": 4})
+ hook.emit_metrics({"vulns_found": 0, "review_ms": 9500})
+ row = self._row(capsys)
+ assert list(row)[-3:] == ["rv_tool_calls", "launcher_probe_ms", "rv_effort"]
+ assert divmod(row["rv_effort"], 10_000_000) == (5, 9100)
+ assert "rv_turns" not in row and "rv_api_ms" not in row
+
+ @pytest.mark.parametrize("metrics, packed", [
+ ({"rv_turns": 3}, (3, 0)),
+ ({"rv_api_ms": 250}, (0, 250)),
+ ({"rv_turns": 54, "rv_api_ms": 123_456_789}, (54, 9_999_999)),
+ ])
+ def test_effort_packing(self, capsys, metrics, packed):
+ hook._note_reviewer_context(metrics)
+ hook.emit_metrics({"vulns_found": 0})
+ assert divmod(self._row(capsys)["rv_effort"], 10_000_000) == packed
+
+ def test_no_effort_key_without_turns_or_model_time(self, capsys):
+ hook._note_reviewer_context({"rv_tool_calls": 2, "agentic_fallback": "import:ImportError"})
+ hook.emit_metrics({"vulns_found": 0})
+ assert "rv_effort" not in self._row(capsys)
+
+ def test_effort_does_not_displace_a_key_at_the_cap(self, capsys, monkeypatch):
+ monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {"launcher_probe_ms": 7000})
+ hook._note_reviewer_context({"rv_api_ms": 9100, "rv_turns": 5})
+ hook.emit_metrics({f"k{i}": i for i in range(40)})
+ keys = list(self._row(capsys))
+ assert keys[-2:] == ["launcher_probe_ms", "rv_effort"]
+
+ def test_effort_fits_under_the_cap_on_a_clean_commit_review_row(self, capsys, monkeypatch):
+ """The keys of a clean agentic commit review row, with tool calls."""
+ monkeypatch.setattr(hook, "_usage_metrics", lambda: {
+ "tok_in": 1, "tok_out": 1, "tok_cache_r": 0, "tok_cache_w": 0, "cost_usd": 0.1, "api_calls": 1})
+ hook._note_reviewer_context({"rv_tool_calls": 2, "rv_turns": 3, "rv_api_ms": 9100})
+ hook.emit_metrics({
+ "vulns_found": 0, "commit_review": True, "commit_review_on": True,
+ "sha_via_reflog": True, "reflog_shas_n": 1, "rate_count": 1, "agentic": True,
+ "candidates": 0, "race_winner": 1, "files_reviewed": 1, "review_ms": 9500,
+ })
+ keys = list(self._row(capsys))
+ assert keys[-2:] == ["rv_tool_calls", "rv_effort"] and len(keys) <= 20
+
def test_zero_or_absent_keys_are_left_out(self, capsys):
hook._note_reviewer_context({"rv_tool_calls": 3, "rv_tool_err": 0})
hook.emit_metrics({"vulns_found": 0})
@@ -161,7 +245,8 @@ class TestRace:
def agentic(*a):
time.sleep(0.3) # fails after the fallback has started
return None, [], {"agentic_fallback": "investigate:RuntimeError",
- "rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5}
+ "rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5,
+ "rv_turns": 18, "rv_api_ms": 60000}
monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
@@ -176,3 +261,4 @@ class TestRace:
_, _, m = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], [])
assert m["race_winner"] == 2 and m["agentic"] is False
assert (m["rv_cwd_gone"], m["rv_tool_err"], m["rv_tool_calls"]) == (2, 4, 5)
+ assert (m["rv_turns"], m["rv_api_ms"]) == (18, 60000)