Coverage for app / router / app / evaluations / router.py: 85%
803 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
1from datetime import datetime, timedelta
2from typing import Any, Optional
3from uuid import UUID
5from fastapi import (
6 APIRouter,
7 BackgroundTasks,
8 Depends,
9 HTTPException,
10 Query,
11 status,
12)
13from sqlalchemy import func
14from sqlalchemy.exc import IntegrityError, SQLAlchemyError
15from sqlalchemy.orm import Session
17from app.dependency.base import get_db
18from app.dependency.workspace import owner_for, requested_workspace
19from app.dependency.user.context import get_current_user
20from app.dependency.resource_access import (
21 annotated,
22 scoped,
23 list_scope,
24 verify_resource_access,
25 verify_resource_read,
26 verify_owner_scope,
27)
28from app.db.postgres.enums import EvaluationEnum, HistoryEnum, RunnableEnum
29from app.db.postgres.models import (
30 Agent,
31 Experiment,
32 ExperimentBatch,
33 ExperimentVariant,
34 ExperimentRun,
35 TestSuite,
36 TestCase,
37 User,
38)
39from app.db.postgres.crud_schemas import Schema
40from app.router.app.history.router import register_history_routes
41from app.services import history as history_service
42from app.util.time import aware_utcnow, utc_isoformat
43from app.router.app.evaluations.schemas import (
44 CompareRequest,
45 EvaluateAgentRequest,
46 EvaluateAgentStarted,
47 ImportCasesRequest,
48 ImportCasesResult,
49 PresetRequest,
50 OptimiseRequest,
51 PromoteRequest,
52 RunExperimentRequest,
53 ScorerCatalogue,
54)
55from app.services.evaluation import assurance as assurance_service
56from app.services.evaluation import benchmark as benchmark_service
57from app.services.evaluation import batches as batch_store
58from app.services.evaluation import context as context_service
59from app.services.evaluation import best as best_service
60from app.services.evaluation import dataset_versions
61from app.services.evaluation import presets as preset_service
62from app.services.evaluation import optimiser, promotion, quick_try, regression, runner
63from app.services.evaluation import scorers as scoring
64from app.services.evaluation import targets as target_service
65from app.services.evaluation.dataset import (
66 DatasetError,
67 cases_from_dataset,
68 parse_import_report,
69)
70from app.services.evaluation.targets import (
71 ModelTarget,
72 TargetResolutionError,
73 build_target,
74)
76import logging
78logger = logging.getLogger(__name__)
80evaluation_router = APIRouter(prefix="/evaluations", tags=["App - Evaluations"])
83@evaluation_router.get("")
84def list_evaluations(
85 db: Session = Depends(get_db),
86 current_user: User = Depends(get_current_user),
87):
88 # In the request's workspace, as the lists these count are.
89 experiment_count = (
90 db.query(Experiment)
91 .filter(
92 _report_scope(db, current_user, None, None, workspace=requested_workspace())
93 )
94 .count()
95 )
96 suite_count = (
97 db.query(TestSuite)
98 .filter(
99 _report_scope(
100 db,
101 current_user,
102 None,
103 None,
104 workspace=requested_workspace(),
105 model=TestSuite,
106 )
107 )
108 .count()
109 )
110 return {"experiments": experiment_count, "test_suites": suite_count}
113# ── Experiments ──────────────────────────────────────────────────────────────
116@evaluation_router.get("/experiments", response_model=list[Schema.Experiment.Read])
117def list_experiments(
118 workspace: Optional[str] = None,
119 owner_organisation_id: Optional[UUID] = None,
120 owner_project_id: Optional[UUID] = None,
121 db: Session = Depends(get_db),
122 current_user: User = Depends(get_current_user),
123):
124 where, ws = scoped(
125 Experiment,
126 current_user,
127 db,
128 workspace=workspace,
129 owner_organisation_id=owner_organisation_id,
130 owner_project_id=owner_project_id,
131 include_system=False,
132 )
133 query = db.query(Experiment).filter(where)
134 return annotated(query.order_by(Experiment.created_at.desc()).all(), ws)
137@evaluation_router.get(
138 "/experiments/{experiment_id}", response_model=Schema.Experiment.Read
139)
140def get_experiment(
141 experiment_id: UUID,
142 db: Session = Depends(get_db),
143 current_user: User = Depends(get_current_user),
144):
145 return _get_experiment(db, experiment_id, current_user, read=True)
148def experiment_children_snapshot(db: Session, experiment_id: UUID) -> dict:
149 """An experiment's current variants, for its version's
150 ``children_snapshot``.
152 Variants are where an experiment's substance lives — including the
153 optimiser's generated candidates — so a version that did not capture them
154 would diff as "nothing changed" across a whole prompt search.
155 """
156 variants = [
157 {"variant_id": str(row.id), "name": row.name}
158 for row in db.query(ExperimentVariant)
159 .filter(ExperimentVariant.experiment_id == experiment_id)
160 .all()
161 ]
162 return {"variants": variants}
165def suite_children_snapshot(db: Session, suite_id: UUID) -> dict:
166 """A dataset's current cases in full, for its version's
167 ``children_snapshot`` — so an older version can be read back."""
168 return dataset_versions.case_snapshot(db, suite_id)
171def _record_experiment_version(
172 db: Session, experiment: Experiment, action: HistoryEnum.Action, actor: User
173) -> None:
174 """One version row for an experiment, variants included.
176 Called for the experiment's own edits *and* for every variant mutation:
177 a variant is the substance of an evaluation, so adding, rewording or
178 removing one is a change to the evaluation and belongs on its trail. The
179 version's ``children_snapshot`` is what the diff reads it from.
180 """
181 history_service.record_version(
182 db,
183 resource_type=HistoryEnum.ResourceType.experiment,
184 model=Experiment,
185 resource=experiment,
186 action=action,
187 actor=actor,
188 children_resolver=lambda: experiment_children_snapshot(db, experiment.id),
189 )
192def _record_suite_version(
193 db: Session, suite: TestSuite, action: HistoryEnum.Action, actor: User
194) -> None:
195 """One version row for a dataset, cases included — see
196 :func:`_record_experiment_version` for why case edits land here."""
197 dataset_versions.record_suite_version(db, suite, action, actor)
200#: How an experiment grades. Fixed once it has runs — see
201#: ``_refuse_redefining_measurement``. Its dataset is fixed from creation:
202#: an experiment is a child of its dataset (see ``update_experiment``).
203MEASUREMENT_FIELDS = ("scorer", "scorer_config", "judge")
206def _measurement_lock(db: Session, experiment: Experiment) -> Optional[str]:
207 """Why this evaluation's dataset and scoring are fixed, or ``None``.
209 An evaluation is "these questions, graded this way"; its runs are the
210 time series and its variants are the thing meant to vary. Changing what
211 it asks or how it grades after a run exists does not edit the
212 evaluation — it silently turns it into a different one whose history
213 spans two measurements, and leaves the leaderboard, the Reports rows and
214 the regression baseline mixing runs that measured different things.
216 A failed or cancelled run does not lock anything: it measured nothing.
217 """
218 try:
219 rows = (
220 db.query(ExperimentBatch.status)
221 .filter(ExperimentBatch.experiment_id == experiment.id)
222 .all()
223 )
224 except SQLAlchemyError:
225 logger.exception("Could not read runs for experiment %s", experiment.id)
226 # Failing open would let the very edit this exists to prevent through
227 # on a transient database error.
228 return "This experiment's runs could not be read, so its scoring cannot be changed right now."
230 statuses = {getattr(r[0], "value", r[0]) for r in rows}
231 if RunnableEnum.Status.completed.value in statuses:
232 return (
233 "This experiment has already been run, so its scoring is fixed — "
234 "changing it would make its runs measure different things. Start a "
235 "new experiment on the dataset to grade another way."
236 )
237 active = {RunnableEnum.Status.queued.value, RunnableEnum.Status.running.value}
238 if statuses & active:
239 return (
240 "A run of this experiment is in progress. Wait for it to finish or "
241 "cancel it before changing the scoring."
242 )
243 return None
246def _refuse_redefining_measurement(
247 db: Session, experiment: Experiment, changes: dict
248) -> None:
249 """409 when a patch would change what a run-bearing evaluation measures.
251 The lock lives here rather than only in the workbench: a read-only
252 control is a presentation choice, and this is an invariant the reports
253 and the regression baseline depend on.
254 """
255 touched = [
256 field
257 for field in MEASUREMENT_FIELDS
258 if field in changes and changes[field] != getattr(experiment, field, None)
259 ]
260 if not touched:
261 return
262 reason = _measurement_lock(db, experiment)
263 if reason:
264 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=reason)
267def _refuse_label_in_scorer(scorer_config: Optional[dict]) -> None:
268 """Refuse scorer settings that say what is correct (422).
270 Criteria and checks are the dataset's — a scorer that carried them would
271 let two experiments over one dataset grade it against two ideas of a
272 right answer. Refused rather than dropped, so a client still sending them
273 learns where they went instead of watching them vanish.
274 """
275 keys = scoring.label_keys_in(scorer_config)
276 if keys:
277 raise HTTPException(
278 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
279 detail=(
280 f"Scorer settings cannot say what is correct ({', '.join(keys)}). "
281 "Put criteria on the dataset or its cases, and checks on each case."
282 ),
283 )
286def _refuse_unusable_judge(db: Session, spec: Optional[dict]) -> None:
287 """Reject a judge model that does not resolve, at write time.
289 A judge spec naming a model that is gone falls back to the platform
290 default at run time and logs a warning nobody reads, so the evaluation
291 looks like it grades with the model on its page and does not. Same
292 reasoning as a rule whose ``scope_id`` resolves to nothing: a setting
293 that silently means something else is worse than a refused save.
294 """
295 if not spec:
296 return
297 try:
298 target = build_target(target_service.judge_spec(spec), db)
299 except TargetResolutionError as exc:
300 raise HTTPException(
301 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
302 detail=f"Judge model unusable: {exc}",
303 ) from exc
304 if not isinstance(target, ModelTarget):
305 raise HTTPException(
306 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
307 detail="A judge must be a model, not an agent.",
308 )
311@evaluation_router.post(
312 "/experiments",
313 status_code=status.HTTP_201_CREATED,
314 response_model=Schema.Experiment.Read,
315)
316def create_experiment(
317 data: Schema.Experiment.Create,
318 db: Session = Depends(get_db),
319 current_user: User = Depends(get_current_user),
320):
321 """Create an evaluation: one dataset, one scorer, its variants.
323 The dataset comes from exactly one of three places — an existing
324 ``dataset_id``, inline ``cases`` that make a dataset of the same name
325 alongside, or a Quick try ``comparison_id`` whose case, scorer and
326 variants are derived from what actually ran and whose results become the
327 first run. Everything lands in one transaction, so a failure cannot leave
328 half an evaluation behind, and the created version already lists its
329 variants.
331 ``response_model`` is not decoration. The session expires every attribute
332 on commit, and a row returned bare after the version commit serialised as
333 ``{}`` — the client got a 201 with no id and built its next request on
334 ``undefined``. The schema reads the columns back explicitly.
335 """
336 payload = data.model_dump()
337 variants = payload.pop("variants", None) or []
338 cases = payload.pop("cases", None)
339 comparison_id = payload.pop("comparison_id", None)
340 dataset_id = payload.pop("dataset_id", None)
341 if not payload.get("owner_organisation_id") and not payload.get("owner_project_id"):
342 # The workspace the request was made in (app/dependency/workspace.py).
343 payload.update(owner_for(db, current_user, model=Experiment))
344 verify_owner_scope(payload, current_user, db, model=Experiment)
345 owner = {
346 key: payload.get(key)
347 for key in ("owner_user_id", "owner_organisation_id", "owner_project_id")
348 }
350 sources = [x for x in (dataset_id, cases, comparison_id) if x is not None]
351 if len(sources) != 1:
352 raise HTTPException(
353 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
354 detail=(
355 "An evaluation needs exactly one source of cases: 'dataset_id', "
356 "inline 'cases', or a Quick try 'comparison_id'."
357 ),
358 )
359 if comparison_id is not None and variants:
360 raise HTTPException(
361 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
362 detail="Pass either 'comparison_id' or 'variants', not both.",
363 )
364 if cases is not None and not cases:
365 raise HTTPException(
366 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
367 detail="'cases' must hold at least one case.",
368 )
370 _refuse_duplicate_name(
371 db, Experiment, "experiment", name=payload.get("name"), **owner
372 )
373 _refuse_label_in_scorer(payload.get("scorer_config"))
374 _refuse_unusable_judge(db, payload.get("judge"))
376 comparison = None
377 if comparison_id is not None:
378 try:
379 comparison = quick_try.get_for_adoption(db, comparison_id, current_user.id)
380 except quick_try.QuickTryError as exc:
381 raise HTTPException(status_code=exc.status, detail=str(exc)) from exc
382 # The comparison graded its cells one way; the evaluation grades the
383 # same way, or its first run would not be a run of it.
384 scorer, scorer_config, judge = quick_try.scorer_of(comparison)
385 payload["scorer"] = scorer
386 payload["scorer_config"] = scorer_config or None
387 payload["judge"] = judge
388 elif dataset_id is not None:
389 dataset = db.get(TestSuite, dataset_id)
390 if dataset is None:
391 raise HTTPException(
392 status_code=status.HTTP_404_NOT_FOUND, detail="Dataset not found"
393 )
394 # A reference is a read: anyone may run an experiment on a gold
395 # dataset. The experiment is theirs; the dataset stays the platform's.
396 verify_resource_read(dataset, current_user, db)
398 try:
399 if comparison is not None:
400 rows = quick_try.runs_of(db, comparison)
401 dataset = quick_try.dataset_for(
402 db, comparison, rows, name=payload["name"], owner=owner
403 )
404 # A dataset like any other: it has an edit history from birth,
405 # and the adopted run asked its first version.
406 _record_suite_version(db, dataset, HistoryEnum.Action.created, current_user)
407 db.flush()
408 comparison.dataset_version = dataset_versions.current_content_version(
409 db, dataset.id
410 )
411 dataset_id = dataset.id
412 elif cases is not None:
413 dataset = TestSuite(
414 name=f"{payload['name']} cases",
415 description="Created with the evaluation.",
416 status=EvaluationEnum.Status.active,
417 **owner,
418 )
419 db.add(dataset)
420 db.flush()
421 for spec in cases:
422 db.add(TestCase(**{**spec, "test_suite_id": dataset.id}))
423 db.flush()
424 _record_suite_version(db, dataset, HistoryEnum.Action.created, current_user)
425 dataset_id = dataset.id
427 experiment = Experiment(**{**payload, "dataset_id": dataset_id})
428 db.add(experiment)
429 db.flush()
430 for spec in variants:
431 db.add(ExperimentVariant(**{**spec, "experiment_id": experiment.id}))
432 if comparison is not None:
433 quick_try.adopt(db, comparison, experiment)
434 db.flush()
435 _record_experiment_version(
436 db, experiment, HistoryEnum.Action.created, current_user
437 )
438 if comparison is not None:
439 # First run, so the verdict is "no baseline" — stamped anyway, so
440 # the adopted batch carries everything a run of its own would.
441 regression.annotate_batch(db, comparison, owner_config=experiment.config)
442 db.commit()
443 db.refresh(experiment)
444 return experiment
445 except IntegrityError as exc:
446 db.rollback()
447 raise _name_conflict(exc, "experiment", data.name) from exc
448 except Exception:
449 db.rollback()
450 logger.exception("Failed to create experiment")
451 raise
454@evaluation_router.patch(
455 "/experiments/{experiment_id}", response_model=Schema.Experiment.Read
456)
457def update_experiment(
458 experiment_id: UUID,
459 data: Schema.Experiment.Update,
460 db: Session = Depends(get_db),
461 current_user: User = Depends(get_current_user),
462):
463 experiment = _get_experiment(db, experiment_id, current_user)
464 if data.name is not None and data.name != experiment.name:
465 _refuse_duplicate_name(
466 db,
467 Experiment,
468 "experiment",
469 name=data.name,
470 owner_user_id=experiment.owner_user_id,
471 owner_organisation_id=experiment.owner_organisation_id,
472 owner_project_id=experiment.owner_project_id,
473 exclude_id=experiment.id,
474 )
476 changes = data.model_dump(exclude_unset=True)
477 # An experiment is a child of its dataset: it asks those questions for
478 # life, its runs are that dataset's runs, and its baseline assumes it.
479 # Moving it would carry a history measured on one dataset onto another.
480 # Something new on different questions is a new experiment there.
481 if "dataset_id" in changes and changes["dataset_id"] != experiment.dataset_id:
482 raise HTTPException(
483 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
484 detail=(
485 "An experiment belongs to its dataset and cannot move to "
486 "another. Start a new experiment on the other dataset."
487 ),
488 )
489 _refuse_label_in_scorer(changes.get("scorer_config"))
490 _refuse_redefining_measurement(db, experiment, changes)
491 if "judge" in changes:
492 _refuse_unusable_judge(db, changes["judge"])
493 for field, value in changes.items():
494 setattr(experiment, field, value)
495 _record_experiment_version(db, experiment, HistoryEnum.Action.updated, current_user)
496 try:
497 db.commit()
498 db.refresh(experiment)
499 return experiment
500 except IntegrityError as exc:
501 db.rollback()
502 raise _name_conflict(exc, "experiment", data.name) from exc
503 except Exception:
504 db.rollback()
505 logger.exception("Failed to update experiment")
506 raise
509@evaluation_router.delete(
510 "/experiments/{experiment_id}", status_code=status.HTTP_204_NO_CONTENT
511)
512def delete_experiment(
513 experiment_id: UUID,
514 db: Session = Depends(get_db),
515 current_user: User = Depends(get_current_user),
516):
517 experiment = _get_experiment(db, experiment_id, current_user)
518 _record_experiment_version(db, experiment, HistoryEnum.Action.deleted, current_user)
519 db.delete(experiment)
520 db.commit()
523# ── Experiment Variants ───────────────────────────────────────────────────────
524#
525# Every variant endpoint resolves the experiment first: a variant id is not a
526# capability, and the experiment's access check is the only one there is.
529@evaluation_router.get(
530 "/experiments/{experiment_id}/variants",
531 response_model=list[Schema.ExperimentVariant.Read],
532)
533def list_variants(
534 experiment_id: UUID,
535 db: Session = Depends(get_db),
536 current_user: User = Depends(get_current_user),
537):
538 _get_experiment(db, experiment_id, current_user, read=True)
539 return (
540 db.query(ExperimentVariant)
541 .filter(ExperimentVariant.experiment_id == experiment_id)
542 .order_by(ExperimentVariant.created_at)
543 .all()
544 )
547@evaluation_router.post(
548 "/experiments/{experiment_id}/variants",
549 status_code=status.HTTP_201_CREATED,
550 response_model=Schema.ExperimentVariant.Read,
551)
552def create_variant(
553 experiment_id: UUID,
554 data: Schema.ExperimentVariant.Create,
555 db: Session = Depends(get_db),
556 current_user: User = Depends(get_current_user),
557):
558 experiment = _get_experiment(db, experiment_id, current_user)
559 variant = ExperimentVariant(**{**data.model_dump(), "experiment_id": experiment_id})
560 try:
561 db.add(variant)
562 db.flush()
563 _record_experiment_version(
564 db, experiment, HistoryEnum.Action.updated, current_user
565 )
566 db.commit()
567 db.refresh(variant)
568 return variant
569 except Exception:
570 db.rollback()
571 logger.exception("Failed to create experiment variant")
572 raise
575@evaluation_router.get("/presets", summary="The variant presets and what each takes")
576def list_presets():
577 """Every preset, with its parameters — the whole of the preset form.
579 A registry like the scorers: the form holds no list of presets, so a new
580 one is a class in ``services/evaluation/presets.py`` and nothing else.
581 """
582 return {
583 "presets": preset_service.preset_catalogue(),
584 "max_variants": preset_service.MAX_PRESET_VARIANTS,
585 }
588def _swarm_budget(db: Session, drafts: list) -> float:
589 """What the new swarm variants may spend on one case between them: each
590 its budget a case, else its swarm's default."""
591 from app.db.postgres.models import Swarm
592 from app.services.swarms import engine as swarm_engine
594 total = 0.0
595 for draft in drafts:
596 target = (draft.config or {}).get("target") or {}
597 if target.get("type") != "swarm":
598 continue
599 if target.get("budget_usd") is not None:
600 total += float(target["budget_usd"])
601 continue
602 swarm = db.get(Swarm, UUID(str(target["swarm_id"])))
603 defaults, _ = swarm_engine.read_defaults(getattr(swarm, "defaults", None) or {})
604 total += float(defaults["budget_usd"])
605 return round(total, 2)
608@evaluation_router.post(
609 "/experiments/{experiment_id}/presets/{preset_key}",
610 summary="Preview, or add, the variants a preset makes",
611)
612def apply_preset(
613 experiment_id: UUID,
614 preset_key: str,
615 data: PresetRequest,
616 db: Session = Depends(get_db),
617 current_user: User = Depends(get_current_user),
618):
619 """Expand a preset into variants, and say what a run would then cost.
621 ``dry_run`` (the default) writes nothing: it answers the variants that
622 would be made and the calls a run of the experiment would then make, so
623 the cost is read before it is committed to. Otherwise the variants are
624 written in one transaction with one version of the experiment — a preset
625 is one edit, not twelve.
627 Every id is checked before anything is written — models exist, agents are
628 the caller's to use, knowledge is reachable from the experiment's owner —
629 and a setting the model would silently drop is refused with the reason.
630 """
631 experiment = _get_experiment(db, experiment_id, current_user)
633 def can_use_agent(agent: Any) -> bool:
634 try:
635 verify_resource_read(agent, current_user, db)
636 except HTTPException:
637 return False
638 return True
640 ctx = preset_service.PresetContext(
641 db=db,
642 owner=experiment,
643 can_use_agent=can_use_agent,
644 # The same read check as an agent: a swarm the caller may read.
645 can_use_swarm=can_use_agent,
646 )
647 try:
648 drafts = preset_service.expand_preset(preset_key, data.params, ctx)
649 except preset_service.PresetError as exc:
650 raise HTTPException(
651 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
652 ) from exc
654 existing = (
655 db.query(ExperimentVariant)
656 .filter(ExperimentVariant.experiment_id == experiment_id)
657 .count()
658 )
659 cases = (
660 db.query(TestCase)
661 .filter(TestCase.test_suite_id == experiment.dataset_id)
662 .count()
663 )
664 variants_after = existing + len(drafts)
665 answers = variants_after * cases
666 judged = runner.scoring_config(experiment)["scorer"] == "llm"
667 calls = {
668 "new_variants": len(drafts),
669 "variants_after": variants_after,
670 "cases": cases,
671 # One run of the experiment once these are added: every variant
672 # answers every case, and an LLM judge grades each answer.
673 "answers_per_run": answers,
674 "judge_calls_per_run": answers if judged else 0,
675 # A swarm variant runs a whole swarm a case: the most it may spend
676 # is its budget a case, every case.
677 "swarm_budget_per_run_usd": _swarm_budget(db, drafts) * cases,
678 }
679 if data.dry_run:
680 return {"variants": [d.as_json() for d in drafts], "calls": calls}
682 try:
683 created = []
684 for draft in drafts:
685 variant = ExperimentVariant(
686 experiment_id=experiment_id,
687 name=draft.name,
688 prompt=draft.prompt,
689 config=draft.config,
690 )
691 db.add(variant)
692 created.append(variant)
693 db.flush()
694 _record_experiment_version(
695 db, experiment, HistoryEnum.Action.updated, current_user
696 )
697 db.commit()
698 except Exception:
699 db.rollback()
700 logger.exception(
701 "Failed to apply preset %s to experiment %s", preset_key, experiment_id
702 )
703 raise
704 for variant in created:
705 db.refresh(variant)
706 return {
707 "variants": [
708 Schema.ExperimentVariant.Read.model_validate(v).model_dump(mode="json")
709 for v in created
710 ],
711 "calls": calls,
712 }
715def _get_variant(
716 db: Session, experiment_id: UUID, variant_id: UUID
717) -> ExperimentVariant:
718 variant = db.get(ExperimentVariant, variant_id)
719 if not variant or variant.experiment_id != experiment_id:
720 raise HTTPException(
721 status_code=status.HTTP_404_NOT_FOUND, detail="Variant not found"
722 )
723 return variant
726@evaluation_router.patch(
727 "/experiments/{experiment_id}/variants/{variant_id}",
728 response_model=Schema.ExperimentVariant.Read,
729)
730def update_variant(
731 experiment_id: UUID,
732 variant_id: UUID,
733 data: Schema.ExperimentVariant.Update,
734 db: Session = Depends(get_db),
735 current_user: User = Depends(get_current_user),
736):
737 experiment = _get_experiment(db, experiment_id, current_user)
738 variant = _get_variant(db, experiment_id, variant_id)
740 for field, value in data.model_dump(exclude_unset=True).items():
741 setattr(variant, field, value)
742 _record_experiment_version(db, experiment, HistoryEnum.Action.updated, current_user)
743 try:
744 db.commit()
745 db.refresh(variant)
746 return variant
747 except Exception:
748 db.rollback()
749 logger.exception("Failed to update variant")
750 raise
753@evaluation_router.delete(
754 "/experiments/{experiment_id}/variants/{variant_id}",
755 status_code=status.HTTP_204_NO_CONTENT,
756)
757def delete_variant(
758 experiment_id: UUID,
759 variant_id: UUID,
760 db: Session = Depends(get_db),
761 current_user: User = Depends(get_current_user),
762):
763 experiment = _get_experiment(db, experiment_id, current_user)
764 variant = _get_variant(db, experiment_id, variant_id)
765 db.delete(variant)
766 db.flush()
767 _record_experiment_version(db, experiment, HistoryEnum.Action.updated, current_user)
768 db.commit()
771# ── Experiment Runs ───────────────────────────────────────────────────────────
772#
773# Read-only. Cells are written by ``runner.execute_batch`` and nothing else, so
774# every row here traces to a batch, a target and a case. There used to be a
775# ``POST .../runs`` that inserted a bare row on request; it was reachable by no
776# client and would have put a score on record that no invocation produced.
779@evaluation_router.get(
780 "/experiments/{experiment_id}/runs",
781 response_model=list[Schema.ExperimentRun.Read],
782)
783def list_experiment_runs(
784 experiment_id: UUID,
785 db: Session = Depends(get_db),
786 current_user: User = Depends(get_current_user),
787):
788 _get_experiment(db, experiment_id, current_user, read=True)
789 return (
790 db.query(ExperimentRun)
791 .filter(ExperimentRun.experiment_id == experiment_id)
792 .order_by(ExperimentRun.created_at.desc())
793 .all()
794 )
797# ── Test Suites ───────────────────────────────────────────────────────────────
800@evaluation_router.get("/test-suites", response_model=list[Schema.TestSuite.Read])
801def list_test_suites(
802 workspace: Optional[str] = None,
803 owner_organisation_id: Optional[UUID] = None,
804 owner_project_id: Optional[UUID] = None,
805 include_system: bool = False,
806 db: Session = Depends(get_db),
807 current_user: User = Depends(get_current_user),
808):
809 """The caller's datasets, or an organisation's or project's.
811 ``include_system`` adds the gold datasets to the personal listing — the
812 Datasets page's Built-in section and the pickers that choose a dataset.
813 Opt-in, so every count built on this listing stays the user's own unless
814 the caller asks otherwise (the pattern skillsets and knowledge follow).
815 """
816 where, ws = scoped(
817 TestSuite,
818 current_user,
819 db,
820 workspace=workspace,
821 owner_organisation_id=owner_organisation_id,
822 owner_project_id=owner_project_id,
823 include_system=include_system,
824 )
825 query = db.query(TestSuite).filter(where)
826 suites = annotated(query.order_by(TestSuite.created_at.desc()).all(), ws)
827 counts = _case_counts(db, [suite.id for suite in suites])
828 for suite in suites:
829 suite.case_count = counts.get(suite.id, 0)
830 return suites
833def _case_counts(db: Session, suite_ids: list[UUID]) -> dict[UUID, int]:
834 """How many cases each dataset holds, in one grouped query."""
835 if not suite_ids:
836 return {}
837 rows = (
838 db.query(TestCase.test_suite_id, func.count(TestCase.id))
839 .filter(TestCase.test_suite_id.in_(suite_ids))
840 .group_by(TestCase.test_suite_id)
841 .all()
842 )
843 return {suite_id: int(count) for suite_id, count in rows}
846@evaluation_router.get("/test-suites/{suite_id}", response_model=Schema.TestSuite.Read)
847def get_test_suite(
848 suite_id: UUID,
849 db: Session = Depends(get_db),
850 current_user: User = Depends(get_current_user),
851):
852 suite = _get_suite(db, suite_id, current_user, read=True)
853 suite.case_count = _case_counts(db, [suite.id]).get(suite.id, 0)
854 return suite
857@evaluation_router.post(
858 "/test-suites",
859 status_code=status.HTTP_201_CREATED,
860 response_model=Schema.TestSuite.Read,
861)
862def create_test_suite(
863 data: Schema.TestSuite.Create,
864 db: Session = Depends(get_db),
865 current_user: User = Depends(get_current_user),
866):
867 payload = data.model_dump()
868 if not payload.get("owner_organisation_id") and not payload.get("owner_project_id"):
869 # The workspace the request was made in (app/dependency/workspace.py).
870 payload.update(owner_for(db, current_user, model=TestSuite))
871 verify_owner_scope(payload, current_user, db, model=TestSuite)
873 _refuse_duplicate_name(
874 db,
875 TestSuite,
876 "dataset",
877 name=payload.get("name"),
878 owner_user_id=payload.get("owner_user_id"),
879 owner_organisation_id=payload.get("owner_organisation_id"),
880 owner_project_id=payload.get("owner_project_id"),
881 )
882 suite = TestSuite(**payload)
883 try:
884 db.add(suite)
885 db.flush()
886 _record_suite_version(db, suite, HistoryEnum.Action.created, current_user)
887 db.commit()
888 db.refresh(suite)
889 return suite
890 except IntegrityError as exc:
891 db.rollback()
892 raise _name_conflict(exc, "dataset", data.name) from exc
893 except Exception:
894 db.rollback()
895 logger.exception("Failed to create test suite")
896 raise
899@evaluation_router.patch(
900 "/test-suites/{suite_id}", response_model=Schema.TestSuite.Read
901)
902def update_test_suite(
903 suite_id: UUID,
904 data: Schema.TestSuite.Update,
905 db: Session = Depends(get_db),
906 current_user: User = Depends(get_current_user),
907):
908 suite = _get_suite(db, suite_id, current_user)
909 if data.name is not None and data.name != suite.name:
910 _refuse_duplicate_name(
911 db,
912 TestSuite,
913 "dataset",
914 name=data.name,
915 owner_user_id=suite.owner_user_id,
916 owner_organisation_id=suite.owner_organisation_id,
917 owner_project_id=suite.owner_project_id,
918 exclude_id=suite.id,
919 )
921 for field, value in data.model_dump(exclude_unset=True).items():
922 setattr(suite, field, value)
923 _record_suite_version(db, suite, HistoryEnum.Action.updated, current_user)
924 try:
925 db.commit()
926 db.refresh(suite)
927 return suite
928 except IntegrityError as exc:
929 db.rollback()
930 raise _name_conflict(exc, "dataset", data.name) from exc
931 except Exception:
932 db.rollback()
933 logger.exception("Failed to update test suite")
934 raise
937@evaluation_router.delete(
938 "/test-suites/{suite_id}", status_code=status.HTTP_204_NO_CONTENT
939)
940def delete_test_suite(
941 suite_id: UUID,
942 db: Session = Depends(get_db),
943 current_user: User = Depends(get_current_user),
944):
945 suite = _get_suite(db, suite_id, current_user)
946 dependants = (
947 db.query(Experiment.name).filter(Experiment.dataset_id == suite_id).all()
948 )
949 if dependants:
950 names = ", ".join(sorted(str(row[0]) for row in dependants)[:5])
951 raise HTTPException(
952 status_code=status.HTTP_409_CONFLICT,
953 detail=(
954 f"This dataset has {len(dependants)} experiment(s) on it ({names}). "
955 "Delete them first."
956 ),
957 )
958 _record_suite_version(db, suite, HistoryEnum.Action.deleted, current_user)
959 db.delete(suite)
960 db.commit()
963@evaluation_router.post(
964 "/test-suites/{suite_id}/copy",
965 status_code=status.HTTP_201_CREATED,
966 response_model=Schema.TestSuite.Read,
967 summary="Copy a dataset — a gold one, usually — into one of your own",
968)
969def copy_test_suite(
970 suite_id: UUID,
971 data: Schema.TestSuite.Copy,
972 db: Session = Depends(get_db),
973 current_user: User = Depends(get_current_user),
974):
975 """A dataset of the caller's own with the source's criteria, pass mark
976 and every case — the way to build on a gold dataset, which cannot itself
977 be edited.
979 The copy is independent: later releases of the source do not reach it,
980 and its runs are its own (they never compare with runs of the source,
981 which is a different dataset). Where it came from, and which version, is
982 recorded in its ``config`` and in its first version.
983 """
984 payload = data.model_dump()
985 requested_name = payload.pop("name", None)
986 if not payload.get("owner_organisation_id") and not payload.get("owner_project_id"):
987 # The workspace the request was made in (app/dependency/workspace.py).
988 payload.update(owner_for(db, current_user, model=TestSuite))
989 verify_owner_scope(payload, current_user, db, model=TestSuite)
990 source = _get_suite(db, suite_id, current_user, read=True)
991 name = requested_name or source.name
992 _refuse_duplicate_name(db, TestSuite, "dataset", name=name, **payload)
994 source_version = dataset_versions.current_content_version(db, source.id)
995 copy = TestSuite(
996 name=name,
997 description=source.description,
998 status=EvaluationEnum.Status.active,
999 criteria=source.criteria,
1000 pass_mark=source.pass_mark,
1001 config={
1002 **(source.config or {}),
1003 "copied_from": {
1004 "dataset_id": str(source.id),
1005 "name": source.name,
1006 "version": source_version,
1007 "built_in": source.is_system is True,
1008 },
1009 },
1010 **payload,
1011 )
1012 try:
1013 db.add(copy)
1014 db.flush()
1015 for case in (
1016 db.query(TestCase)
1017 .filter(TestCase.test_suite_id == source.id)
1018 .order_by(TestCase.created_at)
1019 .all()
1020 ):
1021 db.add(
1022 TestCase(
1023 test_suite_id=copy.id,
1024 **{f: getattr(case, f) for f in dataset_versions.CASE_FIELDS},
1025 )
1026 )
1027 db.flush()
1028 _record_suite_version(db, copy, HistoryEnum.Action.created, current_user)
1029 db.commit()
1030 db.refresh(copy)
1031 copy.case_count = _case_counts(db, [copy.id]).get(copy.id, 0)
1032 return copy
1033 except IntegrityError as exc:
1034 db.rollback()
1035 raise _name_conflict(exc, "dataset", name) from exc
1036 except Exception:
1037 db.rollback()
1038 logger.exception("Failed to copy dataset %s", suite_id)
1039 raise
1042# ── Test Cases ────────────────────────────────────────────────────────────────
1043#
1044# As with variants: the suite is resolved first and its access check is the
1045# one that applies, and every mutation is a version of the suite.
1048@evaluation_router.get(
1049 "/test-suites/{suite_id}/cases", response_model=list[Schema.TestCase.Read]
1050)
1051def list_test_cases(
1052 suite_id: UUID,
1053 db: Session = Depends(get_db),
1054 current_user: User = Depends(get_current_user),
1055):
1056 _get_suite(db, suite_id, current_user, read=True)
1057 return (
1058 db.query(TestCase)
1059 .filter(TestCase.test_suite_id == suite_id)
1060 .order_by(TestCase.created_at)
1061 .all()
1062 )
1065@evaluation_router.post(
1066 "/test-suites/{suite_id}/cases",
1067 status_code=status.HTTP_201_CREATED,
1068 response_model=Schema.TestCase.Read,
1069)
1070def create_test_case(
1071 suite_id: UUID,
1072 data: Schema.TestCase.Create,
1073 db: Session = Depends(get_db),
1074 current_user: User = Depends(get_current_user),
1075):
1076 suite = _get_suite(db, suite_id, current_user)
1077 case = TestCase(**{**data.model_dump(), "test_suite_id": suite_id})
1078 try:
1079 db.add(case)
1080 db.flush()
1081 _record_suite_version(db, suite, HistoryEnum.Action.updated, current_user)
1082 db.commit()
1083 db.refresh(case)
1084 return case
1085 except Exception:
1086 db.rollback()
1087 logger.exception("Failed to create test case")
1088 raise
1091def _get_case(db: Session, suite_id: UUID, case_id: UUID) -> TestCase:
1092 case = db.get(TestCase, case_id)
1093 if not case or case.test_suite_id != suite_id:
1094 raise HTTPException(
1095 status_code=status.HTTP_404_NOT_FOUND, detail="Test case not found"
1096 )
1097 return case
1100@evaluation_router.patch(
1101 "/test-suites/{suite_id}/cases/{case_id}", response_model=Schema.TestCase.Read
1102)
1103def update_test_case(
1104 suite_id: UUID,
1105 case_id: UUID,
1106 data: Schema.TestCase.Update,
1107 db: Session = Depends(get_db),
1108 current_user: User = Depends(get_current_user),
1109):
1110 suite = _get_suite(db, suite_id, current_user)
1111 case = _get_case(db, suite_id, case_id)
1113 for field, value in data.model_dump(exclude_unset=True).items():
1114 setattr(case, field, value)
1115 _record_suite_version(db, suite, HistoryEnum.Action.updated, current_user)
1116 try:
1117 db.commit()
1118 db.refresh(case)
1119 return case
1120 except Exception:
1121 db.rollback()
1122 logger.exception("Failed to update test case")
1123 raise
1126@evaluation_router.delete(
1127 "/test-suites/{suite_id}/cases/{case_id}",
1128 status_code=status.HTTP_204_NO_CONTENT,
1129)
1130def delete_test_case(
1131 suite_id: UUID,
1132 case_id: UUID,
1133 db: Session = Depends(get_db),
1134 current_user: User = Depends(get_current_user),
1135):
1136 suite = _get_suite(db, suite_id, current_user)
1137 case = _get_case(db, suite_id, case_id)
1138 db.delete(case)
1139 db.flush()
1140 _record_suite_version(db, suite, HistoryEnum.Action.updated, current_user)
1141 db.commit()
1144# ── Datasets: what uses them, and every run over them ─────────────────────────
1145#
1146# A dataset has no runs of its own. These are read-only views across the
1147# evaluations that reference it, so a dataset owner can ask "how do my agents
1148# do on this set" without knowing which evaluations asked it.
1151@evaluation_router.get(
1152 "/test-suites/{suite_id}/evaluations",
1153 response_model=list[Schema.Experiment.Read],
1154)
1155def list_suite_evaluations(
1156 suite_id: UUID,
1157 db: Session = Depends(get_db),
1158 current_user: User = Depends(get_current_user),
1159):
1160 """The evaluations of the request's workspace that run this dataset —
1161 a built-in dataset is run from every workspace, and each lists its own."""
1162 _get_suite(db, suite_id, current_user, read=True)
1163 query = db.query(Experiment).filter(
1164 Experiment.dataset_id == suite_id,
1165 _report_scope(db, current_user, None, None, workspace=requested_workspace()),
1166 )
1167 return query.order_by(Experiment.created_at.desc()).all()
1170@evaluation_router.get(
1171 "/test-suites/{suite_id}/best",
1172 summary="What works best on this dataset, across its experiments",
1173)
1174def best_on_suite(
1175 suite_id: UUID,
1176 dataset_version: Optional[int] = Query(default=None, ge=1),
1177 db: Session = Depends(get_db),
1178 current_user: User = Depends(get_current_user),
1179):
1180 """Every variant's result from each experiment's newest completed run on
1181 one dataset version — grouped by how it was graded, ranked, and marked
1182 where it is the best value (``services/evaluation/best.py``).
1184 The version defaults to the latest content version: an earlier one asked
1185 different questions, so its runs are read by asking for it.
1186 """
1187 _get_suite(db, suite_id, current_user, read=True)
1188 version = (
1189 dataset_version
1190 if dataset_version is not None
1191 else dataset_versions.current_content_version(db, suite_id)
1192 )
1193 query = db.query(Experiment).filter(
1194 Experiment.dataset_id == suite_id,
1195 _report_scope(db, current_user, None, None, workspace=requested_workspace()),
1196 )
1197 experiments = query.all()
1199 rows: list[dict] = []
1200 compared = 0
1201 for experiment in experiments:
1202 batch_query = db.query(ExperimentBatch).filter(
1203 ExperimentBatch.experiment_id == experiment.id,
1204 ExperimentBatch.status == RunnableEnum.Status.completed,
1205 ExperimentBatch.dataset_version == version
1206 if version is not None
1207 else ExperimentBatch.dataset_version.is_(None),
1208 )
1209 batch = batch_query.order_by(ExperimentBatch.created_at.desc()).first()
1210 if batch is None or not batch.leaderboard:
1211 continue
1212 compared += 1
1213 variants = {
1214 str(v.id): v
1215 for v in db.query(ExperimentVariant)
1216 .filter(ExperimentVariant.experiment_id == experiment.id)
1217 .all()
1218 }
1219 scorer = getattr(experiment.scorer, "value", experiment.scorer)
1220 for entry in batch.leaderboard:
1221 if not isinstance(entry, dict):
1222 continue
1223 variant = variants.get(str(entry.get("variant_id")))
1224 target = (
1225 entry.get("target") if isinstance(entry.get("target"), dict) else {}
1226 )
1227 config = (variant.config or {}) if variant is not None else {}
1228 rows.append(
1229 {
1230 "experiment_id": str(experiment.id),
1231 "experiment_name": experiment.name,
1232 "batch_id": str(batch.id),
1233 "finished_at": utc_isoformat(batch.finished_at)
1234 if batch.finished_at
1235 else None,
1236 "scorer": scorer,
1237 "judge": experiment.judge,
1238 "variant_id": entry.get("variant_id"),
1239 # A variant deleted since keeps its result under the
1240 # name of what it ran on.
1241 "variant_name": variant.name
1242 if variant is not None
1243 else target.get("label") or "Deleted variant",
1244 "target": target,
1245 "preset": config.get("preset"),
1246 "mean_score": entry.get("mean_score"),
1247 "pass_rate": entry.get("pass_rate"),
1248 "total": entry.get("total"),
1249 "errors": entry.get("errors"),
1250 "mean_latency_ms": entry.get("mean_latency_ms"),
1251 "total_tokens": entry.get("total_tokens"),
1252 "cost_usd": entry.get("cost_usd"),
1253 "cost_per_case_usd": entry.get("cost_per_case_usd"),
1254 # How far the score moved between repeats; None when
1255 # the run asked each case once.
1256 "repeats": entry.get("repeats") or 1,
1257 "score_sd": entry.get("score_sd"),
1258 "consistency": entry.get("consistency"),
1259 }
1260 )
1261 return {
1262 "dataset_version": version,
1263 "experiments_compared": compared,
1264 "groups": best_service.build_groups(rows),
1265 }
1268@evaluation_router.get("/test-suites/{suite_id}/runs")
1269def list_suite_runs(
1270 suite_id: UUID,
1271 include_unfinished: bool = False,
1272 dataset_version: Optional[int] = Query(default=None, ge=1),
1273 unversioned: bool = False,
1274 limit: int = Query(default=batch_store.DEFAULT_REPORT_ROWS, ge=1),
1275 db: Session = Depends(get_db),
1276 current_user: User = Depends(get_current_user),
1277):
1278 """Every run that asked this dataset, across evaluations, newest first.
1280 The same rows the cross-evaluation report answers with, filtered to one
1281 dataset — not a run list the dataset owns. ``dataset_version`` narrows
1282 to the runs that asked one content version (``GET .../versions``);
1283 ``unversioned`` to the runs made before the dataset had any history.
1284 """
1285 _get_suite(db, suite_id, current_user, read=True)
1286 return batch_store.report(
1287 db,
1288 owner_filter=_report_scope(
1289 db, current_user, None, None, workspace=requested_workspace()
1290 ),
1291 dataset_id=suite_id,
1292 dataset_version=dataset_version,
1293 unversioned=unversioned,
1294 limit=limit,
1295 include_unfinished=include_unfinished,
1296 )
1299@evaluation_router.get(
1300 "/test-suites/{suite_id}/versions",
1301 summary="A dataset's content versions, oldest first",
1302)
1303def list_suite_versions(
1304 suite_id: UUID,
1305 db: Session = Depends(get_db),
1306 current_user: User = Depends(get_current_user),
1307):
1308 """Each stretch of history over which the dataset's cases and criteria
1309 held still, with how many of the caller's runs asked it.
1311 Runs compare only within one of these, and a dataset always runs at the
1312 latest; an older one is how a reader looks back at what earlier runs
1313 asked. Metadata edits (a rename, a status change) extend a version rather
1314 than starting one — ``through_version`` is the last history version in it.
1315 """
1316 _get_suite(db, suite_id, current_user, read=True)
1317 versions = dataset_versions.content_versions(db, suite_id)
1318 counts = batch_store.runs_per_dataset_version(
1319 db,
1320 owner_filter=_report_scope(
1321 db, current_user, None, None, workspace=requested_workspace()
1322 ),
1323 dataset_id=suite_id,
1324 )
1325 for version in versions:
1326 version.runs = counts.get(version.version, 0)
1327 return {
1328 "versions": [v.as_json() for v in versions],
1329 # Runs made before the dataset had any history; nothing has been
1330 # edited since they ran, or it would have a version.
1331 "unversioned_runs": counts.get(None, 0),
1332 }
1335@evaluation_router.get(
1336 "/test-suites/{suite_id}/versions/{version}",
1337 summary="One content version of a dataset, cases included",
1338)
1339def get_suite_version(
1340 suite_id: UUID,
1341 version: int,
1342 db: Session = Depends(get_db),
1343 current_user: User = Depends(get_current_user),
1344):
1345 """What a content version asked: its criteria and its cases in full.
1347 ``cases`` is null for a version recorded before datasets kept their cases
1348 in full — the history row names them but did not keep what they said.
1349 """
1350 _get_suite(db, suite_id, current_user, read=True)
1351 for entry in dataset_versions.content_versions(db, suite_id):
1352 if entry.version == version:
1353 return entry.as_json(with_cases=True)
1354 raise HTTPException(
1355 status_code=status.HTTP_404_NOT_FOUND,
1356 detail=f"This dataset has no version {version}.",
1357 )
1360# ── Execution: scorers catalogue ──────────────────────────────────────────────
1363@evaluation_router.get(
1364 "/scorers",
1365 response_model=ScorerCatalogue,
1366 summary="List the available scoring strategies",
1367)
1368def list_scorers():
1369 """Describe every scorer the runner can apply, for the UI's scorer picker.
1371 The picker renders entirely from this: labels, when-to-use lines, how each
1372 score is computed, what each needs from the dataset, and the settings to
1373 show. A scorer added to ``app/services/evaluation/scorers.py`` therefore
1374 appears fully explained with no frontend release — the same contract the
1375 rule and widget catalogues have.
1376 """
1377 return ScorerCatalogue(
1378 scorers=scoring.scorer_catalogue(),
1379 groups=scoring.scorer_groups(),
1380 default_pass_threshold=scoring.DEFAULT_PASS_THRESHOLD,
1381 )
1384# ── Execution: ad-hoc comparison ──────────────────────────────────────────────
1387@evaluation_router.post("/compare", summary="Run one prompt against several targets")
1388def compare_targets(
1389 data: CompareRequest,
1390 db: Session = Depends(get_db),
1391 current_user: User = Depends(get_current_user),
1392):
1393 """Send the same prompt to up to six models/agents and return every output.
1395 The scratchpad a user reaches for before deciding a comparison is worth
1396 keeping. The outcomes are recorded as an unowned batch under the returned
1397 ``comparison_id``; ``POST /experiments`` with that id adopts them as the
1398 new evaluation's first run, and unsaved comparisons are purged after
1399 ``quick_try.RETENTION_HOURS``. Nothing appears in any list until saved.
1400 """
1401 _refuse_label_in_scorer(data.scorer_config)
1402 _refuse_unusable_judge(db, data.judge)
1403 try:
1404 return runner.compare(
1405 db,
1406 prompt=data.prompt,
1407 targets=[t.model_dump(exclude_none=True) for t in data.targets],
1408 owner_user_id=str(current_user.id),
1409 system_prompt=data.system_prompt,
1410 expected_output=data.expected_output,
1411 criteria=[c.model_dump() for c in data.criteria or []],
1412 examples=[e.model_dump() for e in data.examples or []],
1413 expectation=data.expectation,
1414 expected_behaviour=data.expected_behaviour,
1415 scorer=data.scorer,
1416 scorer_config=data.scorer_config,
1417 judge=data.judge,
1418 )
1419 except TargetResolutionError as exc:
1420 raise HTTPException(
1421 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
1422 ) from exc
1425# ── Execution: experiment batches ─────────────────────────────────────────────
1428def _start_run(
1429 db: Session,
1430 experiment: Experiment,
1431 background_tasks: BackgroundTasks,
1432 current_user: User,
1433 *,
1434 variant_ids: Optional[list] = None,
1435 label: Optional[str] = None,
1436 overrides: Optional[dict] = None,
1437) -> tuple[str, list[ExperimentVariant], list]:
1438 """Validate a run and queue it: ``(batch_id, variants, cases)``.
1440 Validation (dataset resolvable, variants present, every target buildable)
1441 happens here so a misconfigured experiment fails visibly at request time
1442 rather than in a background task the caller never sees. Shared by
1443 ``run_experiment`` and ``evaluate_agent``.
1444 """
1445 try:
1446 cases = cases_from_dataset(db, experiment.dataset_id)
1447 except DatasetError as exc:
1448 raise HTTPException(
1449 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
1450 ) from exc
1452 variants = runner.load_variants(db, experiment.id, variant_ids)
1453 if not variants:
1454 raise HTTPException(
1455 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1456 detail="This experiment has no variants to run. Add one first.",
1457 )
1459 # Build every target up front: an unreachable model or a deleted agent is
1460 # a 422 now instead of a batch that fails after burning provider calls.
1461 for variant in variants:
1462 spec = (variant.config or {}).get("target")
1463 if not spec:
1464 raise HTTPException(
1465 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1466 detail=f"Variant '{variant.name}' has no model or agent configured.",
1467 )
1468 try:
1469 build_target(spec, db, owner=experiment)
1470 except TargetResolutionError as exc:
1471 raise HTTPException(
1472 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1473 detail=f"Variant '{variant.name}': {exc}",
1474 ) from exc
1475 # Resolved here as well as in the batch, for the same reason the target
1476 # is: a context naming a repository this evaluation cannot reach should
1477 # be refused now, not discovered by a background task nobody is watching.
1478 try:
1479 context_service.resolve(
1480 db,
1481 (variant.config or {}).get("context") or spec.get("context"),
1482 owner=experiment,
1483 )
1484 except context_service.ContextError as exc:
1485 raise HTTPException(
1486 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1487 detail=f"Variant '{variant.name}': {exc}",
1488 ) from exc
1490 batch_id = runner.start_experiment_batch(
1491 db,
1492 experiment,
1493 variants=variants,
1494 label=label,
1495 config_overrides=overrides or {},
1496 started_by_user_id=current_user.id,
1497 )
1498 background_tasks.add_task(runner.execute_batch, UUID(batch_id))
1499 return batch_id, variants, cases
1502@evaluation_router.post(
1503 "/experiments/{experiment_id}/run",
1504 status_code=status.HTTP_202_ACCEPTED,
1505 summary="Run an experiment's variants against its dataset (async)",
1506)
1507def run_experiment(
1508 experiment_id: UUID,
1509 data: RunExperimentRequest,
1510 background_tasks: BackgroundTasks,
1511 db: Session = Depends(get_db),
1512 current_user: User = Depends(get_current_user),
1513):
1514 """Queue a batch evaluating every selected variant on identical inputs.
1516 Validation (dataset resolvable, variants present, every target buildable)
1517 happens here so a misconfigured experiment fails visibly at request time
1518 rather than in a background task the caller never sees.
1519 """
1520 experiment = _get_experiment(db, experiment_id, current_user)
1521 overrides: dict = {}
1522 if data.concurrency is not None:
1523 overrides["concurrency"] = data.concurrency
1524 if data.repeats > 1:
1525 overrides["repeats"] = data.repeats
1526 batch_id, variants, cases = _start_run(
1527 db,
1528 experiment,
1529 background_tasks,
1530 current_user,
1531 variant_ids=data.variant_ids,
1532 label=data.label,
1533 overrides=overrides,
1534 )
1536 return {
1537 "batch_id": batch_id,
1538 "status": RunnableEnum.Status.queued.value,
1539 "variants": len(variants),
1540 "cases": len(cases),
1541 "repeats": data.repeats,
1542 "total": len(variants) * len(cases) * data.repeats,
1543 }
1546#: Owner columns, in the order ``evidence.evidence_owner`` reads them.
1547_OWNER_COLUMNS = ("owner_user_id", "owner_organisation_id", "owner_project_id")
1550def _evidence_scope(agent: Agent, current_user: User) -> dict[str, Any]:
1551 """Where an evaluation of ``agent`` must live to count as its evidence
1552 (``evidence.evidence_owner``): its own organisation, project or person —
1553 or, for a built-in agent everyone uses, the person evaluating it."""
1554 if getattr(agent, "is_system", False) is True:
1555 return {"owner_user_id": current_user.id}
1556 return {
1557 column: getattr(agent, column)
1558 for column in _OWNER_COLUMNS
1559 if getattr(agent, column, None) is not None
1560 }
1563def _agent_experiment(
1564 db: Session, agent: Agent, dataset: TestSuite, scope: dict[str, Any]
1565) -> Optional[Experiment]:
1566 """The experiment an earlier Evaluate made for this agent and dataset."""
1567 query = db.query(Experiment).filter(
1568 Experiment.dataset_id == dataset.id, Experiment.is_system.isnot(True)
1569 )
1570 for column in _OWNER_COLUMNS:
1571 value = scope.get(column)
1572 column_attr = getattr(Experiment, column)
1573 query = query.filter(column_attr == value if value else column_attr.is_(None))
1574 for experiment in query.all():
1575 if (experiment.config or {}).get("evaluates_agent") == str(agent.id):
1576 return experiment
1577 return None
1580def _free_name(db: Session, scope: dict[str, Any], name: str) -> str:
1581 """``name``, or ``name (2)``… — evaluation names are unique per owner."""
1582 candidate, n = name[:255], 2
1583 while True:
1584 query = db.query(Experiment.id).filter(Experiment.name == candidate)
1585 for column in _OWNER_COLUMNS:
1586 value = scope.get(column)
1587 column_attr = getattr(Experiment, column)
1588 query = query.filter(
1589 column_attr == value if value else column_attr.is_(None)
1590 )
1591 if query.first() is None:
1592 return candidate
1593 suffix = f" ({n})"
1594 candidate, n = name[: 255 - len(suffix)] + suffix, n + 1
1597@evaluation_router.post(
1598 "/agents/{agent_id}/evaluate",
1599 status_code=status.HTTP_202_ACCEPTED,
1600 response_model=list[EvaluateAgentStarted],
1601 summary="Evaluate an agent as configured on chosen datasets (async)",
1602)
1603def evaluate_agent(
1604 agent_id: UUID,
1605 data: EvaluateAgentRequest,
1606 background_tasks: BackgroundTasks,
1607 db: Session = Depends(get_db),
1608 current_user: User = Depends(get_current_user),
1609):
1610 """One step from Assurance or an agent's page to evidence about it.
1612 Per dataset: the experiment an earlier Evaluate made (or a new one, named
1613 "<agent> · <dataset>", LLM-judged with the default judge, one variant
1614 running the agent as configured), and a run of it. The experiment lives
1615 where the agent's evidence is read, so the result counts on Assurance and
1616 for the evidence gate — creating it there takes the same access as
1617 creating any evaluation there. A dataset whose experiment is already
1618 running is reported, not run twice.
1619 """
1620 agent = db.get(Agent, agent_id)
1621 if agent is None:
1622 raise HTTPException(
1623 status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
1624 )
1625 verify_resource_read(agent, current_user, db)
1626 scope = _evidence_scope(agent, current_user)
1627 verify_owner_scope(dict(scope), current_user, db, model=Experiment)
1629 started: list[dict[str, Any]] = []
1630 for dataset_id in dict.fromkeys(data.dataset_ids):
1631 dataset = db.get(TestSuite, dataset_id)
1632 if dataset is None:
1633 raise HTTPException(
1634 status_code=status.HTTP_404_NOT_FOUND, detail="Dataset not found"
1635 )
1636 verify_resource_read(dataset, current_user, db)
1637 experiment = _agent_experiment(db, agent, dataset, scope)
1638 created = experiment is None
1639 if experiment is None:
1640 experiment = Experiment(
1641 name=_free_name(db, scope, f"{agent.name} · {dataset.name}"),
1642 description=(
1643 f"{agent.name}, as configured, on {dataset.name}. Created by "
1644 "Evaluate; run it again after a change to see what moved."
1645 ),
1646 status=EvaluationEnum.Status.active,
1647 dataset_id=dataset.id,
1648 scorer=EvaluationEnum.Scorer.llm,
1649 config={"evaluates_agent": str(agent.id)},
1650 **scope,
1651 )
1652 db.add(experiment)
1653 db.flush()
1654 db.add(
1655 ExperimentVariant(
1656 experiment_id=experiment.id,
1657 name=agent.name,
1658 config={"target": {"type": "agent", "agent_id": str(agent.id)}},
1659 )
1660 )
1661 db.flush()
1662 _record_experiment_version(
1663 db, experiment, HistoryEnum.Action.created, current_user
1664 )
1665 db.commit()
1666 running = (
1667 db.query(ExperimentBatch.id)
1668 .filter(
1669 ExperimentBatch.experiment_id == experiment.id,
1670 ExperimentBatch.status.in_(
1671 (RunnableEnum.Status.queued, RunnableEnum.Status.running)
1672 ),
1673 )
1674 .first()
1675 )
1676 if running is not None:
1677 started.append(
1678 {
1679 "dataset_id": dataset.id,
1680 "experiment_id": experiment.id,
1681 "batch_id": None,
1682 "status": "running",
1683 "created": created,
1684 }
1685 )
1686 continue
1687 batch_id, _, _ = _start_run(
1688 db,
1689 experiment,
1690 background_tasks,
1691 current_user,
1692 label="Evaluate",
1693 overrides={"repeats": data.repeats} if data.repeats > 1 else None,
1694 )
1695 started.append(
1696 {
1697 "dataset_id": dataset.id,
1698 "experiment_id": experiment.id,
1699 "batch_id": UUID(batch_id),
1700 "status": "started",
1701 "created": created,
1702 }
1703 )
1704 return started
1707@evaluation_router.get(
1708 "/experiments/{experiment_id}/batches",
1709 summary="List an experiment's run batches, newest first",
1710)
1711def list_experiment_batches(
1712 experiment_id: UUID,
1713 db: Session = Depends(get_db),
1714 current_user: User = Depends(get_current_user),
1715):
1716 """Every batch this experiment has run, newest first.
1718 Read from ``experiment_batches`` rather than from the experiment's config
1719 blob, so the list is the whole history rather than the twenty most recent —
1720 and so the same rows can be reported on across experiments.
1721 """
1722 _get_experiment(db, experiment_id, current_user, read=True)
1723 return [batch_store.as_payload(b) for b in batch_store.list_for(db, experiment_id)]
1726@evaluation_router.post(
1727 "/experiments/{experiment_id}/batches/{batch_id}/cancel",
1728 summary="Cancel an in-flight experiment batch",
1729)
1730def cancel_experiment_batch(
1731 experiment_id: UUID,
1732 batch_id: str,
1733 db: Session = Depends(get_db),
1734 current_user: User = Depends(get_current_user),
1735):
1736 """Mark a batch cancelled; the runner stops between chunks and keeps the
1737 results it has already produced."""
1738 _get_experiment(db, experiment_id, current_user)
1739 batch = batch_store.get(db, experiment_id, batch_id)
1740 if batch is None:
1741 raise HTTPException(
1742 status_code=status.HTTP_404_NOT_FOUND, detail="Batch not found"
1743 )
1744 current = batch.status.value if batch.status else None
1745 if current in _TERMINAL_STATUSES:
1746 raise HTTPException(
1747 status_code=status.HTTP_409_CONFLICT,
1748 detail=f"Batch is already {current}.",
1749 )
1750 batch.status = RunnableEnum.Status.cancelled
1751 db.commit()
1752 return {"batch_id": batch_id, "status": RunnableEnum.Status.cancelled.value}
1755@evaluation_router.delete(
1756 "/experiments/{experiment_id}/runs",
1757 status_code=status.HTTP_204_NO_CONTENT,
1758 summary="Delete an experiment's runs (optionally just one batch)",
1759)
1760def delete_experiment_runs(
1761 experiment_id: UUID,
1762 batch_id: Optional[str] = None,
1763 db: Session = Depends(get_db),
1764 current_user: User = Depends(get_current_user),
1765):
1766 _get_experiment(db, experiment_id, current_user)
1767 query = db.query(ExperimentRun).filter(ExperimentRun.experiment_id == experiment_id)
1768 if batch_id:
1769 try:
1770 query = query.filter(ExperimentRun.batch_id == UUID(batch_id))
1771 except ValueError as exc:
1772 raise HTTPException(
1773 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1774 detail="Invalid batch_id.",
1775 ) from exc
1776 query.delete(synchronize_session=False)
1777 # The batch row goes with its runs: a batch whose results were deleted
1778 # describes nothing, and leaving it would put an empty row in every report.
1779 batch_store.delete_for(db, experiment_id, batch_id)
1780 db.commit()
1783# ── Execution: prompt optimisation ────────────────────────────────────────────
1786@evaluation_router.post(
1787 "/experiments/{experiment_id}/optimise",
1788 status_code=status.HTTP_202_ACCEPTED,
1789 summary="Automatically search for a better prompt (async)",
1790)
1791def optimise_experiment(
1792 experiment_id: UUID,
1793 data: OptimiseRequest,
1794 background_tasks: BackgroundTasks,
1795 db: Session = Depends(get_db),
1796 current_user: User = Depends(get_current_user),
1797):
1798 """Iteratively rewrite a variant's prompt, keeping whatever scores best.
1800 Each round's candidates are saved as ordinary variants, so the search is
1801 inspectable — and abandonable — with the same UI as a hand-built
1802 experiment.
1803 """
1804 experiment = _get_experiment(db, experiment_id, current_user)
1806 existing = (experiment.config or {}).get("optimisation") or {}
1807 if existing.get("status") in _ACTIVE_STATUSES:
1808 raise HTTPException(
1809 status_code=status.HTTP_409_CONFLICT,
1810 detail="An optimisation is already running on this experiment.",
1811 )
1813 try:
1814 optimisation_id = optimiser.start_optimisation(
1815 db,
1816 experiment,
1817 base_variant_id=data.base_variant_id,
1818 rounds=data.rounds,
1819 candidates_per_round=data.candidates_per_round,
1820 instructions=data.instructions,
1821 )
1822 except (optimiser.OptimisationError, DatasetError) as exc:
1823 raise HTTPException(
1824 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
1825 ) from exc
1827 background_tasks.add_task(
1828 optimiser.execute_optimisation, experiment_id, optimisation_id
1829 )
1830 return {
1831 "optimisation_id": optimisation_id,
1832 "status": RunnableEnum.Status.queued.value,
1833 "rounds": data.rounds,
1834 "candidates_per_round": data.candidates_per_round,
1835 }
1838@evaluation_router.get(
1839 "/experiments/{experiment_id}/optimisation",
1840 summary="Read the current optimisation's progress",
1841)
1842def get_optimisation(
1843 experiment_id: UUID,
1844 db: Session = Depends(get_db),
1845 current_user: User = Depends(get_current_user),
1846):
1847 experiment = _get_experiment(db, experiment_id, current_user, read=True)
1848 return (experiment.config or {}).get("optimisation")
1851@evaluation_router.post(
1852 "/experiments/{experiment_id}/optimisation/cancel",
1853 summary="Cancel the running optimisation",
1854)
1855def cancel_optimisation(
1856 experiment_id: UUID,
1857 db: Session = Depends(get_db),
1858 current_user: User = Depends(get_current_user),
1859):
1860 experiment = _get_experiment(db, experiment_id, current_user)
1861 config = dict(experiment.config or {})
1862 state = dict(config.get("optimisation") or {})
1863 if not state:
1864 raise HTTPException(
1865 status_code=status.HTTP_404_NOT_FOUND, detail="No optimisation to cancel."
1866 )
1867 if state.get("status") in _TERMINAL_STATUSES:
1868 raise HTTPException(
1869 status_code=status.HTTP_409_CONFLICT,
1870 detail=f"Optimisation is already {state['status']}.",
1871 )
1872 state["status"] = RunnableEnum.Status.cancelled.value
1873 config["optimisation"] = state
1874 experiment.config = config
1875 db.commit()
1876 return state
1879@evaluation_router.post(
1880 "/experiments/{experiment_id}/variants/{variant_id}/promote",
1881 summary="Write a variant's prompt onto its target agent",
1882)
1883def promote_variant(
1884 experiment_id: UUID,
1885 variant_id: UUID,
1886 data: PromoteRequest,
1887 db: Session = Depends(get_db),
1888 current_user: User = Depends(get_current_user),
1889):
1890 """Adopt a winning prompt as the agent's system prompt.
1892 This is what closes the loop: without it, a better prompt found by an
1893 experiment or an optimisation run has to be copied across by hand. The gate
1894 is what stops the loop closing in the wrong direction.
1895 """
1896 experiment = _get_experiment(db, experiment_id, current_user)
1898 variant = db.get(ExperimentVariant, variant_id)
1899 if not variant or variant.experiment_id != experiment_id:
1900 raise HTTPException(
1901 status_code=status.HTTP_404_NOT_FOUND, detail="Variant not found"
1902 )
1903 if not (variant.prompt or "").strip():
1904 raise HTTPException(
1905 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1906 detail="This variant has no prompt to promote.",
1907 )
1909 raw_agent_id = data.agent_id or (variant.config or {}).get("target", {}).get(
1910 "agent_id"
1911 )
1912 if not raw_agent_id:
1913 raise HTTPException(
1914 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1915 detail=(
1916 "This variant targets a model, not an agent. Pass 'agent_id' to "
1917 "choose which agent adopts the prompt."
1918 ),
1919 )
1920 try:
1921 agent = db.get(Agent, UUID(str(raw_agent_id)))
1922 except (ValueError, AttributeError) as exc:
1923 raise HTTPException(
1924 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1925 detail="Invalid agent_id.",
1926 ) from exc
1927 if agent is None:
1928 raise HTTPException(
1929 status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
1930 )
1931 verify_resource_access(agent, current_user, db)
1933 gate = promotion.check(db, experiment, variant, agent)
1934 if gate["status"] == promotion.GateStatus.blocked.value and not data.force:
1935 # 409 rather than 422: the request is well-formed and the caller is
1936 # allowed to make it — it conflicts with what the evidence says. The
1937 # whole report comes back so the UI can show the comparison that
1938 # closed the gate instead of just refusing.
1939 raise HTTPException(
1940 status_code=status.HTTP_409_CONFLICT,
1941 detail={
1942 "message": (
1943 "This variant scored worse than the agent's current prompt. "
1944 "Re-run the experiment, or promote with 'force' to override "
1945 "and record the decision."
1946 ),
1947 "gate": gate,
1948 },
1949 )
1951 previous = agent.system_prompt
1952 agent.system_prompt = variant.prompt
1953 # Promotion is an edit to a live agent, so it earns a version like any
1954 # other. Without this the prompt a governed invocation ran under would have
1955 # changed with nothing in the trail to say when, by whom, or from what —
1956 # and the gate would have no history to be measured against next time.
1957 version = history_service.record_version(
1958 db,
1959 resource_type=HistoryEnum.ResourceType.agent,
1960 model=Agent,
1961 resource=agent,
1962 action=HistoryEnum.Action.updated,
1963 actor=current_user,
1964 )
1965 entry = promotion.record_promotion(
1966 db,
1967 experiment,
1968 variant=variant,
1969 agent=agent,
1970 gate=gate,
1971 actor=current_user,
1972 forced=gate["status"] == promotion.GateStatus.blocked.value,
1973 note=data.note,
1974 agent_version=getattr(version, "version_number", None),
1975 )
1976 try:
1977 db.commit()
1978 db.refresh(agent)
1979 except Exception:
1980 db.rollback()
1981 logger.exception(
1982 "Failed to promote variant %s onto agent %s", variant_id, agent.id
1983 )
1984 raise
1986 logger.info(
1987 "Promoted variant %s onto agent %s (gate: %s%s)",
1988 variant_id,
1989 agent.id,
1990 gate["status"],
1991 ", forced" if entry["forced"] else "",
1992 )
1993 return {
1994 "agent_id": str(agent.id),
1995 "agent_name": agent.name,
1996 "previous_system_prompt": previous,
1997 "system_prompt": agent.system_prompt,
1998 "agent_version": entry["agent_version"],
1999 "gate": gate,
2000 "forced": entry["forced"],
2001 }
2004@evaluation_router.get(
2005 "/experiments/{experiment_id}/variants/{variant_id}/promotion-check",
2006 summary="Ask whether a variant may be promoted, without promoting it",
2007)
2008def check_promotion(
2009 experiment_id: UUID,
2010 variant_id: UUID,
2011 agent_id: Optional[UUID] = None,
2012 db: Session = Depends(get_db),
2013 current_user: User = Depends(get_current_user),
2014):
2015 """The gate's verdict ahead of the decision.
2017 Separate from the promote call so the UI can warn *before* somebody clicks,
2018 rather than letting them commit to an action and then refusing it.
2019 """
2020 experiment = _get_experiment(db, experiment_id, current_user, read=True)
2021 variant = db.get(ExperimentVariant, variant_id)
2022 if not variant or variant.experiment_id != experiment_id:
2023 raise HTTPException(
2024 status_code=status.HTTP_404_NOT_FOUND, detail="Variant not found"
2025 )
2027 raw_agent_id = agent_id or (variant.config or {}).get("target", {}).get("agent_id")
2028 if not raw_agent_id:
2029 raise HTTPException(
2030 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
2031 detail=(
2032 "This variant targets a model, not an agent. Pass 'agent_id' to "
2033 "choose which agent the check is against."
2034 ),
2035 )
2036 try:
2037 agent = db.get(Agent, UUID(str(raw_agent_id)))
2038 except (ValueError, AttributeError) as exc:
2039 raise HTTPException(
2040 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
2041 detail="Invalid agent_id.",
2042 ) from exc
2043 if agent is None:
2044 raise HTTPException(
2045 status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
2046 )
2047 verify_resource_read(agent, current_user, db)
2049 return promotion.check(db, experiment, variant, agent)
2052# ── Runs: results and the regression verdict ──────────────────────────────────
2055@evaluation_router.get(
2056 "/experiments/{experiment_id}/batches/{batch_id}/results",
2057 response_model=list[Schema.ExperimentRun.Read],
2058)
2059def list_batch_results(
2060 experiment_id: UUID,
2061 batch_id: UUID,
2062 db: Session = Depends(get_db),
2063 current_user: User = Depends(get_current_user),
2064):
2065 """The scored cells of one run."""
2066 _get_experiment(db, experiment_id, current_user, read=True)
2067 if batch_store.get(db, experiment_id, batch_id) is None:
2068 raise HTTPException(
2069 status_code=status.HTTP_404_NOT_FOUND, detail="Run not found"
2070 )
2071 return (
2072 db.query(ExperimentRun)
2073 .filter(ExperimentRun.batch_id == batch_id)
2074 .order_by(ExperimentRun.created_at)
2075 .all()
2076 )
2079@evaluation_router.get(
2080 "/experiments/{experiment_id}/batches/{batch_id}/regression",
2081 summary="Compare a run against the evaluation's last comparable run",
2082)
2083def get_batch_regression(
2084 experiment_id: UUID,
2085 batch_id: UUID,
2086 db: Session = Depends(get_db),
2087 current_user: User = Depends(get_current_user),
2088):
2089 """Explain how this run differs from its baseline, case by case.
2091 Computed on read rather than served from the row: the run carries only the
2092 headline verdict, and recomputing means runs recorded before regression
2093 detection existed still report, and an evaluation whose tolerances were
2094 retuned reports against the tolerances in force now.
2095 """
2096 experiment = _get_experiment(db, experiment_id, current_user, read=True)
2097 batch = batch_store.get(db, experiment_id, batch_id)
2098 if batch is None:
2099 raise HTTPException(
2100 status_code=status.HTTP_404_NOT_FOUND, detail="Run not found"
2101 )
2102 return regression.evaluate_batch(db, batch, owner_config=experiment.config)
2105# ── Cross-experiment reporting ────────────────────────────────────────────────
2108def _report_scope(
2109 db: Session,
2110 current_user: User,
2111 owner_organisation_id: Optional[UUID],
2112 owner_project_id: Optional[UUID],
2113 *,
2114 workspace: Optional[str] = None,
2115 model=Experiment,
2116):
2117 """The ownership filter a report may see, matching the experiment list.
2119 Reports read across experiments, so scoping is the first thing they get
2120 right rather than the last: the same predicate the list endpoint uses, with
2121 the same membership check in front of it.
2122 """
2123 return list_scope(
2124 model,
2125 current_user,
2126 db,
2127 workspace=workspace,
2128 owner_organisation_id=owner_organisation_id,
2129 owner_project_id=owner_project_id,
2130 )
2133def _since(days: Optional[int]) -> Optional[datetime]:
2134 if days is None:
2135 return None
2136 return aware_utcnow() - timedelta(days=max(1, days))
2139@evaluation_router.get(
2140 "/reports/batches",
2141 summary="Completed batches across experiments, newest first",
2142)
2143def report_batches(
2144 workspace: Optional[str] = None,
2145 owner_organisation_id: Optional[UUID] = None,
2146 owner_project_id: Optional[UUID] = None,
2147 experiment_id: Optional[UUID] = None,
2148 dataset_id: Optional[UUID] = None,
2149 scorer: Optional[str] = None,
2150 days: Optional[int] = None,
2151 min_mean_score: Optional[float] = Query(default=None, ge=0.0, le=1.0),
2152 max_mean_score: Optional[float] = Query(default=None, ge=0.0, le=1.0),
2153 limit: int = Query(default=batch_store.DEFAULT_REPORT_ROWS, ge=1),
2154 offset: int = Query(default=0, ge=0),
2155 include_unfinished: bool = False,
2156 db: Session = Depends(get_db),
2157 current_user: User = Depends(get_current_user),
2158):
2159 """One row per completed batch, with the figures a comparison needs.
2161 This is what batches moving into their own table bought: "every batch in
2162 this project since Monday that scored below 0.7" is one query, where before
2163 it meant loading every experiment and walking a JSON array in Python.
2165 ``include_unfinished`` adds queued, running, failed and cancelled batches,
2166 each carrying its ``status``. That is for the activity feed, which lists
2167 runs as events: a run that failed is the one it must not leave out.
2168 ``offset`` is how that feed pages to older runs.
2169 """
2170 return batch_store.report(
2171 db,
2172 owner_filter=_report_scope(
2173 db,
2174 current_user,
2175 owner_organisation_id,
2176 owner_project_id,
2177 workspace=workspace,
2178 ),
2179 project_id=owner_project_id,
2180 experiment_id=experiment_id,
2181 dataset_id=dataset_id,
2182 scorer=scorer,
2183 since=_since(days),
2184 min_mean_score=min_mean_score,
2185 max_mean_score=max_mean_score,
2186 limit=limit,
2187 offset=offset,
2188 include_unfinished=include_unfinished,
2189 )
2192@evaluation_router.get(
2193 "/assurance",
2194 summary="Every agent in scope, and the evaluation evidence behind the "
2195 "version in force",
2196)
2197def evaluation_assurance(
2198 workspace: Optional[str] = None,
2199 owner_organisation_id: Optional[UUID] = None,
2200 owner_project_id: Optional[UUID] = None,
2201 db: Session = Depends(get_db),
2202 current_user: User = Depends(get_current_user),
2203):
2204 """Which agents have evidence behind the version now in force.
2206 Per agent: ``current`` (a completed run evaluated this version),
2207 ``outdated`` (only an older version was evaluated), ``unrecorded`` (runs
2208 predate version recording), ``never``, or ``regressed`` (its latest run
2209 regressed). The same scope rules as the reports: the experiments read are
2210 the ones the report endpoints would read, and the agents are the ones in
2211 the same owner scope.
2212 """
2213 experiment_filter = _report_scope(
2214 db,
2215 current_user,
2216 owner_organisation_id,
2217 owner_project_id,
2218 workspace=workspace,
2219 )
2220 agent_filter = _report_scope(
2221 db,
2222 current_user,
2223 owner_organisation_id,
2224 owner_project_id,
2225 workspace=workspace,
2226 model=Agent,
2227 )
2228 fleet = assurance_service.fleet_assurance(
2229 db, agent_filter=agent_filter, experiment_filter=experiment_filter
2230 )
2231 # Built-in agents (CHAINR Bot) apart, so the counts stay the user's own:
2232 # judged on the platform benchmark plus the viewer's own runs of them.
2233 fleet["built_in"] = assurance_service.built_in_assurance(db, current_user.id)
2234 return fleet
2237@evaluation_router.get(
2238 "/benchmark",
2239 summary="The platform benchmark: CHAINR Bot and each maker's strongest model on "
2240 "every gold dataset",
2241)
2242def platform_benchmark(
2243 dataset_id: Optional[UUID] = None,
2244 db: Session = Depends(get_db),
2245 current_user: User = Depends(get_current_user),
2246):
2247 """The same for every user: per gold dataset (or one, with
2248 ``dataset_id``), each target's newest result on the dataset's current
2249 content version against its pass mark, and CHAINR Bot's runs over time.
2250 Nothing here is the caller's, so nothing is scoped to them."""
2251 return benchmark_service.view(db, dataset_id)
2254@evaluation_router.get(
2255 "/reports/summary",
2256 summary="Headline totals across every experiment in scope",
2257)
2258def report_summary(
2259 workspace: Optional[str] = None,
2260 owner_organisation_id: Optional[UUID] = None,
2261 owner_project_id: Optional[UUID] = None,
2262 days: int = Query(default=batch_store.DEFAULT_REPORT_DAYS, ge=1),
2263 db: Session = Depends(get_db),
2264 current_user: User = Depends(get_current_user),
2265):
2266 """Aggregated in SQL over every matching batch, not over a listed page."""
2267 return batch_store.totals(
2268 db,
2269 owner_filter=_report_scope(
2270 db,
2271 current_user,
2272 owner_organisation_id,
2273 owner_project_id,
2274 workspace=workspace,
2275 ),
2276 project_id=owner_project_id,
2277 since=_since(days),
2278 )
2281# ── Regression detection ──────────────────────────────────────────────────────
2284@evaluation_router.get(
2285 "/regression/metrics",
2286 summary="List the metrics a regression comparison tracks",
2287)
2288def list_regression_metrics():
2289 """Describe every tracked metric, for the UI and for tolerance tuning.
2291 Served from the registry, so a metric added in
2292 ``app/services/evaluation/regression.py`` appears here with no frontend
2293 release — the same contract the scorer and widget catalogues have.
2294 """
2295 return regression.metric_catalogue()
2298# ── Test case bulk import ─────────────────────────────────────────────────────
2301@evaluation_router.post(
2302 "/test-suites/{suite_id}/cases/import",
2303 status_code=status.HTTP_201_CREATED,
2304 response_model=ImportCasesResult,
2305 summary="Bulk-create test cases from CSV, JSONL, or a JSON array",
2306)
2307def import_test_cases(
2308 suite_id: UUID,
2309 data: ImportCasesRequest,
2310 db: Session = Depends(get_db),
2311 current_user: User = Depends(get_current_user),
2312):
2313 """Turn a pasted dataset into test cases.
2315 Building a suite one case at a time through a modal is the main reason
2316 benchmarking never gets used; a paste box removes that.
2318 Answers the created cases and ``ignored``: every field the import could
2319 not use, why, and on which cases — so a file written for another tool
2320 says what it lost on the way in instead of losing it silently.
2321 """
2322 suite = _get_suite(db, suite_id, current_user)
2324 try:
2325 report = parse_import_report(data.content, data.format)
2326 cases = report.cases
2327 except DatasetError as exc:
2328 raise HTTPException(
2329 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
2330 ) from exc
2332 try:
2333 if data.replace:
2334 db.query(TestCase).filter(TestCase.test_suite_id == suite_id).delete(
2335 synchronize_session=False
2336 )
2337 created = [
2338 TestCase(
2339 test_suite_id=suite_id,
2340 name=case.name,
2341 input={"prompt": case.input},
2342 expected_output=case.expected_output,
2343 criteria=case.criteria,
2344 examples=case.examples or None,
2345 expected_behaviour=case.behaviour,
2346 expectation=case.expectation or None,
2347 situation=case.situation or None,
2348 tags=case.tags or None,
2349 )
2350 for case in cases
2351 ]
2352 db.add_all(created)
2353 db.flush()
2354 # An import is the largest edit a dataset ever gets, and with
2355 # ``replace`` it is also the most destructive: the version's children
2356 # snapshot is how a reader finds out what was there before.
2357 _record_suite_version(db, suite, HistoryEnum.Action.updated, current_user)
2358 db.commit()
2359 except Exception:
2360 db.rollback()
2361 logger.exception("Failed to import test cases into suite %s", suite_id)
2362 raise
2364 for case in created:
2365 db.refresh(case)
2366 return {"created": created, "ignored": report.ignored_list()}
2369# ── Shared helpers ────────────────────────────────────────────────────────────
2372_ACTIVE_STATUSES = (
2373 RunnableEnum.Status.queued.value,
2374 RunnableEnum.Status.running.value,
2375)
2376_TERMINAL_STATUSES = (
2377 RunnableEnum.Status.completed.value,
2378 RunnableEnum.Status.failed.value,
2379 RunnableEnum.Status.cancelled.value,
2380)
2383def _refuse_duplicate_name(
2384 db: Session,
2385 model: type,
2386 noun: str,
2387 *,
2388 name: str | None,
2389 owner_user_id,
2390 owner_organisation_id,
2391 owner_project_id,
2392 exclude_id: UUID | None = None,
2393) -> None:
2394 """409 when this owner already has a ``model`` row called ``name``.
2396 The table's unique constraint spans the three owner columns, and Postgres
2397 treats NULLs as distinct, so for a user-owned row — two NULLs out of three
2398 — it never fires: a second "Shootout" was accepted, and the list then
2399 showed two rows nobody could tell apart. Checked here, for every owner
2400 shape, so the answer is the same 409 the constraint gives where it does
2401 bite (see ``_name_conflict``).
2402 """
2403 if not name:
2404 return
2405 query = db.query(model).filter(
2406 model.name == name,
2407 model.owner_user_id == owner_user_id,
2408 model.owner_organisation_id == owner_organisation_id,
2409 model.owner_project_id == owner_project_id,
2410 )
2411 if exclude_id is not None:
2412 query = query.filter(model.id != exclude_id)
2413 existing = query.first()
2414 # Confirmed on the row, not inferred from "something came back": the
2415 # filter is the query's job, and a row that is not this name is not a
2416 # conflict whatever answered.
2417 if existing is not None and getattr(existing, "name", None) == name:
2418 raise HTTPException(
2419 status_code=status.HTTP_409_CONFLICT,
2420 detail=f"A {noun} named '{name}' already exists. Choose another name.",
2421 )
2424def _name_conflict(exc: IntegrityError, noun: str, name: str | None) -> HTTPException:
2425 """A unique-name violation as a 409 the client can show, or the original.
2427 ``experiments`` and ``test_suites`` are unique on (owner, name). Without
2428 this, saving a second "Shootout" was a 500 with nothing to say why; the
2429 constraint's name in the driver message is what tells the two apart from
2430 any other integrity failure, which is re-raised untouched.
2431 """
2432 text = str(getattr(exc, "orig", exc))
2433 if "uq_owner_experiment_name" in text or "uq_owner_test_suite_name" in text:
2434 shown = f" named '{name}'" if name else ""
2435 return HTTPException(
2436 status_code=status.HTTP_409_CONFLICT,
2437 detail=f"A {noun}{shown} already exists. Choose another name.",
2438 )
2439 logger.exception("Integrity error saving a %s", noun)
2440 return HTTPException(
2441 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
2442 detail=f"Could not save this {noun}.",
2443 )
2446def _get_experiment(
2447 db: Session, experiment_id: UUID, current_user: User, *, read: bool = False
2448) -> Experiment:
2449 """The experiment, or 404 / 403. ``read`` for a route that only reads it
2450 — any member may; changing it needs the caller's governance level
2451 (``app/services/access.py``)."""
2452 experiment = db.get(Experiment, experiment_id)
2453 if not experiment:
2454 raise HTTPException(
2455 status_code=status.HTTP_404_NOT_FOUND, detail="Experiment not found"
2456 )
2457 (verify_resource_read if read else verify_resource_access)(
2458 experiment, current_user, db
2459 )
2460 return experiment
2463def _get_suite(
2464 db: Session, suite_id: UUID, current_user: User, *, read: bool = False
2465) -> TestSuite:
2466 """A dataset the caller may change — or, with ``read``, may read.
2468 Closed by default: a gold dataset (``is_system``) passes only the read
2469 check, so a route that forgets to say which it is refuses to edit one.
2470 """
2471 suite = db.get(TestSuite, suite_id)
2472 if not suite:
2473 raise HTTPException(
2474 status_code=status.HTTP_404_NOT_FOUND, detail="Test suite not found"
2475 )
2476 if read:
2477 verify_resource_read(suite, current_user, db)
2478 else:
2479 verify_resource_access(suite, current_user, db)
2480 return suite
2483# Two resource types share this router, so each mounts its history under its
2484# own path prefix rather than the default bare /{resource_id}/history.
2485register_history_routes(
2486 evaluation_router,
2487 resource_type=HistoryEnum.ResourceType.experiment,
2488 model=Experiment,
2489 not_found_detail="Experiment not found",
2490 # A benchmark experiment's history is its release history, readable by
2491 # all; for one's own, reading history is reading the experiment.
2492 access_check=verify_resource_read,
2493 path_prefix="/experiments",
2494)
2495register_history_routes(
2496 evaluation_router,
2497 resource_type=HistoryEnum.ResourceType.test_suite,
2498 model=TestSuite,
2499 not_found_detail="Test suite not found",
2500 # A gold dataset's history is its release history, readable by all.
2501 access_check=verify_resource_read,
2502 path_prefix="/test-suites",
2503)