Coverage for app / services / evaluation / evidence.py: 85%

213 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Evaluation evidence — what the runs say about an agent, read one way. 

3 

4Two readers ask the same question of the same rows. **Assurance** 

5(``assurance.fleet_assurance``) asks it of a whole fleet, for a person; 

6the **evidence gate** (the ``require_evaluation`` policy action) asks it of 

7one agent, on the inference path, before the model is called. Both read 

8through this module so the page and the gate cannot disagree about whether 

9an agent passed. 

10 

11What counts as evidence about an agent: 

12 

13* **A completed run.** A cancelled run's figures cover whichever cells 

14 happened to finish. 

15* **Of the agent as it is configured.** A variant that runs the agent on 

16 another model, at another temperature, with a candidate prompt or with 

17 different knowledge or tools is an experiment about an *alternative*; its 

18 score says nothing about the agent in production. Decided when the run 

19 starts and stamped on ``ExperimentBatch.target_versions`` (``as_configured``); 

20 runs stamped before that are judged from their variant. 

21* **At a version.** Runs record the agent revision they ran; evidence about 

22 version 3 is not evidence about version 4. 

23 

24And what counts as passing: a scored run whose mean score reaches the 

25dataset's **pass mark** (default :data:`DEFAULT_PASS_MARK`, or what a rule 

26asks for instead) and that did not regress against its last comparable run. 

27""" 

28 

29from __future__ import annotations 

30 

31import logging 

32from dataclasses import dataclass, field 

33from datetime import timedelta 

34from typing import Any, Iterable, Optional 

35from uuid import UUID 

36 

37from sqlalchemy import or_ 

38from sqlalchemy.orm import Session 

39 

40from app.db.postgres.enums import HistoryEnum, RunnableEnum 

41from app.db.postgres.models import ( 

42 Agent, 

43 Experiment, 

44 ExperimentBatch, 

45 ExperimentVariant, 

46 ResourceVersion, 

47 TestSuite, 

48) 

49from app.util.time import utc_isoformat 

50 

51logger = logging.getLogger(__name__) 

52 

53#: The score a dataset asks for when it names none. A dataset's own 

54#: ``pass_mark`` replaces it, and a rule's ``min_score`` replaces both. 

55DEFAULT_PASS_MARK = 0.8 

56 

57#: How many runs one agent's evidence reads. The gate reads only runs made 

58#: since the agent's current version, so this bounds a pathological account, 

59#: not a normal one. 

60MAX_RUNS_READ = 500 

61 

62#: Clock slack when reading "runs since this version". It only admits more 

63#: candidates — the version stamp on each run is what decides. 

64_SINCE_SLACK = timedelta(minutes=5) 

65 

66#: A target spec's keys that change what the agent runs with. 

67_TARGET_OVERRIDES = ( 

68 "model_id", 

69 "model", 

70 "provider", 

71 "temperature", 

72 "max_tokens", 

73 "effort", 

74 "cost_profile", 

75 "context", 

76) 

77 

78 

79def pass_mark_of(value: Any) -> float: 

80 """A dataset's pass mark, or the platform default when it names none.""" 

81 try: 

82 mark = float(value) 

83 except (TypeError, ValueError): 

84 return DEFAULT_PASS_MARK 

85 return mark if 0.0 <= mark <= 1.0 else DEFAULT_PASS_MARK 

86 

87 

88def _set(value: Any) -> bool: 

89 return value not in (None, "", [], {}) 

90 

91 

92def agent_of(variant: Any) -> Optional[str]: 

93 """The agent a variant runs, when it runs one (model variants do not).""" 

94 target = (getattr(variant, "config", None) or {}).get("target") 

95 if not isinstance(target, dict): 

96 return None 

97 kind = target.get("type") or ("agent" if target.get("agent_id") else "model") 

98 agent_id = target.get("agent_id") 

99 return str(agent_id) if kind == "agent" and agent_id else None 

100 

101 

102def runs_as_configured(variant: Any, agent_prompt: Optional[str]) -> bool: 

103 """Whether a variant runs its agent exactly as the agent is configured. 

104 

105 A prompt equal to the agent's own is the promotion gate's *control* 

106 variant, and counts; any other prompt is a candidate. 

107 """ 

108 config = getattr(variant, "config", None) or {} 

109 target = config.get("target") if isinstance(config.get("target"), dict) else {} 

110 if any(_set(target.get(key)) for key in _TARGET_OVERRIDES): 

111 return False 

112 if _set(config.get("context")): 

113 return False 

114 prompt = (getattr(variant, "prompt", None) or "").strip() 

115 return not prompt or prompt == (agent_prompt or "").strip() 

116 

117 

118# --------------------------------------------------------------------------- 

119# One run, as evidence about one agent 

120# --------------------------------------------------------------------------- 

121 

122 

123def _round(value: Any) -> Optional[float]: 

124 try: 

125 return round(float(value), 6) 

126 except (TypeError, ValueError): 

127 return None 

128 

129 

130@dataclass(frozen=True) 

131class RunEvidence: 

132 """One completed run's result for one agent (as configured).""" 

133 

134 batch_id: str 

135 experiment_id: str 

136 experiment_name: str 

137 dataset_id: Optional[str] 

138 dataset_name: Optional[str] 

139 evaluated_version: Optional[int] 

140 mean_score: Optional[float] 

141 pass_rate: Optional[float] 

142 pass_mark: float 

143 regression_verdict: Optional[str] 

144 created_at: Optional[str] 

145 #: The variant that ran the agent — whose answers in the run are its own. 

146 variant_id: Optional[str] = None 

147 

148 def threshold(self, min_score: Optional[float] = None) -> float: 

149 return self.pass_mark if min_score is None else float(min_score) 

150 

151 def passes(self, min_score: Optional[float] = None) -> Optional[bool]: 

152 """Passed, failed, or None when the run has no score to judge.""" 

153 if self.regression_verdict == "regressed": 

154 return False 

155 if self.mean_score is None: 

156 return None 

157 # Rounded both sides: a mean of 0.8 stored as 0.7999999999 has met a 

158 # pass mark of 0.8, and saying otherwise is a float, not a finding. 

159 return self.mean_score >= round(self.threshold(min_score), 6) 

160 

161 def as_json(self, min_score: Optional[float] = None) -> dict[str, Any]: 

162 return { 

163 "batch_id": self.batch_id, 

164 "experiment_id": self.experiment_id, 

165 "experiment_name": self.experiment_name, 

166 "dataset_id": self.dataset_id, 

167 "dataset_name": self.dataset_name, 

168 "evaluated_version": self.evaluated_version, 

169 "regression_verdict": self.regression_verdict, 

170 "mean_score": self.mean_score, 

171 "pass_rate": self.pass_rate, 

172 "pass_mark": self.threshold(min_score), 

173 "passed": self.passes(min_score), 

174 "created_at": self.created_at, 

175 "variant_id": self.variant_id, 

176 } 

177 

178 

179def _variant_row(batch: Any, variant_id: str) -> dict[str, Any]: 

180 for row in getattr(batch, "leaderboard", None) or []: 

181 if isinstance(row, dict) and str(row.get("variant_id")) == variant_id: 

182 return row 

183 return {} 

184 

185 

186def evidence_by_agent( 

187 rows: Iterable[tuple], 

188 variants: dict[str, tuple[str, bool]], 

189) -> dict[str, list[RunEvidence]]: 

190 """``{agent_id: [RunEvidence, …]}``, newest first — pure. 

191 

192 ``rows`` are ``(batch, experiment_name, dataset_id, dataset_name, 

193 pass_mark)``, newest first. ``variants`` maps a variant id to ``(agent_id, 

194 as_configured)`` for the runs whose stamp does not say: runs from before 

195 ``target_versions`` (which name no revision) and runs stamped before 

196 ``as_configured`` was. 

197 """ 

198 out: dict[str, list[RunEvidence]] = {} 

199 for batch, experiment_name, dataset_id, dataset_name, pass_mark in rows: 

200 stamps = batch.target_versions or { 

201 str(v): {"agent_id": variants[str(v)][0], "agent_version": None} 

202 for v in (batch.variant_ids or []) 

203 if str(v) in variants 

204 } 

205 for variant_id, stamp in stamps.items(): 

206 stamp = stamp if isinstance(stamp, dict) else {} 

207 agent_id = str(stamp.get("agent_id") or "") 

208 if not agent_id: 

209 continue 

210 configured = stamp.get("as_configured") 

211 if configured is None: 

212 configured = variants.get(str(variant_id), ("", False))[1] 

213 if not configured: 

214 continue 

215 figures = _variant_row(batch, str(variant_id)) 

216 out.setdefault(agent_id, []).append( 

217 RunEvidence( 

218 batch_id=str(batch.id), 

219 experiment_id=str(batch.experiment_id), 

220 experiment_name=experiment_name, 

221 dataset_id=str(dataset_id) if dataset_id else None, 

222 dataset_name=dataset_name, 

223 evaluated_version=stamp.get("agent_version"), 

224 mean_score=_round(figures.get("mean_score")), 

225 pass_rate=_round(figures.get("pass_rate")), 

226 pass_mark=pass_mark_of(pass_mark), 

227 regression_verdict=batch.regression_verdict, 

228 created_at=utc_isoformat(batch.created_at) 

229 if batch.created_at 

230 else None, 

231 variant_id=str(variant_id), 

232 ) 

233 ) 

234 return out 

235 

236 

237def newest_per_dataset( 

238 entries: Iterable[RunEvidence], min_score: Optional[float] = None 

239) -> list[RunEvidence]: 

240 """The newest run on each dataset, in newest-first order. 

241 

242 Where one run evaluated the agent twice (two variants of it, both as 

243 configured), the worse of the two stands for it: the run is evidence of 

244 both answers, and a gate reading only the kinder one would be choosing. 

245 """ 

246 chosen: dict[Optional[str], RunEvidence] = {} 

247 for entry in entries: 

248 held = chosen.get(entry.dataset_id) 

249 if held is None: 

250 chosen[entry.dataset_id] = entry 

251 elif held.batch_id == entry.batch_id and _worse(entry, held, min_score): 

252 chosen[entry.dataset_id] = entry 

253 return list(chosen.values()) 

254 

255 

256def _worse(a: RunEvidence, b: RunEvidence, min_score: Optional[float]) -> bool: 

257 order = {False: 0, None: 1, True: 2} 

258 pa, pb = order[a.passes(min_score)], order[b.passes(min_score)] 

259 if pa != pb: 

260 return pa < pb 

261 return (a.mean_score or 0.0) < (b.mean_score or 0.0) 

262 

263 

264# --------------------------------------------------------------------------- 

265# The gate's question 

266# --------------------------------------------------------------------------- 

267 

268 

269@dataclass 

270class AgentEvidence: 

271 """Everything the gate needs about one agent, read once per invocation.""" 

272 

273 agent_id: str 

274 current_version: Optional[int] 

275 entries: list[RunEvidence] = field(default_factory=list) 

276 

277 

278@dataclass(frozen=True) 

279class GateVerdict: 

280 allowed: bool 

281 #: Why, in sentences a refused caller can read. 

282 reason: str 

283 #: The runs the verdict rests on — the failing ones on a refusal. 

284 runs: tuple[RunEvidence, ...] = () 

285 #: The agent version the verdict is about. 

286 version: Optional[int] = None 

287 

288 

289def gate_verdict( 

290 evidence: AgentEvidence, 

291 *, 

292 dataset_id: Optional[str] = None, 

293 min_score: Optional[float] = None, 

294) -> GateVerdict: 

295 """Whether the agent's version in force has passing evidence behind it. 

296 

297 Passing means: at least one completed, scored run of the agent as 

298 configured at this version — on ``dataset_id`` if one is named — and the 

299 newest such run on every dataset reaches its pass mark (or ``min_score``) 

300 without regressing. One failing dataset refuses: an agent that passes the 

301 tone set and fails the grounding set has evidence against it. 

302 """ 

303 version = evidence.current_version 

304 if version is None: 

305 return GateVerdict( 

306 False, 

307 "The agent has no recorded version, so no evaluation can be tied to " 

308 "the configuration that would answer.", 

309 ) 

310 on_version = [e for e in evidence.entries if e.evaluated_version == version] 

311 if dataset_id: 

312 on_version = [e for e in on_version if e.dataset_id == str(dataset_id)] 

313 where = " on the required dataset" if dataset_id else "" 

314 if not on_version: 

315 return GateVerdict( 

316 False, 

317 f"Version {version} of this agent has not been evaluated{where}.", 

318 version=version, 

319 ) 

320 # A run nobody has scored yet (manual grading) is not evidence either 

321 # way, so the newest *judged* run on each dataset is the one that counts. 

322 judged = [e for e in on_version if e.passes(min_score) is not None] 

323 if not judged: 

324 return GateVerdict( 

325 False, 

326 f"Version {version} was evaluated{where}, but no run has been scored yet.", 

327 version=version, 

328 ) 

329 newest = newest_per_dataset(judged, min_score) 

330 failing = [e for e in newest if not e.passes(min_score)] 

331 if failing: 

332 return GateVerdict( 

333 False, 

334 " ".join(_why_failed(e, min_score) for e in failing), 

335 tuple(failing), 

336 version=version, 

337 ) 

338 return GateVerdict(True, "Evaluated and passing.", tuple(newest), version=version) 

339 

340 

341def _why_failed(entry: RunEvidence, min_score: Optional[float]) -> str: 

342 name = f"“{entry.dataset_name}”" if entry.dataset_name else "its dataset" 

343 if entry.regression_verdict == "regressed": 

344 return f"Its latest run on {name} regressed." 

345 return ( 

346 f"It scored {entry.mean_score:.2f} on {name}, below the pass mark of " 

347 f"{entry.threshold(min_score):.2f}." 

348 ) 

349 

350 

351# --------------------------------------------------------------------------- 

352# Reading it 

353# --------------------------------------------------------------------------- 

354 

355 

356def _unjudged_variants(db: Session, rows: list[tuple]) -> dict[str, tuple[str, bool]]: 

357 """``variant_id → (agent_id, as_configured)`` for runs whose stamps do 

358 not carry ``as_configured`` — judged from the variant as it is now.""" 

359 experiments = { 

360 batch.experiment_id 

361 for batch, *_ in rows 

362 if not batch.target_versions 

363 or any( 

364 isinstance(s, dict) and "as_configured" not in s 

365 for s in batch.target_versions.values() 

366 ) 

367 } 

368 if not experiments: 

369 return {} 

370 variants = ( 

371 db.query(ExperimentVariant) 

372 .filter(ExperimentVariant.experiment_id.in_(experiments)) 

373 .all() 

374 ) 

375 agent_ids = {a for a in (agent_of(v) for v in variants) if a} 

376 prompts = { 

377 str(a.id): a.system_prompt 

378 for a in ( 

379 db.query(Agent).filter(Agent.id.in_([UUID(a) for a in agent_ids])).all() 

380 if agent_ids 

381 else [] 

382 ) 

383 } 

384 out: dict[str, tuple[str, bool]] = {} 

385 for variant in variants: 

386 agent_id = agent_of(variant) 

387 if agent_id: 

388 out[str(variant.id)] = ( 

389 agent_id, 

390 runs_as_configured(variant, prompts.get(agent_id)), 

391 ) 

392 return out 

393 

394 

395def read_runs(db: Session, experiment_filter: Any, *, since: Any = None) -> list[tuple]: 

396 """Completed runs in scope, newest first, as :func:`evidence_by_agent` 

397 reads them.""" 

398 query = ( 

399 db.query( 

400 ExperimentBatch, 

401 Experiment.name, 

402 TestSuite.id, 

403 TestSuite.name, 

404 TestSuite.pass_mark, 

405 ) 

406 .join(Experiment, Experiment.id == ExperimentBatch.experiment_id) 

407 .outerjoin(TestSuite, TestSuite.id == Experiment.dataset_id) 

408 .filter( 

409 experiment_filter, 

410 ExperimentBatch.status == RunnableEnum.Status.completed, 

411 ) 

412 ) 

413 if since is not None: 

414 query = query.filter(ExperimentBatch.created_at >= since) 

415 return ( 

416 query.order_by(ExperimentBatch.created_at.desc(), ExperimentBatch.id.desc()) 

417 .limit(MAX_RUNS_READ) 

418 .all() 

419 ) 

420 

421 

422def read_evidence( 

423 db: Session, experiment_filter: Any, *, since: Any = None 

424) -> dict[str, list[RunEvidence]]: 

425 """Every agent's evidence among the runs ``experiment_filter`` admits.""" 

426 rows = read_runs(db, experiment_filter, since=since) 

427 return evidence_by_agent(rows, _unjudged_variants(db, rows)) 

428 

429 

430def evidence_owner(agent: Any, invoker_id: Any = None) -> tuple[str, str]: 

431 """Whose evaluations count as ``agent``'s evidence: the organisation's or 

432 project's that owns it, so every member is judged on the same evidence; 

433 otherwise the personal owner's. 

434 

435 A built-in agent (CHAINR Bot) is the same agent for everyone, so it is 

436 judged on the platform benchmark — the built-in experiments the 

437 ``platform_benchmark`` job runs on every deploy — plus the invoker's own 

438 runs of it: ``("system", invoker_id)``, the invoker part empty when there 

439 is none. 

440 """ 

441 if getattr(agent, "is_system", False) is True: 

442 return ("system", str(invoker_id) if invoker_id else "") 

443 if getattr(agent, "owner_organisation_id", None): 

444 return ("organisation", str(agent.owner_organisation_id)) 

445 if getattr(agent, "owner_project_id", None): 

446 return ("project", str(agent.owner_project_id)) 

447 owner = getattr(agent, "owner_user_id", None) or invoker_id 

448 return ("user", str(owner)) 

449 

450 

451_EVIDENCE_COLUMN = { 

452 "organisation": Experiment.owner_organisation_id, 

453 "project": Experiment.owner_project_id, 

454 "user": Experiment.owner_user_id, 

455} 

456 

457 

458def evidence_filter(owner: tuple[str, str]): 

459 kind, owner_id = owner 

460 if kind == "system": 

461 platform = Experiment.is_system.is_(True) 

462 if not owner_id: 

463 return platform 

464 return or_(platform, Experiment.owner_user_id == UUID(owner_id)) 

465 return _EVIDENCE_COLUMN[kind] == UUID(owner_id) 

466 

467 

468class EvidenceLookup: 

469 """The evidence gate's view of the ledger of runs, for one invocation. 

470 

471 Handed to policy actions in the rule context (``EVIDENCE_CONTEXT_KEY``), 

472 like the usage window is. Lazy — an invocation no gate governs never 

473 queries — and cached, so several gates on one invocation read once. 

474 

475 Reads the evaluations of the agent's owner (:func:`evidence_owner`): an 

476 organisation's agent is judged on the organisation's evaluations, the 

477 same for every member, and the evidence the gate acts on is the evidence 

478 Governance → Evaluation → Assurance shows. 

479 """ 

480 

481 def __init__(self, db: Session, owner_user_id: Any, workspace: Any = None) -> None: 

482 self.db = db 

483 self.owner_user_id = owner_user_id 

484 #: Where the invocation happens. Its own evaluations count too: a 

485 #: project that inherits its organisation's agent may evaluate it 

486 #: itself (``app/services/workspace.py``). 

487 self.workspace = workspace 

488 self._cache: dict[str, Optional[AgentEvidence]] = {} 

489 

490 def for_agent(self, agent_id: Any) -> Optional[AgentEvidence]: 

491 """The agent's evidence, or None when it could not be read.""" 

492 key = str(agent_id) 

493 if key not in self._cache: 

494 self._cache[key] = self._read(key) 

495 return self._cache[key] 

496 

497 def verdict( 

498 self, 

499 agent_id: Any, 

500 *, 

501 dataset_id: Optional[str] = None, 

502 min_score: Optional[float] = None, 

503 ) -> Optional[GateVerdict]: 

504 """:func:`gate_verdict` for the agent, or None when its evidence 

505 could not be read — the caller then stands aside.""" 

506 evidence = self.for_agent(agent_id) 

507 if evidence is None: 

508 return None 

509 return gate_verdict(evidence, dataset_id=dataset_id, min_score=min_score) 

510 

511 def _read(self, agent_id: str) -> Optional[AgentEvidence]: 

512 try: 

513 version = ( 

514 self.db.query( 

515 ResourceVersion.version_number, ResourceVersion.created_at 

516 ) 

517 .filter( 

518 ResourceVersion.resource_type == HistoryEnum.ResourceType.agent, 

519 ResourceVersion.resource_id == UUID(agent_id), 

520 ) 

521 .order_by(ResourceVersion.version_number.desc()) 

522 .first() 

523 ) 

524 if version is None: 

525 return AgentEvidence(agent_id=agent_id, current_version=None) 

526 number, created_at = version 

527 agent = self.db.get(Agent, UUID(agent_id)) 

528 owner = evidence_owner(agent, self.owner_user_id) 

529 where = evidence_filter(owner) 

530 if self.workspace is not None: 

531 from sqlalchemy import or_ 

532 

533 where = or_(where, self.workspace.owns(Experiment)) 

534 # Only runs since this version existed can have evaluated it. 

535 since = created_at - _SINCE_SLACK if created_at else None 

536 entries = read_evidence(self.db, where, since=since).get(agent_id, []) 

537 return AgentEvidence( 

538 agent_id=agent_id, current_version=number, entries=entries 

539 ) 

540 except Exception: 

541 logger.exception( 

542 "Could not read evaluation evidence for agent %s", agent_id 

543 ) 

544 return None