Coverage for app / services / evaluation / quick_try.py: 96%
136 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"""
2Quick try — a comparison kept just long enough to be saved.
4Quick try runs one prompt against several targets. It used to persist nothing:
5the outcomes went back in the response, and "save as evaluation" rebuilt the
6evaluation from the client's copy of the inputs — with no results, so the
7saved evaluation opened on "No runs yet" and the numbers the user had just
8read were gone.
10Populating the saved evaluation with those results needs them to exist on the
11server. Taking them back from the client would put a score on record that no
12invocation can be shown to have produced, which is the one thing a result row
13must never be. So ``runner.compare`` records a comparison as an ordinary
14completed :class:`ExperimentBatch` with ordinary :class:`ExperimentRun` rows,
15**owned by nobody**, and :func:`adopt` makes it the first run of the
16evaluation the user saves. Every read path scopes batches by owner, so an
17unowned one is invisible to lists, reports and regression baselines until it
18is adopted; :func:`purge_expired` removes the ones nobody saved.
20Who ran it is recorded on the batch's ``config`` so adoption can refuse
21anybody else — a batch id is not a capability.
22"""
24from __future__ import annotations
26import logging
27from datetime import datetime, timedelta
28from typing import Any, Optional
29from uuid import UUID
31from sqlalchemy import and_
32from sqlalchemy.orm import Session
34from app.db.postgres.enums import EvaluationEnum, RunnableEnum
35from app.db.postgres.models import (
36 Experiment,
37 ExperimentBatch,
38 ExperimentRun,
39 ExperimentVariant,
40 TestCase,
41 TestSuite,
42)
43from app.services.evaluation import scorers as scoring
44from app.services.evaluation.criteria import items
45from app.services.evaluation.dataset import clean_examples
46from app.util.time import aware_utcnow
48logger = logging.getLogger(__name__)
50#: How long an unsaved Quick try stays. Long enough to walk away and come
51#: back; short enough that the scratchpad does not become storage.
52RETENTION_HOURS = 24
54#: The key on ``ExperimentBatch.config`` that marks a quick try and names who
55#: ran it. Removed on adoption, so an adopted batch reads like any other.
56CONFIG_KEY = "quick_try"
58#: The label an unsaved comparison carries. Replaced on adoption.
59LABEL = "Quick try"
61#: Keys on a run row's ``run_metadata`` that adoption reads back: which
62#: target produced the row, what that target was, and the system prompt it
63#: ran with. Written by ``runner.compare`` for every cell.
64META_TARGET_KEY = "target_key"
65META_TARGET = "target"
66META_SYSTEM_PROMPT = "system_prompt"
69class QuickTryError(ValueError):
70 """A comparison cannot be adopted. ``status`` says why, HTTP-style."""
72 def __init__(self, message: str, status: int) -> None:
73 super().__init__(message)
74 self.status = status
77def marker(owner_user_id: UUID | str) -> dict[str, Any]:
78 """The ``config`` entry that marks a batch as a quick try run by a user."""
79 return {CONFIG_KEY: {"owner_user_id": str(owner_user_id)}}
82def owner_of(batch: ExperimentBatch) -> Optional[str]:
83 """The user who ran this quick try, or None for a batch that is not one."""
84 entry = (batch.config or {}).get(CONFIG_KEY)
85 if not isinstance(entry, dict):
86 return None
87 owner = entry.get("owner_user_id")
88 return str(owner) if owner else None
91def is_unowned(batch: ExperimentBatch) -> bool:
92 return batch.experiment_id is None
95def get_for_adoption(
96 db: Session, comparison_id: UUID, user_id: UUID | str
97) -> ExperimentBatch:
98 """The quick try ``comparison_id`` names, checked for adoption by ``user_id``.
100 Raises :class:`QuickTryError` with the status a router should answer:
101 404 when there is no such comparison (or it has expired), 403 when
102 somebody else ran it, 409 when it has already been saved, is not a quick
103 try at all, or never finished.
104 """
105 batch = db.get(ExperimentBatch, comparison_id)
106 if batch is None:
107 raise QuickTryError(
108 "This comparison is no longer available — run it again to save it.",
109 404,
110 )
111 if not is_unowned(batch):
112 raise QuickTryError("This comparison has already been saved.", 409)
113 owner = owner_of(batch)
114 if owner is None:
115 raise QuickTryError("This batch is not a Quick try.", 409)
116 if owner != str(user_id):
117 raise QuickTryError("Forbidden", 403)
118 if batch.status != RunnableEnum.Status.completed:
119 state = getattr(batch.status, "value", batch.status)
120 raise QuickTryError(f"This comparison did not finish ({state}).", 409)
121 return batch
124def runs_of(db: Session, batch: ExperimentBatch) -> list[ExperimentRun]:
125 """The comparison's cells, in the order they were written."""
126 return (
127 db.query(ExperimentRun)
128 .filter(ExperimentRun.batch_id == batch.id)
129 .order_by(ExperimentRun.created_at, ExperimentRun.id)
130 .all()
131 )
134def targets_of(rows: list[ExperimentRun]) -> list[dict[str, Any]]:
135 """The targets a quick try ran, in request order, with the prompt each used.
137 Read off the run rows' metadata, which carry each target's identity and
138 system prompt — the comparison's positional key orders them.
139 """
140 by_key: dict[str, dict[str, Any]] = {}
141 for row in rows:
142 meta = row.run_metadata if isinstance(row.run_metadata, dict) else {}
143 key = str(meta.get(META_TARGET_KEY, ""))
144 if key and key not in by_key:
145 by_key[key] = {
146 "key": key,
147 "target": meta.get(META_TARGET) or {},
148 "system_prompt": meta.get(META_SYSTEM_PROMPT) or None,
149 }
150 return [by_key[key] for key in sorted(by_key, key=_key_order)]
153def _key_order(key: str) -> tuple[int, str]:
154 try:
155 return (int(key), key)
156 except ValueError:
157 return (1 << 30, key)
160def scorer_of(
161 batch: ExperimentBatch,
162) -> tuple[EvaluationEnum.Scorer, dict[str, Any], Optional[dict[str, Any]]]:
163 """The scorer, its settings, and the judge a quick try graded with.
165 Read from what was stored rather than from the request that saves it, so
166 the saved evaluation grades the way the run it holds was graded — the
167 judge included, since two models do not agree on a score and the adopted
168 batch's numbers are the ones the evaluation opens on.
169 """
170 summary = batch.summary if isinstance(batch.summary, dict) else {}
171 batch_config = batch.config if isinstance(batch.config, dict) else {}
172 raw = summary.get("scorer") or batch_config.get("scorer") or "manual"
173 try:
174 scorer = EvaluationEnum.Scorer(str(raw))
175 except ValueError:
176 scorer = EvaluationEnum.Scorer.manual
177 scorer_config = batch_config.get("scorer_config")
178 judge = batch_config.get("judge")
179 # A comparison run before criteria moved onto the dataset may still carry
180 # them in its scorer settings; ``dataset_for`` puts them on the case.
181 settings, _, _ = scoring.split_label(
182 scorer.value, scorer_config if isinstance(scorer_config, dict) else {}
183 )
184 return (
185 scorer,
186 settings,
187 dict(judge) if isinstance(judge, dict) else None,
188 )
191def dataset_for(
192 db: Session,
193 batch: ExperimentBatch,
194 rows: list[ExperimentRun],
195 *,
196 name: str,
197 owner: dict[str, Any],
198) -> TestSuite:
199 """A one-case dataset holding the question a quick try asked.
201 An evaluation always names a dataset — its cases are never inline — so
202 saving a comparison makes a small dataset alongside, owned exactly as the
203 evaluation is. The case is read off the stored run rows, not the request
204 that saves it: the client could have edited the prompt since.
206 Added and flushed, not committed; the caller's transaction holds it.
207 """
208 first = rows[0].input if rows and isinstance(rows[0].input, dict) else {}
209 # The label the cells were graded against. A comparison from before
210 # criteria moved onto the dataset carried them in its scorer settings
211 # instead; they come across to the case, so the saved experiment's next
212 # run is graded the way the adopted one was.
213 batch_config = batch.config if isinstance(batch.config, dict) else {}
214 _, legacy_criteria, legacy_checks = scoring.split_label(
215 batch_config.get("scorer"), batch_config.get("scorer_config")
216 )
217 expectation = {**(first.get("expectation") or {}), **legacy_checks}
218 dataset = TestSuite(
219 name=f"{name} cases",
220 description="Created when a Quick try was saved as an experiment.",
221 status=EvaluationEnum.Status.active,
222 **owner,
223 )
224 db.add(dataset)
225 db.flush()
226 case = TestCase(
227 test_suite_id=dataset.id,
228 name=first.get("name") or "Case 1",
229 input={"prompt": first.get("prompt") or ""},
230 expected_output=first.get("expected_output"),
231 criteria=items(first.get("criteria")) or items(legacy_criteria) or None,
232 examples=clean_examples(first.get("examples")) or None,
233 expected_behaviour=first.get("expected_behaviour"),
234 expectation=expectation or None,
235 )
236 db.add(case)
237 db.flush()
238 # The comparison's cells scored this very case, so they say so — which
239 # is what a later run's per-case regression keys on.
240 for row in rows:
241 row.test_case_id = case.id
242 return dataset
245def adopt(
246 db: Session, batch: ExperimentBatch, experiment: Experiment
247) -> list[ExperimentVariant]:
248 """Make ``batch`` the first run of ``experiment``.
250 Creates one variant per target the comparison ran — in request order,
251 carrying the target and the system prompt that produced its column — and
252 rewrites the batch's leaderboard and run rows from the comparison's
253 positional keys to those variant ids. After this the batch is
254 indistinguishable from one the evaluation ran itself.
256 Does not commit; the caller's transaction also holds the evaluation.
257 """
258 rows = runs_of(db, batch)
259 targets = targets_of(rows)
261 variants: list[ExperimentVariant] = []
262 by_key: dict[str, ExperimentVariant] = {}
263 for entry in targets:
264 variant = ExperimentVariant(
265 experiment_id=experiment.id,
266 name=_variant_name(entry["target"], len(variants) + 1),
267 prompt=entry["system_prompt"],
268 config={"target": entry["target"]},
269 )
270 db.add(variant)
271 variants.append(variant)
272 by_key[entry["key"]] = variant
273 db.flush()
275 for row in rows:
276 meta = row.run_metadata if isinstance(row.run_metadata, dict) else {}
277 variant = by_key.get(str(meta.get(META_TARGET_KEY, "")))
278 row.experiment_id = experiment.id
279 row.variant_id = variant.id if variant is not None else None
281 leaderboard = []
282 for entry in batch.leaderboard or []:
283 if not isinstance(entry, dict):
284 continue
285 variant = by_key.get(str(entry.get("variant_id", "")))
286 leaderboard.append(
287 {
288 **entry,
289 "variant_id": str(variant.id) if variant else entry.get("variant_id"),
290 }
291 )
292 batch.leaderboard = leaderboard
293 batch.variant_ids = [str(v.id) for v in variants]
294 batch.experiment_id = experiment.id
295 batch.dataset_id = experiment.dataset_id
296 batch.label = "Run 1"
297 config = dict(batch.config or {})
298 config.pop(CONFIG_KEY, None)
299 batch.config = config
300 return variants
303def _variant_name(target: dict[str, Any], position: int) -> str:
304 label = target.get("label") or target.get("agent_name")
305 if not label and target.get("provider") and target.get("model"):
306 label = f"{target['provider']}/{target['model']}"
307 return str(label or target.get("model") or f"Target {position}")
310def purge_expired(
311 db: Session,
312 *,
313 older_than: Optional[timedelta] = None,
314 now: Optional[datetime] = None,
315) -> int:
316 """Delete unowned batches older than the retention window, runs included.
318 Returns how many batches went. No commit; the caller (the scheduled job)
319 owns the transaction.
320 """
321 # ``is None`` rather than ``or``: a zero window is a real request (and a
322 # falsy timedelta), not an absent one.
323 window = timedelta(hours=RETENTION_HOURS) if older_than is None else older_than
324 cutoff = (now or aware_utcnow()) - window
325 expired = (
326 db.query(ExperimentBatch.id)
327 .filter(
328 and_(
329 ExperimentBatch.experiment_id.is_(None),
330 ExperimentBatch.created_at < cutoff,
331 )
332 )
333 .all()
334 )
335 ids = [row[0] for row in expired]
336 if not ids:
337 return 0
338 db.query(ExperimentRun).filter(ExperimentRun.batch_id.in_(ids)).delete(
339 synchronize_session=False
340 )
341 db.query(ExperimentBatch).filter(ExperimentBatch.id.in_(ids)).delete(
342 synchronize_session=False
343 )
344 return len(ids)