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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat: publish how often the agent abstains, and how grounded its verdicts are (#677)
Beenu Arorae02e6abf8fb4
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 5d57ffde4..434caca08 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -19180,6 +19180,31 @@ components:type: numbertitle: Repeat Suppression Ratedefault: 0.0+ triaged_alerts:+ type: integer+ title: Triaged Alerts+ default: 0+ abstentions:+ type: integer+ title: Abstentions+ default: 0+ abstention_rate:+ type: number+ title: Abstention Rate+ default: 0.0+ ungrounded_demotions:+ type: integer+ title: Ungrounded Demotions+ default: 0+ mean_groundedness:+ anyOf:+ - type: number+ - type: 'null'+ title: Mean Groundedness+ scored_verdicts:+ type: integer+ title: Scored Verdicts+ default: 0type: objectrequired:- perioddiff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.pyindex 97e7b342c..82964246d 100644--- a/services/agents/app/investigator/ledger.py+++ b/services/agents/app/investigator/ledger.py@@ -399,6 +399,8 @@ async def persist_auto_triage(iterations: int = 0,tokens: int = 0,cost_usd: float = 0.0,+ groundedness: float | None = None,+ ungrounded: bool | None = None,) -> bool:"""Durably record an auto-triage outcome (issue #571) in ONE transaction:@@ -500,6 +502,13 @@ async def persist_auto_triage(ai_recommendations = $6::jsonb,status = CASE WHEN $7 THEN 'resolved' ELSE status END,resolved_at = CASE WHEN $7 THEN now() ELSE resolved_at END,+ -- Nullable on purpose: NULL is "not scored",+ -- which is a different fact from "scored zero".+ -- The deterministic path never assesses+ -- groundedness, and defaulting it would read as+ -- every such verdict being unsupported.+ triage_groundedness = $8,+ triage_ungrounded = $9,updated_at = now()WHERE id = $1 AND tenant_id = $2""",@@ -510,6 +519,8 @@ async def persist_auto_triage((rationale or "")[:8000] or None,json.dumps(recommendations),auto_closed,+ float(groundedness) if groundedness is not None else None,+ ungrounded,)logger.info("ledger.auto_triage_persisted",diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex 479b8d4f9..b71837462 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -712,6 +712,11 @@ class FusedAlertTriageWorker:iterations=state.iteration_count,tokens=tokens,cost_usd=cost_usd,+ # Persisted so an ungrounded auto-closure is auditable after the+ # fact and aggregatable on /metrics/funnel, rather than surviving+ # only inside a findings string.+ groundedness=state.groundedness,+ ungrounded=(state.groundedness is not None and state.groundedness < _groundedness_floor()),)@staticmethoddiff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.pyindex cb561d109..fa0f6fec3 100644--- a/services/api/app/api/v1/endpoints/metrics.py+++ b/services/api/app/api/v1/endpoints/metrics.py@@ -158,6 +158,25 @@ class FunnelMetrics(BaseModel):# ``repeat_suppression_rate`` = suppressed / (alerts_generated + suppressed).repeat_alerts_suppressed: int = 0repeat_suppression_rate: float = 0.0+ # v9 (trust surface): how often the agent declines to decide, and how well+ # its reasoning was supported by the evidence it was given.+ #+ # These exist because they are the questions a buyer evaluating an AI-SOC+ # actually asks, and because a system that never abstains is not+ # calibrated — it is guessing with confidence. Publishing the rate inverts+ # the usual incentive to report only automation percentage.+ #+ # ``abstention_rate`` = needs_review / triaged. ``mean_groundedness`` is+ # averaged over scored verdicts only; verdicts from the deterministic path+ # are never scored and are excluded rather than counted as zero.+ # ``ungrounded_demotions`` is the subset where the agent had a confident+ # auto-closing answer that its evidence did not support.+ triaged_alerts: int = 0+ abstentions: int = 0+ abstention_rate: float = 0.0+ ungrounded_demotions: int = 0+ mean_groundedness: float | None = None+ scored_verdicts: int = 0# ────────────────────────── v1.5 Pipeline-health models ───────────────────────@@ -796,6 +815,63 @@ async def _repeat_alerts_suppressed(db, tenant_id, start, end) -> int:return 0+async def _triage_quality(db, tenant_id, start, end) -> dict[str, object]:+ """Abstention and groundedness over auto-triaged alerts in [start, end).++ Tenant-scoped at the query layer. Returns zeros when the columns do not+ exist yet (pre-migration) rather than failing the funnel, matching+ ``_repeat_alerts_suppressed``.++ ``mean_groundedness`` averages only scored verdicts. The deterministic+ triage path never assesses groundedness, so counting its verdicts as 0.0+ would report a platform-wide collapse in reasoning quality every time the+ LLM path was unavailable.+ """+ empty = {+ "triaged_alerts": 0,+ "abstentions": 0,+ "abstention_rate": 0.0,+ "ungrounded_demotions": 0,+ "mean_groundedness": None,+ "scored_verdicts": 0,+ }+ try:+ row = (+ await db.execute(+ text(+ """+ SELECT+ count(*) FILTER (WHERE disposition IS NOT NULL) AS triaged,+ count(*) FILTER (WHERE disposition = 'needs_review') AS abstentions,+ count(*) FILTER (WHERE triage_ungrounded IS TRUE) AS ungrounded,+ count(*) FILTER (WHERE triage_groundedness IS NOT NULL) AS scored,+ avg(triage_groundedness) AS mean_groundedness+ FROM alerts+ WHERE tenant_id = :tid AND created_at >= :start AND created_at < :end+ """+ ),+ {"tid": tenant_id, "start": start, "end": end},+ )+ ).first()+ except Exception: # noqa: BLE001 — analytics columns optional; never break the funnel+ return empty++ if row is None:+ return empty++ triaged = int(row[0] or 0)+ abstentions = int(row[1] or 0)+ scored = int(row[3] or 0)+ return {+ "triaged_alerts": triaged,+ "abstentions": abstentions,+ "abstention_rate": round(abstentions / triaged, 4) if triaged else 0.0,+ "ungrounded_demotions": int(row[2] or 0),+ "mean_groundedness": round(float(row[4]), 4) if row[4] is not None else None,+ "scored_verdicts": scored,+ }++async def _funnel_window(db, tenant_id, start, end, *, mitre_total: int) -> dict:"""Compute the funnel for a single [start, end) window."""events_of_interest = await _events_of_interest(db, tenant_id, start, end)@@ -916,6 +992,7 @@ async def _funnel_window(db, tenant_id, start, end, *, mitre_total: int) -> dictcoverage = MitreCoverage(covered=covered, total=mitre_total, ratio=ratio)suppressed = await _repeat_alerts_suppressed(db, tenant_id, start, end)+ quality = await _triage_quality(db, tenant_id, start, end)# Compounding reduction: of everything the loop *could* have queued# (generated + suppressed), what share did prior outcomes suppress?denom = alerts_generated + suppressed@@ -933,6 +1010,7 @@ async def _funnel_window(db, tenant_id, start, end, *, mitre_total: int) -> dict"mitre_coverage": coverage,"repeat_alerts_suppressed": int(suppressed),"repeat_suppression_rate": suppression_rate,+ **quality,}diff --git a/services/api/migrations/051_triage_groundedness.sql b/services/api/migrations/051_triage_groundedness.sqlnew file mode 100644index 000000000..64fdd1791--- /dev/null+++ b/services/api/migrations/051_triage_groundedness.sql@@ -0,0 +1,40 @@+-- Record how well each auto-triage verdict was supported by its evidence.+--+-- `app.confidence.groundedness` scores what fraction of the concrete+-- indicators a verdict's reasoning asserts — IPs, hashes, CVEs, MITRE+-- techniques, domains — actually appear in the evidence the agent was given.+-- v8.0 wired it into the triage path so an auto-closing verdict below the+-- floor is demoted to `needs_review` instead of closing.+--+-- The score itself was not persisted. It survived only inside a findings+-- string, which means it could not be aggregated, trended, or used to answer+-- the question a buyer evaluating an AI-SOC actually asks: how often is your+-- agent's reasoning supported by what it was shown, and how often does it+-- decline to decide?+--+-- Both columns are nullable rather than defaulted. NULL means "not scored",+-- which is a different fact from "scored zero" — pre-migration rows and+-- verdicts from the deterministic path were never assessed, and defaulting+-- them to 0.0 would read as every historical verdict being unsupported.++ALTER TABLE alerts+ -- Fraction in [0, 1]. NULL = not scored.+ ADD COLUMN IF NOT EXISTS triage_groundedness DOUBLE PRECISION,+ -- True when the groundedness gate demoted an auto-closing verdict to+ -- needs_review. Distinct from `disposition = 'needs_review'`, which is also+ -- reached by low confidence and by genuine escalation: this flags the subset+ -- where the agent had a confident answer that its evidence did not support.+ ADD COLUMN IF NOT EXISTS triage_ungrounded BOOLEAN;++-- The abstention and groundedness aggregates on /metrics/funnel scan by+-- tenant and window, so index the shape those queries use. Partial, because+-- the vast majority of rows are never scored and including them would make+-- the index mostly dead weight.+CREATE INDEX IF NOT EXISTS ix_alerts_tenant_groundedness+ ON alerts (tenant_id, created_at)+ WHERE triage_groundedness IS NOT NULL;++COMMENT ON COLUMN alerts.triage_groundedness IS+ 'Fraction of indicators cited in the triage reasoning that appear in the evidence. NULL = not scored.';+COMMENT ON COLUMN alerts.triage_ungrounded IS+ 'True when the groundedness gate demoted a confident auto-closing verdict to needs_review.';diff --git a/services/api/tests/test_triage_quality_metrics.py b/services/api/tests/test_triage_quality_metrics.pynew file mode 100644index 000000000..98bc30bca--- /dev/null+++ b/services/api/tests/test_triage_quality_metrics.py@@ -0,0 +1,168 @@+"""Abstention and groundedness are published, not just computed.++v8.0 wired `app.confidence.groundedness` into the triage path so an+auto-closing verdict whose reasoning cites indicators the evidence never+contained is demoted to `needs_review` instead of closing. The score itself+survived only inside a findings string, which meant it could not be+aggregated, trended, or used to answer the question a buyer evaluating an+AI-SOC actually asks: how often is your agent's reasoning supported by what it+was shown, and how often does it decline to decide?++A system that never abstains is not calibrated — it is guessing with+confidence. Publishing the rate inverts the usual vendor incentive to report+only automation percentage.++Two things these tests pin down because both are easy to get wrong in the+flattering direction:++* `mean_groundedness` averages only *scored* verdicts. The deterministic+ triage path never assesses groundedness, so counting its verdicts as 0.0+ would report a platform-wide collapse in reasoning quality every time the+ LLM path was unavailable.+* NULL means "not scored", which is a different fact from "scored zero".+"""++from __future__ import annotations++import pytest++metrics = pytest.importorskip(+ "app.api.v1.endpoints.metrics",+ reason="API dependencies not installed",+)+++class _Row:+ """Positional row shaped like the aggregate query's SELECT list."""++ def __init__(self, triaged, abstentions, ungrounded, scored, mean):+ self._v = (triaged, abstentions, ungrounded, scored, mean)++ def __getitem__(self, i):+ return self._v[i]+++class _DB:+ def __init__(self, row=None, raises=False):+ self._row = row+ self._raises = raises++ async def execute(self, *_a, **_k):+ if self._raises:+ raise RuntimeError("column does not exist")+ row = self._row++ class _Result:+ def first(self_inner): # noqa: N805+ return row++ return _Result()+++async def test_abstention_rate_is_needs_review_over_triaged():+ out = await metrics._triage_quality(+ _DB(_Row(triaged=100, abstentions=25, ungrounded=4, scored=80, mean=0.91)),+ "t",+ None,+ None,+ )+ assert out["triaged_alerts"] == 100+ assert out["abstentions"] == 25+ assert out["abstention_rate"] == 0.25+++async def test_ungrounded_demotions_are_counted_separately():+ """Distinct from the abstention count.++ `needs_review` is also reached by low confidence and by genuine+ escalation. This is the subset where the agent had a confident+ auto-closing answer that its own evidence did not support, which is a+ different and more alarming signal.+ """+ out = await metrics._triage_quality(+ _DB(_Row(triaged=100, abstentions=25, ungrounded=4, scored=80, mean=0.91)),+ "t",+ None,+ None,+ )+ assert out["ungrounded_demotions"] == 4+ assert out["ungrounded_demotions"] < out["abstentions"]+++async def test_mean_groundedness_averages_only_scored_verdicts():+ """Unscored verdicts must not be counted as zero.++ 80 of 100 verdicts were scored; the mean describes those 80.+ """+ out = await metrics._triage_quality(+ _DB(_Row(triaged=100, abstentions=25, ungrounded=4, scored=80, mean=0.91)),+ "t",+ None,+ None,+ )+ assert out["scored_verdicts"] == 80+ assert out["mean_groundedness"] == 0.91+++async def test_no_scored_verdicts_reports_none_not_zero():+ """NULL is "not scored", which is not the same fact as "scored zero"."""+ out = await metrics._triage_quality(+ _DB(_Row(triaged=10, abstentions=1, ungrounded=0, scored=0, mean=None)),+ "t",+ None,+ None,+ )+ assert out["mean_groundedness"] is None+ assert out["scored_verdicts"] == 0+++async def test_nothing_triaged_does_not_divide_by_zero():+ out = await metrics._triage_quality(+ _DB(_Row(triaged=0, abstentions=0, ungrounded=0, scored=0, mean=None)),+ "t",+ None,+ None,+ )+ assert out["abstention_rate"] == 0.0+++async def test_a_missing_column_degrades_instead_of_breaking_the_funnel():+ """Pre-migration deployments must still get a funnel.++ Same contract as `_repeat_alerts_suppressed`: an optional analytics column+ is never allowed to take down the whole dashboard.+ """+ out = await metrics._triage_quality(_DB(raises=True), "t", None, None)+ assert out["triaged_alerts"] == 0+ assert out["mean_groundedness"] is None+++async def test_no_rows_returns_the_empty_shape():+ out = await metrics._triage_quality(_DB(None), "t", None, None)+ assert out["abstention_rate"] == 0.0+ assert out["scored_verdicts"] == 0+++def test_the_funnel_model_exposes_every_field():+ """The endpoint's response model must actually carry these.++ Computing a metric and not publishing it is the shape of defect this whole+ line of work exists to remove.+ """+ fields = metrics.FunnelMetrics.model_fields+ for name in (+ "triaged_alerts",+ "abstentions",+ "abstention_rate",+ "ungrounded_demotions",+ "mean_groundedness",+ "scored_verdicts",+ ):+ assert name in fields, f"{name} is computed but not exposed on FunnelMetrics"