Coverage for app / services / evaluation / benchmark.py: 84%

591 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""The platform benchmark: CHAINR Bot and each maker's strongest built-in 

2model, scored on every gold dataset — again only when something that decides 

3the score moved. 

4 

5Two audiences read it. Users see how the bot — the agent everyone gets — 

6scores against each gold dataset's pass mark, release by release, beside the 

7best model of each maker the platform ships, and can put their own agents next 

8to those baselines. The platform sees whether a deploy changed the pipeline's 

9quality: the bot is a fixed reference agent, so a deploy that moves its scores 

10moved the pipeline (``docs/guides/agent-graph-review.md``). 

11 

12**What runs, and when.** One built-in experiment per (gold dataset, target), 

13each with one variant, so every target's run history and regression verdicts 

14stand on their own. Experiments are provisioned here by fixed id and owned by 

15nobody (``is_system``, migration 89): readable by everyone, runnable by none. 

16They stay out of every workspace's lists and reports (Best configurations 

17included) and are read through ``view``. 

18 

19**Which models** (``model_targets``). One per maker: the strongest of its 

20available built-in chat models, by tier, then price (within a tier, the 

21larger), then knowledge cutoff — plus the deployment's default model, the one 

22the bot runs on, as a bare-model baseline. Every built-in model was scored 

23until 30 October 2026 (the user's decision then); with the other makers' 

24models on Bedrock, each maker's lighter variants were rounds that said little. A 

25model that stops being chosen has its experiments archived (``retire``) and 

26leaves ``view``; chosen again, it comes back with its history. 

27 

28Every result answers for the dataset's content version and the judge; a 

29change to either makes it stale. Beyond that: 

30 

31* **CHAINR Bot** answers through the pipeline, so its result also answers for 

32 the code that shapes its answers (``pipeline_key``): svc-ai's (its 

33 ``/health`` fingerprint), svc-core's that defines the bot and builds and 

34 grades its request (``BOT_CODE_PATHS``), and the model it runs on. A deploy 

35 that changes none of them — the front end, the infrastructure, the docs — 

36 makes nothing stale. 

37* **A built-in model** answers directly: a deploy cannot change its answer. 

38 It is stale when it has no result on the current dataset version under the 

39 current judge, and once that result is 

40 ``PLATFORM_BENCHMARK_MODEL_REFRESH_DAYS`` old — a provider can change what 

41 an unversioned name answers with. A pinned version (a dated snapshot, or a 

42 versioned Bedrock id: svc-ai's ``version_pinned``) cannot change, and is 

43 never re-run for age. 

44 

45**One round per target per month.** A target's *round* is its runs on every 

46gold dataset that is stale for it. A target starts at most one round per 

47calendar month (UTC), on whatever is live then, and a round finishes the 

48datasets it has not done; a dataset run this month waits for next month's 

49round however stale a later deploy makes it. The svc-ai fingerprint moves on 

50most deploys, and re-running the bot on every one spent the whole budget on 

51rounds the next deploy made stale before they finished. Only the latest code 

52is ever pending — nothing queues up while the budget is spent. 

53 

54**A budget per calendar month.** ``PLATFORM_BENCHMARK_BUDGET_USD`` of measured 

55spend per month (``period_spend``), reset on the 1st. A round starts only 

56when what it cost last time fits what is left (``affordable``), so a budget 

57that runs low leaves whole rounds for next month rather than cutting one in 

58half; a round already started is never stopped by that estimate, only by the 

59budget itself being spent. It was a rolling 30 days until October 2026, 

60which re-spent every dollar the moment it aged out. 

61 

62**Gentle on providers.** One experiment at a time, one case at a time 

63(``CONCURRENCY``), on one worker thread — never on the scheduler's tick. The 

64bot runs first, then the models cheapest first. A failed run is retried at 

65most once per month. 

66 

67**Who pays.** Nobody owns these runs, so they are ungoverned and the usage 

68ledger — keyed by user — records nothing. Each run's measured cost is on its 

69summary (``runner.measured_usage``) and on its ``platform_benchmark`` 

70background event, the way a built-in dashboard's refresh is. 

71""" 

72 

73from __future__ import annotations 

74 

75import hashlib 

76import logging 

77import re 

78import threading 

79import time 

80import uuid 

81from concurrent.futures import ThreadPoolExecutor 

82from dataclasses import dataclass, field 

83from datetime import datetime, timedelta, timezone 

84from functools import lru_cache 

85from pathlib import Path 

86from typing import Any, Iterable, Optional 

87from uuid import UUID 

88 

89from sqlalchemy.orm import Session 

90 

91from app.common.settings import get_settings 

92from app.db.postgres.engine import SessionLocal 

93from app.db.postgres.enums import ( 

94 BackgroundEnum, 

95 EvaluationEnum, 

96 HistoryEnum, 

97 RunnableEnum, 

98) 

99from app.db.postgres.models import ( 

100 Experiment, 

101 ExperimentBatch, 

102 ExperimentVariant, 

103 TestSuite, 

104) 

105from app.services import ai_client, background_activity, lighter_model, native_sibling 

106from app.services import history as history_service 

107from app.services.evaluation import batches as batch_store 

108from app.services.evaluation import dataset_versions, runner 

109from app.services.evaluation import risk as risk_service 

110from app.services.system_resources.definition import CHAINR_BOT 

111from app.util.fingerprint import code_fingerprint 

112from app.util.time import as_utc, aware_utcnow, utc_isoformat 

113 

114logger = logging.getLogger(__name__) 

115 

116#: Fixed ids, so every deployment agrees on them and a re-provision finds its 

117#: rows rather than a name a user could reuse. 

118NAMESPACE = UUID("4d1e5c2a-8b7f-4e0a-9c3d-6f2b1a0e9d54") 

119BOT_KEY = "chainr-bot" 

120#: Cases in flight at once, per run — and one run at a time. 

121CONCURRENCY = 1 

122#: Passes CHAINR Bot makes over each dataset per run. With about ten cases a 

123#: dataset, one pass moved its score by 30–40 points between two deploys that 

124#: changed nothing about the bot: a single answer is ten points, and one 

125#: zeroed answer failed a 0.9 pass mark outright. Most of that swing was 

126#: memory leaking between cases, since fixed. With 11–13 cases a dataset 

127#: (October 2026), two passes give about twenty-four answers per score — more 

128#: distinct questions and fewer repeats of the same ones, for less than three 

129#: passes over the old sets cost — and still a measured spread per run 

130#: (``spread.py``). The models run once: a baseline per dataset version. 

131BOT_REPEATS = 2 

132#: Failed or cancelled runs of one experiment, per month, before it waits for 

133#: next month. An interrupted run is not an attempt: it says nothing about 

134#: the target. 

135MAX_ATTEMPTS = 2 

136#: Interrupted runs of one result, per deploy, before it waits for the next. 

137#: Bounded all the same, so a run that keeps taking svc-core down with it is 

138#: not started again on every restart. 

139MAX_INTERRUPTIONS = 3 

140#: The benchmark's share of the deployment's spending ceiling (svc-ai's 

141#: ``/spend``, ``spend_guard``). It starts no run, and stops a running one 

142#: between cases, once today's or this month's spend passes this share of the 

143#: limit: the rest is for people. A run held this way is interrupted, not 

144#: failed, and is not counted against ``MAX_INTERRUPTIONS``: it runs again 

145#: when the day (or month) resets. 

146CEILING_SHARE = 0.5 

147#: How often a running benchmark re-reads svc-ai's spend. 

148SPEND_CHECK_SECONDS = 60.0 

149#: Failed runs in a row after which the worker stops for this tick. Several 

150#: targets failing one after another is svc-ai or a provider in trouble, not 

151#: each of them; going on would spend every target's attempts on one outage. 

152MAX_CONSECUTIVE_FAILURES = 2 

153#: A run with more than this share of errored answers is not a measurement 

154#: (``runner.unusable``): the target is scored on answers it gave, never on 

155#: an outage. 

156MAX_ERROR_SHARE = 0.5 

157#: How long after svc-core starts before the benchmark starts anything. A 

158#: deploy brings svc-ai up beside svc-core, and is sometimes followed by 

159#: another; a run started at once is the likeliest to be cut off. 

160SETTLE_AFTER_START = timedelta(minutes=5) 

161#: A run still queued or running after this long is not shown as running. 

162#: The scheduler marks such runs interrupted sooner (``release_interrupted``); 

163#: this only keeps a page honest in between. 

164ABANDONED_AFTER = timedelta(hours=6) 

165 

166#: The error on a run svc-core stopped in the middle of. 

167INTERRUPTED = runner.INTERRUPTED 

168#: svc-core's part of what shapes CHAINR Bot's answers, relative to the 

169#: service root: the bot's definition (its instructions, its guide) and the 

170#: gold datasets, how an evaluation asks and grades it, and the request svc-ai 

171#: receives. Rules are not here: benchmark runs are ungoverned. 

172BOT_CODE_PATHS = ( 

173 "app/services/evaluation", 

174 "app/services/system_resources", 

175 "app/services/ai_client.py", 

176 "app/services/agent_spec.py", 

177 "app/services/native_sibling.py", 

178 # The bot's knowledge spec, and the kind each knowledge base is sent as. 

179 "app/services/retrieval.py", 

180 "app/util/cost_profiles.py", 

181 "app/util/knowledge_categories.py", 

182 "app/router/app/agents/transformers.py", 

183) 

184_SERVICE_ROOT = Path(__file__).resolve().parents[3] 

185#: A model name ending in a date names a fixed snapshot 

186#: (``claude-haiku-4-5-20251001``, ``gpt-4o-2024-08-06``). 

187_SNAPSHOT = re.compile(r"-(?:\d{8}|\d{4}-\d{2}-\d{2})$") 

188 

189_IN_FLIGHT = (RunnableEnum.Status.queued, RunnableEnum.Status.running) 

190_DONE_BADLY = (RunnableEnum.Status.failed, RunnableEnum.Status.cancelled) 

191 

192 

193# ── Targets ────────────────────────────────────────────────────────────────── 

194 

195 

196@dataclass(frozen=True) 

197class Target: 

198 """What one benchmark experiment evaluates.""" 

199 

200 key: str 

201 name: str 

202 #: ``agent`` (CHAINR Bot) or ``model``. 

203 kind: str 

204 #: The variant's target spec (``targets.build_target``). 

205 spec: dict = field(hash=False, compare=False) 

206 provider: str = "" 

207 model: str = "" 

208 #: List price per input token, for running the cheapest models first. 

209 price: Optional[float] = None 

210 #: A fixed model version, which cannot change and so never ages. 

211 pinned: bool = False 

212 

213 @property 

214 def per_deploy(self) -> bool: 

215 """Whether a deploy can change its answers: the bot's, through the 

216 pipeline; a bare model's, never.""" 

217 return self.kind == "agent" 

218 

219 

220BOT = Target( 

221 key=BOT_KEY, 

222 name=CHAINR_BOT.name, 

223 kind="agent", 

224 spec={"type": "agent", "agent_id": str(CHAINR_BOT.id)}, 

225) 

226 

227 

228def model_targets(models: list[dict]) -> list[Target]: 

229 """Each maker's strongest built-in chat model the catalogue offers, and 

230 the deployment's default, cheapest first. 

231 

232 Built-in means seeded with the platform (svc-ai's ``is_builtin``) — an 

233 operator's own additions are theirs to evaluate. Archived and unavailable 

234 models are left out: nothing may run on them, so a maker whose flagship 

235 is unavailable here is represented by its next strongest. 

236 """ 

237 eligible = [model for model in models if _benchmarkable(model)] 

238 chosen = strongest_per_maker(eligible) 

239 default = next((model for model in eligible if model.get("is_default")), None) 

240 if default is not None and not any( 

241 str(model["id"]) == str(default["id"]) for model in chosen 

242 ): 

243 chosen.append(default) 

244 found = [_model_target(model) for model in chosen] 

245 found.sort(key=lambda t: (t.price is None, t.price or 0.0, t.name.lower())) 

246 return found 

247 

248 

249def _benchmarkable(model: dict) -> bool: 

250 return bool( 

251 model.get("is_builtin") 

252 and model.get("is_chat", True) 

253 and not model.get("is_embedding") 

254 and model.get("is_available") is not False 

255 ) 

256 

257 

258def strongest_per_maker(models: list[dict]) -> list[dict]: 

259 """The strongest of ``models`` for each maker (svc-ai's ``maker``: models 

260 Bedrock alone serves share its provider, not a maker), in the order each 

261 maker first appears.""" 

262 best: dict[str, dict] = {} 

263 for model in models: 

264 maker = lighter_model.maker_of(model) 

265 if maker not in best or _strength(model) > _strength(best[maker]): 

266 best[maker] = model 

267 return list(best.values()) 

268 

269 

270def _strength(model: dict) -> tuple[int, float, str, str]: 

271 """How a model ranks within its maker: its tier (svc-ai's ``effort``); 

272 within a tier the dearer, which is the larger (every open-weight model 

273 is ``light``, the bands being cost-ordered across the catalogue); then 

274 the newer knowledge cutoff (Opus 5 and Opus 4.6 share tier and price); 

275 then the name, so the choice never depends on the catalogue's order.""" 

276 tier = lighter_model.tier_of(model) 

277 price = model.get("input_cost_per_token") 

278 return ( 

279 tier if tier is not None else -1, 

280 float(price) if price not in (None, "") else -1.0, 

281 str(model.get("knowledge_cutoff") or ""), 

282 str(model.get("model_name") or ""), 

283 ) 

284 

285 

286def _model_target(model: dict) -> Target: 

287 provider = (model.get("provider") or {}).get("name") or "" 

288 price = model.get("input_cost_per_token") 

289 name = str(model.get("model_name") or "") 

290 # svc-ai knows the route the model takes here (a Bedrock id carries 

291 # its version); one that does not say is judged by its name. 

292 pinned = model.get("version_pinned") 

293 return Target( 

294 key=f"model:{model['id']}", 

295 name=model.get("display_name") or model.get("model_name") or "", 

296 kind="model", 

297 spec={"type": "model", "model_id": str(model["id"])}, 

298 provider=str(provider), 

299 model=name, 

300 price=float(price) if price not in (None, "") else None, 

301 pinned=bool(pinned) if pinned is not None else is_snapshot(name), 

302 ) 

303 

304 

305def experiment_id(dataset_id: Any, key: str) -> UUID: 

306 return uuid.uuid5(NAMESPACE, f"experiment:{dataset_id}:{key}") 

307 

308 

309def variant_id(dataset_id: Any, key: str) -> UUID: 

310 return uuid.uuid5(NAMESPACE, f"variant:{dataset_id}:{key}") 

311 

312 

313# ── What CHAINR Bot's result answers for ──────────────────────────────────── 

314 

315 

316@lru_cache(maxsize=1) 

317def _core_fingerprint() -> str: 

318 return code_fingerprint(_SERVICE_ROOT, BOT_CODE_PATHS) 

319 

320 

321def pipeline_key(models: list[dict]) -> str: 

322 """What CHAINR Bot's answers depend on, as one short key: svc-core's code 

323 that defines, asks and grades it, svc-ai's code that answers, the model 

324 it runs on (the deployment's default), and whether a native sibling 

325 makes its structured steps (``NATIVE_STRUCTURED_SIBLING``). "" when svc-ai does not say 

326 what code it runs — the caller then falls back to the deploy.""" 

327 answering = ai_client.service_fingerprint() 

328 if not answering: 

329 return "" 

330 default = next((m for m in models if m.get("is_default")), None) or {} 

331 model = "/".join( 

332 filter( 

333 None, 

334 [(default.get("provider") or {}).get("name"), default.get("model_name")], 

335 ) 

336 ) 

337 material = f"{_core_fingerprint()}|{answering}|{model}" 

338 if native_sibling.enabled(): 

339 # Another model makes the bot's structured steps 

340 # (``services/native_sibling.py``). Added only when on, so a 

341 # deployment that leaves it off keeps the key it had. 

342 material += "|native_sibling" 

343 return hashlib.sha256(material.encode()).hexdigest()[:16] 

344 

345 

346def is_snapshot(model_name: str) -> bool: 

347 """Whether a model name pins a dated snapshot, which cannot change. The 

348 fallback for a catalogue that does not say ``version_pinned``.""" 

349 return bool(_SNAPSHOT.search(model_name or "")) 

350 

351 

352# ── The judge ──────────────────────────────────────────────────────────────── 

353 

354 

355def judge_candidates() -> list[dict]: 

356 """``PLATFORM_BENCHMARK_JUDGE`` as model specs, first choice first.""" 

357 candidates = [] 

358 for item in (get_settings().PLATFORM_BENCHMARK_JUDGE or "").split(","): 

359 provider, slash, model = item.strip().partition("/") 

360 if slash and provider.strip() and model.strip(): 

361 candidates.append( 

362 {"type": "model", "provider": provider.strip(), "model": model.strip()} 

363 ) 

364 return candidates 

365 

366 

367def judge_spec() -> Optional[dict]: 

368 """The judge every benchmark experiment names: the first model in 

369 ``PLATFORM_BENCHMARK_JUDGE`` the catalogue has available, or None for the 

370 deployment's default model. 

371 

372 A list because availability follows the deployment: on Bedrock without 

373 Anthropic access (``BEDROCK_MODEL_ACCESS``) the first choice is 

374 unavailable, and the default model the fallback would use is the one 

375 CHAINR Bot answers with. 

376 """ 

377 candidates = judge_candidates() 

378 if len(candidates) <= 1: 

379 return candidates[0] if candidates else None 

380 try: 

381 available = { 

382 ((m.get("provider") or {}).get("name"), m.get("model_name")) 

383 for m in ai_client.list_models(is_available=True) 

384 } 

385 except ai_client.AIServiceError: 

386 logger.warning( 

387 "[benchmark] could not read the catalogue; judging with the first choice" 

388 ) 

389 return candidates[0] 

390 return next( 

391 (c for c in candidates if (c["provider"], c["model"]) in available), None 

392 ) 

393 

394 

395def judge_key(db: Session) -> str: 

396 """Which model grades, as ``provider/model`` — part of what a result 

397 measured, so a change re-runs every baseline. "" when none resolves.""" 

398 from app.services.evaluation.targets import resolve_default_judge_target 

399 

400 spec = judge_spec() 

401 try: 

402 target = resolve_default_judge_target(db, spec) 

403 except Exception: # noqa: BLE001 — an unresolvable judge runs nothing 

404 logger.exception("[benchmark] the judge did not resolve") 

405 return "" 

406 if target is None: 

407 return "" 

408 resolved = f"{getattr(target, 'provider', '')}/{getattr(target, 'model_name', '')}" 

409 wanted = (get_settings().PLATFORM_BENCHMARK_JUDGE or "").strip() 

410 if wanted and (spec is None or f"{spec['provider']}/{spec['model']}" != resolved): 

411 # The fallback is the deployment's default model — the one CHAINR Bot 

412 # answers with — so say so loudly: the bot is grading itself. 

413 logger.warning( 

414 "[benchmark] judge %s is not available here; grading with %s instead", 

415 wanted, 

416 resolved, 

417 ) 

418 return resolved 

419 

420 

421# ── Provisioning ───────────────────────────────────────────────────────────── 

422 

423 

424def gold_datasets(db: Session, dataset_id: Any = None) -> list[TestSuite]: 

425 query = db.query(TestSuite).filter(TestSuite.is_system.is_(True)) 

426 if dataset_id is not None: 

427 query = query.filter(TestSuite.id == dataset_id) 

428 return query.order_by(TestSuite.name.asc()).all() 

429 

430 

431def _fields(dataset: TestSuite, target: Target) -> dict[str, Any]: 

432 return { 

433 "name": f"{target.name} · {dataset.name}", 

434 "description": ( 

435 f"The platform benchmark: {target.name} on {dataset.name}, run by " 

436 "CHAIN-R at most once a month, on the code then live." 

437 if target.per_deploy 

438 else f"The platform benchmark: {target.name} on {dataset.name}, " 

439 "run by CHAIN-R whenever the dataset or the judge changes." 

440 ), 

441 "status": EvaluationEnum.Status.active, 

442 "dataset_id": dataset.id, 

443 "scorer": EvaluationEnum.Scorer.llm, 

444 "scorer_config": None, 

445 "judge": judge_spec(), 

446 "config": { 

447 "concurrency": CONCURRENCY, 

448 **({"repeats": BOT_REPEATS} if target.per_deploy else {}), 

449 "benchmark": {"target": target.key, "kind": target.kind}, 

450 }, 

451 } 

452 

453 

454def provision( 

455 db: Session, datasets: list[TestSuite], targets: list[Target] 

456) -> list[tuple[Experiment, Target, TestSuite]]: 

457 """Create or correct every benchmark experiment. Does not commit. 

458 

459 A version (no actor) is written whenever one is created or changed, so 

460 each experiment's history is its release history, like every built-in's. 

461 Experiments of a model no longer chosen are archived by ``retire``, not 

462 deleted: their results are still history. 

463 """ 

464 out: list[tuple[Experiment, Target, TestSuite]] = [] 

465 for dataset in datasets: 

466 for target in targets: 

467 eid = experiment_id(dataset.id, target.key) 

468 wanted = _fields(dataset, target) 

469 experiment = db.get(Experiment, eid) 

470 action: Optional[HistoryEnum.Action] = None 

471 if experiment is None: 

472 experiment = Experiment(id=eid, is_system=True, **wanted) 

473 db.add(experiment) 

474 db.flush() 

475 action = HistoryEnum.Action.created 

476 else: 

477 for key, value in wanted.items(): 

478 if getattr(experiment, key) != value: 

479 setattr(experiment, key, value) 

480 action = HistoryEnum.Action.updated 

481 vid = variant_id(dataset.id, target.key) 

482 variant = db.get(ExperimentVariant, vid) 

483 variant_config = {"target": target.spec} 

484 if variant is None: 

485 db.add( 

486 ExperimentVariant( 

487 id=vid, 

488 experiment_id=eid, 

489 name=target.name, 

490 config=variant_config, 

491 ) 

492 ) 

493 action = action or HistoryEnum.Action.updated 

494 elif variant.name != target.name or variant.config != variant_config: 

495 variant.name = target.name 

496 variant.config = variant_config 

497 action = action or HistoryEnum.Action.updated 

498 if action is not None: 

499 db.flush() 

500 history_service.record_version( 

501 db, 

502 resource_type=HistoryEnum.ResourceType.experiment, 

503 model=Experiment, 

504 resource=experiment, 

505 action=action, 

506 actor=None, 

507 children_resolver=lambda eid=eid: { 

508 "variants": [ 

509 {"variant_id": str(v.id), "name": v.name} 

510 for v in db.query(ExperimentVariant) 

511 .filter(ExperimentVariant.experiment_id == eid) 

512 .all() 

513 ] 

514 }, 

515 ) 

516 out.append((experiment, target, dataset)) 

517 return out 

518 

519 

520def retire(db: Session, targets: list[Target]) -> int: 

521 """Archive the experiments of every model no longer a target — out of 

522 the catalogue, unavailable here, or no longer its maker's strongest — 

523 so ``view`` stops listing it. Never the bot's. Reversible: ``provision`` 

524 writes ``active`` back if the model is chosen again. A catalogue that 

525 offers no model at all is taken for a fault, not a retirement, and 

526 nothing is archived. Does not commit; returns how many it archived.""" 

527 wanted = {target.key for target in targets} 

528 if not any(target.kind == "model" for target in targets): 

529 return 0 

530 archived = 0 

531 for experiment in ( 

532 db.query(Experiment) 

533 .filter( 

534 Experiment.is_system.is_(True), 

535 Experiment.status == EvaluationEnum.Status.active, 

536 ) 

537 .all() 

538 ): 

539 bench = dict((experiment.config or {}).get("benchmark") or {}) 

540 if bench.get("kind") != "model" or bench.get("target") in wanted: 

541 continue 

542 experiment.status = EvaluationEnum.Status.archived 

543 db.flush() 

544 history_service.record_version( 

545 db, 

546 resource_type=HistoryEnum.ResourceType.experiment, 

547 model=Experiment, 

548 resource=experiment, 

549 action=HistoryEnum.Action.updated, 

550 actor=None, 

551 ) 

552 archived += 1 

553 return archived 

554 

555 

556# ── What is due ────────────────────────────────────────────────────────────── 

557 

558 

559@dataclass(frozen=True) 

560class Plan: 

561 """One run to make: an experiment, and the stamp its result answers.""" 

562 

563 experiment_id: UUID 

564 target_key: str 

565 target_name: str 

566 dataset_name: str 

567 stamp: dict = field(hash=False, compare=False) 

568 #: The first run of the target's round this month, rather than one that 

569 #: finishes a round already started. 

570 new_round: bool = False 

571 

572 

573# ── The month ──────────────────────────────────────────────────────────────── 

574 

575 

576def period_start(now: Any = None) -> datetime: 

577 """The first instant of ``now``'s calendar month, UTC.""" 

578 now = as_utc(now or aware_utcnow()) 

579 return datetime(now.year, now.month, 1, tzinfo=timezone.utc) 

580 

581 

582def next_period_start(now: Any = None) -> datetime: 

583 """When the month after ``now``'s begins: the budget's reset.""" 

584 start = period_start(now) 

585 return ( 

586 start.replace(year=start.year + 1, month=1) 

587 if start.month == 12 

588 else start.replace(month=start.month + 1) 

589 ) 

590 

591 

592def period_key(now: Any = None) -> str: 

593 """``now``'s month as ``YYYY-MM``.""" 

594 return period_start(now).strftime("%Y-%m") 

595 

596 

597def _in_period(batch: Any, start: datetime) -> bool: 

598 """Whether ``batch`` was started in the month beginning ``start``. By 

599 ``created_at``, the clock the budget counts by, so the round and the 

600 spend always agree on which month a run belongs to.""" 

601 created = getattr(batch, "created_at", None) 

602 return created is not None and start <= as_utc(created) < next_period_start(start) 

603 

604 

605def _benchmark_stamp(batch: ExperimentBatch) -> dict: 

606 return dict((batch.config or {}).get("benchmark") or {}) 

607 

608 

609def _fresh(batch: ExperimentBatch) -> bool: 

610 created = getattr(batch, "created_at", None) 

611 if created is None: 

612 return True 

613 return as_utc(created) > aware_utcnow() - ABANDONED_AFTER 

614 

615 

616def _answers(batch: ExperimentBatch, stamp: dict) -> bool: 

617 """Whether ``batch`` was a run for ``stamp``: the same dataset content, 

618 the same judge, the same inference backend and — for the bot — the same 

619 pipeline. A result stamped before the backend was recorded was taken on 

620 the vendors' own APIs (``direct``): the same model reached through 

621 Bedrock is measured again.""" 

622 ran = _benchmark_stamp(batch) 

623 if batch.dataset_version != stamp["dataset_version"]: 

624 return False 

625 if ran.get("judge") != stamp["judge"]: 

626 return False 

627 if ran.get("backend", "direct") != stamp.get("backend", "direct"): 

628 return False 

629 return "pipeline" not in stamp or ran.get("pipeline") == stamp["pipeline"] 

630 

631 

632def _recent(batch: ExperimentBatch, max_age: Optional[timedelta], now: Any) -> bool: 

633 """Whether a completed result is young enough to stand (no limit: yes).""" 

634 if max_age is None: 

635 return True 

636 finished = getattr(batch, "finished_at", None) or getattr(batch, "created_at", None) 

637 return finished is not None and as_utc(finished) > now - max_age 

638 

639 

640def due( 

641 db: Session, 

642 experiments: list[tuple[Experiment, Target, TestSuite]], 

643 *, 

644 deploy_id: str, 

645 judge: str, 

646 pipeline: str = "", 

647 refresh_days: int = 0, 

648 backend: str = "direct", 

649 now: Any = None, 

650) -> list[Plan]: 

651 """The runs still owed this month: the bot's round first, then each 

652 model's, cheapest first (the order targets arrive in), each round's 

653 datasets together. 

654 

655 A (target, dataset) is stale when its result does not answer for what is 

656 live (``_answers``) or has aged out. A stale one is owed when its target 

657 has not started a round this month — that starts one — or when the round 

658 it has started has not yet run this dataset. One already run this month 

659 waits for next month's round. 

660 

661 ``pipeline`` is what the bot's result must answer for (``pipeline_key``, 

662 or the deploy when svc-ai would not say); ``refresh_days`` how old an 

663 unpinned model's result may grow before it is measured again (0: never).""" 

664 now = as_utc(now or aware_utcnow()) 

665 month = period_start(now) 

666 model_max_age = timedelta(days=refresh_days) if refresh_days > 0 else None 

667 # A round is the target's, across its datasets: read every experiment's 

668 # runs first. 

669 batches_of: dict[Any, list[ExperimentBatch]] = {} 

670 started: set[str] = set() 

671 rank: dict[str, int] = {} 

672 for experiment, target, _ in experiments: 

673 rank.setdefault(target.key, len(rank)) 

674 batches_of[experiment.id] = ( 

675 db.query(ExperimentBatch) 

676 .filter(ExperimentBatch.experiment_id == experiment.id) 

677 .all() 

678 ) 

679 if any(_in_period(b, month) for b in batches_of[experiment.id]): 

680 started.add(target.key) 

681 

682 plans: list[Plan] = [] 

683 versions: dict[Any, Any] = {} 

684 for experiment, target, dataset in experiments: 

685 if dataset.id not in versions: 

686 versions[dataset.id] = dataset_versions.current_content_version( 

687 db, dataset.id 

688 ) 

689 stamp: dict[str, Any] = { 

690 "dataset_version": versions[dataset.id], 

691 "judge": judge, 

692 "backend": backend, 

693 } 

694 if target.per_deploy: 

695 stamp["pipeline"] = pipeline or f"deploy:{deploy_id}" 

696 max_age = None if target.per_deploy or target.pinned else model_max_age 

697 batches = batches_of[experiment.id] 

698 answering = [b for b in batches if _answers(b, stamp)] 

699 if any( 

700 b.status == RunnableEnum.Status.completed and _recent(b, max_age, now) 

701 for b in answering 

702 ): 

703 continue 

704 if any(b.status in _IN_FLIGHT and _fresh(b) for b in batches): 

705 continue 

706 this_month = [b for b in batches if _in_period(b, month)] 

707 if any(b.status == RunnableEnum.Status.completed for b in this_month): 

708 continue # run in this month's round; next month's measures again 

709 failed = [ 

710 b 

711 for b in this_month 

712 if b.status in _DONE_BADLY and not runner.is_interrupted(b) 

713 ] 

714 interrupted = [ 

715 b 

716 for b in answering 

717 if b.status in _DONE_BADLY 

718 and _benchmark_stamp(b).get("cycle") == deploy_id 

719 and runner.is_interrupted(b) 

720 and not held_for_spend(b) 

721 ] 

722 if len(failed) >= MAX_ATTEMPTS or len(interrupted) >= MAX_INTERRUPTIONS: 

723 continue 

724 plans.append( 

725 Plan( 

726 experiment_id=experiment.id, 

727 target_key=target.key, 

728 target_name=target.name, 

729 dataset_name=dataset.name, 

730 stamp=stamp, 

731 new_round=target.key not in started, 

732 ) 

733 ) 

734 plans.sort(key=lambda p: (p.target_key != BOT_KEY, rank[p.target_key])) 

735 return plans 

736 

737 

738def _cost(batch: Any) -> Optional[float]: 

739 """A run's measured cost, or None when nothing was measured.""" 

740 usage = ((getattr(batch, "summary", None) or {}).get("usage")) or {} 

741 cost = usage.get("estimated_cost_usd") 

742 return float(cost) if isinstance(cost, (int, float)) else None 

743 

744 

745def period_spend(db: Session, now: Any = None) -> float: 

746 """What the benchmark has cost this calendar month (UTC), measured.""" 

747 since = period_start(now) 

748 rows = ( 

749 db.query(ExperimentBatch) 

750 .join(Experiment, Experiment.id == ExperimentBatch.experiment_id) 

751 .filter( 

752 Experiment.is_system.is_(True), 

753 ExperimentBatch.created_at >= since.replace(tzinfo=None), 

754 ) 

755 .all() 

756 ) 

757 return sum(cost for cost in map(_cost, rows) if cost is not None) 

758 

759 

760def round_estimate(db: Session, plans: list[Plan]) -> Optional[float]: 

761 """What running ``plans`` should cost: each experiment's last completed 

762 run, a dataset never run costing the mean of the rest. None when none of 

763 them has ever been measured — a first round is how it gets measured.""" 

764 costs: list[Optional[float]] = [] 

765 for plan in plans: 

766 last = ( 

767 db.query(ExperimentBatch) 

768 .filter( 

769 ExperimentBatch.experiment_id == plan.experiment_id, 

770 ExperimentBatch.status == RunnableEnum.Status.completed, 

771 ) 

772 .order_by(ExperimentBatch.created_at.desc()) 

773 .first() 

774 ) 

775 costs.append(_cost(last) if last is not None else None) 

776 known = [c for c in costs if c is not None] 

777 if not known: 

778 return None 

779 mean = sum(known) / len(known) 

780 return sum(c if c is not None else mean for c in costs) 

781 

782 

783@dataclass(frozen=True) 

784class Waiting: 

785 """A round left for next month, and why.""" 

786 

787 target_name: str 

788 runs: int 

789 reason: str 

790 

791 

792def affordable( 

793 db: Session, plans: list[Plan], spent: float, budget: float 

794) -> tuple[list[Plan], list[Waiting]]: 

795 """The plans this month's budget can carry, round by round in order, and 

796 the rounds it cannot. 

797 

798 A round already started is kept: stopping it halfway would waste what it 

799 has spent. A new round is kept only when what it cost last time fits 

800 what is left after everything kept before it, so the budget never runs 

801 out in the middle of one. Nothing is kept once the budget is spent. 

802 """ 

803 if spent >= budget: 

804 return [], [ 

805 Waiting( 

806 "the benchmark", 

807 len(plans), 

808 f"${spent:.2f} of ${budget:.2f} spent this month", 

809 ) 

810 ] 

811 rounds: dict[str, list[Plan]] = {} 

812 for plan in plans: 

813 rounds.setdefault(plan.target_key, []).append(plan) 

814 kept: list[Plan] = [] 

815 waiting: list[Waiting] = [] 

816 committed = spent 

817 for group in rounds.values(): 

818 estimate = round_estimate(db, group) 

819 new = any(p.new_round for p in group) 

820 if new and estimate is not None and committed + estimate > budget: 

821 waiting.append( 

822 Waiting( 

823 group[0].target_name, 

824 len(group), 

825 f"its round costs about ${estimate:.2f} and " 

826 f"${max(budget - committed, 0.0):.2f} is left this month", 

827 ) 

828 ) 

829 continue 

830 kept.extend(group) 

831 committed += estimate or 0.0 

832 return kept, waiting 

833 

834 

835# ── Running ────────────────────────────────────────────────────────────────── 

836 

837#: One worker: the benchmark runs one experiment at a time, off the tick. 

838_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="benchmark") 

839_busy = threading.Event() 

840#: Set when svc-core is shutting down: no run starts, and the one in flight 

841#: stops at its next cell. 

842_stopping = threading.Event() 

843_STARTED = time.monotonic() 

844 

845 

846def stop() -> None: 

847 """Tell the benchmark worker svc-core is going away. Called by the 

848 lifespan before the scheduler stands down, so no later leader finds this 

849 process's run still going.""" 

850 _stopping.set() 

851 

852 

853def should_stop() -> bool: 

854 return _stopping.is_set() or runner.process_stopping() 

855 

856 

857def _uptime() -> timedelta: 

858 return timedelta(seconds=time.monotonic() - _STARTED) 

859 

860 

861@dataclass(frozen=True) 

862class TickResult: 

863 #: Runs handed to the worker by this tick. 

864 started: int 

865 detail: str 

866 

867 

868def tick(db: Session) -> TickResult: 

869 """Provision the benchmark and start whatever is owed this month that 

870 the month's budget can carry. 

871 

872 Never runs a model call itself: the work goes to the benchmark worker. 

873 """ 

874 settings = get_settings() 

875 deploy_id = (settings.DEPLOY_ID or "").strip() 

876 if not settings.PLATFORM_BENCHMARK_ENABLED: 

877 return TickResult(0, "The platform benchmark is switched off.") 

878 if not deploy_id: 

879 return TickResult(0, "No DEPLOY_ID: the benchmark runs on deployed hosts only.") 

880 if should_stop(): 

881 return TickResult(0, "svc-core is shutting down.") 

882 if _busy.is_set(): 

883 return TickResult(0, "A benchmark is already running.") 

884 interrupted = release_interrupted(db) 

885 if interrupted: 

886 db.commit() 

887 logger.warning( 

888 "[benchmark] %d run(s) were cut off by a restart; marked interrupted", 

889 interrupted, 

890 ) 

891 if _uptime() < SETTLE_AFTER_START: 

892 return TickResult(0, "Waiting for the deploy to settle before starting.") 

893 

894 models = ai_client.list_models(is_available=True) 

895 targets = [BOT, *model_targets(models)] 

896 experiments = provision(db, gold_datasets(db), targets) 

897 retired = retire(db, targets) 

898 db.commit() 

899 if retired: 

900 logger.info( 

901 "[benchmark] archived %d experiment(s) of models no longer chosen", 

902 retired, 

903 ) 

904 

905 judge = judge_key(db) 

906 if not judge: 

907 return TickResult(0, "No judge model resolves; nothing was run.") 

908 pipeline = pipeline_key(models) 

909 if not pipeline: 

910 logger.warning( 

911 "[benchmark] svc-ai did not report its code; CHAINR Bot's result " 

912 "is keyed on the deploy" 

913 ) 

914 plans = due( 

915 db, 

916 experiments, 

917 deploy_id=deploy_id, 

918 judge=judge, 

919 pipeline=pipeline, 

920 refresh_days=int(settings.PLATFORM_BENCHMARK_MODEL_REFRESH_DAYS or 0), 

921 backend=ai_client.inference_backend(), 

922 ) 

923 if not plans: 

924 return TickResult(0, "The benchmark is up to date.") 

925 budget = float(settings.PLATFORM_BENCHMARK_BUDGET_USD) 

926 plans, waiting = affordable(db, plans, period_spend(db), budget) 

927 if waiting: 

928 _announce_waiting(db, deploy_id, waiting) 

929 if not plans: 

930 return TickResult( 

931 0, 

932 "Nothing fits this month's budget: " 

933 + "; ".join(f"{w.target_name} ({w.reason})" for w in waiting), 

934 ) 

935 _busy.set() 

936 try: 

937 _executor.submit(_run_logged, plans, deploy_id, budget) 

938 except Exception: 

939 _busy.clear() 

940 raise 

941 return TickResult( 

942 len(plans), f"Started {len(plans)} benchmark run(s) for deploy {deploy_id}." 

943 ) 

944 

945 

946#: ``(month, target)`` pairs already announced as waiting by this process: 

947#: the scheduler asks every ten minutes, and the answer holds all month. 

948_announced: set[tuple[str, str]] = set() 

949 

950 

951def _announce_waiting(db: Session, deploy_id: str, waiting: list["Waiting"]) -> None: 

952 """Say once a month, per round, that it waits for next month's budget — 

953 as a log line and a background event. Does not commit.""" 

954 month = period_key() 

955 for item in waiting: 

956 if (month, item.target_name) in _announced: 

957 continue 

958 _announced.add((month, item.target_name)) 

959 logger.warning( 

960 "[benchmark] %s waits for next month: %s (%d run(s))", 

961 item.target_name, 

962 item.reason, 

963 item.runs, 

964 ) 

965 background_activity.record( 

966 db, 

967 kind=BackgroundEnum.Kind.platform_benchmark, 

968 trigger=BackgroundEnum.Trigger.scheduled, 

969 status=BackgroundEnum.Status.ok, 

970 summary=( 

971 f"Benchmark: {item.target_name} waits for next month ({item.reason})" 

972 ), 

973 detail={ 

974 "deploy_id": deploy_id, 

975 "month": month, 

976 "target": item.target_name, 

977 "runs": item.runs, 

978 "reason": item.reason, 

979 }, 

980 ) 

981 db.commit() 

982 

983 

984def release_interrupted(db: Session) -> int: 

985 """Mark interrupted every benchmark run still recorded in flight. Does 

986 not commit; returns how many. 

987 

988 Called only when this process has no benchmark running (``_busy`` is 

989 clear). Benchmark runs are started only by the scheduler's leader, on its 

990 own worker, and nobody else may run a system experiment — so a run still 

991 ``queued`` or ``running`` here was cut off when svc-core stopped (a deploy 

992 or a restart). Left as it was, it would hold every later run back for 

993 ``ABANDONED_AFTER``; interrupted, it is simply due again, and is not 

994 counted as a failed attempt. 

995 """ 

996 rows = ( 

997 db.query(ExperimentBatch) 

998 .join(Experiment, Experiment.id == ExperimentBatch.experiment_id) 

999 .filter( 

1000 Experiment.is_system.is_(True), 

1001 ExperimentBatch.status.in_(_IN_FLIGHT), 

1002 ) 

1003 .all() 

1004 ) 

1005 now = aware_utcnow() 

1006 for batch in rows: 

1007 runner.mark_interrupted(batch, now) 

1008 return len(rows) 

1009 

1010 

1011def over_spend_share( 

1012 status: dict[str, Any] | None, 

1013 *, 

1014 share: float = CEILING_SHARE, 

1015 who: str = "the benchmark", 

1016) -> str | None: 

1017 """Why background work must wait for the deployment's spending ceiling, 

1018 or None when it may spend. svc-ai's own guard is the hard stop; this 

1019 keeps ``who`` to its ``share`` of it — the benchmark's half by default; 

1020 the search-index rebuild passes its own.""" 

1021 if not status or not status.get("enabled"): 

1022 return None 

1023 for period, adjective in (("day", "daily"), ("month", "monthly")): 

1024 entry = status.get(period) or {} 

1025 ceiling, spent = entry.get("ceiling_usd"), entry.get("spent_usd") 

1026 if ( 

1027 isinstance(ceiling, (int, float)) 

1028 and isinstance(spent, (int, float)) 

1029 and ceiling > 0 

1030 and spent >= ceiling * share 

1031 ): 

1032 return ( 

1033 f"the deployment has spent ${spent:.2f} of its ${ceiling:.2f} " 

1034 f"{adjective} AI limit, and {who} uses at most " 

1035 f"{round(share * 100)}% of it" 

1036 ) 

1037 return None 

1038 

1039 

1040def held_for_spend(batch: Any) -> bool: 

1041 """Whether a run was stopped for the spending ceiling — it says nothing 

1042 about the target, and runs again once the period resets.""" 

1043 return (getattr(batch, "config", None) or {}).get("held_for_spend") is True 

1044 

1045 

1046class _SpendWatch: 

1047 """``should_stop`` for a running benchmark: true once the deployment's 

1048 spend passes the benchmark's share. Re-reads svc-ai's figure at most 

1049 every ``SPEND_CHECK_SECONDS``.""" 

1050 

1051 def __init__(self) -> None: 

1052 self.reason: str | None = None 

1053 self._checked = time.monotonic() 

1054 

1055 def __call__(self) -> bool: 

1056 if self.reason is not None: 

1057 return True 

1058 if time.monotonic() - self._checked < SPEND_CHECK_SECONDS: 

1059 return False 

1060 self._checked = time.monotonic() 

1061 self.reason = over_spend_share(ai_client.spend_status()) 

1062 return self.reason is not None 

1063 

1064 

1065def _record_spend_hold( 

1066 db: Session, deploy_id: str, reason: str, plans: list[Plan] 

1067) -> None: 

1068 logger.warning("[benchmark] waiting: %s", reason) 

1069 background_activity.record( 

1070 db, 

1071 kind=BackgroundEnum.Kind.platform_benchmark, 

1072 trigger=BackgroundEnum.Trigger.scheduled, 

1073 status=BackgroundEnum.Status.ok, 

1074 summary=f"Benchmark waits: {reason}; {len(plans)} run(s) wait", 

1075 detail={ 

1076 "deploy_id": deploy_id, 

1077 "reason": reason, 

1078 "waiting": [p.experiment_id.hex for p in plans], 

1079 }, 

1080 ) 

1081 

1082 

1083def _run_logged(plans: list[Plan], deploy_id: str, budget: float) -> None: 

1084 try: 

1085 run_plans(plans, deploy_id, budget) 

1086 except Exception: # pragma: no cover — every run records its own failure 

1087 logger.exception("[benchmark] the benchmark worker failed") 

1088 finally: 

1089 _busy.clear() 

1090 

1091 

1092def run_plans(plans: list[Plan], deploy_id: str, budget: float) -> int: 

1093 """Run ``plans`` one after another. Returns how many ran. 

1094 

1095 Each run is its own transaction and its own background event. ``plans`` 

1096 are what ``affordable`` judged this month's budget could carry; the 

1097 worker still stops — leaving the rest for the next tick, which works out 

1098 afresh what is due — if the budget is spent all the same, when svc-core 

1099 is shutting down (a run it cuts off is interrupted, and nothing is 

1100 started after it), and after ``MAX_CONSECUTIVE_FAILURES`` failed runs in 

1101 a row. 

1102 """ 

1103 ran = 0 

1104 failures = 0 

1105 for index, plan in enumerate(plans): 

1106 if should_stop(): 

1107 logger.info( 

1108 "[benchmark] svc-core is stopping; %d run(s) left", len(plans) - index 

1109 ) 

1110 return ran 

1111 db = SessionLocal() 

1112 try: 

1113 spent = period_spend(db) 

1114 if spent >= budget: 

1115 skipped = len(plans) - index 

1116 logger.warning( 

1117 "[benchmark] budget of $%.2f this month reached ($%.2f spent) " 

1118 "— %d run(s) wait for next month", 

1119 budget, 

1120 spent, 

1121 skipped, 

1122 ) 

1123 background_activity.record( 

1124 db, 

1125 kind=BackgroundEnum.Kind.platform_benchmark, 

1126 trigger=BackgroundEnum.Trigger.scheduled, 

1127 status=BackgroundEnum.Status.ok, 

1128 summary=( 

1129 f"Benchmark budget reached (${spent:.2f} of ${budget:.2f} " 

1130 f"this month); {skipped} run(s) wait for next month" 

1131 ), 

1132 detail={ 

1133 "deploy_id": deploy_id, 

1134 "spent_usd": round(spent, 4), 

1135 "budget_usd": budget, 

1136 "skipped": [p.experiment_id.hex for p in plans[index:]], 

1137 }, 

1138 ) 

1139 db.commit() 

1140 return ran 

1141 held = over_spend_share(ai_client.spend_status()) 

1142 if held is not None: 

1143 _record_spend_hold(db, deploy_id, held, plans[index:]) 

1144 db.commit() 

1145 return ran 

1146 experiment = db.get(Experiment, plan.experiment_id) 

1147 if experiment is None: 

1148 continue 

1149 variants = runner.load_variants(db, experiment.id) 

1150 batch_id = runner.start_experiment_batch( 

1151 db, 

1152 experiment, 

1153 variants=variants, 

1154 label=f"Benchmark · {deploy_id}", 

1155 config_overrides={"benchmark": {**plan.stamp, "cycle": deploy_id}}, 

1156 ) 

1157 finally: 

1158 db.close() 

1159 

1160 started = aware_utcnow() 

1161 watch = _SpendWatch() 

1162 runner.execute_batch( 

1163 UUID(batch_id), 

1164 should_stop=lambda: should_stop() or watch(), 

1165 max_error_share=MAX_ERROR_SHARE, 

1166 ) 

1167 ran += 1 

1168 if watch.reason is not None: 

1169 _mark_held(UUID(batch_id), deploy_id, watch.reason, plans[index:]) 

1170 outcome = _record_run(UUID(batch_id), plan, deploy_id, started) 

1171 if outcome == "interrupted": 

1172 return ran 

1173 failures = failures + 1 if outcome == "failed" else 0 

1174 if failures >= MAX_CONSECUTIVE_FAILURES: 

1175 _record_pause(deploy_id, failures, len(plans) - index - 1) 

1176 return ran 

1177 return ran 

1178 

1179 

1180def _mark_held(batch_id: UUID, deploy_id: str, reason: str, left: list[Plan]) -> None: 

1181 """A run the spending ceiling stopped: interrupted, and marked so that it 

1182 is not counted as one of this deploy's interruptions.""" 

1183 db = SessionLocal() 

1184 try: 

1185 batch = db.get(ExperimentBatch, batch_id) 

1186 if batch is None or not runner.is_interrupted(batch): 

1187 return # it finished first; the next run's check holds the rest 

1188 batch.config = {**(batch.config or {}), "held_for_spend": True} 

1189 _record_spend_hold(db, deploy_id, reason, left) 

1190 db.commit() 

1191 finally: 

1192 db.close() 

1193 

1194 

1195def _record_pause(deploy_id: str, failures: int, left: int) -> None: 

1196 """The worker stopped after failures in a row; the next tick resumes.""" 

1197 logger.warning( 

1198 "[benchmark] %d runs failed in a row; pausing with %d left", failures, left 

1199 ) 

1200 db = SessionLocal() 

1201 try: 

1202 background_activity.record( 

1203 db, 

1204 kind=BackgroundEnum.Kind.platform_benchmark, 

1205 trigger=BackgroundEnum.Trigger.scheduled, 

1206 status=BackgroundEnum.Status.failed, 

1207 summary=( 

1208 f"Benchmark paused: {failures} runs failed in a row; " 

1209 f"{left} run(s) wait for the next attempt" 

1210 ), 

1211 detail={"deploy_id": deploy_id, "failed_in_a_row": failures, "left": left}, 

1212 ) 

1213 db.commit() 

1214 finally: 

1215 db.close() 

1216 

1217 

1218def _record_run(batch_id: UUID, plan: Plan, deploy_id: str, started: Any) -> str: 

1219 """One background event per run, carrying what it cost. Returns how the 

1220 run ended: ``completed``, ``failed``, ``interrupted`` or ``cancelled``.""" 

1221 db = SessionLocal() 

1222 try: 

1223 batch = db.get(ExperimentBatch, batch_id) 

1224 if batch is None: 

1225 return "failed" 

1226 if runner.is_interrupted(batch): 

1227 # Not an outcome of the target: the next start runs it again. 

1228 return "interrupted" 

1229 ok = batch.status == RunnableEnum.Status.completed 

1230 score = batch.mean_score 

1231 background_activity.record( 

1232 db, 

1233 kind=BackgroundEnum.Kind.platform_benchmark, 

1234 trigger=BackgroundEnum.Trigger.scheduled, 

1235 status=BackgroundEnum.Status.ok if ok else BackgroundEnum.Status.failed, 

1236 summary=( 

1237 f"{plan.target_name} on {plan.dataset_name}: " 

1238 + (f"{score:.2f}" if ok and score is not None else str(batch.status)) 

1239 ), 

1240 subject_type="experiment", 

1241 subject_id=plan.experiment_id, 

1242 subject_name=f"{plan.target_name} · {plan.dataset_name}", 

1243 detail={ 

1244 "deploy_id": deploy_id, 

1245 "mean_score": score, 

1246 "usage": (batch.summary or {}).get("usage"), 

1247 }, 

1248 reference={"experiment_id": plan.experiment_id, "batch_id": batch_id}, 

1249 error=batch.error, 

1250 started_at=started, 

1251 ) 

1252 db.commit() 

1253 if ok: 

1254 return "completed" 

1255 return getattr(batch.status, "value", str(batch.status)) 

1256 finally: 

1257 db.close() 

1258 

1259 

1260# ── Reading it ─────────────────────────────────────────────────────────────── 

1261 

1262 

1263def enabled() -> bool: 

1264 """Whether this deployment runs the benchmark at all.""" 

1265 settings = get_settings() 

1266 return bool( 

1267 settings.PLATFORM_BENCHMARK_ENABLED and (settings.DEPLOY_ID or "").strip() 

1268 ) 

1269 

1270 

1271def coverage(db: Session, agent_id: Any, evaluated: Iterable[Any]) -> dict[str, Any]: 

1272 """Where the benchmark is with CHAINR Bot on every gold dataset — so a 

1273 page that lists the bot's results also lists what is still to come, and 

1274 says which results a run for this release is replacing. 

1275 

1276 ``evaluated`` are the dataset ids it has a result on for the version in 

1277 force. Returns ``pending``, one entry per gold dataset without one 

1278 (``running``, ``queued``, ``interrupted`` — cut off by a restart and due 

1279 again — ``failed``, with its error, ``next_round`` — run this month 

1280 already, so measured again in next month's round — or ``off`` where this 

1281 deployment does not run the benchmark), and ``refreshing``, the datasets 

1282 with a result that a run is replacing now. Empty for any agent the 

1283 benchmark does not run. 

1284 """ 

1285 out: dict[str, Any] = {"pending": [], "refreshing": []} 

1286 if str(agent_id) != str(CHAINR_BOT.id): 

1287 return out 

1288 done = {str(d) for d in evaluated} 

1289 running_here = enabled() 

1290 month = period_start() 

1291 for dataset in gold_datasets(db): 

1292 eid = experiment_id(dataset.id, BOT_KEY) 

1293 newest = ( 

1294 db.query(ExperimentBatch) 

1295 .filter(ExperimentBatch.experiment_id == eid) 

1296 .order_by(ExperimentBatch.created_at.desc()) 

1297 .first() 

1298 ) 

1299 in_flight = ( 

1300 newest is not None and newest.status in _IN_FLIGHT and _fresh(newest) 

1301 ) 

1302 if str(dataset.id) in done: 

1303 if in_flight: 

1304 out["refreshing"].append(str(dataset.id)) 

1305 continue 

1306 if not running_here: 

1307 state = "off" 

1308 elif in_flight: 

1309 state = "running" 

1310 elif newest is not None and runner.is_interrupted(newest): 

1311 state = "interrupted" 

1312 elif newest is not None and newest.status in _DONE_BADLY: 

1313 state = "failed" 

1314 elif _ran_this_month(db, eid, month): 

1315 # The same rule ``due`` keeps: one round a month. 

1316 state = "next_round" 

1317 else: 

1318 state = "queued" 

1319 out["pending"].append( 

1320 { 

1321 "dataset_id": str(dataset.id), 

1322 "dataset_name": dataset.name, 

1323 "status": state, 

1324 "error": newest.error if state == "failed" and newest else None, 

1325 } 

1326 ) 

1327 order = { 

1328 "running": 0, 

1329 "queued": 1, 

1330 "interrupted": 2, 

1331 "failed": 3, 

1332 "next_round": 4, 

1333 "off": 5, 

1334 } 

1335 out["pending"].sort(key=lambda d: order[d["status"]]) 

1336 return out 

1337 

1338 

1339def _ran_this_month(db: Session, eid: UUID, month: datetime) -> bool: 

1340 """Whether the experiment completed a run this month — which ``due`` 

1341 leaves until next month, however stale it has become since.""" 

1342 return ( 

1343 db.query(ExperimentBatch) 

1344 .filter( 

1345 ExperimentBatch.experiment_id == eid, 

1346 ExperimentBatch.status == RunnableEnum.Status.completed, 

1347 ExperimentBatch.created_at >= month.replace(tzinfo=None), 

1348 ) 

1349 .first() 

1350 is not None 

1351 ) 

1352 

1353 

1354#: Bot runs shown per dataset in its history, newest last. 

1355HISTORY_LIMIT = 20 

1356 

1357 

1358def _agent_version(batch: ExperimentBatch) -> Optional[int]: 

1359 for stamp in (batch.target_versions or {}).values(): 

1360 if isinstance(stamp, dict) and stamp.get("agent_version") is not None: 

1361 return int(stamp["agent_version"]) 

1362 return None 

1363 

1364 

1365def _result(batch: ExperimentBatch, pass_mark: float) -> dict[str, Any]: 

1366 score = batch.mean_score 

1367 regressed = batch.regression_verdict == "regressed" 

1368 return { 

1369 "batch_id": str(batch.id), 

1370 "score": score, 

1371 "pass_rate": batch.pass_rate, 

1372 "passed": (score is not None and score >= pass_mark and not regressed), 

1373 "regression_verdict": batch.regression_verdict, 

1374 "dataset_version": batch.dataset_version, 

1375 "deploy_id": _benchmark_stamp(batch).get("deploy_id") 

1376 or _benchmark_stamp(batch).get("cycle"), 

1377 "agent_version": _agent_version(batch), 

1378 # Every score is relative to the model that graded it. 

1379 "judge": _benchmark_stamp(batch).get("judge"), 

1380 "cost_usd": ((batch.summary or {}).get("usage") or {}).get( 

1381 "estimated_cost_usd" 

1382 ), 

1383 # What one answer cost, grading left out: beside the score, what 

1384 # the score was bought for. 

1385 "cost_per_answer_usd": batch_store.cost_per_answer(batch.leaderboard), 

1386 "evaluated_at": ( 

1387 utc_isoformat(batch.finished_at or batch.created_at) 

1388 if (batch.finished_at or batch.created_at) 

1389 else None 

1390 ), 

1391 } 

1392 

1393 

1394def view(db: Session, dataset_id: Any = None) -> dict[str, Any]: 

1395 """The benchmark as every user sees it: per gold dataset, CHAINR Bot and 

1396 each maker's strongest built-in model (the experiments ``retire`` has 

1397 not archived) on the dataset's current content version, and the bot's 

1398 runs over time.""" 

1399 from app.services.evaluation.evidence import DEFAULT_PASS_MARK 

1400 

1401 settings = get_settings() 

1402 deploy_id = (settings.DEPLOY_ID or "").strip() 

1403 datasets_out: list[dict[str, Any]] = [] 

1404 # (dataset, row, latest batch) for every target with a current result, 

1405 # so each target's answers can be read in one query afterwards. 

1406 picked: list[tuple[str, dict[str, Any], Any]] = [] 

1407 gold = gold_datasets(db, dataset_id) 

1408 for dataset in gold: 

1409 pass_mark = float(dataset.pass_mark or DEFAULT_PASS_MARK) 

1410 version = dataset_versions.current_content_version(db, dataset.id) 

1411 experiments = ( 

1412 db.query(Experiment) 

1413 .filter( 

1414 Experiment.is_system.is_(True), 

1415 Experiment.dataset_id == dataset.id, 

1416 Experiment.status == EvaluationEnum.Status.active, 

1417 ) 

1418 .all() 

1419 ) 

1420 rows: list[dict[str, Any]] = [] 

1421 history: list[dict[str, Any]] = [] 

1422 for experiment in experiments: 

1423 bench = dict((experiment.config or {}).get("benchmark") or {}) 

1424 batches = sorted( 

1425 db.query(ExperimentBatch) 

1426 .filter(ExperimentBatch.experiment_id == experiment.id) 

1427 .all(), 

1428 key=lambda b: b.created_at or aware_utcnow(), 

1429 reverse=True, 

1430 ) 

1431 completed = [ 

1432 b for b in batches if b.status == RunnableEnum.Status.completed 

1433 ] 

1434 on_version = [b for b in completed if b.dataset_version == version] 

1435 variant = ( 

1436 db.query(ExperimentVariant) 

1437 .filter(ExperimentVariant.experiment_id == experiment.id) 

1438 .first() 

1439 ) 

1440 target = dict((variant.config or {}).get("target") or {}) if variant else {} 

1441 running = any(b.status in _IN_FLIGHT and _fresh(b) for b in batches) 

1442 row: dict[str, Any] = { 

1443 "experiment_id": str(experiment.id), 

1444 "target_key": bench.get("target"), 

1445 "kind": bench.get("kind"), 

1446 "name": variant.name if variant else experiment.name, 

1447 "agent_id": target.get("agent_id"), 

1448 "model_id": target.get("model_id"), 

1449 "status": ( 

1450 "running" if running else ("current" if on_version else "pending") 

1451 ), 

1452 "latest": _result(on_version[0], pass_mark) if on_version else None, 

1453 } 

1454 rows.append(row) 

1455 if on_version: 

1456 picked.append((str(dataset.id), row, on_version[0].id)) 

1457 if bench.get("target") == BOT_KEY: 

1458 history = [ 

1459 _result(b, pass_mark) for b in reversed(completed[:HISTORY_LIMIT]) 

1460 ] 

1461 rows.sort( 

1462 key=lambda r: ( 

1463 r["target_key"] != BOT_KEY, 

1464 r["latest"] is None, 

1465 -((r["latest"] or {}).get("score") or 0.0), 

1466 (r["name"] or "").lower(), 

1467 ) 

1468 ) 

1469 datasets_out.append( 

1470 { 

1471 "dataset_id": str(dataset.id), 

1472 "dataset_name": dataset.name, 

1473 "pass_mark": pass_mark, 

1474 "dataset_version": version, 

1475 "rows": rows, 

1476 "bot_history": history, 

1477 } 

1478 ) 

1479 # Always read, so each row's latest result carries its spread; the 

1480 # comparison across datasets only means something over all of them. 

1481 targets = _target_profiles(db, picked, len(gold)) 

1482 return { 

1483 "enabled": enabled(), 

1484 "deploy_id": deploy_id or None, 

1485 "budget_usd": float(settings.PLATFORM_BENCHMARK_BUDGET_USD), 

1486 # Measured spend this calendar month, and when the budget resets. 

1487 "spend_month_usd": round(period_spend(db), 4), 

1488 "period": period_key(), 

1489 "resets_at": utc_isoformat(next_period_start()), 

1490 "datasets": datasets_out, 

1491 "targets": targets if dataset_id is None else [], 

1492 } 

1493 

1494 

1495def _target_profiles( 

1496 db: Session, picked: list[tuple[str, dict[str, Any], Any]], total: int 

1497) -> list[dict[str, Any]]: 

1498 """Each target's expected quality and risk across the gold datasets 

1499 (``risk.profile``), and whether it sits on the efficient frontier. 

1500 

1501 Also gives each row's latest result its own spread (``answer_sd``). Only 

1502 targets with a result on every gold dataset are compared on the 

1503 frontier: an average over three capabilities is not the same measurement 

1504 as one over seven. 

1505 """ 

1506 scores = risk_service.answer_scores(db, [batch_id for _, _, batch_id in picked]) 

1507 samples: dict[str, dict[str, list[float]]] = {} 

1508 about: dict[str, dict[str, Any]] = {} 

1509 for dataset_id, row, batch_id in picked: 

1510 answers = risk_service.scores_of(scores, batch_id) 

1511 one = risk_service.profile({dataset_id: answers}) 

1512 row["latest"]["answers"] = len(answers) 

1513 row["latest"]["answer_sd"] = round(one.sd, 4) if one else None 

1514 key = row["target_key"] 

1515 samples.setdefault(key, {})[dataset_id] = answers 

1516 about.setdefault( 

1517 key, {"target_key": key, "name": row["name"], "kind": row["kind"]} 

1518 ) 

1519 out: list[dict[str, Any]] = [] 

1520 complete: dict[str, tuple[float, float]] = {} 

1521 for key, by_dataset in samples.items(): 

1522 found = risk_service.profile(by_dataset) 

1523 covered = sum(1 for answers in by_dataset.values() if answers) 

1524 if found is not None and covered == total: 

1525 complete[key] = (found.mean, found.sd) 

1526 out.append( 

1527 { 

1528 **about[key], 

1529 "quality": found.as_json() if found else None, 

1530 "datasets_covered": covered, 

1531 "datasets_total": total, 

1532 } 

1533 ) 

1534 frontier = risk_service.efficient(complete) 

1535 for entry in out: 

1536 entry["efficient"] = entry["target_key"] in frontier 

1537 out.sort( 

1538 key=lambda t: ( 

1539 t["datasets_covered"] < total, 

1540 -((t["quality"] or {}).get("mean") or 0.0), 

1541 (t["name"] or "").lower(), 

1542 ) 

1543 ) 

1544 return out