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.

fix(eval): the live dispatch runs on one event loop and scores failures as 0, with the floor re-derived from fixed-harness runs (#1466) (#1472)

Beenu Arora6cfef3227d5f
diff --git a/scripts/tests/test_wet_eval_live_dispatch.py b/scripts/tests/test_wet_eval_live_dispatch.py
new file mode 100644
index 000000000..65011e5f7
--- /dev/null
+++ b/scripts/tests/test_wet_eval_live_dispatch.py
@@ -0,0 +1,200 @@
+"""The live dispatch loop's two measurement properties (#1466).
+
+1. **One event loop for the whole run.** Per-incident ``asyncio.run`` looked
+ equivalent and was not: langchain-openai caches its default async httpx
+ client across constructions, so incident 2's fresh loop inherited a pooled
+ connection bound to incident 1's closed loop, and the first LLM call of
+ every subsequent incident — recon, always — died with "Event loop is
+ closed" and silently fell back to heuristics. Under the old code the test
+ below observes three distinct loop ids; under the fix, one.
+
+2. **A failed incident is scored 0 with its reason recorded, never dropped.**
+ Dropping it is survivor bias (the mean over the survivors flatters the
+ model) and shrinks the sample below what the floor was derived over, which
+ ``check_live_agent_floor.py`` rightly refuses. Scoring it 0 keeps the
+ sample size equal to the dispatched prefix and makes the failure legible
+ in the report.
+
+The fakes here stand in for ``app.investigator`` / ``app.confidence`` only —
+the loop structure and the record bookkeeping under test are entirely
+``scripts/wet_eval.py``'s own.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import json
+import sys
+import types
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_SCRIPTS = _REPO_ROOT / "scripts"
+
+
+def _load_wet_eval():
+ if str(_SCRIPTS) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS))
+ spec = importlib.util.spec_from_file_location("wet_eval_under_test", _SCRIPTS / "wet_eval.py")
+ assert spec is not None and spec.loader is not None
+ mod = importlib.util.module_from_spec(spec)
+ # Registered before exec: the dataclass machinery resolves the module's
+ # annotations through sys.modules, and an unregistered module leaves it
+ # holding None.
+ sys.modules["wet_eval_under_test"] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _incidents_file(tmp_path: Path, n: int = 3) -> Path:
+ incidents = [
+ {
+ "id": f"INC-{i}",
+ "template_id": "t-1",
+ "title": f"incident {i}",
+ "description": "a login from 203.0.113.7",
+ "severity": "medium",
+ "telemetry": [],
+ "evidence_keywords": [],
+ "expected_techniques": ["T1078"],
+ }
+ for i in range(1, n + 1)
+ ]
+ path = tmp_path / "incidents.json"
+ path.write_text(json.dumps(incidents))
+ return path
+
+
+def _good_state() -> SimpleNamespace:
+ return SimpleNamespace(
+ status="completed",
+ error=None,
+ cost_summary={"call_count": 2, "prompt_tokens": 100, "completion_tokens": 50},
+ recon=SimpleNamespace(
+ summary="observed 203.0.113.7",
+ mitre_techniques=["T1078"],
+ threat_actors=[],
+ iocs=[{"value": "203.0.113.7"}],
+ ),
+ forensic=None,
+ responder=None,
+ )
+
+
+def fake_agent_stack(monkeypatch: pytest.MonkeyPatch):
+ """Install fake ``app.investigator`` / ``app.confidence.groundedness``.
+
+ ``_live_records`` imports both lazily, so placing modules in
+ ``sys.modules`` is the whole injection. The fixture yields a dict the
+ test mutates to control per-incident behaviour and to record what the
+ dispatch did.
+ """
+ control: dict[str, Any] = {"loops": [], "behaviour": {}}
+
+ async def run_investigation(*, case_id: str, alert_summary: str, raw_alert: dict) -> Any:
+ control["loops"].append(id(asyncio.get_running_loop()))
+ behaviour = control["behaviour"].get(case_id)
+ if behaviour == "raise":
+ raise RuntimeError("synthetic dispatch failure")
+ state = _good_state()
+ if behaviour == "failed":
+ state.status = "failed"
+ state.error = "synthetic parse failure"
+ return state
+
+ def score_groundedness(assertion_text: str, evidence_text: str) -> Any:
+ return SimpleNamespace(score=0.8, hallucinated=[])
+
+ app_pkg = types.ModuleType("app")
+ investigator = types.ModuleType("app.investigator")
+ investigator.run_investigation = run_investigation # type: ignore[attr-defined]
+ confidence = types.ModuleType("app.confidence")
+ groundedness = types.ModuleType("app.confidence.groundedness")
+ groundedness.score_groundedness = score_groundedness # type: ignore[attr-defined]
+ app_pkg.investigator = investigator # type: ignore[attr-defined]
+ app_pkg.confidence = confidence # type: ignore[attr-defined]
+ confidence.groundedness = groundedness # type: ignore[attr-defined]
+
+ for name, module in [
+ ("app", app_pkg),
+ ("app.investigator", investigator),
+ ("app.confidence", confidence),
+ ("app.confidence.groundedness", groundedness),
+ ]:
+ monkeypatch.setitem(sys.modules, name, module)
+ monkeypatch.setenv("WET_EVAL_OPENAI_KEY", "test-key")
+ return control
+
+
+def test_every_incident_dispatches_on_one_event_loop(tmp_path: Path, fake_agent_stack: dict) -> None:
+ """Under per-incident ``asyncio.run`` this set has three members."""
+ wet_eval = _load_wet_eval()
+
+ records, warnings, degraded = wet_eval._live_records(_incidents_file(tmp_path, 3), model="fake-model")
+
+ assert not degraded
+ assert len(records) == 3
+ assert len(fake_agent_stack["loops"]) == 3
+ assert len(set(fake_agent_stack["loops"])) == 1, (
+ "incidents dispatched on different event loops — the cached async HTTP client in the LLM stack "
+ "poisons every loop after the first, and recon's call dies with 'Event loop is closed' (#1466)"
+ )
+
+
+def test_a_raised_investigation_scores_zero_and_stays_in_the_sample(tmp_path: Path, fake_agent_stack: dict) -> None:
+ wet_eval = _load_wet_eval()
+ fake_agent_stack["behaviour"]["INC-2"] = "raise"
+
+ records, warnings, degraded = wet_eval._live_records(_incidents_file(tmp_path, 3), model="fake-model")
+
+ assert not degraded
+ assert [r.incident_id for r in records] == ["INC-1", "INC-2", "INC-3"], (
+ "a failed incident was dropped from the sample — the mean over the survivors is survivor bias, "
+ "and the shrunken sample fails the floor checker's size requirement"
+ )
+ failed = records[1]
+ assert failed.groundedness == 0.0
+ assert failed.zero_scored_reason is not None and "raised" in failed.zero_scored_reason
+ assert records[0].groundedness == 0.8 and records[2].groundedness == 0.8
+
+ block = wet_eval._groundedness_block(records)
+ assert block["measured"] is True
+ assert block["scored_incidents"] == 3
+ assert block["zero_scored_incidents"] == 1
+ assert block["zero_scored"] == [{"incident": "INC-2", "reason": failed.zero_scored_reason}]
+ # 0.8, 0.0, 0.8 — the zero participates in the mean rather than vanishing.
+ assert block["mean"] == pytest.approx(0.5333, abs=1e-4)
+
+
+def test_a_status_failed_investigation_scores_zero_with_the_error_recorded(tmp_path: Path, fake_agent_stack: dict) -> None:
+ wet_eval = _load_wet_eval()
+ fake_agent_stack["behaviour"]["INC-3"] = "failed"
+
+ records, _warnings, degraded = wet_eval._live_records(_incidents_file(tmp_path, 3), model="fake-model")
+
+ assert not degraded
+ assert len(records) == 3
+ failed = records[2]
+ assert failed.groundedness == 0.0
+ assert failed.zero_scored_reason is not None
+ assert "status=failed" in failed.zero_scored_reason
+ assert "synthetic parse failure" in failed.zero_scored_reason
+ # The calls the failed run DID place are still counted — they happened.
+ assert failed.llm_calls == 2
+
+
+def test_a_clean_run_reports_no_zero_scored_block(tmp_path: Path, fake_agent_stack: dict) -> None:
+ """The zero-scored keys appear only when there is something to explain."""
+ wet_eval = _load_wet_eval()
+
+ records, _warnings, _degraded = wet_eval._live_records(_incidents_file(tmp_path, 3), model="fake-model")
+
+ block = wet_eval._groundedness_block(records)
+ assert "zero_scored" not in block
+ assert "zero_scored_incidents" not in block
diff --git a/scripts/wet_eval.py b/scripts/wet_eval.py
index 24de8370b..92a74d900 100644
--- a/scripts/wet_eval.py
+++ b/scripts/wet_eval.py
@@ -264,6 +264,14 @@ class WetEvalRecord:
#: through to its deterministic path, which produces plausible records
#: that no model wrote.
llm_calls: int = 0
+ #: Set when the incident could not be investigated at all (the pipeline
+ #: raised, or returned status=failed) and its groundedness was therefore
+ #: scored as 0 with this reason recorded. Scoring the failure as 0 keeps
+ #: the sample size equal to the dispatched prefix; *dropping* it would be
+ #: survivor bias — the mean over the incidents that happened to survive
+ #: flatters the model, and the shrunken sample then fails the floor
+ #: checker's size requirement anyway (#1466).
+ zero_scored_reason: str | None = None
@property
def total_tokens(self) -> int:
@@ -460,37 +468,91 @@ def _live_records(
# already set one (e.g. local dev with a personal key in the env).
os.environ.setdefault("OPENAI_API_KEY", api_key)
- for inc in incidents:
- # Exactly what the agent is handed, and therefore exactly what
- # groundedness scores its output against. The incident's
- # ``expected_*`` keys are the answer sheet and are deliberately left
- # out: an agent that names a technique the telemetry never showed has
- # asserted an ungrounded indicator even when the technique is right.
- alert_summary = f"{inc.get('title') or ''}\n\n{inc.get('description') or ''}".strip()
- raw_alert = {
- "severity": inc.get("severity"),
- "telemetry": inc.get("telemetry") or [],
- "evidence_keywords": inc.get("evidence_keywords") or [],
- }
+ def _zero_scored(inc: dict[str, Any], *, reason: str, latency_s: float, llm_calls: int) -> WetEvalRecord:
+ """A failed investigation scored as 0, not dropped (#1466).
+
+ Dropping it is survivor bias twice over: the mean over the incidents
+ that happened to survive flatters the model, and the shrunken sample
+ then fails ``check_live_agent_floor``'s size requirement anyway. The
+ two honest readings of "the agent could not investigate this" are a
+ groundedness of 0 with the reason recorded — nothing it asserted was
+ grounded, because it asserted nothing scoreable — and a sample size
+ that always equals the dispatched prefix.
+ """
+ return WetEvalRecord(
+ incident_id=str(inc.get("id") or ""),
+ template_id=str(inc.get("template_id") or ""),
+ family=family_for_template(str(inc.get("template_id") or "")),
+ severity=str(inc.get("severity") or "medium").lower(),
+ prompt_tokens=0,
+ completion_tokens=0,
+ latency_seconds=round(latency_s, 4),
+ usd=None,
+ mitre_correct=False,
+ groundedness=0.0,
+ hallucinated=[],
+ llm_calls=llm_calls,
+ zero_scored_reason=reason,
+ )
- t0 = time.perf_counter()
- try:
- state = asyncio.run(
- run_investigation(
+ async def _dispatch_all() -> None:
+ # One event loop for the whole run, matching production, where the
+ # triage worker's loop lives as long as the process. Per-incident
+ # ``asyncio.run`` looked equivalent and was not: langchain-openai
+ # caches its default async httpx client across constructions (keyed
+ # on base_url + timeout), so incident 2's fresh loop inherited a
+ # pooled connection bound to incident 1's closed loop, and the first
+ # LLM call of every subsequent incident — recon, always — died with
+ # "Event loop is closed" and fell back to heuristics while the rest
+ # of the pipeline proceeded on the recycled client. The report then
+ # graded `mode: live` over investigations whose recon stage never
+ # consulted the model (#1466; reproduced locally, incident 1 recon
+ # 9.2s of real tokens, incident 2 recon failing in 9ms).
+ for inc in incidents:
+ # Exactly what the agent is handed, and therefore exactly what
+ # groundedness scores its output against. The incident's
+ # ``expected_*`` keys are the answer sheet and are deliberately left
+ # out: an agent that names a technique the telemetry never showed has
+ # asserted an ungrounded indicator even when the technique is right.
+ alert_summary = f"{inc.get('title') or ''}\n\n{inc.get('description') or ''}".strip()
+ raw_alert = {
+ "severity": inc.get("severity"),
+ "telemetry": inc.get("telemetry") or [],
+ "evidence_keywords": inc.get("evidence_keywords") or [],
+ }
+
+ t0 = time.perf_counter()
+ try:
+ state = await run_investigation(
case_id=str(inc.get("id") or ""),
alert_summary=alert_summary,
raw_alert=raw_alert,
)
- )
- except Exception as exc: # pragma: no cover - defensive.
- warnings.append(f"Live agent failed on incident {inc.get('id')}: {exc!r}; skipping.")
- continue
- latency_s = time.perf_counter() - t0
-
- if str(getattr(state, "status", "")) == "failed":
- warnings.append(f"Live agent returned status=failed on incident {inc.get('id')}: {getattr(state, 'error', None)!r}; skipping.")
- continue
-
+ except Exception as exc: # pragma: no cover - defensive.
+ reason = f"the investigation raised: {exc!r}"
+ warnings.append(f"Live agent failed on incident {inc.get('id')}: {exc!r}; scored as 0 groundedness.")
+ records.append(_zero_scored(inc, reason=reason, latency_s=time.perf_counter() - t0, llm_calls=0))
+ continue
+ latency_s = time.perf_counter() - t0
+
+ if str(getattr(state, "status", "")) == "failed":
+ error = getattr(state, "error", None)
+ reason = f"the investigation returned status=failed: {error!r}"
+ warnings.append(f"Live agent returned status=failed on incident {inc.get('id')}: {error!r}; scored as 0 groundedness.")
+ failed_calls = int((getattr(state, "cost_summary", None) or {}).get("call_count") or 0)
+ records.append(_zero_scored(inc, reason=reason, latency_s=latency_s, llm_calls=failed_calls))
+ continue
+
+ _score_live(inc, state, latency_s, alert_summary=alert_summary, raw_alert=raw_alert)
+
+ def _score_live(
+ inc: dict[str, Any],
+ state: Any,
+ latency_s: float,
+ *,
+ alert_summary: str,
+ raw_alert: dict[str, Any],
+ ) -> None:
# Measured by the run's own CostTracker, which sums the provider's
# reported usage across all four agents' calls. Only estimated when
# the provider surfaced nothing at all.
@@ -534,6 +596,8 @@ def _live_records(
mitre_correct=mitre_correct,
)
)
+
+ asyncio.run(_dispatch_all())
return records, warnings, False
@@ -623,9 +687,22 @@ def _groundedness_block(records: list[WetEvalRecord]) -> dict[str, Any]:
for rec in with_hallucination:
for indicator in rec.hallucinated:
unsupported[indicator] = unsupported.get(indicator, 0) + 1
+ # Incidents the agent could not investigate at all, scored 0 rather than
+ # dropped (#1466): dropping them is survivor bias, and the reader of this
+ # block needs to see *that* a zero was a failure and *why*, or a mean
+ # pulled down by a crash is indistinguishable from a model that grounds
+ # poorly.
+ zero_scored = [r for r in records if r.zero_scored_reason]
+ block_zero: dict[str, Any] = {}
+ if zero_scored:
+ block_zero = {
+ "zero_scored_incidents": len(zero_scored),
+ "zero_scored": [{"incident": r.incident_id, "reason": r.zero_scored_reason} for r in zero_scored],
+ }
return {
"measured": True,
"scored_incidents": len(scored),
+ **block_zero,
# Beside the number, because a reader cannot otherwise tell the
# model's output from the deterministic fallback's.
"llm_calls_placed": sum(r.llm_calls for r in records),
diff --git a/services/agents/tests/eval_data/live_agent_floor.json b/services/agents/tests/eval_data/live_agent_floor.json
index 622ea3b5d..fed9bcd3e 100644
--- a/services/agents/tests/eval_data/live_agent_floor.json
+++ b/services/agents/tests/eval_data/live_agent_floor.json
@@ -1,6 +1,6 @@
{
"axis": "groundedness",
- "metric": "mean fraction of the concrete indicators the agent asserted (IPs, hashes, CVEs, MITRE techniques, domains) that appear in the evidence it was handed, over a deterministic prefix of services/agents/tests/eval_data/synthetic_incidents.json",
+ "metric": "mean fraction of the concrete indicators the agent asserted (IPs, hashes, CVEs, MITRE techniques, domains) that appear in the evidence it was handed, over a deterministic prefix of services/agents/tests/eval_data/synthetic_incidents.json. An incident whose investigation fails outright (raises, or returns status=failed) scores 0 with the reason recorded in the report's groundedness.zero_scored block, so the sample size always equals the dispatched prefix \u2014 dropping failures is survivor bias, and the shrunken sample fails this gate's own size requirement.",
"model": "qwen2.5:0.5b",
"served_by": "Ollama, locally. No hosted provider was involved in any run below and this floor describes none. A hosted model would need its own runs and its own floor.",
"incidents": 10,
@@ -11,36 +11,64 @@
"incidents": 10,
"runs": 7,
"where": "developer machine (Apple silicon, Ollama 0.30.7)",
- "note": "identical to four decimal places across all seven; three were taken after the completion bound landed and returned the same value, so the bound truncates nothing the agents legitimately write"
+ "note": "identical to four decimal places across all seven; three were taken after the completion bound landed and returned the same value, so the bound truncates nothing the agents legitimately write [pre-fix harness: per-incident asyncio.run left langchain-openai's cached async HTTP client on a dead loop, so recon's model call failed on every incident after the first and ran heuristics; failed incidents were dropped from the sample]"
},
{
"mean": 0.5821,
"incidents": 10,
"runs": 1,
"where": "GitHub-hosted ubuntu-latest runner, live-agent-eval.yml run 36508200093",
- "note": "62 LLM calls placed"
+ "note": "62 LLM calls placed [pre-fix harness: per-incident asyncio.run left langchain-openai's cached async HTTP client on a dead loop, so recon's model call failed on every incident after the first and ran heuristics; failed incidents were dropped from the sample]"
},
{
"mean": 0.5329,
"incidents": 10,
"runs": 1,
"where": "GitHub-hosted ubuntu-latest runner, live-agent-eval.yml run 36509668438",
- "note": "62 LLM calls placed; the lowest run observed anywhere"
+ "note": "62 LLM calls placed; the lowest run observed anywhere [pre-fix harness: per-incident asyncio.run left langchain-openai's cached async HTTP client on a dead loop, so recon's model call failed on every incident after the first and ran heuristics; failed incidents were dropped from the sample]"
},
{
"mean": 0.5933,
"incidents": 10,
"runs": 1,
"where": "GitHub-hosted ubuntu-latest runner, live-agent-eval.yml run 36517390566 on main",
- "note": "62 LLM calls placed; the first run of this workflow to complete with the floor asserted, and the highest observed"
+ "note": "62 LLM calls placed; the first run of this workflow to complete with the floor asserted, and the highest observed [pre-fix harness: per-incident asyncio.run left langchain-openai's cached async HTTP client on a dead loop, so recon's model call failed on every incident after the first and ran heuristics; failed incidents were dropped from the sample]"
},
{
"mean": 0.5364,
"incidents": 20,
"runs": 16,
"where": "developer machine, over the 20-incident prefix",
- "note": "not the gated slice - recorded because sixteen identical runs show the measurement is a property of the prefix rather than of the run"
+ "note": "not the gated slice - recorded because sixteen identical runs show the measurement is a property of the prefix rather than of the run [pre-fix harness: per-incident asyncio.run left langchain-openai's cached async HTTP client on a dead loop, so recon's model call failed on every incident after the first and ran heuristics; failed incidents were dropped from the sample]"
+ },
+ {
+ "mean": 0.51,
+ "incidents": 10,
+ "runs": 1,
+ "where": "developer machine (Apple silicon, host Ollama), fixed harness",
+ "note": "74 LLM calls placed (vs 62 pre-fix: recon now consults the model in every incident); 0 zero-scored"
+ },
+ {
+ "mean": 0.445,
+ "incidents": 10,
+ "runs": 1,
+ "where": "developer machine (Apple silicon, containerized Ollama), fixed harness",
+ "note": "78 LLM calls placed; 1 zero-scored (ResponderPlan validation failure \u2014 the same family as the CI drop) participating as 0 in the mean"
+ },
+ {
+ "mean": 0.44,
+ "incidents": 10,
+ "runs": 1,
+ "where": "developer machine (Apple silicon, containerized Ollama), fixed harness",
+ "note": "78 LLM calls placed; 1 zero-scored, same family; the lowest fixed-harness run observed"
+ },
+ {
+ "mean": 0.5234,
+ "incidents": 10,
+ "runs": 2,
+ "where": "GitHub-hosted ubuntu-latest, live-agent-eval.yml runs of Oct 13 and Oct 20 (incl. 39390269883), re-expressed",
+ "note": "both runs reported the identical 0.5815 over 9 incidents after silently dropping one unparseable incident; 0.5815 x 9/10 = 0.5234 is the same measurement under zero-fill semantics, recorded as derived rather than re-run"
}
],
- "derivation": "The four agents decode greedily at temperature 0, and on one machine that makes the measurement a point mass: seven local runs over the 10-incident prefix returned 0.5561 to four decimal places, and sixteen over the 20-incident prefix returned 0.5364. It is not a point mass across machines. Three GitHub-runner runs of the same slice returned 0.5821, 0.5329 and 0.5933 - a spread of 0.0604 - because a quantised model decoding greedily on a different kernel diverges at the margins. The floor is set from that spread rather than from the local stability, which would have been the misleading number to use. 0.40 sits 0.1329 below the lowest run observed anywhere and about 2.2 times the observed cross-runner spread. It still fails anything a quarter worse than today. Raise it only with fresh runs recorded here; a floor above the lowest run it cites is refused by scripts/check_live_agent_floor.py, because that floor would red every run from the day it landed."
+ "derivation": "Two significant figures of history. The original floor was set from the pre-fix harness: seven local runs at 0.5561 and three GitHub-runner runs spread 0.5329-0.5933, with 0.40 chosen 0.1329 below the lowest. Those runs are kept above for provenance but they describe a harness with two defects fixed in the same change as this re-derivation (#1466): per-incident asyncio.run poisoned langchain-openai's cached async HTTP client, so recon ran its deterministic fallback on every incident after the first (llm_calls 62 vs 74-78 now), and an incident whose investigation failed was dropped, inflating the mean and shrinking the sample below what this gate requires. Under the fixed harness (one loop per run, failures scored 0 with reasons recorded) the observed means are 0.51, 0.445 and 0.44 locally and 0.5234 re-expressed from the two identical CI runs that motivated the fix. The floor stays 0.40: it sits below the lowest run cited anywhere (0.44), and the thinner margin is deliberate rather than accidental \u2014 one failed investigation costs the mean about 0.05 under zero-fill, so a run with three or more outright failures dips below the floor and reds the job, which is exactly the signal a reader should get from a model failing a third of its investigations. Raise or move it only with fresh runs recorded here; a floor above the lowest cited run is refused by scripts/check_live_agent_floor.py."
}