Coverage for app / services / scenarios / runner.py: 93%

192 statements  

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

1"""Running a scenario in the background, and keeping its record. 

2 

3``start`` writes the run ``running`` and hands it to a one-worker pool — 

4one scenario at a time on the process, one per person (``RunInProgress``) — 

5and returns at once. The worker (``execute``) makes the run's project and 

6agents, reads each agent's context panel, runs every turn through the chat 

7route (``driver.run_turn``) in order, conversation by conversation, appending 

8each turn's export to the row as it finishes, and closes with the agents' 

9recommendations and the run's summary. A run cut off by a restart keeps what 

10it did and reads as failed once it has been silent for ``STALE_AFTER``. 

11 

12The CLI (``python -m app.services.scenarios``) calls ``execute`` in its own 

13thread, with no switch and no pool. 

14""" 

15 

16from __future__ import annotations 

17 

18import asyncio 

19import logging 

20from collections.abc import Callable 

21from concurrent.futures import ThreadPoolExecutor 

22from datetime import timedelta 

23from enum import StrEnum 

24from typing import Any 

25from uuid import UUID 

26 

27from sqlalchemy.orm import Session 

28from sqlalchemy.orm.attributes import flag_modified 

29 

30from app.db.postgres.models import Agent, ScenarioRun, User 

31from app.services import ai_client, turns 

32from app.services import workspace as workspace_service 

33from app.services.scenarios import driver, export, provision, readiness, schema 

34from app.util.time import aware_utcnow, naive_utcnow, utc_isoformat 

35 

36logger = logging.getLogger(__name__) 

37 

38#: Longer than a turn may run and be stopped (``driver``): silent past 

39#: this, the worker has gone. 

40STALE_AFTER = timedelta(seconds=driver.TURN_TIMEOUT_S + driver.STOP_GRACE_S + 240) 

41STALE_MESSAGE = ( 

42 "The run stopped reporting (the service restarted?); what it did is kept." 

43) 

44 

45 

46class Status(StrEnum): 

47 running = "running" 

48 completed = "completed" 

49 failed = "failed" 

50 cancelled = "cancelled" 

51 

52 

53class RunInProgress(Exception): 

54 """This person already has a scenario running.""" 

55 

56 def __init__(self, run: ScenarioRun) -> None: 

57 super().__init__(f"Scenario run {run.id} ({run.name}) is still running.") 

58 self.run = run 

59 

60 

61_POOL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="scenario-run") 

62 

63 

64# ── The record ──────────────────────────────────────────────────────────────── 

65 

66 

67def is_stale(run: ScenarioRun, now=None) -> bool: 

68 if run.status != Status.running: 

69 return False 

70 moved = run.updated_at or run.created_at 

71 return moved is not None and (now or naive_utcnow()) - moved > STALE_AFTER 

72 

73 

74def settle_stale(db: Session, run: ScenarioRun) -> ScenarioRun: 

75 """A run whose worker has gone, marked failed when it is read.""" 

76 if is_stale(run): 

77 run.status = Status.failed 

78 run.error = STALE_MESSAGE 

79 run.finished_at = naive_utcnow() 

80 db.commit() 

81 return run 

82 

83 

84def running_for(db: Session, user_id: UUID) -> ScenarioRun | None: 

85 for run in ( 

86 db.query(ScenarioRun) 

87 .filter(ScenarioRun.user_id == user_id, ScenarioRun.status == Status.running) 

88 .all() 

89 ): 

90 settle_stale(db, run) 

91 if run.status == Status.running: 

92 return run 

93 return None 

94 

95 

96def start( 

97 db: Session, 

98 user: User, 

99 scenario: schema.ScenarioFile, 

100 *, 

101 submit: Callable[[UUID], Any] | None = None, 

102) -> ScenarioRun: 

103 """Record the run and hand it to the worker. ``RunInProgress`` while 

104 this person has another running.""" 

105 running = running_for(db, user.id) 

106 if running is not None: 

107 raise RunInProgress(running) 

108 run = ScenarioRun( 

109 user_id=user.id, 

110 name=scenario.name, 

111 scenario=scenario.document(), 

112 scenario_sha256=scenario.sha256(), 

113 status=Status.running, 

114 progress={"done": 0, "total": scenario.turn_count, "current": "provisioning"}, 

115 ) 

116 db.add(run) 

117 db.commit() 

118 db.refresh(run) 

119 (submit or _submit)(run.id) 

120 return run 

121 

122 

123def request_cancel(db: Session, run: ScenarioRun) -> ScenarioRun: 

124 """Ask a running scenario to stop: the turn running now is stopped as 

125 Stop stops a chat, and no more start.""" 

126 if run.status != Status.running: 

127 return run 

128 run.cancel_requested = True 

129 db.commit() 

130 workspace_key = (run.results or {}).get("run", {}).get("workspace") 

131 if workspace_key: 

132 for turn in turns.registry.running(str(run.user_id)): 

133 if turn.workspace == workspace_key: 

134 turn.stop() 

135 return run 

136 

137 

138def _submit(run_id: UUID) -> None: 

139 _POOL.submit(_execute_logged, run_id) 

140 

141 

142def _execute_logged(run_id: UUID) -> None: 

143 try: 

144 execute(run_id) 

145 except Exception: # noqa: BLE001 — the worker thread must not die silently 

146 logger.exception("Scenario run %s failed outside its own handling", run_id) 

147 

148 

149# ── The work ────────────────────────────────────────────────────────────────── 

150 

151 

152def execute( 

153 run_id: UUID, 

154 *, 

155 session_factory: Callable[[], Session] | None = None, 

156 handler: driver.TurnHandler | None = None, 

157 catalogue: Callable[[], list[dict]] | None = None, 

158 swarm_execute: Callable[[UUID], None] | None = None, 

159) -> None: 

160 """Run the scenario ``run_id`` to its end, in an event loop of its own. 

161 ``swarm_execute`` coordinates one swarm run to its end (the swarm 

162 engine's, by default).""" 

163 asyncio.run( 

164 _execute( 

165 run_id, 

166 session_factory=session_factory, 

167 handler=handler, 

168 catalogue=catalogue, 

169 swarm_execute=swarm_execute, 

170 ) 

171 ) 

172 

173 

174def _save(db: Session, run: ScenarioRun, results: dict, **fields: Any) -> None: 

175 run.results = results 

176 flag_modified(run, "results") 

177 for name, value in fields.items(): 

178 setattr(run, name, value) 

179 run.updated_at = naive_utcnow() 

180 db.commit() 

181 

182 

183def _settings() -> Any: 

184 from app.common.settings import get_settings 

185 

186 return get_settings() 

187 

188 

189async def _execute( 

190 run_id: UUID, 

191 *, 

192 session_factory: Callable[[], Session] | None, 

193 handler: driver.TurnHandler | None, 

194 catalogue: Callable[[], list[dict]] | None, 

195 swarm_execute: Callable[[UUID], None] | None = None, 

196) -> None: 

197 from app.db.postgres.engine import SessionLocal 

198 

199 factory = session_factory or SessionLocal 

200 db = factory() 

201 run = db.get(ScenarioRun, run_id) 

202 if run is None or run.status != Status.running: 

203 db.close() 

204 return 

205 user = db.get(User, run.user_id) 

206 results: dict[str, Any] = { 

207 "schema": export.EXPORT_SCHEMA, 

208 "run": { 

209 "id": str(run.id), 

210 "scenario": run.name, 

211 "scenario_sha256": run.scenario_sha256, 

212 "started_at": utc_isoformat(aware_utcnow()), 

213 "finished_at": None, 

214 "status": Status.running.value, 

215 "deploy_id": getattr(_settings(), "DEPLOY_ID", "") or None, 

216 "svc_ai": _svc_ai_fingerprint(), 

217 }, 

218 "agents": [], 

219 "turns": [], 

220 "swarm_runs": [], 

221 "recommendations": None, 

222 "summary": None, 

223 } 

224 try: 

225 scenario, repositories = schema.load(run.scenario) 

226 models = ( 

227 (catalogue or ai_client.list_models)() 

228 if any(a.model for a in scenario.agents) 

229 else [] 

230 ) 

231 made = provision.provision( 

232 db, 

233 user, 

234 scenario, 

235 repositories, 

236 run_id=run.id, 

237 now=aware_utcnow(), 

238 catalogue=models, 

239 ) 

240 ws = workspace_service.resolve(db, made.workspace_key, user) 

241 results["run"].update( 

242 project_id=str(made.project_id), workspace=made.workspace_key 

243 ) 

244 _save(db, run, results, project_id=made.project_id) 

245 

246 # The built-in knowledge the file granted, there before the first 

247 # turn (``readiness``): the first run's agent answered every question 

248 # from knowledge bases that held nothing yet. 

249 def progress(line: str) -> None: 

250 run.progress = {"done": 0, "total": scenario.step_count, "current": line} 

251 _save(db, run, results) 

252 

253 def cancelled() -> bool: 

254 db.refresh(run) 

255 return bool(run.cancel_requested) 

256 

257 results["run"]["knowledge"] = await readiness.wait( 

258 db, repositories.values(), progress=progress, cancelled=cancelled 

259 ) 

260 before = { 

261 key: export.agent_context(db, db.get(Agent, agent_id), ws, user) 

262 for key, agent_id in made.agents.items() 

263 } 

264 _save(db, run, results) 

265 

266 done = 0 

267 cancelled = False 

268 for conversation in scenario.conversations: 

269 conversation_id: UUID | None = None 

270 for index, turn in enumerate(conversation.turns): 

271 db.refresh(run) 

272 if run.cancel_requested: 

273 cancelled = True 

274 break 

275 run.progress = { 

276 "done": done, 

277 "total": scenario.step_count, 

278 "current": f"{conversation.key} turn {index + 1}", 

279 } 

280 _save(db, run, results) 

281 ran = await driver.run_turn( 

282 user_id=user.id, 

283 agent_id=made.agents[conversation.agent], 

284 prompt=turn.prompt, 

285 conversation_id=conversation_id, 

286 workspace_key=made.workspace_key, 

287 answers=turn.answers, 

288 answer_unscripted=scenario.pauses == "answer", 

289 command_inputs=turn.command_inputs, 

290 session_factory=factory, 

291 handler=handler, 

292 ) 

293 conversation_id = ran.conversation_id or conversation_id 

294 db.expire_all() 

295 results["turns"].append( 

296 export.turn_export( 

297 db, 

298 ran, 

299 user=user, 

300 conversation=conversation.key, 

301 index=index, 

302 prompt=turn.prompt, 

303 expect=turn.expect, 

304 ) 

305 ) 

306 done += 1 

307 run.progress = { 

308 "done": done, 

309 "total": scenario.step_count, 

310 "current": None, 

311 } 

312 _save(db, run, results) 

313 if cancelled: 

314 break 

315 

316 if not cancelled: 

317 cancelled = await _swarm_runs( 

318 db, 

319 run, 

320 results, 

321 scenario, 

322 made, 

323 user, 

324 done=done, 

325 execute_swarm=swarm_execute, 

326 ) 

327 

328 for spec in scenario.agents: 

329 agent = db.get(Agent, made.agents[spec.key]) 

330 results["agents"].append( 

331 export.agent_export( 

332 spec, 

333 made.agents[spec.key], 

334 context_before=before.get(spec.key), 

335 context_after=export.agent_context(db, agent, ws, user), 

336 recommendations_after=export.recommendations( 

337 db, ws, user, agent_id=agent.id 

338 ), 

339 ) 

340 ) 

341 results["recommendations"] = export.recommendations(db, ws, user) 

342 status = Status.cancelled if cancelled else Status.completed 

343 _finish(db, run, results, status) 

344 except schema.ScenarioInvalid as exc: 

345 db.rollback() 

346 _finish(db, run, results, Status.failed, error=str(exc)) 

347 except Exception as exc: # noqa: BLE001 — recorded on the run 

348 logger.exception("Scenario run %s failed", run_id) 

349 db.rollback() 

350 _finish(db, run, results, Status.failed, error=type(exc).__name__) 

351 finally: 

352 db.close() 

353 

354 

355def _finish( 

356 db: Session, 

357 run: ScenarioRun, 

358 results: dict, 

359 status: Status, 

360 *, 

361 error: str | None = None, 

362) -> None: 

363 results["run"].update( 

364 status=status.value, finished_at=utc_isoformat(aware_utcnow()), error=error 

365 ) 

366 results["summary"] = export.summary( 

367 results["turns"], results["agents"], results.get("swarm_runs") 

368 ) 

369 _save( 

370 db, 

371 run, 

372 results, 

373 status=status, 

374 error=error, 

375 finished_at=naive_utcnow(), 

376 progress={**(run.progress or {}), "current": None}, 

377 ) 

378 

379 

380async def _swarm_runs( 

381 db: Session, 

382 run: ScenarioRun, 

383 results: dict, 

384 scenario: Any, 

385 made: provision.Provisioned, 

386 user: User, 

387 *, 

388 done: int, 

389 execute_swarm: Callable[[UUID], None] | None, 

390) -> bool: 

391 """Send each of the file's swarms on each of its tasks, and each task's 

392 follow-ups in turn, one run at a time: each coordinated to its end on a 

393 thread of its own and exported as it finishes. True when the run was 

394 cancelled meanwhile.""" 

395 from app.db.postgres.models import Swarm, SwarmRun 

396 from app.services.swarms import engine 

397 

398 coordinate = execute_swarm or engine.execute 

399 for swarm_spec in scenario.swarms: 

400 for index, spec in enumerate(swarm_spec.runs): 

401 previous: SwarmRun | None = None 

402 # Every source the thread has cited so far, to tell a follow-up's 

403 # carried sources from the ones it found again. 

404 cited: set[str] = set() 

405 for step, step_spec in enumerate([spec, *spec.follow_ups]): 

406 where = f"swarm {swarm_spec.key} run {index + 1}" + ( 

407 f" follow-up {step}" if step else "" 

408 ) 

409 db.refresh(run) 

410 if run.cancel_requested: 

411 return True 

412 run.progress = { 

413 "done": done, 

414 "total": scenario.step_count, 

415 "current": where, 

416 } 

417 _save(db, run, results) 

418 overrides = { 

419 **{ 

420 k: v 

421 for k, v in ( 

422 ("budget_usd", step_spec.budget_usd), 

423 ("time_cap_s", step_spec.time_cap_s), 

424 ) 

425 if v is not None 

426 }, 

427 "require_approval": False, 

428 "may_ask": False, 

429 } 

430 started = aware_utcnow() 

431 try: 

432 if previous is None: 

433 swarm_run = engine.start( 

434 db, 

435 db.get(Swarm, made.swarms[swarm_spec.key]), 

436 user, 

437 task=step_spec.task, 

438 overrides=overrides, 

439 submit=lambda _id: None, 

440 origin={ 

441 "kind": engine.Origin.scenario.value, 

442 "scenario_run_id": str(run.id), 

443 }, 

444 ) 

445 else: 

446 # The scenario's origin follows the thread. 

447 swarm_run = engine.follow_up( 

448 db, 

449 previous, 

450 user, 

451 task=step_spec.task, 

452 overrides=overrides, 

453 submit=lambda _id: None, 

454 ) 

455 except engine.RunRefused as exc: 

456 problems = "; ".join(f"{k}: {v}" for k, v in exc.fields.items()) 

457 raise schema.ScenarioInvalid( 

458 f"Swarm {where.removeprefix('swarm ')}: {problems or exc}" 

459 ) from exc 

460 await asyncio.to_thread(coordinate, swarm_run.id) 

461 db.expire_all() 

462 finished = db.get(SwarmRun, swarm_run.id) 

463 results["swarm_runs"].append( 

464 export.swarm_run_export( 

465 finished, 

466 swarm=swarm_spec.key, 

467 index=index, 

468 task=step_spec.task, 

469 expect=step_spec.expect, 

470 duration_ms=int( 

471 (aware_utcnow() - started).total_seconds() * 1000 

472 ), 

473 follow_up=step or None, 

474 given=export.thread_documents(db, finished) if step else None, 

475 carried=cited if step else None, 

476 ) 

477 ) 

478 cited |= export.source_keys(finished) 

479 previous = finished 

480 done += 1 

481 run.progress = { 

482 "done": done, 

483 "total": scenario.step_count, 

484 "current": None, 

485 } 

486 _save(db, run, results) 

487 return False 

488 

489 

490def _svc_ai_fingerprint() -> str | None: 

491 """svc-ai's code fingerprint (``/health``), so two runs say whether the 

492 code that answered was the same.""" 

493 try: 

494 return ai_client.service_fingerprint() 

495 except Exception: # noqa: BLE001 — a label, never a failure 

496 return None