Coverage for app / router / app / simulations / router.py: 79%

284 statements  

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

1from typing import Optional 

2from uuid import UUID 

3 

4from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status 

5from sqlalchemy.orm import Session 

6 

7from app.db.postgres.engine import SessionLocal 

8from app.dependency.base import get_db 

9from app.dependency.workspace import owner_for 

10from app.dependency.user.context import get_current_user 

11from app.dependency.resource_access import ( 

12 verify_resource_access, 

13 verify_resource_read, 

14 verify_list_scope, 

15 verify_owner_scope, 

16) 

17from app.db.postgres.enums import HistoryEnum, RunnableEnum, UsageEnum 

18from app.db.postgres.models import ( 

19 Agent, 

20 SimulationWorld, 

21 SimulationScenario, 

22 Simulation, 

23 User, 

24) 

25from app.db.postgres.crud_schemas import Schema 

26from app.router.app.history.router import register_history_routes 

27from app.services import usage as usage_service 

28from app.services import ai_client 

29from app.services import history as history_service 

30from app.services import skill_graph 

31from app.services import workspace as workspace_service 

32from app.services.budgets import gate as budget_gate 

33from app.util.time import aware_utcnow 

34 

35import logging 

36 

37logger = logging.getLogger(__name__) 

38 

39simulation_router = APIRouter(prefix="/simulations", tags=["App - Simulations"]) 

40 

41 

42def _accessible_world( 

43 world_id: UUID, current_user: User, db: Session, *, read: bool = False 

44) -> SimulationWorld: 

45 """The world, or 404 / 403 — the gate on every route beneath a world. 

46 

47 Scenarios and simulations carry no owner of their own; they are the 

48 world's, so reaching one is only as allowed as reaching its world. 

49 """ 

50 world = db.get(SimulationWorld, world_id) 

51 if not world: 

52 raise HTTPException( 

53 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation world not found" 

54 ) 

55 (verify_resource_read if read else verify_resource_access)(world, current_user, db) 

56 return world 

57 

58 

59def _verify_simulation_refs( 

60 world_id: UUID, 

61 scenario_id: UUID | None, 

62 agent_ids: list | None, 

63 current_user: User, 

64 db: Session, 

65) -> None: 

66 """Refuse a scenario from another world and an agent the caller cannot 

67 reach. A run hands each agent's system prompt and configuration to 

68 svc-ai and stores what comes back, so an agent id is a read of that 

69 agent — it has to be one the caller could open directly. 

70 """ 

71 if scenario_id is not None: 

72 scenario = db.get(SimulationScenario, scenario_id) 

73 if not scenario or scenario.world_id != world_id: 

74 raise HTTPException( 

75 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

76 detail="Scenario does not belong to this world.", 

77 ) 

78 for raw in agent_ids or []: 

79 try: 

80 agent = db.get(Agent, UUID(str(raw))) 

81 except ValueError: 

82 agent = None 

83 if agent is None: 

84 raise HTTPException( 

85 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

86 detail=f"Agent {raw} not found.", 

87 ) 

88 verify_resource_read(agent, current_user, db) 

89 

90 

91@simulation_router.get("") 

92def list_simulations_summary( 

93 db: Session = Depends(get_db), 

94 current_user: User = Depends(get_current_user), 

95): 

96 world_count = ( 

97 db.query(SimulationWorld) 

98 .filter(SimulationWorld.owner_user_id == current_user.id) 

99 .count() 

100 ) 

101 return {"worlds": world_count} 

102 

103 

104# ── Simulation Worlds ───────────────────────────────────────────────────────── 

105 

106 

107@simulation_router.get("/worlds") 

108def list_worlds( 

109 workspace: Optional[str] = None, 

110 owner_organisation_id: Optional[UUID] = None, 

111 owner_project_id: Optional[UUID] = None, 

112 db: Session = Depends(get_db), 

113 current_user: User = Depends(get_current_user), 

114): 

115 query = db.query(SimulationWorld) 

116 if workspace: 

117 from app.dependency.resource_access import list_scope 

118 

119 query = query.filter( 

120 list_scope(SimulationWorld, current_user, db, workspace=workspace) 

121 ) 

122 elif owner_organisation_id: 

123 verify_list_scope(owner_organisation_id, "organisation", current_user, db) 

124 query = query.filter( 

125 SimulationWorld.owner_organisation_id == owner_organisation_id 

126 ) 

127 elif owner_project_id: 

128 verify_list_scope(owner_project_id, "project", current_user, db) 

129 query = query.filter(SimulationWorld.owner_project_id == owner_project_id) 

130 else: 

131 query = query.filter(SimulationWorld.owner_user_id == current_user.id) 

132 return query.order_by(SimulationWorld.created_at.desc()).all() 

133 

134 

135@simulation_router.get("/worlds/{world_id}") 

136def get_world( 

137 world_id: UUID, 

138 db: Session = Depends(get_db), 

139 current_user: User = Depends(get_current_user), 

140): 

141 world = db.get(SimulationWorld, world_id) 

142 if not world: 

143 raise HTTPException( 

144 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation world not found" 

145 ) 

146 verify_resource_read(world, current_user, db) 

147 return world 

148 

149 

150def world_children_snapshot(db: Session, world_id: UUID) -> dict: 

151 """A world's current scenarios, for its version's ``children_snapshot``. 

152 

153 Simulations (the runs) are deliberately excluded: they are execution 

154 records, not part of the world's definition, and a version that churned 

155 on every run would drown the edit trail. 

156 """ 

157 scenarios = [ 

158 {"scenario_id": str(row.id), "name": row.name} 

159 for row in db.query(SimulationScenario) 

160 .filter(SimulationScenario.world_id == world_id) 

161 .all() 

162 ] 

163 return {"scenarios": scenarios} 

164 

165 

166@simulation_router.post("/worlds", status_code=status.HTTP_201_CREATED) 

167def create_world( 

168 data: Schema.SimulationWorld.Create, 

169 db: Session = Depends(get_db), 

170 current_user: User = Depends(get_current_user), 

171): 

172 payload = data.model_dump() 

173 if not payload.get("owner_organisation_id") and not payload.get("owner_project_id"): 

174 # The workspace the request was made in (app/dependency/workspace.py). 

175 payload.update(owner_for(db, current_user, model=SimulationWorld)) 

176 verify_owner_scope(payload, current_user, db, model=SimulationWorld) 

177 

178 world = SimulationWorld(**payload) 

179 try: 

180 db.add(world) 

181 db.commit() 

182 db.refresh(world) 

183 history_service.record_version( 

184 db, 

185 resource_type=HistoryEnum.ResourceType.simulation_world, 

186 model=SimulationWorld, 

187 resource=world, 

188 action=HistoryEnum.Action.created, 

189 actor=current_user, 

190 children_resolver=lambda: world_children_snapshot(db, world.id), 

191 ) 

192 db.commit() 

193 return world 

194 except Exception: 

195 db.rollback() 

196 logger.exception("Failed to create simulation world") 

197 raise 

198 

199 

200@simulation_router.patch("/worlds/{world_id}") 

201def update_world( 

202 world_id: UUID, 

203 data: Schema.SimulationWorld.Update, 

204 db: Session = Depends(get_db), 

205 current_user: User = Depends(get_current_user), 

206): 

207 world = db.get(SimulationWorld, world_id) 

208 if not world: 

209 raise HTTPException( 

210 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation world not found" 

211 ) 

212 verify_resource_access(world, current_user, db) 

213 

214 for field, value in data.model_dump(exclude_unset=True).items(): 

215 setattr(world, field, value) 

216 history_service.record_version( 

217 db, 

218 resource_type=HistoryEnum.ResourceType.simulation_world, 

219 model=SimulationWorld, 

220 resource=world, 

221 action=HistoryEnum.Action.updated, 

222 actor=current_user, 

223 children_resolver=lambda: world_children_snapshot(db, world_id), 

224 ) 

225 try: 

226 db.commit() 

227 db.refresh(world) 

228 return world 

229 except Exception: 

230 db.rollback() 

231 logger.exception("Failed to update simulation world") 

232 raise 

233 

234 

235@simulation_router.delete("/worlds/{world_id}", status_code=status.HTTP_204_NO_CONTENT) 

236def delete_world( 

237 world_id: UUID, 

238 db: Session = Depends(get_db), 

239 current_user: User = Depends(get_current_user), 

240): 

241 world = db.get(SimulationWorld, world_id) 

242 if not world: 

243 raise HTTPException( 

244 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation world not found" 

245 ) 

246 verify_resource_access(world, current_user, db) 

247 history_service.record_version( 

248 db, 

249 resource_type=HistoryEnum.ResourceType.simulation_world, 

250 model=SimulationWorld, 

251 resource=world, 

252 action=HistoryEnum.Action.deleted, 

253 actor=current_user, 

254 children_resolver=lambda: world_children_snapshot(db, world_id), 

255 ) 

256 db.delete(world) 

257 db.commit() 

258 

259 

260# ── Simulation Scenarios ────────────────────────────────────────────────────── 

261 

262 

263@simulation_router.get("/worlds/{world_id}/scenarios") 

264def list_scenarios( 

265 world_id: UUID, 

266 db: Session = Depends(get_db), 

267 current_user: User = Depends(get_current_user), 

268): 

269 _accessible_world(world_id, current_user, db, read=True) 

270 return ( 

271 db.query(SimulationScenario) 

272 .filter(SimulationScenario.world_id == world_id) 

273 .order_by(SimulationScenario.created_at) 

274 .all() 

275 ) 

276 

277 

278@simulation_router.get("/worlds/{world_id}/scenarios/{scenario_id}") 

279def get_scenario( 

280 world_id: UUID, 

281 scenario_id: UUID, 

282 db: Session = Depends(get_db), 

283 current_user: User = Depends(get_current_user), 

284): 

285 _accessible_world(world_id, current_user, db, read=True) 

286 scenario = db.get(SimulationScenario, scenario_id) 

287 if not scenario or scenario.world_id != world_id: 

288 raise HTTPException( 

289 status_code=status.HTTP_404_NOT_FOUND, detail="Scenario not found" 

290 ) 

291 return scenario 

292 

293 

294@simulation_router.post( 

295 "/worlds/{world_id}/scenarios", status_code=status.HTTP_201_CREATED 

296) 

297def create_scenario( 

298 world_id: UUID, 

299 data: Schema.SimulationScenario.Create, 

300 db: Session = Depends(get_db), 

301 current_user: User = Depends(get_current_user), 

302): 

303 _accessible_world(world_id, current_user, db) 

304 scenario = SimulationScenario(**{**data.model_dump(), "world_id": world_id}) 

305 try: 

306 db.add(scenario) 

307 db.commit() 

308 db.refresh(scenario) 

309 return scenario 

310 except Exception: 

311 db.rollback() 

312 logger.exception("Failed to create simulation scenario") 

313 raise 

314 

315 

316@simulation_router.patch("/worlds/{world_id}/scenarios/{scenario_id}") 

317def update_scenario( 

318 world_id: UUID, 

319 scenario_id: UUID, 

320 data: Schema.SimulationScenario.Update, 

321 db: Session = Depends(get_db), 

322 current_user: User = Depends(get_current_user), 

323): 

324 _accessible_world(world_id, current_user, db) 

325 scenario = db.get(SimulationScenario, scenario_id) 

326 if not scenario or scenario.world_id != world_id: 

327 raise HTTPException( 

328 status_code=status.HTTP_404_NOT_FOUND, detail="Scenario not found" 

329 ) 

330 

331 for field, value in data.model_dump(exclude_unset=True).items(): 

332 setattr(scenario, field, value) 

333 try: 

334 db.commit() 

335 db.refresh(scenario) 

336 return scenario 

337 except Exception: 

338 db.rollback() 

339 logger.exception("Failed to update simulation scenario") 

340 raise 

341 

342 

343@simulation_router.delete( 

344 "/worlds/{world_id}/scenarios/{scenario_id}", 

345 status_code=status.HTTP_204_NO_CONTENT, 

346) 

347def delete_scenario( 

348 world_id: UUID, 

349 scenario_id: UUID, 

350 db: Session = Depends(get_db), 

351 current_user: User = Depends(get_current_user), 

352): 

353 _accessible_world(world_id, current_user, db) 

354 scenario = db.get(SimulationScenario, scenario_id) 

355 if not scenario or scenario.world_id != world_id: 

356 raise HTTPException( 

357 status_code=status.HTTP_404_NOT_FOUND, detail="Scenario not found" 

358 ) 

359 db.delete(scenario) 

360 db.commit() 

361 

362 

363# ── Simulations ─────────────────────────────────────────────────────────────── 

364 

365 

366@simulation_router.get("/worlds/{world_id}/simulations") 

367def list_world_simulations( 

368 world_id: UUID, 

369 db: Session = Depends(get_db), 

370 current_user: User = Depends(get_current_user), 

371): 

372 _accessible_world(world_id, current_user, db, read=True) 

373 return ( 

374 db.query(Simulation) 

375 .filter(Simulation.world_id == world_id) 

376 .order_by(Simulation.created_at.desc()) 

377 .all() 

378 ) 

379 

380 

381@simulation_router.get("/worlds/{world_id}/simulations/{simulation_id}") 

382def get_simulation( 

383 world_id: UUID, 

384 simulation_id: UUID, 

385 db: Session = Depends(get_db), 

386 current_user: User = Depends(get_current_user), 

387): 

388 _accessible_world(world_id, current_user, db, read=True) 

389 simulation = db.get(Simulation, simulation_id) 

390 if not simulation or simulation.world_id != world_id: 

391 raise HTTPException( 

392 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation not found" 

393 ) 

394 return simulation 

395 

396 

397@simulation_router.post( 

398 "/worlds/{world_id}/simulations", status_code=status.HTTP_201_CREATED 

399) 

400def create_simulation( 

401 world_id: UUID, 

402 data: Schema.Simulation.Create, 

403 db: Session = Depends(get_db), 

404 current_user: User = Depends(get_current_user), 

405): 

406 _accessible_world(world_id, current_user, db) 

407 _verify_simulation_refs( 

408 world_id, data.scenario_id, data.agent_ids, current_user, db 

409 ) 

410 simulation = Simulation(**{**data.model_dump(), "world_id": world_id}) 

411 try: 

412 db.add(simulation) 

413 db.commit() 

414 db.refresh(simulation) 

415 return simulation 

416 except Exception: 

417 db.rollback() 

418 logger.exception("Failed to create simulation") 

419 raise 

420 

421 

422@simulation_router.patch("/worlds/{world_id}/simulations/{simulation_id}") 

423def update_simulation( 

424 world_id: UUID, 

425 simulation_id: UUID, 

426 data: Schema.Simulation.Update, 

427 db: Session = Depends(get_db), 

428 current_user: User = Depends(get_current_user), 

429): 

430 _accessible_world(world_id, current_user, db) 

431 simulation = db.get(Simulation, simulation_id) 

432 if not simulation or simulation.world_id != world_id: 

433 raise HTTPException( 

434 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation not found" 

435 ) 

436 

437 if data.agent_ids is not None: 

438 _verify_simulation_refs(world_id, None, data.agent_ids, current_user, db) 

439 

440 for field, value in data.model_dump(exclude_unset=True).items(): 

441 setattr(simulation, field, value) 

442 try: 

443 db.commit() 

444 db.refresh(simulation) 

445 return simulation 

446 except Exception: 

447 db.rollback() 

448 logger.exception("Failed to update simulation") 

449 raise 

450 

451 

452@simulation_router.delete( 

453 "/worlds/{world_id}/simulations/{simulation_id}", 

454 status_code=status.HTTP_204_NO_CONTENT, 

455) 

456def delete_simulation( 

457 world_id: UUID, 

458 simulation_id: UUID, 

459 db: Session = Depends(get_db), 

460 current_user: User = Depends(get_current_user), 

461): 

462 _accessible_world(world_id, current_user, db) 

463 simulation = db.get(Simulation, simulation_id) 

464 if not simulation or simulation.world_id != world_id: 

465 raise HTTPException( 

466 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation not found" 

467 ) 

468 db.delete(simulation) 

469 db.commit() 

470 

471 

472# ── Run ─────────────────────────────────────────────────────────────────────── 

473 

474 

475def _ledger_simulation( 

476 db, simulation_id: UUID, used, failed: bool = False, actor_user_id=None 

477) -> None: 

478 """Put a simulation's spend on the usage ledger, against the simulation. 

479 

480 Owned through its world, so it is filed in the world's workspace, and 

481 counted for whoever ran it (the world's owner, for a personal one). 

482 """ 

483 sim = db.get(Simulation, simulation_id) 

484 world = db.get(SimulationWorld, sim.world_id) if sim else None 

485 if world is None: 

486 return 

487 usage_service.record_measured( 

488 db, 

489 owner_user_id=actor_user_id or world.owner_user_id, 

490 execution_type="simulation", 

491 source_type=UsageEnum.Source.simulation, 

492 source_id=simulation_id, 

493 measured=used, 

494 owner_project_id=world.owner_project_id, 

495 owner_organisation_id=world.owner_organisation_id, 

496 failed=failed, 

497 ) 

498 

499 

500async def _execute_simulation_background( 

501 simulation_id: UUID, payload: dict, limit=None 

502) -> None: 

503 """Background task: calls svc-ai and writes results back to the DB. 

504 ``limit`` is what the world's workspace's budgets left the run 

505 (``budgets.gate``), where svc-ai stops it.""" 

506 db = SessionLocal() 

507 used = None 

508 actor = payload.get("user_id") 

509 try: 

510 with ai_client.usage_capture() as used, ai_client.in_spend_limit(limit): 

511 result = await ai_client.run_simulation(payload) 

512 _ledger_simulation(db, simulation_id, used, actor_user_id=actor) 

513 sim = db.get(Simulation, simulation_id) 

514 if sim: 

515 sim.status = RunnableEnum.Status.completed 

516 sim.results = result 

517 sim.finished_at = aware_utcnow() 

518 db.commit() 

519 except Exception as exc: 

520 logger.exception( 

521 "Background simulation run failed for simulation_id=%s", simulation_id 

522 ) 

523 db.rollback() 

524 # A run that failed after the model answered was still paid for. 

525 _ledger_simulation(db, simulation_id, used, failed=True, actor_user_id=actor) 

526 sim = db.get(Simulation, simulation_id) 

527 if sim: 

528 sim.status = RunnableEnum.Status.failed 

529 sim.results = {"error": f"{type(exc).__name__}: {exc}"} 

530 sim.finished_at = aware_utcnow() 

531 db.commit() 

532 finally: 

533 db.close() 

534 

535 

536@simulation_router.post( 

537 "/worlds/{world_id}/simulations/{simulation_id}/run", 

538 status_code=status.HTTP_202_ACCEPTED, 

539 summary="Trigger a simulation run (async — poll GET for results)", 

540) 

541async def run_simulation( 

542 world_id: UUID, 

543 simulation_id: UUID, 

544 background_tasks: BackgroundTasks, 

545 initial_prompt: Optional[str] = None, 

546 db: Session = Depends(get_db), 

547 current_user: User = Depends(get_current_user), 

548): 

549 _accessible_world(world_id, current_user, db) 

550 simulation = db.get(Simulation, simulation_id) 

551 if not simulation or simulation.world_id != world_id: 

552 raise HTTPException( 

553 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation not found" 

554 ) 

555 # Re-checked at run time rather than trusted from save: a simulation 

556 # stored before this check existed may name anybody's agents. 

557 _verify_simulation_refs( 

558 world_id, simulation.scenario_id, simulation.agent_ids, current_user, db 

559 ) 

560 

561 if simulation.status == RunnableEnum.Status.running: 

562 raise HTTPException( 

563 status_code=status.HTTP_409_CONFLICT, 

564 detail="Simulation is already running.", 

565 ) 

566 

567 world = db.get(SimulationWorld, world_id) 

568 if not world: 

569 raise HTTPException( 

570 status_code=status.HTTP_404_NOT_FOUND, detail="Simulation world not found" 

571 ) 

572 

573 scenario = ( 

574 db.get(SimulationScenario, simulation.scenario_id) 

575 if simulation.scenario_id 

576 else None 

577 ) 

578 

579 agent_specs: list[dict] = [] 

580 for agent_id_str in simulation.agent_ids or []: 

581 try: 

582 agent = db.get(Agent, UUID(str(agent_id_str))) 

583 except Exception: 

584 agent = None 

585 if agent: 

586 # svc-ai builds each tool from its stored config, so a knowledge 

587 # tool reads only what the agent's own workspace has — the rule 

588 # a skill's tool node follows when it runs. 

589 home = workspace_service.home_of(db, agent) 

590 tools = [ 

591 { 

592 **tool, 

593 "config": skill_graph.scope_tool_config( 

594 tool.get("config") or {}, 

595 db, 

596 home, 

597 label=f"Agent {agent.name!r}'s tool {tool.get('name')!r}", 

598 ), 

599 } 

600 for tool in agent.tools or [] 

601 if isinstance(tool, dict) and isinstance(tool.get("config") or {}, dict) 

602 ] 

603 agent_specs.append( 

604 { 

605 "agent_id": str(agent.id), 

606 "name": agent.name, 

607 "system_prompt": agent.system_prompt, 

608 "model": agent.config or {}, 

609 "tools": tools, 

610 } 

611 ) 

612 

613 if not agent_specs: 

614 raise HTTPException( 

615 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

616 detail="No resolvable agents found for this simulation.", 

617 ) 

618 

619 # The world's workspace's budgets (cost-control plan A1.5): one used up 

620 # refuses the run (403); one with something left limits it. 

621 home = workspace_service.home_of(db, world) 

622 limit = ( 

623 budget_gate.check( 

624 db, ws=home, actor_user_id=current_user.id, execution_type="simulation" 

625 ) 

626 if home is not None 

627 else None 

628 ) 

629 

630 simulation.status = RunnableEnum.Status.running 

631 simulation.started_at = aware_utcnow() 

632 db.commit() 

633 db.refresh(simulation) 

634 

635 payload: dict = { 

636 "simulation_id": str(simulation_id), 

637 # Who ran it — svc-ai traces the run's model calls to them. 

638 "user_id": str(current_user.id), 

639 "world": { 

640 "id": str(world.id), 

641 "name": world.name, 

642 "description": world.description, 

643 "rules": world.rules or {}, 

644 "logic": world.logic or {}, 

645 }, 

646 "agents": agent_specs, 

647 } 

648 if scenario: 

649 strategy = scenario.strategy 

650 payload["scenario"] = { 

651 "id": str(scenario.id), 

652 "name": scenario.name, 

653 "description": scenario.description, 

654 "strategy": strategy.value if hasattr(strategy, "value") else str(strategy), 

655 "config": scenario.config or {}, 

656 "tags": scenario.tags or [], 

657 } 

658 if initial_prompt: 

659 payload["initial_prompt"] = initial_prompt 

660 

661 background_tasks.add_task( 

662 _execute_simulation_background, simulation_id, payload, limit 

663 ) 

664 

665 return simulation 

666 

667 

668register_history_routes( 

669 simulation_router, 

670 resource_type=HistoryEnum.ResourceType.simulation_world, 

671 model=SimulationWorld, 

672 not_found_detail="Simulation world not found", 

673 path_prefix="/worlds", 

674)