Coverage for app / services / evaluation / runner.py: 96%
432 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"""
2Execution engine for evaluation runs.
4Two entry points, both designed to be handed to ``BackgroundTasks``:
6* :func:`execute_batch` — runs one batch's *target × case* matrix, whether that
7 batch belongs to an evaluation (a target per variant) or to a dataset (one
8 target). They were two functions writing to two table pairs, which is why
9 regression verdicts only ever worked on one and leaderboards, promotion gates
10 and reporting only on the other.
12It uses :func:`_execute_matrix`, which fans invocation-and-scoring out
13across a small thread pool (provider calls are IO-bound and the default suite
14is dozens of cases) while keeping every database write on the calling thread —
15a SQLAlchemy ``Session`` is not thread-safe.
16"""
18from __future__ import annotations
20import logging
21import threading
22from concurrent.futures import ThreadPoolExecutor
23from dataclasses import dataclass
24from types import SimpleNamespace
25from typing import Any, Callable, Iterable, Optional
26from uuid import UUID
28from sqlalchemy.orm import Session
30from app.db.postgres.engine import SessionLocal
31from app.db.postgres.enums import EvaluationEnum, RunnableEnum, UsageEnum
32from app.db.postgres.enums import HistoryEnum
33from app.db.postgres.models import (
34 Experiment,
35 ExperimentBatch,
36 ExperimentRun,
37 ExperimentVariant,
38)
39from app.services import ai_client
40from app.services import history as history_service
41from app.services import usage as usage_service
42from app.services.evaluation import batches as batch_store
43from app.services.evaluation import context as context_service
44from app.services.evaluation import criteria as criteria_service
45from app.services.evaluation import assurance, dataset_versions
46from app.services.evaluation import quick_try, regression
47from app.services.evaluation import scorers as scoring
48from app.services.evaluation import spread as spread_service
49from app.services.evaluation.dataset import (
50 DatasetCase,
51 DatasetError,
52 cases_from_dataset,
53 clean_examples,
54)
55from app.services.evaluation.targets import (
56 ExecutionTarget,
57 Invocation,
58 TargetResolutionError,
59 _actor_of,
60 build_target,
61 ledger_identity,
62 make_judge_fn,
63 resolve_default_judge_target,
64)
65from app.util.time import aware_utcnow
67logger = logging.getLogger(__name__)
69# Concurrent provider calls per run. High enough that a 50-case suite finishes
70# in a reasonable time, low enough to stay well inside provider rate limits
71# when several runs overlap.
72DEFAULT_CONCURRENCY = 4
73MAX_CONCURRENCY = 16
75#: The error on a run svc-core stopped in the middle of (a deploy or a
76#: restart). Such a run says nothing about what it evaluated, so it is marked
77#: as interrupted (``config.interrupted``) rather than as a failure.
78INTERRUPTED = "Interrupted: svc-core stopped during the run (a deploy or a restart)."
80#: What a Quick try call's trace points at: there is no batch, so the
81#: reference names the surface instead.
82COMPARE_REFERENCE: dict[str, str] = {"source": "quick_try"}
85@dataclass
86class CaseOutcome:
87 """One (target, case) cell of an evaluation matrix, invoked and scored."""
89 case: DatasetCase
90 target_key: str
91 invocation: Invocation
92 score: scoring.ScoreResult
93 scorer_kind: str
94 #: Which pass of a repeated run produced this cell (0 on a plain run).
95 repeat: int = 0
97 @property
98 def passed(self) -> Optional[bool]:
99 # A failed invocation is a failure regardless of what the scorer says:
100 # there is no output to grade, and silently leaving it unscored would
101 # inflate the pass rate of a target whose provider is down.
102 if not self.invocation.ok:
103 return False
104 return self.score.passed
106 def metadata(self) -> dict[str, Any]:
107 meta = self.invocation.as_metadata()
108 meta["case_name"] = self.case.name
109 if self.case.case_id:
110 meta["case_id"] = self.case.case_id
111 if self.case.tags:
112 meta["tags"] = self.case.tags
113 meta["repeat"] = self.repeat
114 return meta
117# ── Scoring helpers ───────────────────────────────────────────────────────────
120def _scorer_for(
121 default_kind: str,
122 default_config: dict,
123 judge_fn: Optional[Callable],
124) -> scoring.Scorer:
125 """Build the experiment's scorer.
127 One scorer per experiment, never per case: how strictly to judge is the
128 experiment's decision, and a case that could override it would let one
129 dataset be graded two ways. What differs per case is what correct looks
130 like — criteria, reference, examples, checks — which the scorer reads off
131 the case and never out of its own config.
132 """
133 config = dict(default_config)
134 if judge_fn is not None:
135 config["judge"] = judge_fn
136 return scoring.build_scorer(default_kind, config)
139def _score_of(outcome: CaseOutcome) -> Optional[float]:
140 return outcome.score.value
143def aggregate(outcomes: Iterable[CaseOutcome], duration_ms: int = 0) -> dict[str, Any]:
144 """Summarise a set of outcomes into the shape stored on a run."""
145 items = list(outcomes)
146 scored = [o for o in items if _score_of(o) is not None]
147 verdicts = [o.passed for o in items if o.passed is not None]
148 latencies = [o.invocation.latency_ms for o in items if o.invocation.ok]
149 errors = [o for o in items if not o.invocation.ok]
151 input_tokens = sum(o.invocation.input_tokens for o in items)
152 output_tokens = sum(o.invocation.output_tokens for o in items)
154 return {
155 "total": len(items),
156 "scored": len(scored),
157 "passed": sum(1 for v in verdicts if v),
158 "failed": sum(1 for v in verdicts if not v),
159 "errors": len(errors),
160 "pass_rate": (
161 round(sum(1 for v in verdicts if v) / len(verdicts), 4)
162 if verdicts
163 else None
164 ),
165 "mean_score": (
166 round(sum(_score_of(o) or 0.0 for o in scored) / len(scored), 4)
167 if scored
168 else None
169 ),
170 "mean_latency_ms": round(sum(latencies) / len(latencies))
171 if latencies
172 else None,
173 "input_tokens": input_tokens,
174 "output_tokens": output_tokens,
175 "total_tokens": input_tokens + output_tokens,
176 "duration_ms": duration_ms,
177 "criteria": criteria_pass_rates(items),
178 **spread_service.spread(items),
179 }
182def criteria_pass_rates(outcomes: Iterable[CaseOutcome]) -> list[dict[str, Any]]:
183 """How often each of the dataset's criteria was met, across the run.
185 Only dataset criteria: they apply to every case, so "does not fabricate:
186 met 7 of 10" is a statement about the agent. A case's own criteria apply
187 to one question, and are read on that cell. Listed in the order the
188 dataset states them; empty for a run graded without per-item verdicts.
189 """
190 tally: dict[str, dict[str, Any]] = {}
191 for outcome in outcomes:
192 for verdict in (outcome.score.detail or {}).get("criteria") or []:
193 if verdict.get("source") != "dataset":
194 continue
195 entry = tally.setdefault(
196 verdict["text"],
197 {
198 "text": verdict["text"],
199 "gate": verdict.get("gate") is True,
200 "met": 0,
201 "total": 0,
202 },
203 )
204 entry["total"] += 1
205 entry["met"] += 1 if verdict.get("met") else 0
206 return list(tally.values())
209#: Answers needed before a case that every one of them failed is worth
210#: questioning. One failing answer says something about that answer; several
211#: independent ones failing the same case says something about the case.
212SUSPECT_LABEL_MIN_ANSWERS = 2
214#: Judge reasons kept per suspect case — enough to see *why* without storing
215#: every cell twice.
216SUSPECT_LABEL_REASONS = 3
219def suspect_labels(outcomes: Iterable[CaseOutcome]) -> list[dict[str, Any]]:
220 """Cases every variant failed — the first place to look for a wrong label.
222 When capable, differently configured answerers all fail the same case,
223 the likelier explanation is often the case: a wrong reference answer, a
224 criterion that contradicts the prompt, a check nobody could pass. Reported
225 beside the results rather than acted on — it is a prompt to look, not a
226 verdict — and only from graded answers: a call that errored says the
227 provider was down, not that the label is wrong.
228 """
229 by_case: dict[str, list[CaseOutcome]] = {}
230 for outcome in outcomes:
231 key = outcome.case.case_id or outcome.case.name
232 by_case.setdefault(key, []).append(outcome)
234 suspects = []
235 for cells in by_case.values():
236 graded = [o for o in cells if o.invocation.ok and o.score.passed is not None]
237 # Independent answerers, not answers: one variant failing the same
238 # case on every repeat is one configuration's weakness, not a label
239 # that nobody could satisfy.
240 answerers = {o.target_key for o in graded}
241 if len(answerers) < SUSPECT_LABEL_MIN_ANSWERS or any(o.passed for o in graded):
242 continue
243 case = graded[0].case
244 suspects.append(
245 {
246 "case_id": case.case_id,
247 "case_name": case.name,
248 "answers": len(graded),
249 "reasons": [o.score.reason for o in graded if o.score.reason][
250 :SUSPECT_LABEL_REASONS
251 ],
252 }
253 )
254 return suspects
257# ── Matrix execution ──────────────────────────────────────────────────────────
260def _case_context(case: DatasetCase) -> context_service.EvaluationContext:
261 """The situation a case declares — its history and variables.
263 Parsed rather than resolved: a case never names knowledge or tools (those
264 belong to the variant), so there is nothing here to look up or scope.
265 """
266 try:
267 return context_service.parse_situation(case.situation or None)
268 except context_service.ContextError:
269 # One malformed case must not fail the run; it evaluates without the
270 # context it asked for, and the failure is on record.
271 logger.exception("Case %r has an unusable context", case.name)
272 return context_service.EvaluationContext()
275def _rendered(
276 effective: context_service.EvaluationContext, items: list[dict[str, Any]]
277) -> list[dict[str, Any]]:
278 """Criteria items with the case's variables substituted, like its prompt."""
279 return [{**item, "text": effective.render(item["text"])} for item in items]
282def _execute_matrix(
283 targets: dict[str, tuple[ExecutionTarget, str]],
284 cases: list[DatasetCase],
285 default_scorer: str,
286 scorer_config: dict,
287 judge_fn: Optional[Callable],
288 concurrency: int,
289 should_cancel: Optional[Callable[[], bool]] = None,
290 on_progress: Optional[Callable[[int, int], None]] = None,
291 repeats: int = 1,
292) -> list[CaseOutcome]:
293 """Invoke and score every (target, case) pair, ``repeats`` times over.
295 Repeats run as whole passes — every cell once, then every cell again —
296 so a run cancelled part-way leaves complete passes behind rather than
297 some cases asked three times and others once.
299 ``targets`` maps an opaque key (variant id, or ``"target"`` for a suite
300 run) to the target and the system prompt it should run with.
302 Results come back in submission order regardless of completion order, so a
303 re-run of the same matrix writes its rows in the same sequence and the UI's
304 matrix stays stable.
305 """
306 work: list[tuple[int, str, ExecutionTarget, str, DatasetCase]] = [
307 (repeat, key, target, system_prompt, case)
308 for repeat in range(spread_service.clamp_repeats(repeats))
309 for key, (target, system_prompt) in targets.items()
310 for case in cases
311 ]
312 total = len(work)
313 # The pool's threads start with an empty context: svc-ai is told the
314 # caller's workspace for each cell's trace rows by hand (``ai_client``).
315 workspace = ai_client.current_workspace()
317 def run_one(
318 item: tuple[int, str, ExecutionTarget, str, DatasetCase],
319 ) -> CaseOutcome:
320 with ai_client.in_workspace(workspace):
321 return _run_cell(item)
323 def _run_cell(
324 item: tuple[int, str, ExecutionTarget, str, DatasetCase],
325 ) -> CaseOutcome:
326 repeat, key, target, system_prompt, case = item
327 # The variant owns capability, the case owns situation.
328 effective = context_service.merge(
329 target.context or context_service.EvaluationContext(),
330 _case_context(case),
331 )
332 # What the agent is actually asked: the prompt with the case's
333 # variables substituted and its data written out after it.
334 asked = effective.present(effective.render(case.input))
335 invocation = target.invoke(
336 asked,
337 effective.render(system_prompt),
338 context=effective,
339 )
340 scorer = _scorer_for(default_scorer, scorer_config, judge_fn)
341 if not invocation.ok:
342 result = scoring.ScoreResult(
343 value=0.0, passed=False, reason=invocation.error
344 )
345 else:
346 try:
347 result = scorer.score(
348 invocation.output,
349 effective.render(case.expected_output or "") or None,
350 {
351 # The prompt as sent, data included, so an LLM judge
352 # grades the question that was actually asked — and
353 # the conversation before it, which the agent read too.
354 "input": asked,
355 "history": effective.history,
356 "case_name": case.name,
357 "target": target.label,
358 # What correct looks like — always the dataset's,
359 # never the scorer's.
360 "expectation": case.expectation,
361 "criteria": {
362 "dataset": _rendered(effective, case.dataset_criteria),
363 "case": _rendered(effective, case.criteria),
364 },
365 "examples": [
366 {**e, "output": effective.render(e["output"])}
367 for e in case.examples
368 ],
369 # What the case expects the agent to do, and whether
370 # it paused to ask — the one behaviour code can see.
371 "behaviour": case.behaviour,
372 "asked": invocation.clarification is not None,
373 # Every tool call, for tool expectations and the judge.
374 "tool_calls": invocation.tool_calls,
375 },
376 )
377 except Exception as exc: # noqa: BLE001 — one bad cell, not the run
378 logger.exception(
379 "Scorer %s failed on case %r", default_scorer, case.name
380 )
381 result = scoring.ScoreResult(
382 value=None, passed=None, reason=f"Scoring failed: {exc}"
383 )
384 return CaseOutcome(
385 case=case,
386 target_key=key,
387 invocation=invocation,
388 score=result,
389 scorer_kind=default_scorer,
390 repeat=repeat,
391 )
393 outcomes: list[CaseOutcome] = []
394 workers = max(1, min(int(concurrency or DEFAULT_CONCURRENCY), MAX_CONCURRENCY))
395 with ThreadPoolExecutor(max_workers=workers) as pool:
396 # Chunked rather than one big map so cancellation is checked between
397 # batches and progress can be reported while the run is in flight.
398 chunk_size = workers * 2
399 for offset in range(0, total, chunk_size):
400 if should_cancel and should_cancel():
401 logger.info(
402 "Evaluation run cancelled after %d/%d", len(outcomes), total
403 )
404 break
405 outcomes.extend(pool.map(run_one, work[offset : offset + chunk_size]))
406 if on_progress:
407 on_progress(len(outcomes), total)
408 return outcomes
411def scoring_config(experiment: Any) -> dict[str, Any]:
412 """An evaluation's grading, in the shape ``_prepare_scoring`` reads.
414 Read off the columns — ``scorer``, ``scorer_config``, ``judge`` — which
415 are the evaluation's identity. Nothing else on the platform decides how a
416 cell is judged.
417 """
418 scorer = getattr(experiment, "scorer", None)
419 return {
420 "scorer": str(
421 getattr(scorer, "value", scorer) or EvaluationEnum.Scorer.manual.value
422 ),
423 "scorer_config": dict(getattr(experiment, "scorer_config", None) or {}),
424 "judge": getattr(experiment, "judge", None),
425 }
428def _prepare_scoring(
429 db: Session,
430 config: dict,
431 *,
432 owner: Any = None,
433 reference: Optional[dict[str, str]] = None,
434) -> tuple[str, dict, Optional[Callable]]:
435 """Resolve the scorer, its config, and a judge callable if needed.
437 ``config`` is what :func:`scoring_config` produces for an evaluation, or
438 Quick try's own. ``owner`` and ``reference`` make the judge as traceable
439 as the cells it grades: governed and ledgered as the owner's, and stamped
440 with the same batch on its invocation trace.
441 """
442 default_scorer = str(config.get("scorer") or EvaluationEnum.Scorer.manual.value)
443 scorer_config = dict(config.get("scorer_config") or {})
444 if (
445 "pass_threshold" not in scorer_config
446 and config.get("pass_threshold") is not None
447 ):
448 scorer_config["pass_threshold"] = config["pass_threshold"]
450 needs_judge = default_scorer == EvaluationEnum.Scorer.llm.value
451 judge_fn = None
452 if needs_judge:
453 judge_target = resolve_default_judge_target(
454 db, config.get("judge"), owner=owner
455 )
456 if judge_target is not None and reference:
457 judge_target.reference = dict(reference)
458 judge_fn = make_judge_fn(judge_target)
459 if judge_fn is None:
460 logger.warning("LLM scoring requested but no judge model is available.")
461 return default_scorer, scorer_config, judge_fn
464# ── Batch execution ───────────────────────────────────────────────────────────
465#
466# One executor. A dataset run is a batch with a single target and no variants;
467# an evaluation's batch is the same matrix with one target per variant. They
468# used to be two functions writing to two table pairs, which is why per-case
469# regression only ever worked on the first and leaderboards, promotion gates
470# and cross-experiment reporting only on the second.
473def _scorer_enum(kind: str) -> Optional[EvaluationEnum.Scorer]:
474 try:
475 return EvaluationEnum.Scorer(str(kind))
476 except ValueError:
477 return None
480def start_experiment_batch(
481 db: Session,
482 experiment: Experiment,
483 *,
484 variants: list[ExperimentVariant],
485 label: Optional[str] = None,
486 config_overrides: Optional[dict] = None,
487 started_by_user_id: Any = None,
488) -> str:
489 """Record a queued run for an evaluation and return its id.
491 Stamped with the dataset's *content* version, the evaluation's revision
492 in force and the revision of every agent it runs, so a result resolves to
493 the exact configuration that produced it — and compares only with runs
494 that asked the same content (see ``dataset_versions``). The agent
495 revisions are what make a result evidence about a *version* (see
496 ``assurance``).
497 """
498 batch = batch_store.create(
499 db,
500 experiment=experiment,
501 variant_ids=[v.id for v in variants],
502 label=label,
503 config_overrides=config_overrides,
504 dataset_id=experiment.dataset_id,
505 dataset_version=dataset_versions.current_content_version(
506 db, experiment.dataset_id
507 ),
508 evaluation_version=history_service.current_version(
509 db, HistoryEnum.ResourceType.experiment, experiment.id
510 ),
511 target_versions=assurance.target_versions(db, variants),
512 started_by_user_id=started_by_user_id,
513 )
514 return str(batch.id)
517def _owner_of(db: Session, batch: ExperimentBatch) -> Optional[Experiment]:
518 """The evaluation a run belongs to — its dataset, grading and scope.
520 Carries who started the run (``run_by_user_id``, not a column): an
521 organisation's or project's evaluation is governed and ledgered as them
522 (``targets.govern``)."""
523 if batch.experiment_id is None:
524 return None
525 experiment = db.get(Experiment, batch.experiment_id)
526 if experiment is not None:
527 experiment.run_by_user_id = getattr(batch, "started_by_user_id", None)
528 return experiment
531def _build_matrix(
532 db: Session,
533 batch: ExperimentBatch,
534 owner: Experiment,
535) -> tuple[dict[str, tuple[ExecutionTarget, str]], list[DatasetCase]]:
536 """The targets and cases this run executes.
538 Cases come from the evaluation's dataset; a target per variant. Everything
539 downstream — scoring, aggregation, the leaderboard, the regression
540 comparison — works on the (target key, case) cell and never cares which.
541 """
542 reference = batch_reference(batch)
543 cases = cases_from_dataset(db, owner.dataset_id)
544 variants = load_variants(db, batch.experiment_id, batch.variant_ids or [])
545 if not variants:
546 raise DatasetError("This run has no runnable variants.")
548 targets: dict[str, tuple[ExecutionTarget, str]] = {}
549 for variant in variants:
550 variant_config = dict(variant.config or {})
551 spec = variant_config.get("target")
552 if not spec:
553 raise TargetResolutionError(
554 f"Variant {variant.name!r} has no model or agent configured."
555 )
556 # A variant's context is its capability — what it may reach while
557 # it answers. Resolved once per variant, not once per case.
558 target = build_target(
559 spec,
560 db,
561 context_service.resolve(
562 db,
563 variant_config.get("context") or spec.get("context"),
564 owner=owner,
565 ),
566 owner=owner,
567 )
568 target.reference = {**reference, "variant_id": str(variant.id)}
569 targets[str(variant.id)] = (target, variant.prompt or "")
570 return targets, cases
573def batch_reference(batch: ExperimentBatch) -> dict[str, str]:
574 """The ids an invocation trace carries back to this batch.
576 Sent to svc-ai on every cell (and on the judge) and stored on the
577 invocation's request snapshot, so the activity feed can open the exact
578 evaluation or dataset — and the run — a recorded LLM call belongs to.
579 """
580 reference = {"batch_id": str(batch.id)}
581 if batch.experiment_id is not None:
582 reference["experiment_id"] = str(batch.experiment_id)
583 if getattr(batch, "dataset_id", None) is not None:
584 reference["dataset_id"] = str(batch.dataset_id)
585 return reference
588def _ledger_owner(db: Session, owner: Any) -> Any:
589 """Whose ledger an evaluation's calls go on: its owner, or — for an
590 organisation's or project's evaluation — the person it ran as
591 (``targets.govern``); those used to be ledgered as nobody. None for a run
592 nobody owns (the platform benchmark), which is not ledgered."""
593 if owner is None:
594 return None
595 return getattr(owner, "owner_user_id", None) or _actor_of(db, owner)
598def _ledger_call(
599 db: Session,
600 owner: Any,
601 owner_user_id: Any,
602 target: ExecutionTarget,
603 invocation: Invocation,
604) -> Any:
605 """Append the ledger row for one call an evaluation made — a cell, or
606 the judge grading one. Recorded against the target's own scope (the
607 agent or model that answered) plus the project or organisation that owns
608 the evaluation, so an ownership-scoped quota has traffic to count. The
609 row, or None when the write failed. Does not commit."""
610 # The model that wrote the answer: an Economy profile's lighter one when
611 # svc-ai says it did, else the target's own.
612 scope_type, scope_id, model_info = ledger_identity(target, invocation)
613 return usage_service.record_usage(
614 db,
615 owner_user_id=owner_user_id,
616 execution_type="evaluation",
617 scope_type=scope_type,
618 scope_id=scope_id,
619 owner_project_id=getattr(owner, "owner_project_id", None),
620 owner_organisation_id=getattr(owner, "owner_organisation_id", None),
621 ai_model_id=model_info.get("id") if model_info else None,
622 input_tokens=invocation.input_tokens,
623 output_tokens=invocation.output_tokens,
624 model_info=model_info or None,
625 latency_ms=invocation.latency_ms,
626 outcome=UsageEnum.Outcome.ok if invocation.ok else UsageEnum.Outcome.error,
627 # Attributed to the evaluation, whatever agent or model answered:
628 # "what did testing this cost?" is asked of the evaluation. A
629 # Quick try has no evaluation yet, so it has no id.
630 source_type=UsageEnum.Source.experiment,
631 source_id=getattr(owner, "id", None),
632 measured=invocation.usage,
633 invocation_id=invocation.invocation_id,
634 )
637def ledger_as_it_goes(
638 db: Session,
639 owner: Any,
640 targets: dict[str, tuple[ExecutionTarget, str]],
641 judge_fn: Any = None,
642) -> None:
643 """Put each of a run's calls on the usage ledger the moment it finishes.
645 A run's calls used to reach the ledger only when the whole run ended, so
646 a cost cap judging cell 40 had not seen cells 1–39 — and a run could
647 spend past any cap by its whole cost. Now each cell, and each call the
648 judge makes grading one, is written in a transaction of its own as it
649 finishes (``ExecutionTarget.on_call``, from the pool thread that made
650 it), and the next cell's policy check reads it like any other spend.
651 Concurrent cells still in flight are the only overshoot.
653 Its own transaction on purpose: the money is spent whether or not the
654 run's results are stored, and a run that dies mid-way has its spend on
655 record rather than none. A write that fails leaves the call for
656 :func:`record_ledger`'s sweep at the end.
657 """
658 owner_user_id = _ledger_owner(db, owner)
659 if not owner_user_id:
660 return
662 def ledger(target: ExecutionTarget, invocation: Invocation) -> None:
663 if invocation.blocked or invocation.ledgered:
664 return
665 session = SessionLocal()
666 try:
667 if _ledger_call(session, owner, owner_user_id, target, invocation):
668 session.commit()
669 invocation.ledgered = True
670 except Exception: # noqa: BLE001 — the sweep at the end retries it
671 logger.exception("Could not ledger an evaluation call as it finished")
672 session.rollback()
673 finally:
674 session.close()
676 for target, _system_prompt in targets.values():
677 target.on_call = ledger
678 judge_target = getattr(judge_fn, "target", None)
679 if judge_target is not None:
680 judge_target.on_call = ledger
683def record_ledger(
684 db: Session,
685 owner: Any,
686 targets: dict[str, tuple[ExecutionTarget, str]],
687 outcomes: Iterable[CaseOutcome],
688 judge_fn: Any = None,
689) -> int:
690 """Append one usage-ledger row per call that reached the provider and is
691 not on the ledger yet — every one, for a run that does not ledger as it
692 goes (Quick try), else the few whose write failed then.
694 Evaluation cells used to be invisible to the ledger, so a cost cap could
695 not count them and a spend board could not show what testing cost.
697 A blocked cell is *not* written: it never reached the provider, and it is
698 already on record as one ``governance_events`` row per rule that refused
699 it (see ``UsageEnum.Outcome``). A failed call is written with the error
700 outcome: an error rate counts it, and a cost cap counts what it spent.
702 Does not commit — the caller appends it to the transaction holding the
703 rows it documents. Returns the number of rows written.
704 """
705 owner_user_id = _ledger_owner(db, owner)
706 if not owner_user_id:
707 return 0
708 written = 0
709 # The cells, then the judge's grading calls: both are the evaluation's
710 # spend, and the judge — a model call per graded answer — used to be the
711 # part of it nothing counted.
712 calls: list[tuple[ExecutionTarget, Invocation]] = []
713 for outcome in outcomes:
714 entry = targets.get(outcome.target_key)
715 if entry is not None:
716 calls.append((entry[0], outcome.invocation))
717 judge_target = getattr(judge_fn, "target", None)
718 if judge_target is not None:
719 # Drained, not read: the optimiser reuses one judge across rounds and
720 # ledgers after each, so a call must be counted exactly once.
721 judged = getattr(judge_fn, "invocations", [])
722 drained = list(judged)
723 del judged[: len(drained)]
724 calls.extend((judge_target, invocation) for invocation in drained)
725 for target, invocation in calls:
726 if invocation.blocked or invocation.ledgered:
727 continue
728 row = _ledger_call(db, owner, owner_user_id, target, invocation)
729 if row is not None:
730 invocation.ledgered = True
731 written += 1
732 return written
735def _summed(captures: Iterable[Any]) -> ai_client.UsageCapture:
736 """Every capture in ``captures`` added up."""
737 total = ai_client.UsageCapture()
738 for capture in captures:
739 if hasattr(capture, "as_summary"):
740 total.add(capture.as_summary())
741 return total
744def measured_usage(
745 outcomes: Iterable[CaseOutcome], judge_fn: Any = None
746) -> Optional[dict[str, Any]]:
747 """What a run's model calls cost as svc-ai measured them: every cell and
748 every judge call, priced per model — or None when none was made.
750 Stored on the run's summary: for a run nobody owns — the platform
751 benchmark — the only record of its spend, since the usage ledger is
752 keyed by user. The top level is the whole run; ``cells`` is what the
753 answers cost, ``judge`` what grading them did, and ``answers`` how many
754 cells there were — so a run's cost per answer leaves the grading out, as
755 a target's own cost should. Read before ``record_ledger``, which drains
756 the judge's calls.
757 """
758 outcomes = list(outcomes)
759 cells = _summed(getattr(o.invocation, "usage", None) for o in outcomes)
760 judge = _summed(
761 getattr(invocation, "usage", None)
762 for invocation in getattr(judge_fn, "invocations", None) or []
763 )
764 report = _summed([cells, judge]).report()
765 if report is None:
766 return None
767 return {
768 **report,
769 "cells": cells.report(),
770 "judge": judge.report(),
771 "answers": len(outcomes),
772 }
775def process_stopping() -> bool:
776 """Whether this process is shutting down.
778 Once the main thread has finished, Python is joining the pool threads
779 and refuses every new task ("cannot schedule new futures after
780 interpreter shutdown"): a run still going would fail on its next cell and
781 be recorded as a failure it is not.
782 """
783 return not threading.main_thread().is_alive()
786def is_interrupted(batch: Any) -> bool:
787 """Whether ``batch`` was cut off by a stop rather than failing."""
788 return (getattr(batch, "config", None) or {}).get("interrupted") is True
791def mark_interrupted(batch: Any, now: Any = None) -> None:
792 """Record ``batch`` as interrupted. Does not commit."""
793 batch.status = RunnableEnum.Status.failed
794 batch.finished_at = now or aware_utcnow()
795 batch.error = INTERRUPTED
796 batch.config = {**(batch.config or {}), "interrupted": True}
799def _shutdown_error(exc: BaseException) -> bool:
800 """An error that means the process is stopping, not that the run failed."""
801 return isinstance(exc, RuntimeError) and "cannot schedule new futures" in str(exc)
804def unusable(
805 outcomes: list[CaseOutcome], max_error_share: float = 1.0
806) -> Optional[str]:
807 """Why a finished run measures nothing, or None when it measures something.
809 A cell whose call errored is scored 0 — right for a target that fails on
810 one question, wrong for a run where svc-ai was unreachable throughout, which
811 would otherwise be stored as a score of 0 and compared as a regression. So a
812 run in which every answer errored is no measurement, and a caller may set
813 a lower bar (``max_error_share``) where a measurement must be clean.
814 """
815 if not outcomes:
816 return None
817 errors = [o for o in outcomes if not o.invocation.ok]
818 if not errors:
819 return None
820 if len(errors) < len(outcomes) and len(errors) / len(outcomes) <= max_error_share:
821 return None
822 first = errors[0].invocation.error or "no error was given"
823 return (
824 f"{len(errors)} of {len(outcomes)} answers failed, so the run measures "
825 f"nothing (first error: {first})"
826 )
829def execute_batch(
830 batch_id: UUID,
831 *,
832 should_stop: Optional[Callable[[], bool]] = None,
833 max_error_share: float = 1.0,
834) -> None:
835 """Background task: run one batch's (target x case) matrix to completion.
837 Every target is evaluated on identical inputs with an identical scorer,
838 which is what makes the resulting leaderboard a fair comparison and the
839 resulting regression verdict a real one.
841 ``should_stop`` ends the run between cells — the process is going away —
842 and the run is recorded as interrupted. A run in which more than
843 ``max_error_share`` of the answers errored (every answer, by default) is
844 recorded as failed with the reason (:func:`unusable`), not as a score.
845 """
847 def stopping() -> bool:
848 return process_stopping() or bool(should_stop and should_stop())
850 db = SessionLocal()
851 started = aware_utcnow()
852 workspace_token = None
853 try:
854 batch = db.get(ExperimentBatch, batch_id)
855 if batch is None:
856 logger.warning("Batch %s vanished before execution", batch_id)
857 return
858 owner = _owner_of(db, batch)
859 if owner is None:
860 logger.warning("Batch %s has no evaluation", batch_id)
861 return
863 owner_id = batch.experiment_id
864 config = {**(owner.config or {}), **(batch.config or {})}
865 # The evaluation's workspace, for svc-ai's trace rows: a background
866 # task, so whichever page started the run is not the authority.
867 from app.services import workspace as workspace_service
869 home = workspace_service.home_of(db, owner)
870 if home is not None:
871 workspace_token = ai_client.use_workspace(home.key)
873 batch_store.update(
874 db,
875 owner_id,
876 batch_id,
877 status=RunnableEnum.Status.running,
878 started_at=started,
879 )
881 targets, cases = _build_matrix(db, batch, owner)
882 default_scorer, scorer_config, judge_fn = _prepare_scoring(
883 db, scoring_config(owner), owner=owner, reference=batch_reference(batch)
884 )
885 # Each cell and judge call on the ledger as it finishes, so a cost
886 # cap judging the next cell counts it (``record_ledger`` below sweeps
887 # up any write that failed).
888 ledger_as_it_goes(db, owner, targets, judge_fn)
890 repeats = spread_service.clamp_repeats(config.get("repeats"))
891 total = len(targets) * len(cases) * repeats
892 batch_store.update(
893 db, owner_id, batch_id, progress={"completed": 0, "total": total}
894 )
896 outcomes = _execute_matrix(
897 targets=targets,
898 cases=cases,
899 default_scorer=default_scorer,
900 scorer_config=scorer_config,
901 judge_fn=judge_fn,
902 concurrency=int(config.get("concurrency") or DEFAULT_CONCURRENCY),
903 repeats=repeats,
904 should_cancel=lambda: (
905 stopping() or batch_store.is_cancelled(db, owner_id, batch_id)
906 ),
907 on_progress=lambda done, tot: batch_store.update(
908 db, owner_id, batch_id, progress={"completed": done, "total": tot}
909 ),
910 )
912 finished = aware_utcnow()
913 for outcome in outcomes:
914 db.add(
915 _run_row(
916 batch,
917 outcome,
918 variant_id=_variant_id(outcome.target_key),
919 started=started,
920 finished=finished,
921 )
922 )
923 usage = measured_usage(outcomes, judge_fn)
924 record_ledger(db, owner, targets, outcomes, judge_fn=judge_fn)
925 db.commit()
927 duration_ms = int((finished - started).total_seconds() * 1000)
928 summary = aggregate(outcomes, duration_ms)
929 if usage is not None:
930 summary["usage"] = usage
931 summary["scorer"] = default_scorer
932 summary["suspect_labels"] = suspect_labels(outcomes)
933 summary["inconsistent_cases"] = spread_service.inconsistent_cases(outcomes)
934 cancelled = batch_store.is_cancelled(db, owner_id, batch_id)
935 # Stopped short by the process going away: what ran is kept (it was
936 # paid for), and the run is marked interrupted rather than scored.
937 interrupted = not cancelled and len(outcomes) < total and stopping()
938 problem = (
939 None if (cancelled or interrupted) else unusable(outcomes, max_error_share)
940 )
941 batch_store.update(
942 db,
943 owner_id,
944 batch_id,
945 status=(
946 RunnableEnum.Status.cancelled
947 if cancelled
948 else RunnableEnum.Status.failed
949 if (interrupted or problem)
950 else RunnableEnum.Status.completed
951 ),
952 finished_at=finished,
953 summary=summary,
954 leaderboard=leaderboard(outcomes, targets),
955 progress={"completed": len(outcomes), "total": total},
956 **({"error": problem} if problem else {}),
957 )
958 if interrupted:
959 batch = db.get(ExperimentBatch, batch_id)
960 mark_interrupted(batch, finished)
961 db.commit()
963 if not (cancelled or interrupted or problem):
964 # Compare against the last comparable run of the same experiment or
965 # dataset. Skipped for a cancelled batch: its aggregate covers only
966 # the cells that happened to finish, and comparing a partial run
967 # against a full one invents a regression that is not there.
968 batch = db.get(ExperimentBatch, batch_id)
969 regression.annotate_batch(db, batch, owner_config=owner.config)
970 # A regression is a governance signal, not just a badge: it goes
971 # to the same review queue an audit rule's flag does.
972 assurance.open_regression_review(db, batch, owner)
973 db.commit()
975 logger.info(
976 "Batch %s finished: %d outcome(s) across %d target(s)",
977 batch_id,
978 len(outcomes),
979 len(targets),
980 )
981 except Exception as exc: # noqa: BLE001 — the failure must land on the batch
982 db.rollback()
983 batch = db.get(ExperimentBatch, batch_id)
984 if _shutdown_error(exc) or stopping():
985 # Not a failure of what was evaluated: the process is stopping.
986 logger.warning("Batch %s interrupted by shutdown", batch_id)
987 if batch is not None:
988 mark_interrupted(batch)
989 db.commit()
990 else:
991 logger.exception("Batch %s failed", batch_id)
992 if batch is not None:
993 batch_store.update(
994 db,
995 batch.experiment_id,
996 batch_id,
997 status=RunnableEnum.Status.failed,
998 finished_at=aware_utcnow(),
999 error=f"{type(exc).__name__}: {exc}",
1000 )
1001 finally:
1002 if workspace_token is not None:
1003 ai_client.reset_workspace(workspace_token)
1004 db.close()
1007def _run_row(
1008 batch: ExperimentBatch,
1009 outcome: CaseOutcome,
1010 *,
1011 variant_id: Optional[UUID],
1012 started: Any,
1013 finished: Any,
1014 extra_metadata: Optional[dict[str, Any]] = None,
1015) -> ExperimentRun:
1016 """One ``experiment_runs`` row for a scored cell.
1018 Shared by a batch's execution and by Quick try, so a comparison's cell is
1019 stored exactly as an evaluation's would be — which is what lets an
1020 evaluation adopt a comparison as its first run without translation.
1021 """
1022 return ExperimentRun(
1023 experiment_id=batch.experiment_id,
1024 variant_id=variant_id,
1025 batch_id=batch.id,
1026 test_case_id=_case_id(outcome.case),
1027 input=outcome.case.describe(),
1028 output=outcome.invocation.output or None,
1029 score=outcome.score.as_score_json(outcome.scorer_kind),
1030 score_reason=outcome.score.reason,
1031 scorer=_scorer_enum(outcome.scorer_kind),
1032 passed=outcome.passed,
1033 status=(
1034 RunnableEnum.Status.completed
1035 if outcome.invocation.ok
1036 else RunnableEnum.Status.failed
1037 ),
1038 started_at=started,
1039 finished_at=finished,
1040 run_metadata={**outcome.metadata(), **(extra_metadata or {})},
1041 )
1044def _variant_id(target_key: str) -> Optional[UUID]:
1045 """The variant a matrix key names, or None for a positional key."""
1046 try:
1047 return UUID(target_key)
1048 except (ValueError, AttributeError):
1049 return None
1052def _case_id(case: DatasetCase) -> Optional[UUID]:
1053 """The stored case this cell scored, or None for an inline one."""
1054 if not case.case_id:
1055 return None
1056 try:
1057 return UUID(str(case.case_id))
1058 except (ValueError, AttributeError):
1059 return None
1062def _variant_cost(
1063 target: Optional[ExecutionTarget], items: list[CaseOutcome]
1064) -> dict[str, Any]:
1065 """What a variant's answers cost — over its answers only: grading is the
1066 experiment's cost, not the variant's, so judge calls are not in it.
1068 What svc-ai measured for each answer, priced per call on the model that
1069 made it — an agent's triage, retrieval and quality check included, cache
1070 reads at their own rate. The estimate from the answers' tokens at the
1071 variant's list price (``usage.estimate_cost``) is the fallback for a run
1072 nothing measured. None, not zero, when any of it could not be priced:
1073 an unpriced variant is not a free one, and "best value" must not rank
1074 it as if it were.
1075 """
1076 measured = _summed(getattr(o.invocation, "usage", None) for o in items)
1077 if measured.measured:
1078 if measured.cost_usd is None or measured.unpriced_calls:
1079 return {"cost_usd": None, "cost_per_case_usd": None}
1080 cost = measured.cost_usd
1081 else:
1082 # A cost estimate is worth less than the run it describes: a target
1083 # that cannot say its model is an unpriced variant, never a failed
1084 # batch.
1085 model_info = getattr(target, "model_info", None) if target is not None else None
1086 input_tokens = sum(o.invocation.input_tokens for o in items)
1087 output_tokens = sum(o.invocation.output_tokens for o in items)
1088 cost = usage_service.estimate_cost(input_tokens, output_tokens, model_info)
1089 if cost is None:
1090 return {"cost_usd": None, "cost_per_case_usd": None}
1091 # Per answer: on a repeated run ``items`` holds every repeat, so this is
1092 # still what asking one case once costs.
1093 return {
1094 "cost_usd": float(cost),
1095 "cost_per_case_usd": float(cost) / len(items) if items else None,
1096 }
1099def leaderboard(
1100 outcomes: Iterable[CaseOutcome],
1101 targets: dict[str, tuple[ExecutionTarget, str]],
1102) -> list[dict[str, Any]]:
1103 """Rank variants by mean score, then pass rate, then latency.
1105 Latency breaks ties because two prompts that score identically are not
1106 equally good — the faster and cheaper one wins.
1107 """
1108 grouped: dict[str, list[CaseOutcome]] = {}
1109 for outcome in outcomes:
1110 grouped.setdefault(outcome.target_key, []).append(outcome)
1112 rows = [
1113 {
1114 "variant_id": key,
1115 "target": targets[key][0].describe() if key in targets else None,
1116 **aggregate(items),
1117 **_variant_cost(targets[key][0] if key in targets else None, items),
1118 }
1119 for key, items in grouped.items()
1120 ]
1121 rows.sort(
1122 key=lambda r: (
1123 -(r.get("mean_score") if r.get("mean_score") is not None else -1),
1124 -(r.get("pass_rate") if r.get("pass_rate") is not None else -1),
1125 r.get("mean_latency_ms") or 0,
1126 )
1127 )
1128 for rank, row in enumerate(rows, start=1):
1129 row["rank"] = rank
1130 return rows
1133def load_variants(
1134 db: Session, experiment_id: UUID, variant_ids: Optional[list] = None
1135) -> list[ExperimentVariant]:
1136 """Load an experiment's variants in stable creation order.
1138 Shared with the router so the variants validated at request time are
1139 exactly the ones the batch later runs, in the same order.
1140 """
1141 query = db.query(ExperimentVariant).filter(
1142 ExperimentVariant.experiment_id == experiment_id
1143 )
1144 if variant_ids:
1145 wanted = []
1146 for raw in variant_ids:
1147 try:
1148 wanted.append(raw if isinstance(raw, UUID) else UUID(str(raw)))
1149 except (ValueError, AttributeError):
1150 continue
1151 query = query.filter(ExperimentVariant.id.in_(wanted))
1152 return query.order_by(ExperimentVariant.created_at, ExperimentVariant.id).all()
1155# ── Ad-hoc comparison ─────────────────────────────────────────────────────────
1158def compare(
1159 db: Session,
1160 *,
1161 prompt: str,
1162 targets: list[dict],
1163 owner_user_id: str | None = None,
1164 system_prompt: str = "",
1165 expected_output: Optional[str] = None,
1166 criteria: Any = None,
1167 examples: Optional[list[dict]] = None,
1168 expectation: Optional[dict] = None,
1169 expected_behaviour: Optional[str] = None,
1170 scorer: Optional[str] = None,
1171 scorer_config: Optional[dict] = None,
1172 judge: Optional[dict] = None,
1173) -> dict[str, Any]:
1174 """Run one prompt against several targets at once and return the outputs.
1176 This is the scratchpad path: a user tries a prompt across three models
1177 before deciding whether it is worth keeping. The outcomes are recorded as
1178 an **unowned** batch — ordinary run rows, ordinary summary and leaderboard,
1179 belonging to no evaluation — so that "save as evaluation" can adopt them
1180 as the evaluation's first run rather than discard the numbers the user
1181 just read (see ``quick_try``). Nothing appears in any list until it is
1182 saved; unsaved comparisons are purged after ``quick_try.RETENTION_HOURS``.
1184 The question's label — reference answer, criteria, graded examples,
1185 checks — travels as the case's, exactly as a dataset case's would, so
1186 saving the comparison puts it on the dataset's one case rather than on
1187 the experiment's scorer.
1189 Answers ``{"comparison_id": ..., "results": [...]}``. The id is None when
1190 there is no user to record the comparison for, in which case nothing is
1191 persisted at all.
1192 """
1193 # The scratchpad reaches a provider, so it is governed by the user's rules
1194 # and on the ledger like any other call.
1195 owner = SimpleNamespace(
1196 owner_user_id=owner_user_id,
1197 owner_organisation_id=None,
1198 owner_project_id=None,
1199 )
1200 config = {
1201 "scorer": scorer,
1202 "scorer_config": scorer_config or {},
1203 "judge": judge,
1204 }
1205 case = DatasetCase(
1206 input=prompt,
1207 name="Comparison",
1208 expected_output=expected_output,
1209 criteria=criteria_service.items(criteria),
1210 examples=clean_examples(examples),
1211 expectation=dict(expectation or {}),
1212 behaviour=expected_behaviour,
1213 )
1214 batch: Optional[ExperimentBatch] = None
1215 if owner_user_id:
1216 batch = batch_store.create(
1217 db,
1218 variant_ids=[],
1219 dataset_spec={
1220 "type": "inline",
1221 "cases": [case.describe()],
1222 },
1223 config_overrides={
1224 "scorer": scorer or EvaluationEnum.Scorer.manual.value,
1225 "scorer_config": scorer_config or {},
1226 # Stored so adopting this comparison as an evaluation carries
1227 # the judge that actually graded it — an evaluation that
1228 # opened on these results while naming a different judge
1229 # would misattribute every score on the page.
1230 "judge": judge,
1231 },
1232 quick_try_owner_id=owner_user_id,
1233 )
1234 reference = (
1235 {**COMPARE_REFERENCE, "batch_id": str(batch.id)}
1236 if batch
1237 else dict(COMPARE_REFERENCE)
1238 )
1240 built: dict[str, tuple[ExecutionTarget, str]] = {}
1241 for index, spec in enumerate(targets):
1242 target = build_target(spec, db, owner=owner)
1243 # The trace says what the call was, so it never reads as a chat — and
1244 # which comparison it belongs to, so it can be walked back to.
1245 target.reference = dict(reference)
1246 built[str(index)] = (target, spec.get("system_prompt") or system_prompt)
1248 default_scorer, resolved_config, judge_fn = _prepare_scoring(
1249 db, config, owner=owner, reference=reference
1250 )
1252 started = aware_utcnow()
1253 if batch is not None:
1254 batch_store.update(
1255 db,
1256 None,
1257 batch.id,
1258 status=RunnableEnum.Status.running,
1259 started_at=started,
1260 progress={"completed": 0, "total": len(built)},
1261 )
1263 outcomes = _execute_matrix(
1264 targets=built,
1265 cases=[case],
1266 default_scorer=default_scorer,
1267 scorer_config=resolved_config,
1268 judge_fn=judge_fn,
1269 concurrency=len(built) or 1,
1270 )
1271 finished = aware_utcnow()
1273 if batch is not None:
1274 # Stored exactly as an evaluation's cells are, keyed by position until
1275 # adoption maps each key to the variant it becomes.
1276 for outcome in outcomes:
1277 target, prompt_used = built[outcome.target_key]
1278 db.add(
1279 _run_row(
1280 batch,
1281 outcome,
1282 variant_id=None,
1283 started=started,
1284 finished=finished,
1285 extra_metadata={
1286 quick_try.META_TARGET_KEY: outcome.target_key,
1287 quick_try.META_TARGET: target.describe(),
1288 quick_try.META_SYSTEM_PROMPT: prompt_used or None,
1289 },
1290 )
1291 )
1292 record_ledger(db, owner, built, outcomes, judge_fn=judge_fn)
1293 summary = aggregate(outcomes, int((finished - started).total_seconds() * 1000))
1294 summary["scorer"] = default_scorer
1295 summary["suspect_labels"] = suspect_labels(outcomes)
1296 # ``update`` commits, and the run and ledger rows added above go with
1297 # it — one transaction, so the batch cannot exist without its cells.
1298 batch_store.update(
1299 db,
1300 None,
1301 batch.id,
1302 status=RunnableEnum.Status.completed,
1303 finished_at=finished,
1304 summary=summary,
1305 leaderboard=leaderboard(outcomes, built),
1306 progress={"completed": len(outcomes), "total": len(built)},
1307 )
1309 by_key = {o.target_key: o for o in outcomes}
1310 results = []
1311 for key, (target, prompt_used) in built.items():
1312 outcome = by_key.get(key)
1313 if outcome is None:
1314 continue
1315 results.append(
1316 {
1317 "target": target.describe(),
1318 "system_prompt": prompt_used,
1319 "output": outcome.invocation.output,
1320 "error": outcome.invocation.error,
1321 "score": outcome.score.value,
1322 "score_reason": outcome.score.reason,
1323 "passed": outcome.passed,
1324 "scorer": default_scorer,
1325 **outcome.invocation.as_metadata(),
1326 }
1327 )
1328 return {"comparison_id": str(batch.id) if batch else None, "results": results}