Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(benchmark): scorecard metrics that survive an imbalanced corpus (depth 1.2) (#1191)

Beenu Arora1c55bd3ae8ab
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/replay.py b/packages/aisoc-benchmark/aisoc_benchmark/replay.py
index d5b790edc..e7021d0d2 100644
--- a/packages/aisoc-benchmark/aisoc_benchmark/replay.py
+++ b/packages/aisoc-benchmark/aisoc_benchmark/replay.py
@@ -50,6 +50,7 @@ so.
from __future__ import annotations
import json
+import math
import random
from collections import Counter
from dataclasses import asdict, dataclass, field
@@ -65,6 +66,7 @@ __all__ = [
"GRADED_DISPOSITIONS",
"LATENCY_FIELDS",
"LATENCY_LINE_PREFIX",
+ "LATENCY_LINE_PREFIXES",
"MALICIOUS",
"MIN_MALICIOUS_FOR_HEADLINE",
"UNLABELED",
@@ -83,8 +85,20 @@ __all__ = [
#: cannot drift into disagreeing about which line that is.
LATENCY_LINE_PREFIX = "- Mean latency:"
+#: Every other rendered line that measures the host. The "time to verdict"
+#: section reports the same measurements under the name an operator uses,
+#: so it is wall clock too and must be strippable for the same reason: the
+#: reproducibility claim is "byte for byte apart from the host figures", and
+#: a figure the stripper does not know about silently falsifies it.
+LATENCY_LINE_PREFIXES: tuple[str, ...] = (LATENCY_LINE_PREFIX, "- p50:", "- p95:")
+
#: The matching fields in :meth:`ReplayScore.as_dict`, for the JSON export.
-LATENCY_FIELDS: tuple[str, ...] = ("mean_latency_ms", "p95_latency_ms")
+LATENCY_FIELDS: tuple[str, ...] = (
+ "mean_latency_ms",
+ "p95_latency_ms",
+ "time_to_verdict_p50_ms",
+ "time_to_verdict_p95_ms",
+)
#: The canonical disposition that means "this was a real threat". Written once
#: because "malicious recall" has to mean the same thing in the metric, the
@@ -105,6 +119,17 @@ GRADED_DISPOSITIONS: tuple[str, ...] = (
#: An analyst who declined to classify. Excluded from accuracy, never guessed.
UNLABELED = "unlabeled"
+#: The confidence at which auto-close precision is reported when a caller
+#: names no tenant policy. Not a recommendation and not a default the
+#: product applies -- closure is governed per tenant by the autonomy policy.
+#: It exists so the figure is comparable across runs that did not state one.
+DEFAULT_AUTO_CLOSE_THRESHOLD = 0.9
+
+#: Verdicts a closure policy can act on without a human. `true_positive` is
+#: absent deliberately: a confirmed attack escalates, it is never closed,
+#: which is the rule `siem_writeback` already follows.
+_AUTO_CLOSABLE_VERDICTS: frozenset[str] = frozenset({"false_positive", "benign", "benign_true_positive"})
+
#: Agent outputs that are a refusal to decide rather than a decision. These are
#: abstentions: scored as neither right nor wrong, and counted separately so
#: accuracy and abstention cannot be traded off invisibly. ``escalate`` belongs
@@ -194,6 +219,61 @@ class ReplayScore:
headline_accuracy_ci: tuple[float, float] | None = None
headline_withheld_reason: str | None = None
+ # ---- the figures that survive an imbalanced corpus -------------------
+ #
+ # Plain accuracy on a queue that is 90% false positive is 0.90 for an
+ # agent that reads nothing. These three are published together, always,
+ # because the first two are only interpretable against the third: a
+ # reader given 0.74 alone cannot tell whether the agent is good or the
+ # queue is.
+ #
+ # Balanced accuracy is the unweighted mean recall over the classes the
+ # corpus actually holds. Averaging over all four canonical dispositions
+ # would cap a perfect agent at 0.5 on a two-class corpus, which is a
+ # scoring bug that reads as a model failure.
+ balanced_accuracy: float | None = None
+ #: Matthews correlation. The one headline figure the base rate cannot
+ #: buy: 0.0 for any predictor with no relationship to the label, +1 for
+ #: perfect agreement, -1 for perfect disagreement. Computed over the
+ #: multi-class confusion matrix, so it covers all four dispositions
+ #: rather than collapsing them to malicious/not.
+ matthews_corrcoef: float | None = None
+ majority_class_accuracy: float | None = None
+ majority_class_label: str | None = None
+
+ #: Wilson score interval on malicious recall, beside the bootstrap one.
+ #:
+ #: Closed-form rather than resampled, for two reasons. It is
+ #: deterministic for a given (successes, trials), so two runs over one
+ #: corpus cannot disagree; and it keeps width at the boundary, where a
+ #: percentile bootstrap over an all-ones vector returns [1.0, 1.0] and
+ #: claims a certainty the sample size does not support.
+ malicious_recall_wilson: tuple[float, float] | None = None
+
+ #: "If the tenant let the agent close at confidence >= threshold, what
+ #: share of what it closed was really closable?" A malicious case above
+ #: the threshold is an attack the platform would have closed by itself,
+ #: which is the outcome this number exists to price. `None` rather than
+ #: 0.0 when nothing crossed the threshold: 0.0 reads as "it closed
+ #: things and got them all wrong".
+ auto_close_threshold: float | None = None
+ auto_close_considered: int = 0
+ auto_close_correct: int = 0
+ auto_close_precision: float | None = None
+ #: Share of labelled decisions the agent routed to a human instead of
+ #: deciding. The same population as `abstention_rate`, named the way an
+ #: operator sizing a queue thinks about it.
+ escalation_rate: float | None = None
+
+ # ---- time to verdict: reported, never graded -------------------------
+ #
+ # Latency is a property of the hardware the run happened on, so it must
+ # not move a score -- a scoreboard that graded it would rank a faster
+ # laptop as a better agent. Published beside the figures and labelled
+ # with the hardware by the caller, never inside them.
+ time_to_verdict_p50_ms: float | None = None
+ time_to_verdict_p95_ms: float | None = None
+
# ---- the rest --------------------------------------------------------
abstention_rate: float | None = None
per_class: list[ClassScore] = field(default_factory=list)
@@ -236,6 +316,64 @@ def _f1(precision: float | None, recall: float | None) -> float | None:
return 2 * precision * recall / (precision + recall)
+def _wilson_interval(successes: int, trials: int, *, z: float = 1.959963984540054) -> tuple[float, float] | None:
+ """Wilson score interval at 95%, clamped to [0, 1].
+
+ `z` is the two-sided 97.5th percentile of the standard normal, written
+ out rather than imported so this package keeps no numeric dependency.
+
+ The interval is centred on a shrunk estimate rather than on the raw
+ proportion, which is exactly why it keeps width at 0 and 1 where the
+ normal approximation and a percentile bootstrap both collapse.
+ """
+ if trials <= 0:
+ return None
+ phat = successes / trials
+ denom = 1.0 + z * z / trials
+ centre = (phat + z * z / (2 * trials)) / denom
+ margin = (z / denom) * ((phat * (1.0 - phat) / trials + z * z / (4 * trials * trials)) ** 0.5)
+ return (max(0.0, centre - margin), min(1.0, centre + margin))
+
+
+def _matthews(matrix: dict[str, dict[str, int]], labels: list[str]) -> float | None:
+ """Multi-class Matthews correlation over the confusion matrix.
+
+ The K-class generalisation (Gorodkin), which reduces to the familiar
+ 2x2 formula when K is 2. Abstentions are excluded by the caller: an
+ alert routed to a human is not a wrong prediction, and counting it as
+ one would make an appropriately humble agent look like a bad one.
+
+ Two different zeros, kept apart:
+
+ * **no rows at all** -> `None`. Nothing was measured, and 0.0 would
+ read as "measured, and no relationship".
+ * **rows, but the predictor or the labels are constant** -> `0.0`.
+ The denominator is zero here too, but the answer is not unknown: a
+ predictor that says one thing to everything has exactly zero
+ correlation with the label, which is the finding this coefficient
+ exists to surface. Returning `None` would hide the constant-answer
+ agent behind "not measurable", and that agent is the whole reason
+ plain accuracy was not enough.
+ """
+ total = sum(matrix[t].get(p, 0) for t in labels for p in labels)
+ if total == 0:
+ return None
+ correct = sum(matrix[label].get(label, 0) for label in labels)
+ actual = {label: sum(matrix[label].get(p, 0) for p in labels) for label in labels}
+ predicted = {label: sum(matrix[t].get(label, 0) for t in labels) for label in labels}
+
+ cov_xy = correct * total - sum(actual[label] * predicted[label] for label in labels)
+ cov_xx = total * total - sum(predicted[label] ** 2 for label in labels)
+ cov_yy = total * total - sum(actual[label] ** 2 for label in labels)
+ # `math.sqrt` rather than `** 0.5`: typeshed types the float power
+ # operator as returning `Any`, which the baseline gate reports as a
+ # `no-any-return` out of a function declared `float | None`.
+ denom = math.sqrt(cov_xx * cov_yy)
+ if denom == 0:
+ return 0.0
+ return cov_xy / denom
+
+
def _percentile(values: list[float], fraction: float) -> float | None:
if not values:
return None
@@ -327,6 +465,7 @@ def score_replay(
*,
bootstrap_resamples: int = BOOTSTRAP_RESAMPLES,
bootstrap_seed: int = BOOTSTRAP_SEED,
+ auto_close_threshold: float = DEFAULT_AUTO_CLOSE_THRESHOLD,
) -> ReplayScore:
"""Grade a replay run's decisions against the analysts' own labels.
@@ -385,6 +524,11 @@ def score_replay(
latencies = [float(d.get("latency_ms") or 0.0) for d in decisions]
score.mean_latency_ms = (sum(latencies) / len(latencies)) if latencies else None
score.p95_latency_ms = _percentile(latencies, 0.95)
+ # Named for what an operator calls it. Same measurements as the two
+ # fields above; published under the plan's own term so the scorecard
+ # and the page agree about which number is "time to verdict".
+ score.time_to_verdict_p50_ms = _percentile(latencies, 0.50)
+ score.time_to_verdict_p95_ms = score.p95_latency_ms
score.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})
if not labelled:
@@ -459,6 +603,45 @@ def score_replay(
verdicts[key] = verdicts.get(key, 0) + 1
score.false_negative_verdicts = dict(sorted(verdicts.items()))
+ score.malicious_recall_wilson = _wilson_interval(
+ sum(1 for d in malicious_rows if d.get("verdict") == MALICIOUS),
+ len(malicious_rows),
+ )
+
+ # ---- figures that survive an imbalanced corpus ------------------------
+ #
+ # Over `answered` only, matching per-class precision above: an
+ # abstention is a decision to involve a human, not a wrong prediction.
+ # It is still visible, as `escalation_rate` directly below.
+ present = [label for label in GRADED_DISPOSITIONS if support.get(label, 0) > 0]
+ recalls = [c.recall for c in score.per_class if c.label in present and c.recall is not None]
+ score.balanced_accuracy = (sum(recalls) / len(recalls)) if recalls else None
+
+ answered_matrix: dict[str, dict[str, int]] = {expected: dict.fromkeys(GRADED_DISPOSITIONS, 0) for expected in GRADED_DISPOSITIONS}
+ for decision in answered:
+ expected = str(decision.get("expected_disposition"))
+ predicted = str(decision.get("verdict") or "")
+ if expected in answered_matrix and predicted in answered_matrix[expected]:
+ answered_matrix[expected][predicted] += 1
+ score.matthews_corrcoef = _matthews(answered_matrix, list(GRADED_DISPOSITIONS))
+
+ # The number every other number has to be read against.
+ if support:
+ majority = max(support, key=lambda label: support[label])
+ score.majority_class_label = majority
+ score.majority_class_accuracy = _ratio(support[majority], len(labelled))
+
+ # ---- auto-close precision at the closure threshold --------------------
+ score.auto_close_threshold = auto_close_threshold
+ closable = [
+ d for d in answered if d.get("verdict") in _AUTO_CLOSABLE_VERDICTS and float(d.get("confidence") or 0.0) >= auto_close_threshold
+ ]
+ score.auto_close_considered = len(closable)
+ score.auto_close_correct = sum(1 for d in closable if _is_correct(d))
+ score.auto_close_precision = _ratio(score.auto_close_correct, len(closable))
+
+ score.escalation_rate = score.abstention_rate
+
# ---- calibration ------------------------------------------------------
score.calibration, score.expected_calibration_error = _calibration(answered)
@@ -500,6 +683,20 @@ def _interval(bounds: tuple[float, float] | None) -> str:
return "not measured" if bounds is None else f"{bounds[0] * 100:.1f}% to {bounds[1] * 100:.1f}%"
+def _number(value: float | None) -> str:
+ """A bare coefficient, for the figures that are not rates.
+
+ Matthews correlation runs -1 to +1 and the closure threshold is a
+ confidence, so neither is a percentage. Same "not measured" rule as
+ `_pct`.
+ """
+ return "not measured" if value is None else f"{value:.2f}"
+
+
+def _ms(value: float | None) -> str:
+ return "not measured" if value is None else f"{value:,.0f} ms"
+
+
def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None = None) -> str:
"""Render the report as Markdown, malicious recall first.
@@ -523,6 +720,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =
"",
f"- Malicious cases in the test window: {score.malicious_support}",
f"- Recall: {_pct(score.malicious_recall)} (95% CI {_interval(score.malicious_recall_ci)})",
+ f"- Recall, Wilson 95% interval: {_interval(score.malicious_recall_wilson)}",
f"- Precision: {_pct(score.malicious_precision)}",
"",
"## Headline accuracy",
@@ -536,6 +734,45 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =
"",
]
+ # Printed immediately under the headline, and never without the
+ # baseline. Plain accuracy on a queue that is 90% false positive is
+ # 0.90 for an agent that reads nothing; a reader who sees the headline
+ # without what a constant would have scored cannot tell the two apart.
+ lines += [
+ "## Against a constant answer",
+ "",
+ f"- Majority-class baseline: {_pct(score.majority_class_accuracy)} (always answering `{score.majority_class_label}`)",
+ f"- Balanced accuracy: {_pct(score.balanced_accuracy)}",
+ f"- Matthews correlation: {_number(score.matthews_corrcoef)}",
+ "",
+ "Balanced accuracy is the unweighted mean recall over the classes this",
+ "corpus holds, so a constant answer scores 0.50 however skewed the queue",
+ "is. Matthews correlation is 0.00 for any predictor with no relationship",
+ "to the label, which is the one headline figure the base rate cannot buy.",
+ "",
+ "## Auto-close and escalation",
+ "",
+ f"- Auto-close precision at confidence >= {_number(score.auto_close_threshold)}:"
+ f" {_pct(score.auto_close_precision)}"
+ f" over {score.auto_close_considered} decision(s) the policy would have closed",
+ f"- Escalation rate: {_pct(score.escalation_rate)}",
+ "",
+ "A malicious case above the threshold is an attack the platform would",
+ "have closed by itself. Nothing above the threshold reports no figure",
+ "rather than a zero, which would read as closing things and getting",
+ "them all wrong.",
+ "",
+ "## Time to verdict",
+ "",
+ f"- p50: {_ms(score.time_to_verdict_p50_ms)}",
+ f"- p95: {_ms(score.time_to_verdict_p95_ms)}",
+ "",
+ "Reported, never graded: latency is a property of the hardware the run",
+ "happened on, and a scoreboard that graded it would rank a faster",
+ "machine as a better agent.",
+ "",
+ ]
+
lines += ["## Per class", "", "| Disposition | Support | Predicted | Precision | Recall | F1 |", "|---|---|---|---|---|---|"]
for row in score.per_class:
lines.append(f"| {row.label} | {row.support} | {row.predicted} | {_pct(row.precision)} | {_pct(row.recall)} | {_pct(row.f1)} |")
@@ -626,10 +863,14 @@ def strip_latency(report: str) -> str:
the line count are unchanged and a diff of two reports points at content
rather than at an offset.
"""
- return "\n".join(
- f"{LATENCY_LINE_PREFIX} excluded from this export (wall clock, not reproducible)" if line.startswith(LATENCY_LINE_PREFIX) else line
- for line in report.split("\n")
- )
+
+ def _strip(line: str) -> str:
+ for prefix in LATENCY_LINE_PREFIXES:
+ if line.startswith(prefix):
+ return f"{prefix} excluded from this export (wall clock, not reproducible)"
+ return line
+
+ return "\n".join(_strip(line) for line in report.split("\n"))
def _calibration(answered: list[dict[str, Any]]) -> tuple[list[CalibrationBin], float | None]:
diff --git a/packages/aisoc-benchmark/tests/test_replay_metrics.py b/packages/aisoc-benchmark/tests/test_replay_metrics.py
index a1a5d59cf..a511862ef 100644
--- a/packages/aisoc-benchmark/tests/test_replay_metrics.py
+++ b/packages/aisoc-benchmark/tests/test_replay_metrics.py
@@ -16,6 +16,7 @@ from aisoc_benchmark.metrics import extract_checkable_indicators
from aisoc_benchmark.replay import (
LATENCY_FIELDS,
LATENCY_LINE_PREFIX,
+ LATENCY_LINE_PREFIXES,
MIN_MALICIOUS_FOR_HEADLINE,
format_replay_report,
score_replay,
@@ -100,7 +101,13 @@ def test_the_withheld_headline_renders_as_words_not_as_zero() -> None:
report = format_replay_report(score_replay(_corpus(malicious=2, benign=50)))
assert "Withheld." in report
- assert "0.0%" not in report.split("## Per class")[0].split("## Headline accuracy")[1]
+ # Sliced to the headline section alone. It used to run to "## Per class",
+ # which stopped being the next heading when the scorecard sections landed
+ # between them -- and one of those prints "100.0%", which *contains*
+ # "0.0%", so the old window made this pass or fail on an unrelated
+ # figure's digits.
+ headline = report.split("## Against a constant answer")[0].split("## Headline accuracy")[1]
+ assert "0.0%" not in headline
# --------------------------------------------------------------------------
@@ -343,8 +350,13 @@ def test_stripping_latency_changes_exactly_one_line() -> None:
# points at content rather than at an offset.
assert len(original_lines) == len(stripped_lines)
differing = [(a, b) for a, b in zip(original_lines, stripped_lines, strict=True) if a != b]
- assert len(differing) == 1
- assert differing[0][0].startswith(LATENCY_LINE_PREFIX)
+ # Asserted as a property rather than a count. The report carries more
+ # than one host-measured line since the scorecard added "time to
+ # verdict", and the guarantee worth keeping is that the stripper touches
+ # *only* lines it declares -- not that there happens to be one of them.
+ assert differing, "the stripper changed nothing, so it is a no-op that still claims to exclude latency"
+ for before, _ in differing:
+ assert before.startswith(LATENCY_LINE_PREFIXES), f"stripped a line it does not declare: {before!r}"
def test_the_renderer_emits_the_line_the_stripper_looks_for() -> None:
diff --git a/packages/aisoc-benchmark/tests/test_verdict_scorecard.py b/packages/aisoc-benchmark/tests/test_verdict_scorecard.py
new file mode 100644
index 000000000..9fe181549
--- /dev/null
+++ b/packages/aisoc-benchmark/tests/test_verdict_scorecard.py
@@ -0,0 +1,239 @@
+"""Scorecard metrics: the ones that survive an imbalanced corpus.
+
+Depth plan 1.2. The existing report publishes headline accuracy, malicious
+recall with a bootstrap interval, per-class precision and recall, and a
+confusion matrix. On a real queue that is not enough to tell a classifier
+from a constant, and the plan names exactly what is missing:
+
+* **balanced accuracy and the Matthews correlation coefficient, always next
+ to the majority-class baseline.** Plain accuracy on a queue that is 90%
+ false positive is 0.90 for an agent that reads nothing. Balanced accuracy
+ is 0.50 for that agent and MCC is 0.0, which is the whole point -- but
+ only if the baseline travels with them, so no number is ever read without
+ what a constant answer would have scored.
+* **a Wilson interval on malicious recall.** The bootstrap interval already
+ there is resample-based; Wilson is closed-form, deterministic for a given
+ (successes, trials), and does not collapse to a zero-width interval at
+ 0 or 1 the way a percentile bootstrap does. That degenerate case is not
+ hypothetical: an agent that catches every malicious case in a small
+ corpus gets `[1.0, 1.0]` from the bootstrap, which reads as certainty
+ earned by sample size that does not exist.
+* **auto-close precision at the closure threshold, and escalation rate.**
+ The question an operator is actually deciding is "if I let it close
+ things at confidence >= X, what fraction of what it closed was really
+ closable?" -- which is not any existing field.
+* **time to verdict at p50 and p95, labelled with hardware and never
+ graded.** Reported beside the scores, never inside them.
+
+Every test here fails on the pre-1.2 tree because the field does not exist.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest # type: ignore[import-not-found]
+from aisoc_benchmark.replay import score_replay
+
+MALICIOUS = "true_positive"
+FP = "false_positive"
+BENIGN = "benign"
+
+
+def _decision(
+ index: int,
+ expected: str,
+ verdict: str | None,
+ *,
+ confidence: float = 0.8,
+ latency_ms: float = 10.0,
+) -> dict[str, Any]:
+ return {
+ "finding_id": f"F-{index:03d}",
+ "vendor": "splunk",
+ "rule_id": "rule-1",
+ "closed_at": "2026-05-01T00:00:00+00:00",
+ "expected_disposition": expected,
+ "labelled": True,
+ "verdict": verdict,
+ "confidence": confidence,
+ "tier": "deterministic",
+ "findings": [],
+ "confidence_basis": [],
+ "evidence": {},
+ "tokens": 0,
+ "measured_usd": None,
+ "estimated_usd": None,
+ "unpriced_calls": 0,
+ "latency_ms": latency_ms,
+ "resolved_models": [],
+ "error": None,
+ }
+
+
+def _skewed_queue(malicious: int, benign: int, *, verdict_for_all: str = FP) -> list[dict[str, Any]]:
+ """A queue mostly of false positives, and an agent that says so to everything.
+
+ The constant-answer agent, which is the thing plain accuracy cannot see.
+ """
+ rows = [_decision(i, MALICIOUS, verdict_for_all) for i in range(malicious)]
+ rows += [_decision(1000 + i, FP, verdict_for_all) for i in range(benign)]
+ return rows
+
+
+class TestBalancedAccuracyAndMCC:
+ def test_a_constant_answer_scores_half_on_balanced_accuracy(self) -> None:
+ """Plain accuracy would read 0.90 here. Balanced accuracy reads 0.50."""
+ score = score_replay(_skewed_queue(malicious=40, benign=360))
+
+ assert score.balanced_accuracy == pytest.approx(0.5, abs=1e-9)
+
+ def test_a_constant_answer_scores_zero_on_mcc(self) -> None:
+ """MCC is 0 for a predictor with no relationship to the label.
+
+ The coefficient is the one headline number that cannot be bought
+ with the base rate.
+ """
+ score = score_replay(_skewed_queue(malicious=40, benign=360))
+
+ assert score.matthews_corrcoef == pytest.approx(0.0, abs=1e-9)
+
+ def test_the_majority_baseline_travels_with_them(self) -> None:
+ """Neither figure may be published without what a constant would score.
+
+ This is the plan's wording and it is load-bearing: a reader given
+ 0.74 alone cannot tell whether the agent is good or the queue is.
+ """
+ score = score_replay(_skewed_queue(malicious=40, benign=360))
+
+ assert score.majority_class_accuracy == pytest.approx(0.9, abs=1e-9)
+ assert score.majority_class_label == FP
+
+ def test_a_perfect_agent_scores_one_on_both(self) -> None:
+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(40)]
+ rows += [_decision(1000 + i, FP, FP) for i in range(360)]
+
+ score = score_replay(rows)
+
+ assert score.balanced_accuracy == pytest.approx(1.0, abs=1e-9)
+ assert score.matthews_corrcoef == pytest.approx(1.0, abs=1e-9)
+
+ def test_balanced_accuracy_averages_recall_over_present_classes_only(self) -> None:
+ """A class with no support must not be averaged in as a zero.
+
+ Dividing by four when the corpus holds two classes would cap the
+ score at 0.5 for a perfect agent, which is a scoring bug that reads
+ as a model failure.
+ """
+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(10)]
+ rows += [_decision(100 + i, BENIGN, BENIGN) for i in range(10)]
+
+ score = score_replay(rows)
+
+ assert score.balanced_accuracy == pytest.approx(1.0, abs=1e-9)
+
+
+class TestWilsonInterval:
+ def test_recall_carries_a_wilson_interval(self) -> None:
+ score = score_replay(_skewed_queue(malicious=40, benign=360, verdict_for_all=MALICIOUS))
+
+ interval = score.malicious_recall_wilson
+ assert interval is not None
+ low, high = interval
+ assert 0.0 <= low <= 1.0 and 0.0 <= high <= 1.0
+
+ def test_a_perfect_run_still_has_width(self) -> None:
+ """The failure a percentile bootstrap has at the boundary.
+
+ 40 for 40 is not proof of a 100% recall rate; Wilson says so and a
+ bootstrap over an all-ones vector cannot.
+ """
+ score = score_replay(_skewed_queue(malicious=40, benign=360, verdict_for_all=MALICIOUS))
+
+ interval = score.malicious_recall_wilson
+ assert interval is not None
+ low, high = interval
+ assert high == pytest.approx(1.0, abs=1e-9)
+ assert low < 0.95, f"a 40/40 run should not claim a lower bound of {low}"
+
+ def test_a_smaller_sample_gives_a_wider_interval(self) -> None:
+ """The property that makes the interval worth publishing at all."""
+ wide = score_replay(_skewed_queue(malicious=10, benign=90, verdict_for_all=MALICIOUS))
+ narrow = score_replay(_skewed_queue(malicious=200, benign=200, verdict_for_all=MALICIOUS))
+
+ wide_interval, narrow_interval = wide.malicious_recall_wilson, narrow.malicious_recall_wilson
+ assert wide_interval is not None and narrow_interval is not None
+ assert (wide_interval[1] - wide_interval[0]) > (narrow_interval[1] - narrow_interval[0])
+
+ def test_it_is_deterministic(self) -> None:
+ """Closed form, so two runs over one corpus cannot disagree."""
+ rows = _skewed_queue(malicious=37, benign=211, verdict_for_all=MALICIOUS)
+
+ assert score_replay(rows).malicious_recall_wilson == score_replay(rows).malicious_recall_wilson
+
+
+class TestAutoCloseAndEscalation:
+ def test_auto_close_precision_counts_only_what_would_have_closed(self) -> None:
+ """Of the rows the policy would auto-close, how many were closable?
+
+ One malicious case above the threshold is a missed attack that the
+ platform would have closed by itself, which is the outcome this
+ number exists to price.
+ """
+ rows = [
+ _decision(1, FP, FP, confidence=0.95),
+ _decision(2, FP, FP, confidence=0.95),
+ _decision(3, FP, FP, confidence=0.95),
+ # Above the threshold and wrong: the agent would have closed a
+ # real attack.
+ _decision(4, MALICIOUS, FP, confidence=0.95),
+ # Below the threshold: not auto-closed, so not counted either way.
+ _decision(5, MALICIOUS, FP, confidence=0.10),
+ ]
+
+ score = score_replay(rows, auto_close_threshold=0.9)
+
+ assert score.auto_close_considered == 4
+ assert score.auto_close_precision == pytest.approx(0.75, abs=1e-9)
+ assert score.auto_close_threshold == pytest.approx(0.9, abs=1e-9)
+
+ def test_nothing_above_the_threshold_reports_none_not_zero(self) -> None:
+ """`0.0` would read as "it closed things and got them all wrong"."""
+ score = score_replay([_decision(1, FP, FP, confidence=0.2)], auto_close_threshold=0.9)
+
+ assert score.auto_close_considered == 0
+ assert score.auto_close_precision is None
+
+ def test_escalation_rate_is_the_share_routed_to_a_human(self) -> None:
+ rows = [_decision(i, FP, FP) for i in range(6)]
+ rows += [_decision(100 + i, MALICIOUS, "escalate") for i in range(2)]
+ rows += [_decision(200 + i, MALICIOUS, "needs_review") for i in range(2)]
+
+ score = score_replay(rows)
+
+ assert score.escalation_rate == pytest.approx(0.4, abs=1e-9)
+
+
+class TestTimeToVerdict:
+ def test_p50_and_p95_are_reported(self) -> None:
+ rows = [_decision(i, FP, FP, latency_ms=float(i)) for i in range(1, 101)]
+
+ score = score_replay(rows)
+
+ assert score.time_to_verdict_p50_ms == pytest.approx(50.0, abs=1.0)
+ assert score.time_to_verdict_p95_ms == pytest.approx(95.0, abs=1.0)
+
+ def test_it_is_never_graded(self) -> None:
+ """Latency is hardware, so it must not move a score.
+
+ Two runs identical but for latency must score identically, or the
+ scoreboard would rank a faster laptop as a better agent.
+ """
+ slow = [_decision(i, FP, FP, latency_ms=9000.0) for i in range(50)]
+ fast = [_decision(i, FP, FP, latency_ms=1.0) for i in range(50)]
+
+ a, b = score_replay(slow), score_replay(fast)
+
+ assert a.balanced_accuracy == b.balanced_accuracy
+ assert a.matthews_corrcoef == b.matthews_corrcoef
+ assert a.time_to_verdict_p50_ms != b.time_to_verdict_p50_ms
diff --git a/services/api/app/_vendor/aisoc_benchmark/replay.py b/services/api/app/_vendor/aisoc_benchmark/replay.py
index d5b790edc..e7021d0d2 100644
--- a/services/api/app/_vendor/aisoc_benchmark/replay.py
+++ b/services/api/app/_vendor/aisoc_benchmark/replay.py
@@ -50,6 +50,7 @@ so.
from __future__ import annotations
import json
+import math
import random
from collections import Counter
from dataclasses import asdict, dataclass, field
@@ -65,6 +66,7 @@ __all__ = [
"GRADED_DISPOSITIONS",
"LATENCY_FIELDS",
"LATENCY_LINE_PREFIX",
+ "LATENCY_LINE_PREFIXES",
"MALICIOUS",
"MIN_MALICIOUS_FOR_HEADLINE",
"UNLABELED",
@@ -83,8 +85,20 @@ __all__ = [
#: cannot drift into disagreeing about which line that is.
LATENCY_LINE_PREFIX = "- Mean latency:"
+#: Every other rendered line that measures the host. The "time to verdict"
+#: section reports the same measurements under the name an operator uses,
+#: so it is wall clock too and must be strippable for the same reason: the
+#: reproducibility claim is "byte for byte apart from the host figures", and
+#: a figure the stripper does not know about silently falsifies it.
+LATENCY_LINE_PREFIXES: tuple[str, ...] = (LATENCY_LINE_PREFIX, "- p50:", "- p95:")
+
#: The matching fields in :meth:`ReplayScore.as_dict`, for the JSON export.
-LATENCY_FIELDS: tuple[str, ...] = ("mean_latency_ms", "p95_latency_ms")
+LATENCY_FIELDS: tuple[str, ...] = (
+ "mean_latency_ms",
+ "p95_latency_ms",
+ "time_to_verdict_p50_ms",
+ "time_to_verdict_p95_ms",
+)
#: The canonical disposition that means "this was a real threat". Written once
#: because "malicious recall" has to mean the same thing in the metric, the
@@ -105,6 +119,17 @@ GRADED_DISPOSITIONS: tuple[str, ...] = (
#: An analyst who declined to classify. Excluded from accuracy, never guessed.
UNLABELED = "unlabeled"
+#: The confidence at which auto-close precision is reported when a caller
+#: names no tenant policy. Not a recommendation and not a default the
+#: product applies -- closure is governed per tenant by the autonomy policy.
+#: It exists so the figure is comparable across runs that did not state one.
+DEFAULT_AUTO_CLOSE_THRESHOLD = 0.9
+
+#: Verdicts a closure policy can act on without a human. `true_positive` is
+#: absent deliberately: a confirmed attack escalates, it is never closed,
+#: which is the rule `siem_writeback` already follows.
+_AUTO_CLOSABLE_VERDICTS: frozenset[str] = frozenset({"false_positive", "benign", "benign_true_positive"})
+
#: Agent outputs that are a refusal to decide rather than a decision. These are
#: abstentions: scored as neither right nor wrong, and counted separately so
#: accuracy and abstention cannot be traded off invisibly. ``escalate`` belongs
@@ -194,6 +219,61 @@ class ReplayScore:
headline_accuracy_ci: tuple[float, float] | None = None
headline_withheld_reason: str | None = None
+ # ---- the figures that survive an imbalanced corpus -------------------
+ #
+ # Plain accuracy on a queue that is 90% false positive is 0.90 for an
+ # agent that reads nothing. These three are published together, always,
+ # because the first two are only interpretable against the third: a
+ # reader given 0.74 alone cannot tell whether the agent is good or the
+ # queue is.
+ #
+ # Balanced accuracy is the unweighted mean recall over the classes the
+ # corpus actually holds. Averaging over all four canonical dispositions
+ # would cap a perfect agent at 0.5 on a two-class corpus, which is a
+ # scoring bug that reads as a model failure.
+ balanced_accuracy: float | None = None
+ #: Matthews correlation. The one headline figure the base rate cannot
+ #: buy: 0.0 for any predictor with no relationship to the label, +1 for
+ #: perfect agreement, -1 for perfect disagreement. Computed over the
+ #: multi-class confusion matrix, so it covers all four dispositions
+ #: rather than collapsing them to malicious/not.
+ matthews_corrcoef: float | None = None
+ majority_class_accuracy: float | None = None
+ majority_class_label: str | None = None
+
+ #: Wilson score interval on malicious recall, beside the bootstrap one.
+ #:
+ #: Closed-form rather than resampled, for two reasons. It is
+ #: deterministic for a given (successes, trials), so two runs over one
+ #: corpus cannot disagree; and it keeps width at the boundary, where a
+ #: percentile bootstrap over an all-ones vector returns [1.0, 1.0] and
+ #: claims a certainty the sample size does not support.
+ malicious_recall_wilson: tuple[float, float] | None = None
+
+ #: "If the tenant let the agent close at confidence >= threshold, what
+ #: share of what it closed was really closable?" A malicious case above
+ #: the threshold is an attack the platform would have closed by itself,
+ #: which is the outcome this number exists to price. `None` rather than
+ #: 0.0 when nothing crossed the threshold: 0.0 reads as "it closed
+ #: things and got them all wrong".
+ auto_close_threshold: float | None = None
+ auto_close_considered: int = 0
+ auto_close_correct: int = 0
+ auto_close_precision: float | None = None
+ #: Share of labelled decisions the agent routed to a human instead of
+ #: deciding. The same population as `abstention_rate`, named the way an
+ #: operator sizing a queue thinks about it.
+ escalation_rate: float | None = None
+
+ # ---- time to verdict: reported, never graded -------------------------
+ #
+ # Latency is a property of the hardware the run happened on, so it must
+ # not move a score -- a scoreboard that graded it would rank a faster
+ # laptop as a better agent. Published beside the figures and labelled
+ # with the hardware by the caller, never inside them.
+ time_to_verdict_p50_ms: float | None = None
+ time_to_verdict_p95_ms: float | None = None
+
# ---- the rest --------------------------------------------------------
abstention_rate: float | None = None
per_class: list[ClassScore] = field(default_factory=list)
@@ -236,6 +316,64 @@ def _f1(precision: float | None, recall: float | None) -> float | None:
return 2 * precision * recall / (precision + recall)
+def _wilson_interval(successes: int, trials: int, *, z: float = 1.959963984540054) -> tuple[float, float] | None:
+ """Wilson score interval at 95%, clamped to [0, 1].
+
+ `z` is the two-sided 97.5th percentile of the standard normal, written
+ out rather than imported so this package keeps no numeric dependency.
+
+ The interval is centred on a shrunk estimate rather than on the raw
+ proportion, which is exactly why it keeps width at 0 and 1 where the
+ normal approximation and a percentile bootstrap both collapse.
+ """
+ if trials <= 0:
+ return None
+ phat = successes / trials
+ denom = 1.0 + z * z / trials
+ centre = (phat + z * z / (2 * trials)) / denom
+ margin = (z / denom) * ((phat * (1.0 - phat) / trials + z * z / (4 * trials * trials)) ** 0.5)
+ return (max(0.0, centre - margin), min(1.0, centre + margin))
+
+
+def _matthews(matrix: dict[str, dict[str, int]], labels: list[str]) -> float | None:
+ """Multi-class Matthews correlation over the confusion matrix.
+
+ The K-class generalisation (Gorodkin), which reduces to the familiar
+ 2x2 formula when K is 2. Abstentions are excluded by the caller: an
+ alert routed to a human is not a wrong prediction, and counting it as
+ one would make an appropriately humble agent look like a bad one.
+
+ Two different zeros, kept apart:
+
+ * **no rows at all** -> `None`. Nothing was measured, and 0.0 would
+ read as "measured, and no relationship".
+ * **rows, but the predictor or the labels are constant** -> `0.0`.
+ The denominator is zero here too, but the answer is not unknown: a
+ predictor that says one thing to everything has exactly zero
+ correlation with the label, which is the finding this coefficient
+ exists to surface. Returning `None` would hide the constant-answer
+ agent behind "not measurable", and that agent is the whole reason
+ plain accuracy was not enough.
+ """
+ total = sum(matrix[t].get(p, 0) for t in labels for p in labels)
+ if total == 0:
+ return None
+ correct = sum(matrix[label].get(label, 0) for label in labels)
+ actual = {label: sum(matrix[label].get(p, 0) for p in labels) for label in labels}
+ predicted = {label: sum(matrix[t].get(label, 0) for t in labels) for label in labels}
+
+ cov_xy = correct * total - sum(actual[label] * predicted[label] for label in labels)
+ cov_xx = total * total - sum(predicted[label] ** 2 for label in labels)
+ cov_yy = total * total - sum(actual[label] ** 2 for label in labels)
+ # `math.sqrt` rather than `** 0.5`: typeshed types the float power
+ # operator as returning `Any`, which the baseline gate reports as a
+ # `no-any-return` out of a function declared `float | None`.
+ denom = math.sqrt(cov_xx * cov_yy)
+ if denom == 0:
+ return 0.0
+ return cov_xy / denom
+
+
def _percentile(values: list[float], fraction: float) -> float | None:
if not values:
return None
@@ -327,6 +465,7 @@ def score_replay(
*,
bootstrap_resamples: int = BOOTSTRAP_RESAMPLES,
bootstrap_seed: int = BOOTSTRAP_SEED,
+ auto_close_threshold: float = DEFAULT_AUTO_CLOSE_THRESHOLD,
) -> ReplayScore:
"""Grade a replay run's decisions against the analysts' own labels.
@@ -385,6 +524,11 @@ def score_replay(
latencies = [float(d.get("latency_ms") or 0.0) for d in decisions]
score.mean_latency_ms = (sum(latencies) / len(latencies)) if latencies else None
score.p95_latency_ms = _percentile(latencies, 0.95)
+ # Named for what an operator calls it. Same measurements as the two
+ # fields above; published under the plan's own term so the scorecard
+ # and the page agree about which number is "time to verdict".
+ score.time_to_verdict_p50_ms = _percentile(latencies, 0.50)
+ score.time_to_verdict_p95_ms = score.p95_latency_ms
score.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})
if not labelled:
@@ -459,6 +603,45 @@ def score_replay(
verdicts[key] = verdicts.get(key, 0) + 1
score.false_negative_verdicts = dict(sorted(verdicts.items()))
+ score.malicious_recall_wilson = _wilson_interval(
+ sum(1 for d in malicious_rows if d.get("verdict") == MALICIOUS),
+ len(malicious_rows),
+ )
+
+ # ---- figures that survive an imbalanced corpus ------------------------
+ #
+ # Over `answered` only, matching per-class precision above: an
+ # abstention is a decision to involve a human, not a wrong prediction.
+ # It is still visible, as `escalation_rate` directly below.
+ present = [label for label in GRADED_DISPOSITIONS if support.get(label, 0) > 0]
+ recalls = [c.recall for c in score.per_class if c.label in present and c.recall is not None]
+ score.balanced_accuracy = (sum(recalls) / len(recalls)) if recalls else None
+
+ answered_matrix: dict[str, dict[str, int]] = {expected: dict.fromkeys(GRADED_DISPOSITIONS, 0) for expected in GRADED_DISPOSITIONS}
+ for decision in answered:
+ expected = str(decision.get("expected_disposition"))
+ predicted = str(decision.get("verdict") or "")
+ if expected in answered_matrix and predicted in answered_matrix[expected]:
+ answered_matrix[expected][predicted] += 1
+ score.matthews_corrcoef = _matthews(answered_matrix, list(GRADED_DISPOSITIONS))
+
+ # The number every other number has to be read against.
+ if support:
+ majority = max(support, key=lambda label: support[label])
+ score.majority_class_label = majority
+ score.majority_class_accuracy = _ratio(support[majority], len(labelled))
+
+ # ---- auto-close precision at the closure threshold --------------------
+ score.auto_close_threshold = auto_close_threshold
+ closable = [
+ d for d in answered if d.get("verdict") in _AUTO_CLOSABLE_VERDICTS and float(d.get("confidence") or 0.0) >= auto_close_threshold
+ ]
+ score.auto_close_considered = len(closable)
+ score.auto_close_correct = sum(1 for d in closable if _is_correct(d))
+ score.auto_close_precision = _ratio(score.auto_close_correct, len(closable))
+
+ score.escalation_rate = score.abstention_rate
+
# ---- calibration ------------------------------------------------------
score.calibration, score.expected_calibration_error = _calibration(answered)
@@ -500,6 +683,20 @@ def _interval(bounds: tuple[float, float] | None) -> str:
return "not measured" if bounds is None else f"{bounds[0] * 100:.1f}% to {bounds[1] * 100:.1f}%"
+def _number(value: float | None) -> str:
+ """A bare coefficient, for the figures that are not rates.
+
+ Matthews correlation runs -1 to +1 and the closure threshold is a
+ confidence, so neither is a percentage. Same "not measured" rule as
+ `_pct`.
+ """
+ return "not measured" if value is None else f"{value:.2f}"
+
+
+def _ms(value: float | None) -> str:
+ return "not measured" if value is None else f"{value:,.0f} ms"
+
+
def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None = None) -> str:
"""Render the report as Markdown, malicious recall first.
@@ -523,6 +720,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =
"",
f"- Malicious cases in the test window: {score.malicious_support}",
f"- Recall: {_pct(score.malicious_recall)} (95% CI {_interval(score.malicious_recall_ci)})",
+ f"- Recall, Wilson 95% interval: {_interval(score.malicious_recall_wilson)}",
f"- Precision: {_pct(score.malicious_precision)}",
"",
"## Headline accuracy",
@@ -536,6 +734,45 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =
"",
]
+ # Printed immediately under the headline, and never without the
+ # baseline. Plain accuracy on a queue that is 90% false positive is
+ # 0.90 for an agent that reads nothing; a reader who sees the headline
+ # without what a constant would have scored cannot tell the two apart.
+ lines += [
+ "## Against a constant answer",
+ "",
+ f"- Majority-class baseline: {_pct(score.majority_class_accuracy)} (always answering `{score.majority_class_label}`)",
+ f"- Balanced accuracy: {_pct(score.balanced_accuracy)}",
+ f"- Matthews correlation: {_number(score.matthews_corrcoef)}",
+ "",
+ "Balanced accuracy is the unweighted mean recall over the classes this",
+ "corpus holds, so a constant answer scores 0.50 however skewed the queue",
+ "is. Matthews correlation is 0.00 for any predictor with no relationship",
+ "to the label, which is the one headline figure the base rate cannot buy.",
+ "",
+ "## Auto-close and escalation",
+ "",
+ f"- Auto-close precision at confidence >= {_number(score.auto_close_threshold)}:"
+ f" {_pct(score.auto_close_precision)}"
+ f" over {score.auto_close_considered} decision(s) the policy would have closed",
+ f"- Escalation rate: {_pct(score.escalation_rate)}",
+ "",
+ "A malicious case above the threshold is an attack the platform would",
+ "have closed by itself. Nothing above the threshold reports no figure",
+ "rather than a zero, which would read as closing things and getting",
+ "them all wrong.",
+ "",
+ "## Time to verdict",
+ "",
+ f"- p50: {_ms(score.time_to_verdict_p50_ms)}",
+ f"- p95: {_ms(score.time_to_verdict_p95_ms)}",
+ "",
+ "Reported, never graded: latency is a property of the hardware the run",
+ "happened on, and a scoreboard that graded it would rank a faster",
+ "machine as a better agent.",
+ "",
+ ]
+
lines += ["## Per class", "", "| Disposition | Support | Predicted | Precision | Recall | F1 |", "|---|---|---|---|---|---|"]
for row in score.per_class:
lines.append(f"| {row.label} | {row.support} | {row.predicted} | {_pct(row.precision)} | {_pct(row.recall)} | {_pct(row.f1)} |")
@@ -626,10 +863,14 @@ def strip_latency(report: str) -> str:
the line count are unchanged and a diff of two reports points at content
rather than at an offset.
"""
- return "\n".join(
- f"{LATENCY_LINE_PREFIX} excluded from this export (wall clock, not reproducible)" if line.startswith(LATENCY_LINE_PREFIX) else line
- for line in report.split("\n")
- )
+
+ def _strip(line: str) -> str:
+ for prefix in LATENCY_LINE_PREFIXES:
+ if line.startswith(prefix):
+ return f"{prefix} excluded from this export (wall clock, not reproducible)"
+ return line
+
+ return "\n".join(_strip(line) for line in report.split("\n"))
def _calibration(answered: list[dict[str, Any]]) -> tuple[list[CalibrationBin], float | None]:
diff --git a/services/api/tests/test_replay_evaluation.py b/services/api/tests/test_replay_evaluation.py
index c96952a9e..d2246740d 100644
--- a/services/api/tests/test_replay_evaluation.py
+++ b/services/api/tests/test_replay_evaluation.py
@@ -27,7 +27,7 @@ from typing import Any
import httpx
import pytest
-from app._vendor.aisoc_benchmark.replay import LATENCY_LINE_PREFIX, format_replay_report, score_replay
+from app._vendor.aisoc_benchmark.replay import LATENCY_LINE_PREFIXES, format_replay_report, score_replay
from app.api.v1.deps import CurrentUser, get_current_user
from app.api.v1.endpoints.evaluations import StartReplayRequest
from app.api.v1.endpoints.evaluations import router as evaluations_router
@@ -204,10 +204,15 @@ class TestExport:
after = stripped.split("\n")
assert len(original) == len(after)
differing = [(a, b) for a, b in zip(original, after, strict=True) if a != b]
- assert len(differing) == 1
- assert differing[0][0].startswith(LATENCY_LINE_PREFIX)
- assert differing[0][1].startswith(LATENCY_LINE_PREFIX)
- assert "not reproducible" in differing[0][1]
+ # A property, not a count. The report carries more than one
+ # host-measured line since the scorecard added "time to verdict",
+ # and what has to hold is that the export touches *only* lines the
+ # stripper declares -- not that there happens to be one of them.
+ assert differing, "the export changed nothing while claiming to exclude latency"
+ for before, line in differing:
+ assert before.startswith(LATENCY_LINE_PREFIXES), f"excluded a line it does not declare: {before!r}"
+ assert line.startswith(LATENCY_LINE_PREFIXES)
+ assert "not reproducible" in line
def test_the_json_export_nulls_latency_rather_than_dropping_the_keys(self) -> None:
score = score_replay(_corpus()).as_dict()