Coverage for app / services / evaluation / promotion.py: 97%
89 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"""
2Promotion gates — the check between "this variant scored well" and "this
3variant is now what the agent says".
5Promoting a variant overwrites a live agent's system prompt. Until now that was
6an unconditional write: the endpoint existed to save a copy-and-paste, and
7nothing stopped somebody promoting the variant that scored *worse* than the
8prompt already in production. This module is the check, and it is deliberately
9narrow about what it will claim.
11The comparison is against the **control** — the variant representing what the
12agent already says — measured in the same batch, on the same cases, with the
13same scorer. Comparing against the batch winner instead would be a different
14question ("is this the best?"), and promoting a non-winner is a legitimate
15choice; comparing against a previous batch would compare across datasets.
17The gate blocks on evidence of a regression, never on the absence of evidence.
18A variant that was never scored, a batch with no control, an experiment whose
19config was hand-edited into nonsense: all report ``unmeasured`` and let the
20promotion through with the reason attached. A gate that blocked whenever it
21could not tell would be routed around within a week, and then it would be
22protecting nothing. What it does instead is refuse to be *silent*: a forced
23promotion past a real regression is recorded on the experiment, alongside the
24agent version it produced.
25"""
27from __future__ import annotations
29import logging
30from enum import StrEnum
31from typing import Any, Optional
33from sqlalchemy.exc import SQLAlchemyError
34from sqlalchemy.orm import Session
36from app.db.postgres.enums import RunnableEnum
37from app.db.postgres.models import (
38 Agent,
39 Experiment,
40 ExperimentBatch,
41 ExperimentVariant,
42)
43from app.services.evaluation import batches as batch_store
44from app.services.evaluation import regression
45from app.services.evaluation.runner import load_variants
46from app.util.time import aware_utcnow, utc_isoformat
48logger = logging.getLogger(__name__)
50#: Promotion records retained on ``Experiment.config``. A promotion is a
51#: decision rather than a derivable fact, so unlike a batch summary it cannot be
52#: recomputed — but the agent's own version history is the durable record, and
53#: this is the experiment-side index into it.
54MAX_RETAINED_PROMOTIONS = 20
56#: How much of a reviewer's note to keep.
57MAX_NOTE_LENGTH = 1000
60class GateStatus(StrEnum):
61 """What the gate was able to establish."""
63 #: Measured against a control and no gating metric was worse.
64 clear = "clear"
65 #: Measured against a control and a gating metric was worse.
66 blocked = "blocked"
67 #: Could not be measured. Never blocks — see the module docstring.
68 unmeasured = "unmeasured"
71def _completed_batches(db: Session, experiment: Experiment) -> list[ExperimentBatch]:
72 """The experiment's completed batches, newest first.
74 A cancelled or failed batch's leaderboard covers only the cells that
75 happened to finish, which is not a basis for a promotion decision. A batch
76 with no leaderboard is no basis either — there is nothing to compare.
77 """
78 try:
79 batches = batch_store.list_for(db, experiment.id)
80 except SQLAlchemyError:
81 logger.exception("Could not load batches for experiment %s", experiment.id)
82 return []
83 return [
84 batch
85 for batch in batches
86 if batch.status == RunnableEnum.Status.completed
87 and isinstance(batch.leaderboard, list)
88 ]
91def _leaderboard_row(batch: ExperimentBatch, variant_id: str) -> Optional[dict]:
92 for row in batch.leaderboard or []:
93 if isinstance(row, dict) and str(row.get("variant_id")) == variant_id:
94 return row
95 return None
98def _control_variant(
99 variants: list[ExperimentVariant], agent: Agent, *, exclude: Any
100) -> tuple[Optional[ExperimentVariant], Optional[str]]:
101 """The variant that stands for what the agent already says.
103 Two ways to be the control, in order:
105 1. ``config['control'] is True`` — declared, so an experiment can name its
106 baseline even after the agent has moved on.
107 2. Its prompt is the agent's current system prompt — inferred, so the
108 common case (one variant carries the existing prompt, the others are
109 rewrites of it) needs no extra bookkeeping.
111 Returns the control and, when there is none, why.
112 """
113 candidates = [v for v in variants if v.id != exclude]
115 declared = [v for v in candidates if (v.config or {}).get("control") is True]
116 if len(declared) == 1:
117 return declared[0], None
118 if len(declared) > 1:
119 # Ambiguous by declaration. Guessing which one counts would make the
120 # verdict depend on row order, so it reports instead.
121 return None, (
122 "This experiment declares more than one control variant, so there "
123 "is no single baseline to compare against."
124 )
126 current = (agent.system_prompt or "").strip()
127 if not current:
128 return None, (
129 "This agent has no system prompt yet, so there is nothing for the "
130 "variant to be worse than."
131 )
132 matching = [v for v in candidates if (v.prompt or "").strip() == current]
133 if matching:
134 return matching[0], None
135 return None, (
136 "No variant in this experiment carries the agent's current prompt, so "
137 "there is no like-for-like baseline. Mark one variant as the control "
138 "to gate future promotions."
139 )
142def _describe_variant(
143 variant: ExperimentVariant, row: Optional[dict]
144) -> dict[str, Any]:
145 described: dict[str, Any] = {
146 "variant_id": str(variant.id),
147 "variant_name": variant.name,
148 }
149 for key in ("mean_score", "pass_rate", "rank", "total", "errors"):
150 if row and key in row:
151 described[key] = row[key]
152 return described
155def _unmeasured(reason: str, **extra: Any) -> dict[str, Any]:
156 return {
157 "status": GateStatus.unmeasured.value,
158 "reasons": [reason],
159 "metrics": [],
160 "batch": None,
161 "candidate": None,
162 "control": None,
163 **extra,
164 }
167def check(
168 db: Session,
169 experiment: Experiment,
170 variant: ExperimentVariant,
171 agent: Agent,
172) -> dict[str, Any]:
173 """Decide whether ``variant`` may be promoted onto ``agent``.
175 Never raises: a gate that fell over would either block every promotion or
176 be caught by the endpoint and reported as a server error, and neither is an
177 honest answer to "is this change safe?".
178 """
179 try:
180 variant_id = str(variant.id)
181 batches = _completed_batches(db, experiment)
182 if not batches:
183 return _unmeasured(
184 "This experiment has no completed batch, so the variant has "
185 "never been scored."
186 )
188 for batch in batches:
189 candidate_row = _leaderboard_row(batch, variant_id)
190 if candidate_row is not None:
191 break
192 else:
193 return _unmeasured(
194 "This variant does not appear in any completed batch, so there "
195 "is no score to compare."
196 )
198 variants = load_variants(db, experiment.id)
199 control, reason = _control_variant(variants, agent, exclude=variant.id)
200 if control is None:
201 return _unmeasured(reason or "No control variant could be identified.")
203 control_row = _leaderboard_row(batch, str(control.id))
204 if control_row is None:
205 return _unmeasured(
206 f"The control variant '{control.name}' was not part of this "
207 "batch, so the two were not measured on the same cases.",
208 control=_describe_variant(control, None),
209 )
211 deltas = regression.compare_summaries(
212 control_row,
213 candidate_row,
214 tolerances=regression.tolerance_overrides(experiment.config),
215 )
216 regressed = [d for d in deltas if d.metric.gating and d.regressed]
217 reasons = [
218 f"{d.metric.label} is {d.current} against the control's {d.baseline}."
219 for d in regressed
220 ] or ["No tracked metric is worse than the control."]
222 return {
223 "status": (
224 GateStatus.blocked.value if regressed else GateStatus.clear.value
225 ),
226 "reasons": reasons,
227 "metrics": [d.as_dict() for d in deltas],
228 "batch": {
229 "id": str(batch.id),
230 "label": batch.label,
231 "finished_at": (
232 utc_isoformat(batch.finished_at) if batch.finished_at else None
233 ),
234 "scorer": batch.scorer.value if batch.scorer else None,
235 },
236 "candidate": _describe_variant(variant, candidate_row),
237 "control": _describe_variant(control, control_row),
238 }
239 # Broad on purpose: see the docstring. An unusable gate must degrade to
240 # "could not tell", which is a decision the caller can act on, rather than
241 # to an exception the caller can only fail on.
242 except Exception:
243 logger.exception(
244 "Promotion gate failed for variant %s onto agent %s",
245 getattr(variant, "id", None),
246 getattr(agent, "id", None),
247 )
248 return _unmeasured("The promotion gate could not be evaluated.")
251def record_promotion(
252 db: Session,
253 experiment: Experiment,
254 *,
255 variant: ExperimentVariant,
256 agent: Agent,
257 gate: dict[str, Any],
258 actor: Any,
259 forced: bool,
260 note: Optional[str] = None,
261 agent_version: Optional[int] = None,
262) -> dict[str, Any]:
263 """Append this promotion to the experiment's record and return the entry.
265 Kept on ``Experiment.config['promotions']`` next to the batch summaries,
266 because a promotion is the answer to "what did we do about the numbers in
267 that batch?" and belongs with them. The durable record of *what changed* is
268 the agent's own version history; ``agent_version`` is the link between the
269 two, so a promotion resolves to the exact revision it produced and its diff.
271 Does not commit; the caller owns the transaction the prompt write is in, so
272 a promotion can never be recorded without the change it describes.
273 """
274 entry = {
275 "variant_id": str(variant.id),
276 "variant_name": variant.name,
277 "agent_id": str(agent.id),
278 "agent_name": agent.name,
279 "agent_version": agent_version,
280 "batch_id": (gate.get("batch") or {}).get("id"),
281 "gate_status": gate.get("status"),
282 "gate_reasons": gate.get("reasons") or [],
283 # The whole point of the record: a promotion made *past* a regression is
284 # the one somebody will need to explain later.
285 "forced": bool(forced),
286 "note": (note or "").strip()[:MAX_NOTE_LENGTH] or None,
287 "promoted_by_user_id": str(actor.id) if actor is not None else None,
288 "promoted_at": aware_utcnow().isoformat(),
289 }
290 try:
291 config = dict(experiment.config or {})
292 promotions = [
293 p for p in (config.get("promotions") or []) if isinstance(p, dict)
294 ]
295 promotions.insert(0, entry)
296 config["promotions"] = promotions[:MAX_RETAINED_PROMOTIONS]
297 experiment.config = config
298 except Exception:
299 # The prompt write is the user's actual request and has already been
300 # made; losing the index entry must not undo it. The agent's version
301 # history still records the change either way.
302 logger.exception(
303 "Could not record the promotion of variant %s onto agent %s",
304 variant.id,
305 agent.id,
306 )
307 return entry