summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-26 20:18:49 +0000
committerClaude <noreply@anthropic.com>2026-10-26 20:18:49 +0000
commit23be88c2900bfbfc845e31d7cd58a5e8af57035e (patch)
tree02f0f976ded6509676f7ed24f5e1af1882899cdb /plugins/security-guidance/tests
parent58267944f92187b7d6a1c822165c96c81c864806 (diff)
security-guidance: report how many turns and how much model time a commit review took
review_ms says how long an agentic commit review took but not why. Add one count-only key, rv_effort, on rows where the agentic reviewer ran: the turns it took and the time it spent waiting on the model, summed over all stages and packed as turns * 10,000,000 + model ms. It is emitted after every other key, so it never displaces one at the metric key cap. No behaviour change.
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/test_reviewer_context_metrics.py94
1 files changed, 90 insertions, 4 deletions
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)