Coverage for app / services / evaluation / regression.py: 96%

387 statements  

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

1""" 

2Regression detection for evaluation runs. 

3 

4An evaluation suite is only a safety net if somebody notices when the numbers 

5move the wrong way. Until now runs were stored and comparable *by hand*: two 

6suite runs sat next to each other in a list, each with its own pass rate, and 

7whether the second was worse than the first was left to whoever happened to 

8look. This module answers that question automatically, so a prompt edit or a 

9model swap that makes the suite worse announces itself. 

10 

11The comparison is a **registry of metrics** rather than a hand-written diff: 

12each metric is one class declaring which way is better, how much movement is 

13noise, and whether it gates a promotion. Adding "output tokens per case" as a 

14tracked figure is one class, not an edit to three comparison sites — the same 

15shape the scorer and rule vocabularies take. 

16 

17Three things are deliberately *not* symmetric with each other: 

18 

19* **A different scorer makes a baseline unusable.** An LLM judge's 0.8 and an 

20 exact-match 0.8 are not the same measurement, so comparing them would invent 

21 a regression (or hide one). The search walks back for a run scored the same 

22 way instead. 

23* **A different target does not.** Detecting that a cheaper model scores worse 

24 on the same dataset is the entire point, so a target change is reported 

25 alongside the verdict, never used to dismiss it. 

26* **A different case count does not either.** Suites gain cases; refusing to 

27 compare the moment one is added would make this useless. Summary metrics are 

28 flagged as spanning a changed dataset, and the per-case comparison keys on 

29 the case itself, so it only ever compares like with like. 

30 

31Nothing here raises. A regression report is commentary on a run that has 

32already happened; failing the run because the commentary failed would turn one 

33problem into two. 

34""" 

35 

36from __future__ import annotations 

37 

38import logging 

39from abc import ABC, abstractmethod 

40from dataclasses import dataclass, field 

41from enum import StrEnum 

42from types import SimpleNamespace 

43from typing import Any, ClassVar, Iterable, Optional 

44 

45from sqlalchemy.exc import SQLAlchemyError 

46from sqlalchemy.orm import Session 

47 

48from app.db.postgres.enums import RunnableEnum 

49from app.db.postgres.models import ExperimentBatch, ExperimentRun, TestCase 

50from app.services.evaluation.scorers import stored_value 

51from app.util.time import utc_isoformat 

52 

53logger = logging.getLogger(__name__) 

54 

55#: How far back to look for a comparable baseline. A suite whose last ten runs 

56#: were all scored differently has no baseline worth reporting, and walking the 

57#: whole history to say so would cost more than the answer is worth. 

58BASELINE_SEARCH_LIMIT = 10 

59 

60#: Per-case deltas returned by the API. Enough to see the pattern in a failing 

61#: suite; not so many that the response becomes a second copy of the run. 

62MAX_CASE_DELTAS = 50 

63 

64#: Broken-case names kept inline on the run row. The full list is always 

65#: recomputable from the results, so this is a headline, not the record. 

66MAX_STORED_BROKEN = 10 

67 

68#: Decimal places a movement is rounded to before it is judged. Summary 

69#: figures are stored as JSON floats (``aggregate`` rounds rates to four 

70#: places), so ``0.90 - 0.88`` is 0.020000000000000018 in binary and a 

71#: tolerance boundary compared raw would be decided by representation noise 

72#: rather than by the numbers. Six places is strictly finer than anything 

73#: stored, so rounding here discards noise and never real signal. 

74COMPARISON_PLACES = 6 

75 

76#: Movement in a normalised score below which nothing is reported. LLM judges 

77#: are not deterministic and neither are the models under test, so a regression 

78#: detector with no tolerance reports noise on every run and gets ignored. 

79DEFAULT_SCORE_TOLERANCE = 0.02 

80 

81 

82class Direction(StrEnum): 

83 """Which way a metric has to move to be an improvement.""" 

84 

85 higher_is_better = "higher_is_better" 

86 lower_is_better = "lower_is_better" 

87 

88 

89class Verdict(StrEnum): 

90 """The headline answer about one run relative to its baseline.""" 

91 

92 #: A gating metric moved the wrong way, or a passing case started failing. 

93 regressed = "regressed" 

94 #: Nothing regressed and something got better. 

95 improved = "improved" 

96 #: Within tolerance on everything that gates. 

97 unchanged = "unchanged" 

98 #: Nothing earlier to compare against — the first run of a suite. 

99 no_baseline = "no_baseline" 

100 #: Earlier runs exist, but none measured the same thing. 

101 incomparable = "incomparable" 

102 

103 

104# ── Metric registry ─────────────────────────────────────────────────────────── 

105 

106 

107class Metric(ABC): 

108 """One tracked figure, read off a run's aggregate summary. 

109 

110 Subclass, set the class attributes, and decorate with 

111 :func:`register_metric`. 

112 """ 

113 

114 #: Stable key — used in payloads and in a suite's tolerance overrides. 

115 key: ClassVar[str] 

116 label: ClassVar[str] 

117 description: ClassVar[str] = "" 

118 direction: ClassVar[Direction] 

119 

120 #: Whether moving the wrong way makes the verdict ``regressed`` (and so 

121 #: closes a promotion gate). False for figures that vary with provider 

122 #: load rather than with the change under test. 

123 gating: ClassVar[bool] = True 

124 

125 #: How much movement counts as noise. Interpreted as a fraction of the 

126 #: baseline when :attr:`relative_tolerance` is set, and in the metric's own 

127 #: units otherwise. 

128 tolerance: ClassVar[float] = 0.0 

129 relative_tolerance: ClassVar[bool] = False 

130 

131 @abstractmethod 

132 def read(self, summary: dict[str, Any]) -> Optional[float]: 

133 """The metric's value for one run, or None when it was not measured.""" 

134 

135 # -- helpers --------------------------------------------------------- 

136 

137 @staticmethod 

138 def _number(value: Any) -> Optional[float]: 

139 """``value`` as a float, or None when it is missing or not a number. 

140 

141 Booleans are rejected: ``True`` is arithmetically 1.0, and a summary 

142 field that turned into a flag should read as "not measured" rather than 

143 as a suspiciously perfect score. 

144 """ 

145 if value is None or isinstance(value, bool): 

146 return None 

147 try: 

148 return float(value) 

149 except (TypeError, ValueError): 

150 return None 

151 

152 @classmethod 

153 def _ratio( 

154 cls, summary: dict[str, Any], numerator: str, denominator: str 

155 ) -> Optional[float]: 

156 """``numerator / denominator``, or None when either is unusable. 

157 

158 Ratios are derived rather than stored so they stay comparable between 

159 runs of different sizes — an absolute error count says nothing when one 

160 run had 12 cases and the next had 40. 

161 """ 

162 top = cls._number(summary.get(numerator)) 

163 bottom = cls._number(summary.get(denominator)) 

164 if top is None or not bottom: 

165 return None 

166 return top / bottom 

167 

168 

169_METRICS: dict[str, type[Metric]] = {} 

170 

171 

172def register_metric(cls: type[Metric]) -> type[Metric]: 

173 """Class decorator registering ``cls`` under its :attr:`Metric.key`.""" 

174 _METRICS[cls.key] = cls 

175 return cls 

176 

177 

178def metrics() -> list[Metric]: 

179 """Every registered metric, in registration order. 

180 

181 Registration order is the reading order the UI shows, which is why this is 

182 not sorted alphabetically: score before latency, because that is the order 

183 somebody asks the questions in. 

184 """ 

185 return [cls() for cls in _METRICS.values()] 

186 

187 

188def metric_catalogue() -> list[dict[str, Any]]: 

189 """Describe every metric, for the UI and for tolerance configuration.""" 

190 return [ 

191 { 

192 "key": metric.key, 

193 "label": metric.label, 

194 "description": metric.description, 

195 "direction": metric.direction.value, 

196 "gating": metric.gating, 

197 "tolerance": metric.tolerance, 

198 "relative_tolerance": metric.relative_tolerance, 

199 } 

200 for metric in metrics() 

201 ] 

202 

203 

204@register_metric 

205class MeanScoreMetric(Metric): 

206 key = "mean_score" 

207 label = "Mean score" 

208 description = "Average normalised score across every scored case." 

209 direction = Direction.higher_is_better 

210 tolerance = DEFAULT_SCORE_TOLERANCE 

211 

212 def read(self, summary): 

213 return self._number(summary.get("mean_score")) 

214 

215 

216@register_metric 

217class PassRateMetric(Metric): 

218 key = "pass_rate" 

219 label = "Pass rate" 

220 description = "Fraction of cases that met their scorer's pass threshold." 

221 direction = Direction.higher_is_better 

222 tolerance = DEFAULT_SCORE_TOLERANCE 

223 

224 def read(self, summary): 

225 return self._number(summary.get("pass_rate")) 

226 

227 

228@register_metric 

229class ErrorRateMetric(Metric): 

230 key = "error_rate" 

231 label = "Error rate" 

232 description = "Fraction of cases whose invocation failed outright." 

233 direction = Direction.lower_is_better 

234 # No tolerance: an invocation that started failing is a fact, not noise. 

235 tolerance = 0.0 

236 

237 def read(self, summary): 

238 return self._ratio(summary, "errors", "total") 

239 

240 

241@register_metric 

242class MeanLatencyMetric(Metric): 

243 key = "mean_latency_ms" 

244 label = "Mean latency" 

245 description = "Average successful invocation time in milliseconds." 

246 direction = Direction.lower_is_better 

247 # Informational. Provider latency moves for reasons that have nothing to do 

248 # with the prompt under test, so blocking a promotion on it would block 

249 # good changes at random. 

250 gating = False 

251 tolerance = 0.25 

252 relative_tolerance = True 

253 

254 def read(self, summary): 

255 return self._number(summary.get("mean_latency_ms")) 

256 

257 

258@register_metric 

259class TokensPerCaseMetric(Metric): 

260 key = "tokens_per_case" 

261 label = "Tokens per case" 

262 description = "Average total tokens spent per case — the cost proxy." 

263 direction = Direction.lower_is_better 

264 # Informational for the same reason as latency: a more verbose answer is 

265 # not automatically a worse one, but a prompt that doubled spend for the 

266 # same score is worth seeing. 

267 gating = False 

268 tolerance = 0.2 

269 relative_tolerance = True 

270 

271 def read(self, summary): 

272 return self._ratio(summary, "total_tokens", "total") 

273 

274 

275# ── Summary comparison ──────────────────────────────────────────────────────── 

276 

277 

278@dataclass 

279class MetricDelta: 

280 """One metric, measured on both runs and judged.""" 

281 

282 metric: Metric 

283 baseline: Optional[float] 

284 current: Optional[float] 

285 

286 @property 

287 def delta(self) -> Optional[float]: 

288 if self.baseline is None or self.current is None: 

289 return None 

290 return round(self.current - self.baseline, COMPARISON_PLACES) 

291 

292 @property 

293 def relative_delta(self) -> Optional[float]: 

294 """Movement as a fraction of the baseline, or None when undefined. 

295 

296 Undefined against a zero baseline: "infinitely worse" is not a useful 

297 thing to report, and the absolute delta already says what happened. 

298 """ 

299 if self.delta is None or not self.baseline: 

300 return None 

301 return self.delta / abs(self.baseline) 

302 

303 @property 

304 def allowance(self) -> float: 

305 """Movement treated as noise, in the metric's own units.""" 

306 if not self.metric.relative_tolerance: 

307 return self.metric.tolerance 

308 if self.baseline is None: 

309 return 0.0 

310 return round(abs(self.baseline) * self.metric.tolerance, COMPARISON_PLACES) 

311 

312 @property 

313 def movement(self) -> Optional[float]: 

314 """Signed movement in the *better* direction, past the allowance. 

315 

316 Positive means better, negative means worse, zero means within 

317 tolerance. Folding direction and tolerance into one number here is what 

318 keeps every caller from re-deriving "is lower better again?". 

319 """ 

320 delta = self.delta 

321 if delta is None: 

322 return None 

323 if self.metric.direction is Direction.lower_is_better: 

324 delta = -delta 

325 if abs(delta) <= self.allowance: 

326 return 0.0 

327 return delta 

328 

329 @property 

330 def regressed(self) -> bool: 

331 movement = self.movement 

332 return movement is not None and movement < 0 

333 

334 @property 

335 def improved(self) -> bool: 

336 movement = self.movement 

337 return movement is not None and movement > 0 

338 

339 def as_dict(self) -> dict[str, Any]: 

340 return { 

341 "key": self.metric.key, 

342 "label": self.metric.label, 

343 "direction": self.metric.direction.value, 

344 "gating": self.metric.gating, 

345 "baseline": self.baseline, 

346 "current": self.current, 

347 "delta": _round(self.delta), 

348 "relative_delta": _round(self.relative_delta), 

349 "tolerance": _round(self.allowance), 

350 "regressed": self.regressed, 

351 "improved": self.improved, 

352 } 

353 

354 

355def _round(value: Optional[float], places: int = 4) -> Optional[float]: 

356 return None if value is None else round(value, places) 

357 

358 

359def tolerance_overrides(config: Optional[dict]) -> dict[str, float]: 

360 """Per-suite tolerance overrides, ignoring anything unusable. 

361 

362 A malformed tolerance falls back to the metric's default rather than 

363 failing: the alternative is a suite that cannot be compared at all because 

364 somebody typed ``"2%"`` into a config blob. 

365 """ 

366 raw = ((config or {}).get("regression") or {}).get("tolerance") or {} 

367 if not isinstance(raw, dict): 

368 return {} 

369 overrides: dict[str, float] = {} 

370 for key, value in raw.items(): 

371 if key not in _METRICS: 

372 logger.warning("Unknown regression metric %r in tolerance config", key) 

373 continue 

374 try: 

375 number = float(value) 

376 except (TypeError, ValueError): 

377 logger.warning( 

378 "Regression tolerance for %s is not a number: %r", key, value 

379 ) 

380 continue 

381 if number < 0: 

382 logger.warning("Regression tolerance for %s is negative: %r", key, value) 

383 continue 

384 overrides[key] = number 

385 return overrides 

386 

387 

388def compare_summaries( 

389 baseline: Optional[dict[str, Any]], 

390 current: Optional[dict[str, Any]], 

391 *, 

392 tolerances: Optional[dict[str, float]] = None, 

393) -> list[MetricDelta]: 

394 """Measure every registered metric on both summaries. 

395 

396 Metrics neither run measured are dropped — a suite of manually scored cases 

397 has no mean score, and reporting ``None → None`` as a row would fill the UI 

398 with rows that say nothing. 

399 """ 

400 baseline = baseline or {} 

401 current = current or {} 

402 overrides = tolerances or {} 

403 

404 deltas: list[MetricDelta] = [] 

405 for metric in metrics(): 

406 if metric.key in overrides: 

407 # Per-instance, so one suite's tolerance never leaks into another's. 

408 metric.tolerance = overrides[metric.key] 

409 before, after = metric.read(baseline), metric.read(current) 

410 if before is None and after is None: 

411 continue 

412 deltas.append(MetricDelta(metric=metric, baseline=before, current=after)) 

413 return deltas 

414 

415 

416# ── Case comparison ─────────────────────────────────────────────────────────── 

417 

418 

419@dataclass 

420class CaseDelta: 

421 """One test case, as it did before and as it did now.""" 

422 

423 case_id: str 

424 case_name: Optional[str] 

425 baseline_passed: Optional[bool] 

426 current_passed: Optional[bool] 

427 baseline_score: Optional[float] 

428 current_score: Optional[float] 

429 kind: str 

430 

431 def as_dict(self) -> dict[str, Any]: 

432 return { 

433 "case_id": self.case_id, 

434 "case_name": self.case_name, 

435 "baseline_passed": self.baseline_passed, 

436 "current_passed": self.current_passed, 

437 "baseline_score": self.baseline_score, 

438 "current_score": self.current_score, 

439 "delta": _round( 

440 None 

441 if self.baseline_score is None or self.current_score is None 

442 else self.current_score - self.baseline_score 

443 ), 

444 "kind": self.kind, 

445 } 

446 

447 

448@dataclass 

449class CaseComparison: 

450 """Per-case movement between two runs of the same suite.""" 

451 

452 deltas: list[CaseDelta] = field(default_factory=list) 

453 compared: int = 0 

454 added: int = 0 

455 removed: int = 0 

456 

457 @property 

458 def broke(self) -> list[CaseDelta]: 

459 return [d for d in self.deltas if d.kind == "broke"] 

460 

461 @property 

462 def fixed(self) -> list[CaseDelta]: 

463 return [d for d in self.deltas if d.kind == "fixed"] 

464 

465 @property 

466 def score_drops(self) -> list[CaseDelta]: 

467 return [d for d in self.deltas if d.kind == "score_drop"] 

468 

469 @property 

470 def score_gains(self) -> list[CaseDelta]: 

471 return [d for d in self.deltas if d.kind == "score_gain"] 

472 

473 def as_dict(self, limit: int = MAX_CASE_DELTAS) -> dict[str, Any]: 

474 # Worst first: a reviewer opening a regressed run wants the cases that 

475 # broke, and truncation must never cut those in favour of improvements. 

476 order = {"broke": 0, "score_drop": 1, "fixed": 2, "score_gain": 3} 

477 ranked = sorted(self.deltas, key=lambda d: order.get(d.kind, 4)) 

478 return { 

479 "compared": self.compared, 

480 "added": self.added, 

481 "removed": self.removed, 

482 "broke": len(self.broke), 

483 "fixed": len(self.fixed), 

484 "score_drops": len(self.score_drops), 

485 "score_gains": len(self.score_gains), 

486 "truncated": len(ranked) > limit, 

487 "deltas": [d.as_dict() for d in ranked[:limit]], 

488 } 

489 

490 

491def _result_score(result: Any) -> Optional[float]: 

492 """The numeric score off an ``ExperimentRun.score`` blob. 

493 

494 The column is a dict keyed by scorer with ``value`` duplicated at the top 

495 level (see ``ScoreResult.as_score_json``); a bare number is accepted too, 

496 because rows written before that shape existed still have to compare. 

497 """ 

498 return stored_value(getattr(result, "score", None)) 

499 

500 

501def _classify( 

502 before_passed: Optional[bool], 

503 after_passed: Optional[bool], 

504 before_score: Optional[float], 

505 after_score: Optional[float], 

506 tolerance: float, 

507) -> Optional[str]: 

508 """What happened to one case, or None when nothing worth reporting did. 

509 

510 A pass/fail flip outranks a score movement: a case that went from passing 

511 to failing is the actionable fact, and describing it as a score drop would 

512 bury it among near-misses. 

513 """ 

514 if before_passed is True and after_passed is False: 

515 return "broke" 

516 if before_passed is False and after_passed is True: 

517 return "fixed" 

518 if before_score is None or after_score is None: 

519 return None 

520 delta = round(after_score - before_score, COMPARISON_PLACES) 

521 if abs(delta) <= tolerance: 

522 return None 

523 return "score_drop" if delta < 0 else "score_gain" 

524 

525 

526def collapse_repeats(results: Iterable[Any]) -> dict[str, Any]: 

527 """One result per test case, however many times the run asked it. 

528 

529 A repeated run has a cell per repeat. Keyed naively the last repeat 

530 would silently stand for the case; instead the case's score is the mean 

531 of its repeats and its verdict the majority — a tie is no verdict, so a 

532 case that passed once and failed once is neither "broke" nor "fixed", 

533 only (if its mean moved) a score movement. 

534 """ 

535 grouped: dict[str, list[Any]] = {} 

536 for result in results: 

537 if result.test_case_id is None: 

538 continue 

539 grouped.setdefault(str(result.test_case_id), []).append(result) 

540 collapsed: dict[str, Any] = {} 

541 for case_id, rows in grouped.items(): 

542 if len(rows) == 1: 

543 collapsed[case_id] = rows[0] 

544 continue 

545 scores = [s for s in (_result_score(r) for r in rows) if s is not None] 

546 verdicts = [r.passed for r in rows if r.passed is not None] 

547 passes = sum(1 for v in verdicts if v) 

548 fails = len(verdicts) - passes 

549 collapsed[case_id] = SimpleNamespace( 

550 test_case_id=rows[0].test_case_id, 

551 passed=None if passes == fails else passes > fails, 

552 score={"value": sum(scores) / len(scores)} if scores else None, 

553 result_metadata=getattr(rows[0], "result_metadata", None), 

554 ) 

555 return collapsed 

556 

557 

558def compare_cases( 

559 baseline_results: Iterable[Any], 

560 current_results: Iterable[Any], 

561 *, 

562 tolerance: float = DEFAULT_SCORE_TOLERANCE, 

563 case_names: Optional[dict[str, str]] = None, 

564) -> CaseComparison: 

565 """Match two runs' results by test case and classify each movement. 

566 

567 Matching is by ``test_case_id``, so a suite that gained or lost cases still 

568 compares correctly: cases present in only one run are counted as added or 

569 removed and never scored against nothing. 

570 """ 

571 before = collapse_repeats(baseline_results) 

572 after = collapse_repeats(current_results) 

573 names = case_names or {} 

574 

575 comparison = CaseComparison( 

576 compared=len(before.keys() & after.keys()), 

577 added=len(after.keys() - before.keys()), 

578 removed=len(before.keys() - after.keys()), 

579 ) 

580 for case_id in before.keys() & after.keys(): 

581 old, new = before[case_id], after[case_id] 

582 old_score, new_score = _result_score(old), _result_score(new) 

583 kind = _classify( 

584 getattr(old, "passed", None), 

585 getattr(new, "passed", None), 

586 old_score, 

587 new_score, 

588 tolerance, 

589 ) 

590 if kind is None: 

591 continue 

592 comparison.deltas.append( 

593 CaseDelta( 

594 case_id=case_id, 

595 case_name=names.get(case_id) 

596 or (getattr(new, "result_metadata", None) or {}).get("case_name"), 

597 baseline_passed=getattr(old, "passed", None), 

598 current_passed=getattr(new, "passed", None), 

599 baseline_score=old_score, 

600 current_score=new_score, 

601 kind=kind, 

602 ) 

603 ) 

604 return comparison 

605 

606 

607# ── Baseline resolution ─────────────────────────────────────────────────────── 

608 

609 

610def _scorer_of(batch: Any) -> Optional[str]: 

611 """Which scorer a batch used. 

612 

613 The column first, the summary blob second: the column is denormalised from 

614 the blob on every write, so they agree — but a batch folded in from the old 

615 dataset tables may carry a scorer the enum did not recognise, and the blob 

616 still has it. 

617 """ 

618 column = getattr(batch, "scorer", None) 

619 if column is not None: 

620 return str(getattr(column, "value", column)) 

621 summary = getattr(batch, "summary", None) 

622 if isinstance(summary, dict) and summary.get("scorer"): 

623 return str(summary["scorer"]) 

624 return None 

625 

626 

627def _dataset_of(batch: Any) -> Optional[str]: 

628 """Which dataset a batch asked. 

629 

630 Recorded on the run itself rather than read off the evaluation, because 

631 the evaluation's dataset is what it asks *now* and the run is what it 

632 asked *then*. 

633 """ 

634 value = getattr(batch, "dataset_id", None) 

635 return str(value) if value else None 

636 

637 

638def _target_of(batch: Any) -> Optional[dict[str, Any]]: 

639 """What a batch ran against, when it ran against exactly one thing. 

640 

641 Read off the leaderboard: a run with one variant has one row, and that 

642 row records the target. A run of several variants has no single answer 

643 and the comparison does not claim one — a variant swap shows up in the 

644 leaderboard, which is the right place for it. 

645 """ 

646 rows = getattr(batch, "leaderboard", None) 

647 if isinstance(rows, list) and len(rows) == 1 and isinstance(rows[0], dict): 

648 target = rows[0].get("target") 

649 return target if isinstance(target, dict) else None 

650 return None 

651 

652 

653def _target_identity(target: Optional[dict[str, Any]]) -> Optional[str]: 

654 """A stable string for "the same thing was invoked". 

655 

656 Only the fields that change *what answers* are included: an agent id and 

657 the skill it answered through, or a provider and model name. Labels and 

658 inference parameters are deliberately left out — a renamed target is the 

659 same target, and a temperature change is exactly the kind of thing a 

660 regression report should be able to attribute. An agent evaluated 

661 through its skill graph (as it answers in chat, since October 2026) 

662 after a run without it is a changed target, not a regression. 

663 """ 

664 if not target: 

665 return None 

666 parts = [str(target.get("type") or "")] 

667 for key in ( 

668 "agent_id", 

669 "swarm_id", 

670 "skill_id", 

671 "provider", 

672 "model_name", 

673 "model", 

674 "model_id", 

675 ): 

676 value = target.get(key) 

677 if value: 

678 parts.append(f"{key}={value}") 

679 return "|".join(parts) if len(parts) > 1 else None 

680 

681 

682def _describe_run(batch: Any) -> dict[str, Any]: 

683 finished = getattr(batch, "finished_at", None) 

684 created = getattr(batch, "created_at", None) 

685 return { 

686 "run_id": str(batch.id), 

687 "label": getattr(batch, "label", None), 

688 "scorer": _scorer_of(batch), 

689 "dataset_id": _dataset_of(batch), 

690 "target": _target_of(batch), 

691 "total": getattr(batch, "total_cases", None), 

692 "finished_at": utc_isoformat(finished) if finished else None, 

693 "created_at": utc_isoformat(created) if created else None, 

694 } 

695 

696 

697def _owner_filter(batch: Any): 

698 """Match the other runs of the same evaluation. 

699 

700 The population a baseline is drawn from. An evaluation is one dataset, 

701 one scorer and one set of variants, so its previous run is the 

702 like-for-like comparison; a dataset's previous run, whichever evaluation 

703 made it, was not. 

704 """ 

705 return ExperimentBatch.experiment_id == batch.experiment_id 

706 

707 

708def find_baseline( 

709 db: Session, batch: ExperimentBatch, *, limit: int = BASELINE_SEARCH_LIMIT 

710) -> tuple[Optional[ExperimentBatch], Optional[str]]: 

711 """The most recent earlier run worth comparing this one against. 

712 

713 Returns the batch and, when there is none, why. Walks back through 

714 completed runs for a **scorer and dataset** match rather than taking the 

715 immediately previous one blindly: a one-off run with a different scorer 

716 sitting in between would otherwise make every subsequent run 

717 incomparable. 

718 

719 The dataset has to match for the same reason the scorer does. An LLM 

720 judge's 0.8 and an exact-match 0.8 are not the same measurement, and 

721 neither is 0.8 on the refund set and 0.8 on the compliance set — they are 

722 different questions. Per-case comparison already degrades safely when the 

723 dataset changes (nothing matches by ``test_case_id``, so every case reads 

724 as added or removed), but the metric deltas the verdict is derived from 

725 are run aggregates, which compare regardless and would report a harder 

726 dataset as a regression. 

727 

728 And the dataset *version* has to match: runs are compared only within 

729 one content version of the dataset (``dataset_versions``). Editing a case 

730 or the criteria changes what a run measures, so the first run after an 

731 edit has no baseline rather than a verdict against different questions. 

732 

733 Cancelled and failed runs are skipped — a half-finished run's aggregate is 

734 over whichever cells happened to complete, which is not a baseline. 

735 """ 

736 try: 

737 candidates = ( 

738 db.query(ExperimentBatch) 

739 .filter( 

740 _owner_filter(batch), 

741 ExperimentBatch.id != batch.id, 

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

743 ExperimentBatch.created_at < batch.created_at, 

744 ) 

745 .order_by(ExperimentBatch.created_at.desc(), ExperimentBatch.id.desc()) 

746 .limit(limit) 

747 .all() 

748 ) 

749 except SQLAlchemyError: 

750 logger.exception("Could not load baseline candidates for batch %s", batch.id) 

751 return None, "The earlier runs could not be read." 

752 

753 if not candidates: 

754 return None, "This is the first completed run." 

755 

756 scorer = _scorer_of(batch) 

757 dataset = _dataset_of(batch) 

758 version = getattr(batch, "dataset_version", None) 

759 for candidate in candidates: 

760 # An unknown value on either side is not treated as a mismatch: runs 

761 # folded in from the old dataset tables carry neither, and refusing 

762 # to compare them would be a regression in the reporting itself. 

763 if scorer is not None and _scorer_of(candidate) not in (None, scorer): 

764 continue 

765 if dataset is not None and _dataset_of(candidate) not in (None, dataset): 

766 continue 

767 # The same dataset is not enough: an edited case or criterion is a 

768 # different measurement, so runs compare only within one content 

769 # version. Equality, None included — a dataset with no history has 

770 # had no recorded edit, so its unversioned runs all asked the same. 

771 # Runs folded in with no dataset recorded predate versions entirely. 

772 if ( 

773 dataset is not None 

774 and _dataset_of(candidate) is not None 

775 and getattr(candidate, "dataset_version", None) != version 

776 ): 

777 continue 

778 return candidate, None 

779 if dataset is not None and version is not None: 

780 return None, ( 

781 f"This is the first run on version {version} of the dataset scored " 

782 f"with '{scorer}'. Runs on earlier versions asked different cases " 

783 "or criteria, so they are not compared." 

784 ) 

785 return None, ( 

786 f"No earlier run asked this dataset and scored it with '{scorer}', so " 

787 "there is nothing comparable to measure against." 

788 ) 

789 

790 

791# ── Report ──────────────────────────────────────────────────────────────────── 

792 

793 

794def _verdict( 

795 deltas: list[MetricDelta], cases: CaseComparison 

796) -> tuple[Verdict, list[str]]: 

797 """Fold metric and case movement into one answer, with its reasons. 

798 

799 A broken case is a regression on its own, even when every summary metric 

800 stayed inside tolerance: a suite that swapped one failure for one pass has 

801 an unchanged pass rate and a real problem. 

802 """ 

803 reasons: list[str] = [] 

804 regressed = [d for d in deltas if d.metric.gating and d.regressed] 

805 improved = [d for d in deltas if d.improved] 

806 

807 for delta in regressed: 

808 reasons.append( 

809 f"{delta.metric.label} moved from {delta.baseline} to {delta.current}." 

810 ) 

811 if cases.broke: 

812 names = ", ".join( 

813 d.case_name or d.case_id for d in cases.broke[:MAX_STORED_BROKEN] 

814 ) 

815 reasons.append( 

816 f"{len(cases.broke)} case(s) that passed before now fail: {names}." 

817 ) 

818 

819 if regressed or cases.broke: 

820 return Verdict.regressed, reasons 

821 if improved or cases.fixed: 

822 if cases.fixed: 

823 reasons.append(f"{len(cases.fixed)} previously failing case(s) now pass.") 

824 reasons.extend( 

825 f"{d.metric.label} improved from {d.baseline} to {d.current}." 

826 for d in improved 

827 ) 

828 return Verdict.improved, reasons 

829 return Verdict.unchanged, ["Every tracked metric stayed within tolerance."] 

830 

831 

832def _case_results( 

833 db: Session, batch_id: Any, variant_id: Any = None 

834) -> list[ExperimentRun]: 

835 """The scored cells of one batch, optionally for one variant. 

836 

837 An evaluation's batch has a cell per (variant, case), so comparing it 

838 case-by-case without narrowing to a variant would put the same case in 

839 twice and compare it against itself. 

840 """ 

841 try: 

842 query = db.query(ExperimentRun).filter(ExperimentRun.batch_id == batch_id) 

843 if variant_id is not None: 

844 query = query.filter(ExperimentRun.variant_id == variant_id) 

845 return query.all() 

846 except SQLAlchemyError: 

847 logger.exception("Could not load case results for batch %s", batch_id) 

848 return [] 

849 

850 

851def _case_names(db: Session, dataset_id: Any) -> dict[str, str]: 

852 """Case ids to names, so a delta reads as a case rather than a UUID.""" 

853 if dataset_id is None: 

854 return {} 

855 try: 

856 rows = ( 

857 db.query(TestCase.id, TestCase.name) 

858 .filter(TestCase.test_suite_id == dataset_id) 

859 .all() 

860 ) 

861 except SQLAlchemyError: 

862 logger.exception("Could not load case names for dataset %s", dataset_id) 

863 return {} 

864 return {str(row[0]): row[1] for row in rows if row[1]} 

865 

866 

867def _comparable_variant(batch: Any) -> Any: 

868 """Which variant's cells to compare, or None when there is one target. 

869 

870 An evaluation's batch may run several variants. Comparing "the batch" to 

871 "the previous batch" case-by-case is only meaningful for one variant at a 

872 time, and the only one both runs are guaranteed to share is the first the 

873 batch declared — so that is the one the per-case section speaks about. The 

874 summary metrics still cover the whole batch, and the leaderboard is where a 

875 variant-to-variant comparison belongs. 

876 """ 

877 ids = getattr(batch, "variant_ids", None) or [] 

878 return ids[0] if len(ids) == 1 else None 

879 

880 

881def _empty_report(run: Any, verdict: Verdict, reason: str) -> dict[str, Any]: 

882 return { 

883 "verdict": verdict.value, 

884 "reasons": [reason], 

885 "current": _describe_run(run), 

886 "baseline": None, 

887 "metrics": [], 

888 "cases": CaseComparison().as_dict(), 

889 "target_changed": False, 

890 "dataset_changed": False, 

891 } 

892 

893 

894def evaluate_batch( 

895 db: Session, 

896 batch: ExperimentBatch, 

897 *, 

898 owner_config: Optional[dict] = None, 

899 include_cases: bool = True, 

900 baseline: Optional[ExperimentBatch] = None, 

901) -> dict[str, Any]: 

902 """Compare ``batch`` against its baseline and return the full report. 

903 

904 Works for an evaluation's batch and a dataset's run alike, which is the 

905 point of folding them into one table: a regression verdict used to be 

906 something only dataset runs got. 

907 

908 Recomputed on demand rather than only at write time, so runs recorded 

909 before this existed still report — and so a report never goes stale against 

910 a suite whose tolerances were retuned afterwards. 

911 

912 Never raises. On any failure the report degrades to "no baseline" with the 

913 reason attached, because a run that cannot be compared is not a run that 

914 should look regressed. 

915 """ 

916 try: 

917 if baseline is None: 

918 baseline, reason = find_baseline(db, batch) 

919 if baseline is None: 

920 verdict = ( 

921 Verdict.no_baseline 

922 if reason and reason.startswith("This is the first") 

923 else Verdict.incomparable 

924 ) 

925 return _empty_report( 

926 batch, verdict, reason or "There is nothing to compare against." 

927 ) 

928 

929 tolerances = tolerance_overrides(owner_config) 

930 deltas = compare_summaries( 

931 baseline.summary, batch.summary, tolerances=tolerances 

932 ) 

933 

934 cases = CaseComparison() 

935 if include_cases: 

936 cases = compare_cases( 

937 _case_results(db, baseline.id, _comparable_variant(baseline)), 

938 _case_results(db, batch.id, _comparable_variant(batch)), 

939 tolerance=tolerances.get("mean_score", DEFAULT_SCORE_TOLERANCE), 

940 case_names=_case_names(db, getattr(batch, "dataset_id", None)), 

941 ) 

942 

943 verdict, reasons = _verdict(deltas, cases) 

944 before, after = _describe_run(baseline), _describe_run(batch) 

945 return { 

946 "verdict": verdict.value, 

947 "reasons": reasons, 

948 "current": after, 

949 "baseline": before, 

950 "metrics": [d.as_dict() for d in deltas], 

951 "cases": cases.as_dict(), 

952 # Both are attribution, not disqualification: they say *what else* 

953 # changed between the two runs, so a reader can tell a prompt 

954 # regression from a model swap. 

955 "target_changed": _target_identity(before.get("target")) 

956 != _target_identity(after.get("target")), 

957 "dataset_changed": bool(cases.added or cases.removed) 

958 or before.get("total") != after.get("total"), 

959 } 

960 # Deliberately broad: see the module docstring. A report is commentary on a 

961 # run that already happened, and no comparison failure is worth failing it. 

962 except Exception: 

963 logger.exception("Could not build a regression report for batch %s", batch.id) 

964 return _empty_report( 

965 batch, 

966 Verdict.no_baseline, 

967 "The regression comparison could not be completed.", 

968 ) 

969 

970 

971def summarise(report: dict[str, Any]) -> dict[str, Any]: 

972 """The compact form stored on ``ExperimentBatch.regression``. 

973 

974 A headline, not the record: enough for a list page to show a badge without 

975 loading every case result, and always recomputable in full from 

976 :func:`evaluate_batch`. 

977 """ 

978 cases = report.get("cases") or {} 

979 regressed = [ 

980 m for m in report.get("metrics") or [] if m.get("gating") and m.get("regressed") 

981 ] 

982 return { 

983 "verdict": report.get("verdict"), 

984 "baseline_run_id": (report.get("baseline") or {}).get("run_id"), 

985 "regressed_metrics": [m["key"] for m in regressed], 

986 "broke": cases.get("broke", 0), 

987 "fixed": cases.get("fixed", 0), 

988 "target_changed": report.get("target_changed", False), 

989 "reasons": (report.get("reasons") or [])[:MAX_STORED_BROKEN], 

990 } 

991 

992 

993def annotate_batch( 

994 db: Session, batch: ExperimentBatch, *, owner_config: Optional[dict] = None 

995) -> dict[str, Any]: 

996 """Compute a batch's regression report and stamp the headline onto it. 

997 

998 Called from the runner as the last step of a completed batch, so the 

999 verdict is on the row by the time anybody can read it. The verdict is 

1000 denormalised onto its own column by the same call that writes the headline, 

1001 so a report filtering on "regressed" can never disagree with the badge. 

1002 

1003 Does not commit; the caller owns the transaction it is already inside. 

1004 """ 

1005 report = evaluate_batch(db, batch, owner_config=owner_config) 

1006 try: 

1007 headline = summarise(report) 

1008 batch.regression = headline 

1009 batch.regression_verdict = headline.get("verdict") 

1010 # Broad for the same reason: a run that finished must still be recorded as 

1011 # finished even if its verdict could not be written onto it. 

1012 except Exception: 

1013 logger.exception("Could not stamp a regression verdict onto batch %s", batch.id) 

1014 return report