Coverage for app / services / evaluation / batches.py: 95%
168 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"""
2Experiment batches — creating them, tracking them, and reporting across them.
4A batch is one execution of an experiment's variant x case matrix. Batches used
5to live on ``Experiment.config['batches']`` as a JSON array capped at the twenty
6most recent, which was enough to drive a progress bar and nothing else. Two
7things were wrong with that:
9* **Nothing could be asked across experiments.** "Which experiments in this
10 project scored below 0.7 this month" is a query, and a JSON array inside
11 another table's column cannot answer one — every figure had to be assembled
12 in Python from rows already loaded, one experiment at a time.
13* **History was silently discarded.** The twenty-first batch pushed the first
14 out of the array while its runs stayed in ``experiment_runs`` forever, so the
15 scores survived and the thing that explained them did not.
17This module owns the batch row. The runner owns execution and calls in here to
18record what it finds; the router reads through here so the API shape stays one
19decision in one place.
21``as_payload`` deliberately reproduces the old JSON shape — nested ``progress``
22and all. The frontend's `ExperimentBatch` describes that shape and there is
23nothing wrong with it; changing the wire format as a side effect of changing the
24storage would be two migrations for the price of one.
25"""
27from __future__ import annotations
29import logging
30from datetime import datetime, timedelta
31from typing import Any, Optional
32from uuid import UUID, uuid4
34from sqlalchemy import func
35from sqlalchemy.exc import SQLAlchemyError
36from sqlalchemy.orm import Session
38from app.db.postgres.enums import EvaluationEnum, RunnableEnum
39from app.db.postgres.models import Experiment, ExperimentBatch, TestSuite
40from app.util.time import aware_utcnow, utc_isoformat
42logger = logging.getLogger(__name__)
44#: Batches returned by one reporting query. A report is something a person
45#: reads, and a page of a thousand rows is not one.
46MAX_REPORT_ROWS = 200
47DEFAULT_REPORT_ROWS = 50
49#: How far back a report looks when the caller does not say.
50DEFAULT_REPORT_DAYS = 30
52#: Where a batch's figures are copied from on the summary blob. The column name
53#: is the key except where the summary's word is narrower than the column's.
54_SUMMARY_COLUMNS = {
55 "mean_score": "mean_score",
56 "pass_rate": "pass_rate",
57 "total_cases": "total",
58 "errors": "errors",
59 "mean_latency_ms": "mean_latency_ms",
60 "total_tokens": "total_tokens",
61 "duration_ms": "duration_ms",
62}
65def _number(value: Any) -> Optional[float]:
66 """``value`` as a float, or None when it is missing or not a number."""
67 if value is None or isinstance(value, bool):
68 return None
69 try:
70 return float(value)
71 except (TypeError, ValueError):
72 return None
75def _integer(value: Any) -> Optional[int]:
76 number = _number(value)
77 return None if number is None else int(number)
80def _scorer(value: Any) -> Optional[EvaluationEnum.Scorer]:
81 if isinstance(value, EvaluationEnum.Scorer):
82 return value
83 if not value:
84 return None
85 try:
86 return EvaluationEnum.Scorer(str(value))
87 except ValueError:
88 logger.warning("Batch recorded an unknown scorer %r", value)
89 return None
92def apply_summary(batch: ExperimentBatch, summary: Optional[dict]) -> None:
93 """Copy a finished batch's aggregate onto its reporting columns.
95 The blob stays too — it carries figures nothing filters on (token split,
96 scored count) and a reader wants those next to the ones that do.
98 A figure the summary does not carry is left as NULL rather than zeroed: a
99 report has to be able to tell "scored zero" from "never produced a score".
100 """
101 batch.summary = summary
102 if not isinstance(summary, dict):
103 return
104 batch.scorer = _scorer(summary.get("scorer"))
105 batch.mean_score = _number(summary.get(_SUMMARY_COLUMNS["mean_score"]))
106 batch.pass_rate = _number(summary.get(_SUMMARY_COLUMNS["pass_rate"]))
107 batch.total_cases = _integer(summary.get(_SUMMARY_COLUMNS["total_cases"]))
108 batch.errors = _integer(summary.get(_SUMMARY_COLUMNS["errors"]))
109 batch.mean_latency_ms = _integer(summary.get(_SUMMARY_COLUMNS["mean_latency_ms"]))
110 batch.total_tokens = _integer(summary.get(_SUMMARY_COLUMNS["total_tokens"]))
111 batch.duration_ms = _integer(summary.get(_SUMMARY_COLUMNS["duration_ms"]))
114def as_payload(batch: ExperimentBatch) -> dict[str, Any]:
115 """The API shape for one batch.
117 Matches what ``Experiment.config['batches']`` used to hold, so moving the
118 storage changed no contract. ``progress`` is nested for the same reason.
119 """
120 return {
121 "id": str(batch.id),
122 "label": batch.label,
123 "status": getattr(batch.status, "value", batch.status)
124 if batch.status
125 else None,
126 "created_at": utc_isoformat(batch.created_at) if batch.created_at else None,
127 "started_at": utc_isoformat(batch.started_at) if batch.started_at else None,
128 "finished_at": utc_isoformat(batch.finished_at) if batch.finished_at else None,
129 "variant_ids": batch.variant_ids or [],
130 "dataset_id": str(batch.dataset_id)
131 if getattr(batch, "dataset_id", None)
132 else None,
133 "dataset_version": getattr(batch, "dataset_version", None),
134 "evaluation_version": getattr(batch, "evaluation_version", None),
135 "regression": getattr(batch, "regression", None),
136 "config": batch.config or {},
137 "progress": {
138 "completed": batch.completed or 0,
139 "total": batch.total or 0,
140 },
141 "summary": batch.summary,
142 "leaderboard": batch.leaderboard,
143 "error": batch.error,
144 }
147# ── Lifecycle ─────────────────────────────────────────────────────────────────
150def create(
151 db: Session,
152 *,
153 experiment: Any = None,
154 variant_ids: list,
155 label: Optional[str] = None,
156 config_overrides: Optional[dict] = None,
157 dataset_id: Any = None,
158 dataset_version: Optional[int] = None,
159 evaluation_version: Optional[int] = None,
160 target_versions: Optional[dict] = None,
161 quick_try_owner_id: Any = None,
162 dataset_spec: Optional[dict] = None,
163 started_by_user_id: Any = None,
164) -> ExperimentBatch:
165 """Record a queued run and return it.
167 A run belongs to an ``experiment`` — the evaluation whose dataset, scorer
168 and variants it executes. ``dataset_id`` and the two versions say exactly
169 what was in force, and ``target_versions`` which revision of each agent it
170 ran, so a result resolves to the configuration that produced it. Or pass
171 no experiment and a ``quick_try_owner_id``: a Quick try is a
172 run with no evaluation yet, marked with who ran it so that only they can
173 save it (see ``quick_try.adopt``).
175 Commits: the background task that executes it runs in a different session
176 and has to be able to find it.
177 """
178 if experiment is None:
179 if not quick_try_owner_id:
180 raise ValueError(
181 "A run belongs to an experiment, unless it is a Quick try run by "
182 "a named user."
183 )
184 from app.services.evaluation import quick_try
186 batch = ExperimentBatch(
187 id=uuid4(),
188 experiment_id=None,
189 dataset_id=None,
190 label=label or quick_try.LABEL,
191 status=RunnableEnum.Status.queued,
192 variant_ids=[],
193 dataset=dataset_spec,
194 config={**(config_overrides or {}), **quick_try.marker(quick_try_owner_id)},
195 completed=0,
196 total=0,
197 created_at=aware_utcnow(),
198 )
199 db.add(batch)
200 db.commit()
201 return batch
202 existing = count_for(db, experiment.id)
203 batch = ExperimentBatch(
204 id=uuid4(),
205 experiment_id=experiment.id,
206 dataset_id=dataset_id
207 if dataset_id is not None
208 else getattr(experiment, "dataset_id", None),
209 dataset_version=dataset_version,
210 evaluation_version=evaluation_version,
211 target_versions=target_versions or None,
212 label=label or f"Run {existing + 1}",
213 status=RunnableEnum.Status.queued,
214 variant_ids=[str(v) for v in variant_ids],
215 dataset=dataset_spec,
216 config=config_overrides or {},
217 completed=0,
218 total=0,
219 created_at=aware_utcnow(),
220 started_by_user_id=started_by_user_id,
221 )
222 db.add(batch)
223 db.commit()
224 return batch
227def _owned_by(owner_id):
228 """Match the runs of one evaluation."""
229 return ExperimentBatch.experiment_id == owner_id
232def count_for(db: Session, owner_id) -> int:
233 """How many batches this experiment or dataset has had — the label's number.
235 Counted rather than taken from the list's length, which is what the JSON
236 array did: once the array was capped at twenty, batch twenty-one was
237 labelled "Run 21" only by accident and batch forty was labelled "Run 21"
238 again for real.
239 """
240 try:
241 return int(
242 db.query(func.count(ExperimentBatch.id))
243 .filter(_owned_by(owner_id))
244 .scalar()
245 or 0
246 )
247 except SQLAlchemyError:
248 logger.exception("Could not count batches for %s", owner_id)
249 return 0
252def get(db: Session, owner_id, batch_id) -> Optional[ExperimentBatch]:
253 """One batch, or None — including when ``batch_id`` is not a UUID at all.
255 Batch ids reach this from the URL, so a malformed one is a 404 rather than
256 an exception: it names a batch that does not exist, which is what 404 says.
257 """
258 try:
259 identifier = batch_id if isinstance(batch_id, UUID) else UUID(str(batch_id))
260 except (ValueError, AttributeError, TypeError):
261 return None
262 batch = db.get(ExperimentBatch, identifier)
263 if batch is None:
264 return None
265 if owner_id is None:
266 # No owner named resolves only an unowned batch — a Quick try — never
267 # somebody's evaluation run through the back door.
268 return batch if batch.experiment_id is None else None
269 if batch.experiment_id is None:
270 return None
271 return batch if str(batch.experiment_id) == str(owner_id) else None
274def list_for(db: Session, owner_id) -> list[ExperimentBatch]:
275 """An experiment's or dataset's batches, newest first."""
276 return (
277 db.query(ExperimentBatch)
278 .filter(_owned_by(owner_id))
279 .order_by(ExperimentBatch.created_at.desc(), ExperimentBatch.id.desc())
280 .all()
281 )
284def update(db: Session, owner_id, batch_id, **fields: Any) -> None:
285 """Merge ``fields`` into a batch row and commit.
287 Called from the background task on every progress tick, so it re-reads the
288 row rather than holding one: the request thread may have written a cancel
289 in between, and that write has to be the one that survives.
291 ``summary`` is routed through :func:`apply_summary` so the reporting columns
292 can never drift from the blob they are derived from.
293 """
294 batch = get(db, owner_id, batch_id)
295 if batch is None:
296 logger.warning("Batch %s not found on %s", batch_id, owner_id)
297 return
298 progress = fields.pop("progress", None)
299 # Distinguished from "not mentioned": clearing a summary is a real thing to
300 # ask for, and `pop`'s default cannot tell the two apart on its own.
301 has_summary = "summary" in fields
302 summary = fields.pop("summary", None)
303 for key, value in fields.items():
304 setattr(batch, key, value)
305 if isinstance(progress, dict):
306 batch.completed = _integer(progress.get("completed")) or 0
307 batch.total = _integer(progress.get("total")) or 0
308 if has_summary:
309 apply_summary(batch, summary)
310 db.commit()
313def is_cancelled(db: Session, owner_id, batch_id) -> bool:
314 """Re-read a batch's status so an in-flight cancel is noticed.
316 ``expire`` forces the next read to hit the database rather than the identity
317 map, which is what makes a cancel issued by the request thread visible to
318 the background thread running the matrix.
319 """
320 batch = get(db, owner_id, batch_id)
321 if batch is None:
322 return True
323 db.expire(batch, ["status"])
324 return batch.status == RunnableEnum.Status.cancelled
327def delete_for(db: Session, owner_id, batch_id=None) -> int:
328 """Delete an experiment's or dataset's batches — one, or all. No commit."""
329 query = db.query(ExperimentBatch).filter(_owned_by(owner_id))
330 if batch_id is not None:
331 try:
332 identifier = batch_id if isinstance(batch_id, UUID) else UUID(str(batch_id))
333 except (ValueError, AttributeError, TypeError):
334 return 0
335 query = query.filter(ExperimentBatch.id == identifier)
336 return int(query.delete(synchronize_session=False) or 0)
339# ── Cross-experiment reporting ────────────────────────────────────────────────
340#
341# The reason the table exists. Everything below asks questions that span
342# experiments, which is precisely what a JSON array on one experiment's row
343# could not answer.
346def _visible(db: Session, owner_filter, project_id=None):
347 """A subquery of the evaluation ids this report may include.
349 Scoping is by ownership, exactly as the resource lists are: a report that
350 reached across accounts would be a data leak wearing a chart.
351 """
352 query = db.query(Experiment.id).filter(owner_filter)
353 if project_id is not None:
354 query = query.filter(Experiment.owner_project_id == project_id)
355 return query
358def _owned_population(db: Session, owner_filter, project_id=None):
359 """Runs belonging to an evaluation the caller may see."""
360 return ExperimentBatch.experiment_id.in_(_visible(db, owner_filter, project_id))
363def runs_per_dataset_version(
364 db: Session, *, owner_filter, dataset_id
365) -> dict[Optional[int], int]:
366 """How many runs the caller can see asked each version of one dataset.
368 Every run, finished or not — the dataset page lists them as events.
369 """
370 rows = (
371 db.query(ExperimentBatch.dataset_version, func.count(ExperimentBatch.id))
372 .filter(
373 ExperimentBatch.dataset_id == dataset_id,
374 _owned_population(db, owner_filter),
375 )
376 .group_by(ExperimentBatch.dataset_version)
377 .all()
378 )
379 return {version: count for version, count in rows}
382def report(
383 db: Session,
384 *,
385 owner_filter,
386 project_id=None,
387 experiment_id=None,
388 dataset_id=None,
389 dataset_version: Optional[int] = None,
390 unversioned: bool = False,
391 scorer: Optional[str] = None,
392 since: Optional[datetime] = None,
393 max_mean_score: Optional[float] = None,
394 min_mean_score: Optional[float] = None,
395 limit: int = DEFAULT_REPORT_ROWS,
396 offset: int = 0,
397 include_unfinished: bool = False,
398) -> list[dict[str, Any]]:
399 """Completed batches across experiments, newest first, ``offset`` rows in.
401 Only completed batches by default: a queued batch has no figures and a
402 cancelled one has partial figures over whichever cells happened to finish,
403 so including either would put numbers in a report that do not mean what
404 they appear to. ``include_unfinished`` lifts that for the one reader that
405 wants every run *as an event* rather than as a figure — the activity feed,
406 where a failed or cancelled run is exactly the row that must not be
407 missing. Each row says its ``status`` so that reader can tell them apart.
409 Every filter is optional and every one is applied in SQL. The point of the
410 exercise is that "every batch in this project since Monday that scored below
411 0.7" is one query rather than a full load and a Python loop.
412 """
413 # The dataset is an outer join: a run records which dataset it asked as a
414 # soft reference, and a dataset deleted since still leaves the run on
415 # record — with its name blank rather than the row gone.
416 rows = (
417 db.query(ExperimentBatch, Experiment.name, TestSuite.name)
418 .join(Experiment, Experiment.id == ExperimentBatch.experiment_id)
419 .outerjoin(TestSuite, TestSuite.id == ExperimentBatch.dataset_id)
420 .filter(_owned_population(db, owner_filter, project_id))
421 )
422 if not include_unfinished:
423 rows = rows.filter(ExperimentBatch.status == RunnableEnum.Status.completed)
424 if experiment_id is not None:
425 rows = rows.filter(ExperimentBatch.experiment_id == experiment_id)
426 if dataset_id is not None:
427 rows = rows.filter(ExperimentBatch.dataset_id == dataset_id)
428 if dataset_version is not None:
429 rows = rows.filter(ExperimentBatch.dataset_version == dataset_version)
430 elif unversioned:
431 rows = rows.filter(ExperimentBatch.dataset_version.is_(None))
432 if scorer is not None:
433 member = _scorer(scorer)
434 if member is None:
435 # An unknown scorer matches nothing rather than everything: a
436 # filter that silently stopped filtering would misreport.
437 return []
438 rows = rows.filter(ExperimentBatch.scorer == member)
439 if since is not None:
440 rows = rows.filter(ExperimentBatch.created_at >= since)
441 if min_mean_score is not None:
442 rows = rows.filter(ExperimentBatch.mean_score >= min_mean_score)
443 if max_mean_score is not None:
444 # Unscored batches are excluded rather than treated as zero — "below
445 # 0.7" is a question about scores, and a batch with none has no answer.
446 rows = rows.filter(
447 ExperimentBatch.mean_score.isnot(None),
448 ExperimentBatch.mean_score <= max_mean_score,
449 )
451 rows = (
452 rows.order_by(ExperimentBatch.created_at.desc(), ExperimentBatch.id.desc())
453 .offset(max(0, int(offset or 0)))
454 .limit(max(1, min(int(limit or DEFAULT_REPORT_ROWS), MAX_REPORT_ROWS)))
455 )
457 return [
458 {
459 "batch_id": str(batch.id),
460 "experiment_id": str(batch.experiment_id),
461 "experiment_name": experiment_name,
462 "dataset_id": str(batch.dataset_id) if batch.dataset_id else None,
463 "dataset_name": dataset_name,
464 "dataset_version": batch.dataset_version,
465 "label": batch.label,
466 "regression_verdict": getattr(batch, "regression_verdict", None),
467 "status": getattr(batch.status, "value", batch.status)
468 if batch.status
469 else None,
470 "error": batch.error,
471 "scorer": batch.scorer.value if batch.scorer else None,
472 "mean_score": batch.mean_score,
473 "pass_rate": batch.pass_rate,
474 "total_cases": batch.total_cases,
475 "errors": batch.errors,
476 "mean_latency_ms": batch.mean_latency_ms,
477 "total_tokens": batch.total_tokens,
478 "duration_ms": batch.duration_ms,
479 "variants": len(batch.variant_ids or []),
480 "finished_at": utc_isoformat(batch.finished_at)
481 if batch.finished_at
482 else None,
483 "created_at": utc_isoformat(batch.created_at) if batch.created_at else None,
484 }
485 for batch, experiment_name, dataset_name in rows.all()
486 ]
489def totals(
490 db: Session,
491 *,
492 owner_filter,
493 project_id=None,
494 since: Optional[datetime] = None,
495) -> dict[str, Any]:
496 """One row of headline figures over the same population ``report`` lists.
498 Aggregated in SQL rather than over the listed page, so the totals describe
499 every matching batch and not just the fifty most recent — a summary that
500 silently covered only what fitted on screen would be worse than none.
501 """
502 window = since or (aware_utcnow() - timedelta(days=DEFAULT_REPORT_DAYS))
503 try:
504 row = (
505 db.query(
506 func.count(ExperimentBatch.id),
507 func.count(func.distinct(ExperimentBatch.experiment_id)),
508 func.avg(ExperimentBatch.mean_score),
509 func.sum(ExperimentBatch.total_cases),
510 func.sum(ExperimentBatch.errors),
511 func.sum(ExperimentBatch.total_tokens),
512 )
513 .filter(
514 ExperimentBatch.status == RunnableEnum.Status.completed,
515 ExperimentBatch.created_at >= window,
516 _owned_population(db, owner_filter, project_id),
517 )
518 .one()
519 )
520 except SQLAlchemyError:
521 logger.exception("Could not aggregate the batch report")
522 row = (0, 0, None, 0, 0, 0)
524 batches, experiments, mean_score, cases, errors, tokens = row
525 return {
526 "since": utc_isoformat(window),
527 "batches": int(batches or 0),
528 "experiments": int(experiments or 0),
529 # Averaged over batches, not over cases: each batch is one measurement
530 # of one configuration, and weighting by case count would let a large
531 # dataset speak for an experiment that was only run once.
532 "mean_score": round(float(mean_score), 4) if mean_score is not None else None,
533 "cases": int(cases or 0),
534 "errors": int(errors or 0),
535 "total_tokens": int(tokens or 0),
536 }
539def cost_per_answer(board: Any, variant_id: Any = None) -> Optional[float]:
540 """What one answer cost a variant in a run, from its stored leaderboard
541 (``runner._variant_cost``: its answers only, the grading left out) — the named
542 variant's, or with none named the run's first. None when it could not
543 be priced, or the run kept no leaderboard."""
544 rows = [r for r in board or [] if isinstance(r, dict)]
545 if variant_id is not None:
546 rows = [r for r in rows if str(r.get("variant_id")) == str(variant_id)]
547 cost = rows[0].get("cost_per_case_usd") if rows else None
548 return float(cost) if isinstance(cost, (int, float)) else None