mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-25 09:35:49 +08:00
* agents: serving-model attribution from gateway header or response body
Every published verdict-eval row placed 72 model calls and shipped
resolved_models: [] — the runs were served by an OpenAI-compatible endpoint
directly, and the LiteLLM header extractor was the only serving-identity
reader in the tree. The serving identity was in the response body's model
field the whole time.
app/core/model_attribution.py reads it with the one guard that matters:
langchain_openai builds response_metadata['model_name'] with the requested
name as the fallback, so the body value is credited only when it differs
from the request or the response carries its own id (set by langchain only
when the body had one). A requested alias is never copied into serving
metadata.
CallRecord/CostTracker/CostSummary carry the attribution source and the
backend's system_fingerprint beside the resolved model; the replay decision
and the worker's cost payload publish per-source call counts so a grader
can compute an honest run-level provenance status (verified /
self_reported / unattributed / serving_mismatch / no_calls).
Also carried per decision: the alert's severity, for the per-severity miss
breakdown the scorer now reports.
* agents: a measurement cannot authorise a closure it cannot be bound to
evaluate_eligibility gains model_attribution — who vouched that the
evaluated model served this call. A clearing measurement with no
attribution now BLOCKS instead of binding: the gateway may have
re-pointed the alias since the measurement was taken, which is exactly
the drift a measurement-gated closure exists to catch. With no matching
row the state stays UNMEASURED whatever the attribution, so the strict
posture keeps meaning something.
run_auto_triage evaluates eligibility against the serving identity when
one was attributed (falling back to the requested name so the UNMEASURED
default is unchanged), records serving_model/attribution on the
confidence basis and in the ledger exchange, and the positive-control
test now proves a clearing measurement closes only through an attributed
response.
run_verdict_eval publishes provenance_status and
advertisable_as_model_performance on every scorecard, threads
requested_total into the score, and refuses to attribute a live run
whose serving identity mismatches the requested model — the scorecard is
preserved as a diagnostic with the limitation recorded.
check_verdict_quality renders an Attribution column: historical rows read
'unverified (recorded before per-decision attribution existed)' rather
than receiving invented attribution, and a serving_mismatch row is
refused outright.
* fusion: a missing identifier narrows the correlation group instead of widening it
Neither detection engine has ever set mitre_tactics — the ruleset carries
technique ids only — so every detection alert's correlation key fell back
to {tenant}:{entity}:unknown and all of an entity's detection alerts,
whatever the rule or kill-chain stage, collapsed into one incident per
window, titled after whichever arrived first. Alerts with no entity merged
tenant-wide under {tenant}:unknown:unknown. Both collapses bury exactly
the alert an analyst needed rendered.
correlation_key() now narrows on missing evidence: entity+tactic is
unchanged; entity with no tactic scopes to the detection rule (the same
rule repeating is the storm correlation exists for; different rules on one
entity are not known to be one incident); no entity never groups across
rules; no identifiers at all groups only exact repeats of one shape via
the dedup fingerprint. The cost is stated where it is paid: one event
firing N tactic-less rules fragments into N incidents rather than burying
N-1 of them — the recoverable direction.
Measured on a fixed detection-shaped cohort (1000 alerts, rule_id set, no
tactics, ~4% entity-less), real correlation_key() both sides: before 574
incidents / 42.6% reduction with 36 incident-groups spanning more than one
rule and every no-entity alert merged tenant-wide; after 755 incidents /
24.5% reduction with zero cross-rule groups. The reduction went DOWN and
that is the honest direction — the difference was unrelated alerts being
counted as grouped. The tactic-carrying headline cohort is untouched at
33.3% and its gate passes unchanged.
The Correlator's creation race is closed with SET NX: the previous plain
SET let two concurrent first-arrivals both win, the last writer owning the
index while the first writer's incident — carrying a real alert — became
an unreachable orphan. The loser now merges into the winner. The narrower
merge/merge read-modify-write window is documented, not closed; closing it
takes an owner-checked script like the windowed engine's.
tests/integration/test_correlator_live.py proves window expiry, tenant
boundaries, restart continuity, per-rule fallback grouping and creator
convergence against a real Redis (negative control: reverting to the plain
SET fails the convergence test). integration.yml gains a fusion-redis-live
job keyed on the existing spine filter, which also gives the previously
unwired windowed-claim live suite a workflow that actually runs it — with
an all-skipped run refused rather than green.
* agents+api: the reflex path reports its stages; retro-hunt gains a rehearsal mode
Reflex observability (services/agents): FusedAlertTriageWorker.triage now
measures named stages — business context, memory suppression, context
fetch, decide, verification, persist, escalate, approvals, writeback —
plus the queue delay read off the envelope's fused_at (None when the
envelope carries none; a replayed historical finding legitimately has no
delay and inventing one would put a plausible number on a measurement
nobody took). Timings land on the summary, the completion log line joined
by run id, and every replay decision, so an eval can split 'slow' into
the queue, the context fetch, the model and the persistence.
The summary also carries a structured decision contract assembled from
signals that already ran — verdict, operational disposition, supporting
and contradictory decisive claims (the claim-support review now travels
on the state as structure, not only as basis strings), groundedness,
missing prerequisites, the blocking or demoting gates, and the escalation
reason. A signal that never ran reports None, never an empty list
pretending the check happened.
Retro-hunt rehearsal (services/api): sweep_tenant gains dry_run, withheld
at the mutation boundary that owns the writes — the warehouse sweep runs
exactly as live (and still consumes the sweep budget, because the scan
the budget bounds was performed), but matches come back as recorded
proposals: no alert opens, no sighting row lands, and the dedup branch
leaves even its counters untouched, so an evaluation re-running history
cannot advance production records. RETRO_HUNT_DRY_RUN selects the mode;
the guard is not the flag. The negative control proves the same sweep
without dry_run still adds the alert and the sighting row.
run_verdict_eval scorecards now carry the model-knowledge disclosure:
evidence cutoffs constrain supplied context only, and the weights'
training cutoff is recorded when the operator states it and 'unknown'
otherwise — never an implied 'before the events'.
* scripts: the model matrix grades the verdict task and records its runtime
run_model_matrix gains --task verdict, wrapping run_verdict_eval per model
exactly as the wet task wraps run_evals — a thin collator defining no
scoring of its own. A verdict row carries its configuration (pins, endpoint,
prompt provenance, corpus digest, the provenance_status the scorecard
earned and the serving models behind it) so two rows can be compared
knowing they were configured alike, and a run the eval refused — a serving
mismatch — comes back as that row's error with the scorecard kept as
evidence, never as numbers under the requested model's name.
The payload records the runtime in comparable-but-unidentifying terms (OS
family, arch, interpreter, core count — no hostname, no paths) and the
constant-answer baselines a verdict table is read against. An endpoint
with no hosted key is a first-class subject for the verdict task, because
a locally served model is exactly what the corpus was built to grade.
* docs+tests: the benchmark page carries the attribution mechanism and the third reduction figure
The 'attribution is unverified' paragraph now says what changed: the five
historical rows keep their honest unverified rather than receiving
invented attribution, and every run after them carries a provenance_status
the Attribution column renders. The alert-reduction section names all
three figures with their cohorts — the tactic-carrying 33.3%, the
detection-shaped 24.5% with its before/after and zero cross-rule groups,
and the retained legacy 75.3% — and says why the honest direction for the
second was down.
Replay reproducibility comparators exclude the new wall-clock fields
(stage_timings_ms, queue_delay_ms) exactly as they exclude latency_ms:
all three measure the host, not the input, and two identical runs on one
machine legitimately differ on them.
* agents+docs: deterministic baseline published; annotated claim-support measurement; changelog
The committed verdict scorecard gains the deterministic-fallback row — the
rules baseline every measured model is read against, and it lands exactly
on the 0.250 constant-answer floor with zero of 36 malicious cases caught.
Published through the same gate and rendered with 'no calls' attribution.
tests/test_claim_support_measured.py is the first unsupported-claim-rate
measurement in the tree: sixteen hand-annotated cases, the confusion
matrix pinned exactly in both directions (TP 7, FP 0, FN 1, TN 8), a
recorded known miss (verbal authority that avoids the approval
vocabulary) that must stay missed until the pins move with it, and the
annotation-independence limit stated beside the number — the annotator
authored the cases and had read the detector, so this is regression-grade,
not an audit.
The measurement immediately found a production defect and the fix is the
smaller half of this commit: the MAINTENANCE claim pattern recognises
'scheduled (scan|job|task|reboot)' while the support keys covered only two
of the four nouns, so an alert whose evidence recorded scheduled_scan
could state the claim the pattern knows and still be refused support —
flagging exactly the analyst language the detector cannot afford to flag.
Negative control: reverting the two keys fails the pinned matrix.
CHANGELOG carries the whole wave under [Unreleased].
* chore: close out the feedback-eval progress tracker
* scripts: verdict scorecards record the sampling the production call pins
The full audit legs confirmed sampling settings were recorded nowhere on
the verdict path while the reliability harness already carries the
production-pinned constants. Scorecards now carry a sampling block
(temperature, max_tokens, json_mode) imported from that harness, so the
call site, the harness and the scorecard share one declaration and drift
together loudly; the verdict matrix threads it into each row's
configuration. Two scorecards sampled differently are not comparable, and
until now nothing a reader could open said how a row was sampled.
The progress tracker gains the residual-gap addendum from the completed
audit legs: ModelRouter/cost_aware_cascade and sources_from_ledger exist
unwired, evidence_completeness has no corpus referent, retro-hunt records
no intelligence-version identifier, replay proxies occurrence time via
closed_at, and policy rows carry no revision id — recorded, not fixed.
* matrix+ci: five GATED rows for the feedback-hardening gates; one migration_paths assignment
The claim matrix gains rows for serving-model attribution provenance, the
replay scorer's full-cohort and closure accounting, the conservative
correlation fallback with its live-Redis proof, the retro-hunt rehearsal
mode, and the annotated unsupported-claim measurement — each naming the
exact tests and jobs that fail when the claim stops being true, with the
tallies recomputed where they are published (Summary stanza, ROADMAP,
evidence pack): 334 rows — 329 GATED / 5 PARTIAL / 0 NO GATE.
integration.yml's area filter had grown three parallel migration_paths
assignments — three lanes each appended theirs as a fresh line, and in
shell the last silently wins — so the asset-context live leg and the
business-context rail legs were inert in the filter: their live tests ran
only when something else in the surviving list changed. One union
assignment now, with the comment telling the next lane to extend rather
than re-assign.
* ci: fix the four first-cycle check failures
The vendored benchmark copy under services/api/app/_vendor is re-synced
byte-identically after the scorer gained its cohort metrics — the package
was edited and its mirror was not, which is exactly what the drift gate
exists to catch. ADVERTISABLE_STATUSES joins model_attribution's __all__
(it is the module's public contract and run_verdict_eval imports it;
CodeQL correctly read its absence as an unused global). The fusion-redis-
live job pins cryptography to the contract range the dependency-pin gate
holds every install path to, and the progress tracker stops naming a
machine-local absolute path — a worktree path exists on one computer and
the machine-path gate is right to refuse it.
* matrix: re-sync with main's Agentmetry row; drop the stale duplicate injection row
Main gained the Agentmetry ingest-template row while this branch added
five, so the shared base of 329 became 330 and the combined table is 334
after one correction: 'Prompt-injection resistance' appeared twice, a
duplication already present on main, and the two variants had drifted
into contradiction — one says no payload is xfail at present, the stale
one still said two payloads are currently xfail. The richer, current
variant is kept; the stale one is dropped rather than left to tell a
reader something false. Tallies recomputed in the Summary stanza, ROADMAP
and the evidence pack: 334 rows — 329 GATED / 5 PARTIAL / 0 NO GATE.
* ci: the fusion live job installs the service's committed lock into its own venv
The install-parity gate is right on both counts it raised. A job that runs
the whole services/fusion suite must install fusion's poetry.lock rather
than a hand-picked closure — the tiny closure re-resolved inside the
declared ranges, so the versions CI graded need not be the versions the
image installs, and its missing clickhouse-driver silently graded the
lake writer's except-ImportError fallback where production grades the
real path. And the lock belongs in the interpreter the tests actually
run under, so the job now mirrors ci.yml's convention exactly: the lock
into $RUNNER_TEMP/.venv-fusion, the suite from its bin/python.
435 lines
18 KiB
Python
435 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade the same corpus across several models and publish the comparison.
|
|
|
|
Phase 4's last open item. The wet eval runs one model — whichever the pins
|
|
resolve to — so the published numbers describe the agent *on that model*
|
|
and say nothing about whether the result is a property of the agent or of
|
|
the backend. Those are different claims, and only one of them is about
|
|
this project.
|
|
|
|
A matrix answers it: same corpus, same prompts, same grader, one variable.
|
|
If accuracy collapses on a cheaper model, that is a fact a reader deciding
|
|
what to self-host needs, and it is a fact no single-model run can produce.
|
|
|
|
Deliberately a wrapper, not a second evaluator. It sets the model pin and
|
|
invokes `scripts/run_evals.py --wet` per model, then collates the blocks
|
|
that script already emits. Reimplementing the eval would create a second
|
|
definition of "accuracy" that could drift from the one on the scoreboard —
|
|
the exact defect the alert-reduction suite had, where an in-test
|
|
reimplementation published a number the product did not produce.
|
|
|
|
Without a funded key it reports **not measured** and exits zero. It does
|
|
not emit zeros: a zero is a measurement, and "we did not run this" is not.
|
|
|
|
Run: python3 scripts/run_model_matrix.py --models gpt-4o-mini,gpt-4o
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import platform
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
RUN_EVALS = REPO_ROOT / "scripts" / "run_evals.py"
|
|
RUN_VERDICT_EVAL = REPO_ROOT / "scripts" / "run_verdict_eval.py"
|
|
|
|
#: Roles the pin override has to cover. Setting only one leaves the other
|
|
#: agents on their default model, which would make the matrix a comparison
|
|
#: of one role rather than of the system.
|
|
PIN_ROLES = ("triage", "investigation", "report", "recon")
|
|
|
|
|
|
def runtime_record() -> dict[str, Any]:
|
|
"""The host this matrix ran on, in terms two runs can be compared by.
|
|
|
|
Generic by design: OS family, architecture, interpreter and core count
|
|
say whether two matrices ran on comparable machines, and none of them
|
|
identifies the machine. No hostname, no paths — a matrix artifact is a
|
|
publishable file and must not carry anything that only describes one
|
|
contributor's laptop. Latency differences between hosts are disclosed,
|
|
never attributed to the models (same rule as the scorecards).
|
|
"""
|
|
return {
|
|
"os": platform.system(),
|
|
"arch": platform.machine(),
|
|
"python": platform.python_version(),
|
|
"cpu_count": os.cpu_count(),
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class ModelResult:
|
|
model: str
|
|
measured: bool
|
|
#: Populated only when measured. Absent rather than zeroed, because a
|
|
#: zero accuracy and an unrun model must not render the same.
|
|
metrics: dict[str, Any] = field(default_factory=dict)
|
|
#: What was actually configured for this row: the pins applied, the
|
|
#: endpoint, and — for verdict runs — the provenance status the scorecard
|
|
#: earned. A row without its configuration cannot be reproduced, and two
|
|
#: rows cannot be compared without knowing they were configured alike.
|
|
configuration: dict[str, Any] = field(default_factory=dict)
|
|
error: str | None = None
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
out: dict[str, Any] = {"model": self.model, "measured": self.measured}
|
|
if self.measured:
|
|
out["metrics"] = self.metrics
|
|
if self.configuration:
|
|
out["configuration"] = self.configuration
|
|
if self.error:
|
|
out["error"] = self.error
|
|
return out
|
|
|
|
|
|
def has_live_key() -> bool:
|
|
return bool((os.getenv("WET_EVAL_OPENAI_KEY") or os.getenv("OPENAI_API_KEY") or "").strip())
|
|
|
|
|
|
def run_one(model: str, *, limit: int | None, timeout: int) -> ModelResult:
|
|
"""Run the existing wet eval with every model pin set to `model`."""
|
|
env = dict(os.environ)
|
|
for role in PIN_ROLES:
|
|
env[f"AISOC_MODEL_PIN_{role.upper()}"] = model
|
|
# The agent's resolver reads OPENAI_API_KEY; the workflow supplies the
|
|
# key under the wet-eval name.
|
|
if env.get("WET_EVAL_OPENAI_KEY") and not env.get("OPENAI_API_KEY"):
|
|
env["OPENAI_API_KEY"] = env["WET_EVAL_OPENAI_KEY"]
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
wet_out = Path(tmp) / "wet.json"
|
|
cmd = [
|
|
sys.executable,
|
|
str(RUN_EVALS),
|
|
"--wet",
|
|
"--out",
|
|
str(Path(tmp) / "report.json"),
|
|
"--wet-out",
|
|
str(wet_out),
|
|
]
|
|
if limit:
|
|
cmd += ["--limit", str(limit)]
|
|
|
|
try:
|
|
completed = subprocess.run(
|
|
cmd,
|
|
env=env,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=timeout,
|
|
cwd=REPO_ROOT,
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return ModelResult(
|
|
model,
|
|
measured=False,
|
|
error=f"timed out after {timeout}s",
|
|
)
|
|
|
|
if completed.returncode != 0:
|
|
# The model's own failure is a result about that model, not a
|
|
# reason to abandon the matrix — a model that cannot complete
|
|
# the corpus is exactly what a reader wants to know.
|
|
tail = (completed.stderr or completed.stdout or "").strip().splitlines()
|
|
return ModelResult(
|
|
model,
|
|
measured=False,
|
|
error=tail[-1][:300] if tail else f"exit {completed.returncode}",
|
|
)
|
|
|
|
if not wet_out.exists():
|
|
return ModelResult(model, measured=False, error="no wet block produced")
|
|
|
|
block = json.loads(wet_out.read_text(encoding="utf-8"))
|
|
|
|
return ModelResult(model, measured=True, metrics=_project(block))
|
|
|
|
|
|
def _project(block: dict[str, Any]) -> dict[str, Any]:
|
|
"""The comparable subset. A full wet block is large and most of it is
|
|
identical across models; the point of the matrix is the part that is
|
|
not."""
|
|
latency = block.get("latency_seconds") or {}
|
|
tokens = (block.get("tokens") or {}).get("total") or {}
|
|
usd = block.get("usd") or {}
|
|
return {
|
|
"incidents": block.get("incidents"),
|
|
"mitre_accuracy": block.get("mitre_accuracy"),
|
|
"abstention_rate": block.get("abstention_rate"),
|
|
"mean_groundedness": block.get("mean_groundedness"),
|
|
"latency_p95_s": latency.get("p95"),
|
|
"tokens_mean": tokens.get("mean"),
|
|
"usd_total": usd.get("total"),
|
|
"usd_per_incident": usd.get("mean"),
|
|
}
|
|
|
|
|
|
def run_one_verdict(model: str, *, api_base: str, timeout: int) -> ModelResult:
|
|
"""Grade the verdict corpus on `model` through `run_verdict_eval.py`.
|
|
|
|
The same thin-wrapper rule as the wet task: this collates a scorecard the
|
|
verdict eval produced and computes nothing of its own. The scorecard's
|
|
own refusals apply unchanged — a run that placed no model call, or whose
|
|
serving identity mismatches the requested model, comes back as that
|
|
row's error rather than as numbers.
|
|
"""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
card_path = Path(tmp) / "scorecard.json"
|
|
cmd = [
|
|
sys.executable,
|
|
str(RUN_VERDICT_EVAL),
|
|
"--model",
|
|
model,
|
|
"--api-base",
|
|
api_base,
|
|
"--out",
|
|
str(card_path),
|
|
]
|
|
try:
|
|
completed = subprocess.run(
|
|
cmd,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=timeout,
|
|
cwd=REPO_ROOT,
|
|
env={**os.environ, "PYTHONPATH": str(REPO_ROOT / "services" / "agents")},
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return ModelResult(model, measured=False, error=f"timed out after {timeout}s")
|
|
|
|
if not card_path.exists():
|
|
tail = (completed.stderr or completed.stdout or "").strip().splitlines()
|
|
return ModelResult(model, measured=False, error=tail[-1][:300] if tail else f"exit {completed.returncode}")
|
|
|
|
card = json.loads(card_path.read_text(encoding="utf-8"))
|
|
|
|
configuration = {
|
|
"requested_model": model,
|
|
"api_base": api_base,
|
|
"pins": [f"AISOC_MODEL_PIN_{role.upper()}" for role in ("triage", "investigation", "report", "recon", "summary", "copilot")],
|
|
"prompt": card.get("prompt"),
|
|
"sampling": card.get("sampling"),
|
|
"corpus_digest": card.get("corpus_digest"),
|
|
"provenance_status": card.get("provenance_status"),
|
|
"resolved_models": card.get("resolved_models"),
|
|
"model_knowledge": card.get("model_knowledge"),
|
|
}
|
|
|
|
if completed.returncode != 0:
|
|
# The scorecard exists and the eval still refused the run — a
|
|
# serving mismatch, most likely. The card is kept as the row's
|
|
# configuration evidence; the row is not published as measured.
|
|
return ModelResult(
|
|
model,
|
|
measured=False,
|
|
configuration=configuration,
|
|
error=f"refused by run_verdict_eval (provenance: {card.get('provenance_status')})",
|
|
)
|
|
|
|
return ModelResult(
|
|
model,
|
|
measured=True,
|
|
configuration=configuration,
|
|
metrics={
|
|
"balanced_accuracy": card.get("balanced_accuracy"),
|
|
"matthews_corrcoef": card.get("matthews_corrcoef"),
|
|
"malicious_recall": card.get("malicious_recall"),
|
|
"malicious_support": card.get("malicious_support"),
|
|
"abstention_rate": card.get("abstention_rate"),
|
|
"hallucination_rate": card.get("hallucination_rate"),
|
|
"auto_close_precision": card.get("auto_close_precision"),
|
|
"auto_close_considered": card.get("auto_close_considered"),
|
|
"majority_class_accuracy": card.get("majority_class_accuracy"),
|
|
"llm_calls_placed": card.get("llm_calls_placed"),
|
|
"time_to_verdict_p95_ms": card.get("time_to_verdict_p95_ms"),
|
|
"total_tokens": card.get("total_tokens"),
|
|
},
|
|
)
|
|
|
|
|
|
def render_verdict_markdown(results: list[ModelResult]) -> str:
|
|
lines = [
|
|
"| Model | Balanced accuracy | MCC | Malicious recall | Abstention | Auto-close precision | Calls | Attribution |",
|
|
"|-------|-------------------|-----|------------------|------------|----------------------|-------|-------------|",
|
|
]
|
|
for result in results:
|
|
if not result.measured:
|
|
reason = result.error or "not measured"
|
|
lines.append(f"| `{result.model}` | _not measured — {reason}_ |||||||")
|
|
continue
|
|
m = result.metrics
|
|
|
|
def fmt(key: str, spec: str = "{:.3f}", metrics: dict = m) -> str:
|
|
value = metrics.get(key)
|
|
return spec.format(value) if isinstance(value, int | float) else "not measured"
|
|
|
|
recall = (
|
|
f"{fmt('malicious_recall')} / {m.get('malicious_support', '?')}" if m.get("malicious_recall") is not None else "not measured"
|
|
)
|
|
close = (
|
|
f"{fmt('auto_close_precision')} over {m.get('auto_close_considered', 0)}"
|
|
if m.get("auto_close_precision") is not None
|
|
else "not measured"
|
|
)
|
|
lines.append(
|
|
f"| `{result.model}` | {fmt('balanced_accuracy')} | {fmt('matthews_corrcoef')} | {recall} "
|
|
f"| {fmt('abstention_rate', '{:.1%}')} | {close} | {m.get('llm_calls_placed', 0)} "
|
|
f"| {result.configuration.get('provenance_status') or 'unattributed'} |"
|
|
)
|
|
lines.append("")
|
|
lines.append(
|
|
"_Baselines: a constant answer scores at most 0.250 balanced accuracy on this four-class corpus; "
|
|
"compare plain accuracy against each row's majority_class_accuracy in the JSON._"
|
|
)
|
|
return "\n".join(lines)
|
|
|
|
|
|
def render_markdown(results: list[ModelResult]) -> str:
|
|
lines = [
|
|
"| Model | Incidents | MITRE accuracy | Abstention | Groundedness | p95 latency | Tokens/inv | $/incident |",
|
|
"|-------|-----------|----------------|------------|--------------|-------------|------------|------------|",
|
|
]
|
|
for result in results:
|
|
if not result.measured:
|
|
# One cell, spanning the intent: this row was not measured.
|
|
# Filling the columns with dashes reads as zero at a glance.
|
|
reason = result.error or "no live key configured"
|
|
lines.append(f"| `{result.model}` | _not measured — {reason}_ |||||||")
|
|
continue
|
|
m = result.metrics
|
|
|
|
# `m` is bound as a default rather than captured: the closure is
|
|
# used inside this iteration, so capturing works today and breaks
|
|
# the moment anyone defers the call.
|
|
def fmt(key: str, spec: str = "{:.3f}", metrics: dict = m) -> str:
|
|
value = metrics.get(key)
|
|
return spec.format(value) if isinstance(value, int | float) else "—"
|
|
|
|
lines.append(
|
|
f"| `{result.model}` | {m.get('incidents') or '—'} "
|
|
f"| {fmt('mitre_accuracy', '{:.1%}')} "
|
|
f"| {fmt('abstention_rate', '{:.1%}')} "
|
|
f"| {fmt('mean_groundedness')} "
|
|
f"| {fmt('latency_p95_s', '{:.2f}s')} "
|
|
f"| {fmt('tokens_mean', '{:.0f}')} "
|
|
f"| {fmt('usd_per_incident', '${:.4f}')} |"
|
|
)
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument(
|
|
"--models",
|
|
default=os.getenv("AISOC_MATRIX_MODELS", "gpt-4o-mini,gpt-4o"),
|
|
help="Comma-separated model names to grade.",
|
|
)
|
|
parser.add_argument(
|
|
"--task",
|
|
choices=("wet", "verdict"),
|
|
default="wet",
|
|
help=(
|
|
"which evaluation each model is graded on: 'wet' drives the 200-incident wet eval "
|
|
"(scripts/run_evals.py --wet); 'verdict' drives the balanced verdict corpus "
|
|
"(scripts/run_verdict_eval.py), one task per run because a model qualified on one task "
|
|
"is not qualified on every task."
|
|
),
|
|
)
|
|
parser.add_argument(
|
|
"--api-base",
|
|
default=os.getenv("OPENAI_BASE_URL") or "",
|
|
help="OpenAI-compatible base URL for --task verdict (a local server works; any non-empty key).",
|
|
)
|
|
parser.add_argument("--out", type=Path, help="Write the JSON result here.")
|
|
parser.add_argument("--markdown-out", type=Path, help="Write the table here.")
|
|
parser.add_argument(
|
|
"--limit",
|
|
type=int,
|
|
help="Grade only the first N incidents. For a smoke run; a limited matrix must not be published as a full one.",
|
|
)
|
|
parser.add_argument("--timeout", type=int, default=3600)
|
|
args = parser.parse_args(argv)
|
|
|
|
models = [m.strip() for m in args.models.split(",") if m.strip()]
|
|
if not models:
|
|
print("model-matrix: no models requested", file=sys.stderr)
|
|
return 2
|
|
|
|
if args.task == "verdict":
|
|
# The verdict task needs an endpoint, not a hosted key: a locally
|
|
# served model is a first-class subject here, and the per-run
|
|
# scorecard carries the attribution that says who really answered.
|
|
live = bool(args.api_base) or has_live_key()
|
|
reason = "no --api-base and no live key configured"
|
|
else:
|
|
live = has_live_key()
|
|
reason = "no live key configured"
|
|
if not live:
|
|
print(f"model-matrix: {reason} — reporting 'not measured' for every model rather than emitting zeros.")
|
|
|
|
if args.task == "verdict":
|
|
results = [
|
|
run_one_verdict(model, api_base=args.api_base, timeout=args.timeout)
|
|
if live
|
|
else ModelResult(model, measured=False, error=reason)
|
|
for model in models
|
|
]
|
|
else:
|
|
results = [
|
|
run_one(model, limit=args.limit, timeout=args.timeout) if live else ModelResult(model, measured=False, error=reason)
|
|
for model in models
|
|
]
|
|
|
|
payload = {
|
|
"task": args.task,
|
|
"corpus": "verdict_corpus_v1.json" if args.task == "verdict" else "synthetic_incidents.json",
|
|
"limit": args.limit,
|
|
"partial": bool(args.limit),
|
|
"live": live,
|
|
# The host, in comparable-but-unidentifying terms, and the baselines a
|
|
# verdict table is read against: with four classes a constant answer
|
|
# scores 0.250 balanced accuracy, and each measured scorecard carries
|
|
# its own majority_class_accuracy. Neither is a model result and
|
|
# neither may be omitted from a published comparison.
|
|
"runtime": runtime_record(),
|
|
"baselines_note": (
|
|
"Verdict task: a constant answer scores at most 0.250 balanced accuracy on the four-class "
|
|
"corpus; majority_class_accuracy per row is what a reader compares plain accuracy against."
|
|
if args.task == "verdict"
|
|
else None
|
|
),
|
|
"results": [r.to_dict() for r in results],
|
|
}
|
|
|
|
if args.out:
|
|
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
args.out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
table = render_verdict_markdown(results) if args.task == "verdict" else render_markdown(results)
|
|
if args.markdown_out:
|
|
args.markdown_out.parent.mkdir(parents=True, exist_ok=True)
|
|
args.markdown_out.write_text(table + "\n", encoding="utf-8")
|
|
|
|
print()
|
|
print(table)
|
|
print()
|
|
measured = sum(1 for r in results if r.measured)
|
|
print(f"model-matrix: {measured}/{len(results)} model(s) measured")
|
|
if args.limit:
|
|
print(f" PARTIAL: limited to {args.limit} incidents — not comparable with a full run and must not be published as one.")
|
|
# Exit zero even with nothing measured: an absent key is a
|
|
# configuration state, not a build failure, and failing here would
|
|
# make every fork's CI red.
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|