Coverage for app / services / evaluation / assurance.py: 88%
152 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Evaluation as governance evidence.
4Evaluation sits under Governance because its results are what show a model or
5agent is fit for purpose. A score is only evidence about something if you can
6say *which version* of it was scored, and a regression is only governance if
7a person has to decide about it. This module supplies both:
9* :func:`target_versions` — which revision of each agent a run evaluated,
10 stamped on the batch when it starts (``ExperimentBatch.target_versions``).
11* :func:`open_regression_review` — a regressed run opens an item in the same
12 review queue an audit rule's flag lands in (``ReviewFlag.kind``).
13* :func:`fleet_assurance` — for every agent, whether the version in force has
14 evidence behind it: evaluated and passing, evaluated and below a dataset's
15 pass mark, only an older version evaluated, never evaluated, or regressed
16 on its latest run. It reads through :mod:`.evidence`, as the evidence gate
17 does, so the page and the gate cannot disagree.
18"""
20from __future__ import annotations
22import logging
23from typing import Any, Iterable, Optional
24from uuid import UUID
26from sqlalchemy import and_
27from sqlalchemy.orm import Session
29from app.db.postgres.enums import HistoryEnum, ReviewEnum
30from app.db.postgres.models import (
31 Agent,
32 Experiment,
33 ExperimentBatch,
34 ReviewFlag,
35)
36from app.services import history as history_service
37from app.services.evaluation import batches as batch_store
38from app.services.evaluation import evidence as evidence_service
39from app.services.evaluation import risk as risk_service
40from app.services.evaluation.evidence import RunEvidence
41from app.util.time import aware_utcnow
43logger = logging.getLogger(__name__)
46# ---------------------------------------------------------------------------
47# Which version a run evaluated
48# ---------------------------------------------------------------------------
51def target_versions(db: Session, variants: Iterable[Any]) -> dict[str, dict]:
52 """``{variant_id: {"agent_id", "agent_version", "as_configured"}}`` for
53 every agent variant.
55 Read when the run starts, so the stamp is the revision the run executed
56 even if the agent is edited while it is still going — and whether the
57 variant ran that revision *as configured* or an alternative of it (another
58 model, a candidate prompt …), which only the former is evidence about
59 (see :mod:`.evidence`). A model variant has no entry: models are svc-ai's
60 records and carry no version history.
61 """
62 variants = list(variants)
63 agents = {str(v.id): evidence_service.agent_of(v) for v in variants}
64 ids = sorted({a for a in agents.values() if a})
65 if not ids:
66 return {}
67 versions = history_service.current_versions(
68 db, HistoryEnum.ResourceType.agent, [UUID(a) for a in ids]
69 )
70 prompts = {
71 str(agent.id): agent.system_prompt
72 for agent in db.query(Agent).filter(Agent.id.in_([UUID(a) for a in ids]))
73 }
74 return {
75 str(variant.id): {
76 "agent_id": agents[str(variant.id)],
77 "agent_version": versions.get(agents[str(variant.id)]),
78 "as_configured": evidence_service.runs_as_configured(
79 variant, prompts.get(agents[str(variant.id)])
80 ),
81 }
82 for variant in variants
83 if agents[str(variant.id)]
84 }
87# ---------------------------------------------------------------------------
88# A regression is a decision for a person
89# ---------------------------------------------------------------------------
92def _describe_regression(experiment: Experiment, batch: ExperimentBatch) -> str:
93 headline = batch.regression or {}
94 parts = [f"“{experiment.name}” regressed against its last comparable run"]
95 metrics = headline.get("regressed_metrics") or []
96 if metrics:
97 parts.append("on " + ", ".join(str(m).replace("_", " ") for m in metrics))
98 broke = headline.get("broke") or 0
99 if broke:
100 parts.append(f"{broke} case{'s' if broke != 1 else ''} that passed now fail")
101 reasons = [str(r) for r in (headline.get("reasons") or [])[:3]]
102 text = "; ".join(parts) + "."
103 if reasons:
104 text += " " + " ".join(reasons)
105 return text[:2000]
108def open_regression_review(
109 db: Session, batch: ExperimentBatch, experiment: Experiment
110) -> Optional[ReviewFlag]:
111 """Put a regressed run in the review queue. Does not commit; never raises.
113 Only a ``regressed`` verdict opens one — ``improved``, ``unchanged`` and
114 the verdicts that could not compare need nobody's judgement. One item per
115 run, however often this is called. An experiment owned by an organisation
116 or project is queued for that organisation or project, whose admins
117 review it. A built-in experiment (the platform benchmark) opens none: it
118 belongs to nobody, so its flag would sit in nobody's queue — its verdict
119 is shown on the benchmark itself.
120 """
121 try:
122 if batch.regression_verdict != "regressed":
123 return None
124 if getattr(experiment, "is_system", False) is True:
125 return None
126 existing = (
127 db.query(ReviewFlag)
128 .filter(
129 ReviewFlag.kind == ReviewEnum.Kind.regression.value,
130 ReviewFlag.batch_id == batch.id,
131 )
132 .first()
133 )
134 if existing is not None:
135 return existing
136 agents = {
137 v.get("agent_id")
138 for v in (batch.target_versions or {}).values()
139 if isinstance(v, dict) and v.get("agent_id")
140 }
141 flag = ReviewFlag(
142 owner_user_id=experiment.owner_user_id,
143 owner_organisation_id=experiment.owner_organisation_id,
144 owner_project_id=experiment.owner_project_id,
145 kind=ReviewEnum.Kind.regression.value,
146 execution_type="evaluation",
147 experiment_id=experiment.id,
148 batch_id=batch.id,
149 # Named only when the run evaluated exactly one agent: a
150 # comparison of three agents regressed as a whole, not one of them.
151 agent_id=UUID(next(iter(agents))) if len(agents) == 1 else None,
152 excerpt=_describe_regression(experiment, batch),
153 status=ReviewEnum.Status.pending,
154 created_at=aware_utcnow(),
155 )
156 db.add(flag)
157 return flag
158 except Exception:
159 logger.exception("Could not queue regressed run %s for review", batch.id)
160 return None
163# ---------------------------------------------------------------------------
164# The fleet's evidence
165# ---------------------------------------------------------------------------
167#: Worst first — the order the assurance view sorts by.
168STATUSES = (
169 "regressed",
170 "failing",
171 "never",
172 "unscored",
173 "outdated",
174 "unrecorded",
175 "current",
176)
179def fleet_assurance(db: Session, *, agent_filter, experiment_filter) -> dict[str, Any]:
180 """Every agent in scope, and the evidence behind the version in force.
182 ``status`` per agent:
184 ``current`` the version in force was evaluated, and its newest scored
185 run on every dataset reaches that dataset's pass mark
186 ``failing`` the version in force was evaluated, and falls below the
187 pass mark on at least one dataset
188 ``unscored`` the version in force was evaluated, but no run of it has
189 been scored yet (manual grading)
190 ``outdated`` runs evaluated an older version; the agent changed since
191 ``unrecorded`` runs evaluated it before versions were recorded
192 ``never`` no completed run has evaluated it as configured
193 ``regressed`` its latest run regressed — whatever else is true
195 Only completed runs of the agent *as configured* count (see
196 :mod:`.evidence`).
197 """
198 agents = (
199 db.query(Agent)
200 .filter(agent_filter, Agent.is_system.isnot(True))
201 .order_by(Agent.name.asc())
202 .all()
203 )
204 ids = [a.id for a in agents]
205 current = (
206 history_service.current_versions(db, HistoryEnum.ResourceType.agent, ids)
207 if ids
208 else {}
209 )
210 # Each agent's evidence comes from its owner's evaluations, exactly as the
211 # gate reads it (``evidence.evidence_owner``): an organisation's agent is
212 # judged on the organisation's runs, a personal one on its owner's. One
213 # read per owner rather than one for the whole page, so a personal run of
214 # an organisation's agent cannot make it look passing here while the gate
215 # refuses it. ``experiment_filter`` still narrows what is read.
216 evidence: dict[str, list] = {}
217 groups: dict[tuple[str, str], list[str]] = {}
218 for agent in agents:
219 groups.setdefault(evidence_service.evidence_owner(agent), []).append(
220 str(agent.id)
221 )
222 for owner, agent_ids in groups.items():
223 read = evidence_service.read_evidence(
224 db, and_(experiment_filter, evidence_service.evidence_filter(owner))
225 )
226 for agent_id in agent_ids:
227 if agent_id in read:
228 evidence[agent_id] = read[agent_id]
229 result = assess(agents, current, evidence)
230 attach_quality(db, result["agents"])
231 return result
234def attach_quality(db: Session, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
235 """Each agent's expected quality and risk (``risk.profile``) over the
236 datasets its status was read from, reading their answers in one query —
237 and what an answer cost it there (:func:`with_cost`)."""
238 batch_ids = [d["batch_id"] for row in rows for d in row.get("datasets") or []]
239 with_quality(rows, risk_service.answer_scores(db, batch_ids))
240 return with_cost(rows, _leaderboards(db, batch_ids))
243def _leaderboards(db: Session, batch_ids: list[Any]) -> dict[str, Any]:
244 ids: list[UUID] = []
245 for value in dict.fromkeys(str(b) for b in batch_ids if b):
246 try:
247 ids.append(UUID(value))
248 except ValueError:
249 continue
250 if not ids:
251 return {}
252 return {
253 str(batch_id): board
254 for batch_id, board in db.query(ExperimentBatch.id, ExperimentBatch.leaderboard)
255 .filter(ExperimentBatch.id.in_(ids))
256 .all()
257 }
260def with_cost(
261 rows: list[dict[str, Any]], boards: dict[str, Any]
262) -> list[dict[str, Any]]:
263 """``cost_per_answer_usd`` on each dataset — what one of the agent's
264 answers cost in the run its status was read from, grading left out — and
265 on the row, their mean with each dataset weighted equally, as its quality
266 is. None on the row unless every dataset has one: a mean over the priced
267 ones would read as the whole agent's."""
268 for row in rows:
269 costs: list[Optional[float]] = []
270 for entry in row.get("datasets") or []:
271 cost = batch_store.cost_per_answer(
272 boards.get(str(entry["batch_id"])), entry.get("variant_id")
273 )
274 entry["cost_per_answer_usd"] = cost
275 costs.append(cost)
276 row["cost_per_answer_usd"] = (
277 sum(costs) / len(costs)
278 if costs and all(c is not None for c in costs)
279 else None
280 )
281 return rows
284def with_quality(
285 rows: list[dict[str, Any]], scores: dict[tuple[str, Optional[str]], list[float]]
286) -> list[dict[str, Any]]:
287 """Pure half of :func:`attach_quality`. ``quality`` on each row (None
288 with no scored answer); ``answers`` and ``answer_sd`` on each dataset.
290 Over the same runs as the status beside it — the newest scored run of the
291 version in force on each dataset — and the agent's own answers in each
292 (its variant's cells, not the run's other variants').
293 """
294 for row in rows:
295 samples: dict[str, list[float]] = {}
296 for entry in row.get("datasets") or []:
297 answers = risk_service.scores_of(
298 scores, entry["batch_id"], entry.get("variant_id")
299 )
300 one = risk_service.profile({0: answers})
301 entry["answers"] = len(answers)
302 entry["answer_sd"] = round(one.sd, 4) if one else None
303 samples[str(entry.get("dataset_id") or entry["batch_id"])] = answers
304 found = risk_service.profile(samples)
305 row["quality"] = found.as_json() if found else None
306 return rows
309def built_in_assurance(db: Session, viewer_id: Any) -> list[dict[str, Any]]:
310 """The built-in agents (CHAINR Bot), with the evidence behind each.
312 Kept out of ``fleet_assurance`` so a workspace's counts stay its own
313 agents'. Each is judged exactly as the evidence gate judges it for this
314 viewer (``evidence.evidence_owner``): the platform benchmark plus the
315 viewer's own runs of it.
316 """
317 agents = (
318 db.query(Agent)
319 .filter(Agent.is_system.is_(True))
320 .order_by(Agent.name.asc())
321 .all()
322 )
323 if not agents:
324 return []
325 current = history_service.current_versions(
326 db, HistoryEnum.ResourceType.agent, [a.id for a in agents]
327 )
328 evidence: dict[str, list] = {}
329 for agent in agents:
330 owner = evidence_service.evidence_owner(agent, viewer_id)
331 read = evidence_service.read_evidence(
332 db, evidence_service.evidence_filter(owner)
333 )
334 if str(agent.id) in read:
335 evidence[str(agent.id)] = read[str(agent.id)]
336 rows = attach_quality(db, assess(agents, current, evidence)["agents"])
337 # Every gold dataset the benchmark has still to report on, so the bot's
338 # results never read as the only datasets it is judged on.
339 from app.services.evaluation import benchmark
341 for row in rows:
342 found = benchmark.coverage(
343 db,
344 row["agent_id"],
345 [d["dataset_id"] for d in row["datasets"] if d.get("dataset_id")],
346 )
347 row["pending_datasets"] = found["pending"]
348 # Results a run for this release is replacing: shown, and marked so.
349 for entry in row["datasets"]:
350 entry["refreshing"] = entry.get("dataset_id") in found["refreshing"]
351 return rows
354def assess(
355 agents: list[Any],
356 current: dict[str, int],
357 evidence: dict[str, list[RunEvidence]],
358) -> dict[str, Any]:
359 """The assurance view from what was read — pure, so it is testable
360 without a database. ``evidence`` is :func:`.evidence.evidence_by_agent`'s
361 answer: each agent's runs, newest first."""
362 out: list[dict[str, Any]] = []
363 for agent in agents:
364 agent_id = str(agent.id)
365 entries = evidence.get(agent_id, [])
366 version = current.get(agent_id)
367 on_version = [
368 e for e in entries if version is not None and e.evaluated_version == version
369 ]
370 # The newest *scored* run on each dataset — the reading the evidence
371 # gate makes, so "current" here is exactly "the gate lets it through".
372 datasets = evidence_service.newest_per_dataset(
373 [e for e in on_version if e.passes() is not None]
374 )
375 latest = entries[0] if entries else None
376 if latest is None:
377 status = "never"
378 elif latest.regression_verdict == "regressed":
379 status = "regressed"
380 elif datasets:
381 status = "failing" if any(not d.passes() for d in datasets) else "current"
382 elif on_version:
383 status = "unscored"
384 elif latest.evaluated_version is None:
385 status = "unrecorded"
386 else:
387 status = "outdated"
388 out.append(
389 {
390 "agent_id": agent_id,
391 "agent_name": agent.name,
392 "current_version": version,
393 "status": status,
394 "runs": len(entries),
395 "latest_run": latest.as_json() if latest else None,
396 "current_version_run": on_version[0].as_json() if on_version else None,
397 # The newest scored run of the version in force on each
398 # dataset, against that dataset's pass mark.
399 "datasets": [d.as_json() for d in datasets],
400 }
401 )
402 out.sort(key=lambda r: (STATUSES.index(r["status"]), r["agent_name"].lower()))
403 summary = {status: 0 for status in STATUSES}
404 for row in out:
405 summary[row["status"]] += 1
406 summary["total"] = len(out)
407 return {"agents": out, "summary": summary}