Coverage for app / router / app / scenario_runs / router.py: 96%
78 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Scenario runs (docs/guides/scenario-runs.md): a developer uploads a
2scenario file, svc-core runs it in the background on the real chat path
3(``app/services/scenarios``), and the export is downloaded for review.
5Gated twice: ``SCENARIO_RUNS_ENABLED`` (404 when off, as if the routes were
6not there) and the ``developer`` platform role (403). Every route acts on
7the caller's own runs only; another person's is 404.
8"""
10from __future__ import annotations
12import json
13from typing import Any, Optional
14from uuid import UUID
16from fastapi import APIRouter, Body, Depends, HTTPException, Response, status
17from pydantic import BaseModel
18from sqlalchemy.orm import Session
20from app.common.settings import get_settings
21from app.db.postgres.models import ScenarioRun, User
22from app.util.time import UTCDateTime
23from app.dependency.base import get_db
24from app.dependency.user.context import require_role
25from app.services.platform_roles import PlatformRole
26from app.services.scenarios import export, provision, runner, schema
27from app.util.http_headers import content_disposition
29#: How many of a person's runs the list shows, newest first.
30LIST_LIMIT = 20
33def require_enabled() -> None:
34 """404 unless this deployment switches scenario runs on."""
35 if not get_settings().SCENARIO_RUNS_ENABLED:
36 raise HTTPException(
37 status_code=status.HTTP_404_NOT_FOUND,
38 detail="Scenario runs are switched off on this deployment.",
39 )
42scenario_runs_router = APIRouter(
43 prefix="/scenario-runs",
44 tags=["App - Scenario runs"],
45 dependencies=[Depends(require_enabled)],
46)
48developer = require_role(PlatformRole.developer)
51class RunRead(BaseModel):
52 """A run as the page lists it; its export is downloaded apart."""
54 id: UUID
55 name: str
56 status: str
57 progress: dict[str, Any]
58 error: Optional[str] = None
59 project_id: Optional[UUID] = None
60 scenario_sha256: str
61 cancel_requested: bool
62 created_at: UTCDateTime
63 updated_at: UTCDateTime
64 finished_at: Optional[UTCDateTime] = None
65 #: ``export.summary`` once the run has finished.
66 summary: Optional[dict[str, Any]] = None
68 @classmethod
69 def of(cls, run: ScenarioRun) -> RunRead:
70 return cls(
71 id=run.id,
72 name=run.name,
73 status=run.status,
74 progress=run.progress or {},
75 error=run.error,
76 project_id=run.project_id,
77 scenario_sha256=run.scenario_sha256,
78 cancel_requested=bool(run.cancel_requested),
79 created_at=run.created_at,
80 updated_at=run.updated_at,
81 finished_at=run.finished_at,
82 summary=(run.results or {}).get("summary"),
83 )
86def _own_run(db: Session, run_id: UUID, user: User) -> ScenarioRun:
87 run = db.get(ScenarioRun, run_id)
88 if run is None or run.user_id != user.id:
89 raise HTTPException(
90 status_code=status.HTTP_404_NOT_FOUND, detail="Scenario run not found"
91 )
92 return runner.settle_stale(db, run)
95@scenario_runs_router.post(
96 "", response_model=RunRead, status_code=status.HTTP_202_ACCEPTED
97)
98def start_scenario_run(
99 scenario: dict[str, Any] = Body(..., embed=True),
100 db: Session = Depends(get_db),
101 current_user: User = Depends(developer),
102):
103 """Validate a scenario file and start running it. 422 names what is
104 wrong with the file; 409 while another of the caller's runs is going."""
105 try:
106 parsed, _ = schema.load(scenario)
107 except schema.ScenarioInvalid as exc:
108 raise HTTPException(
109 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
110 ) from exc
111 try:
112 run = runner.start(db, current_user, parsed)
113 except runner.RunInProgress as exc:
114 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
115 return RunRead.of(run)
118@scenario_runs_router.get("", response_model=list[RunRead])
119def list_scenario_runs(
120 db: Session = Depends(get_db),
121 current_user: User = Depends(developer),
122):
123 """The caller's newest runs, each with its progress and, once finished,
124 its summary."""
125 runs = (
126 db.query(ScenarioRun)
127 .filter(ScenarioRun.user_id == current_user.id)
128 .order_by(ScenarioRun.created_at.desc())
129 .limit(LIST_LIMIT)
130 .all()
131 )
132 return [RunRead.of(runner.settle_stale(db, run)) for run in runs]
135@scenario_runs_router.get("/{run_id}", response_model=RunRead)
136def get_scenario_run(
137 run_id: UUID,
138 db: Session = Depends(get_db),
139 current_user: User = Depends(developer),
140):
141 """One of the caller's runs, as the page polls it while it goes."""
142 return RunRead.of(_own_run(db, run_id, current_user))
145@scenario_runs_router.post("/{run_id}/cancel", response_model=RunRead)
146def cancel_scenario_run(
147 run_id: UUID,
148 db: Session = Depends(get_db),
149 current_user: User = Depends(developer),
150):
151 """Stop the turn running now and start no more; the run then reads
152 ``cancelled``, with what it did kept."""
153 return RunRead.of(runner.request_cancel(db, _own_run(db, run_id, current_user)))
156@scenario_runs_router.get(
157 "/{run_id}/export",
158 response_class=Response,
159 responses={200: {"content": {"application/json": {}}}},
160)
161def export_scenario_run(
162 run_id: UUID,
163 db: Session = Depends(get_db),
164 current_user: User = Depends(developer),
165):
166 """The run's export as a file, as far as it has got."""
167 run = _own_run(db, run_id, current_user)
168 document = run.results or {"schema": export.EXPORT_SCHEMA, "run": None}
169 return Response(
170 content=json.dumps(document, indent=2, ensure_ascii=False),
171 media_type="application/json",
172 headers={
173 "Content-Disposition": content_disposition(
174 export.filename(run.name, run.created_at)
175 ),
176 "Cache-Control": "private, no-store",
177 },
178 )
181@scenario_runs_router.delete("/{run_id}", status_code=status.HTTP_204_NO_CONTENT)
182def delete_scenario_run(
183 run_id: UUID,
184 db: Session = Depends(get_db),
185 current_user: User = Depends(developer),
186):
187 """Delete a finished run and its project (its agents, and what they
188 remembered). 409 while it runs: cancel it first."""
189 run = _own_run(db, run_id, current_user)
190 if run.status == runner.Status.running:
191 raise HTTPException(
192 status_code=status.HTTP_409_CONFLICT,
193 detail="The run is still going; cancel it first.",
194 )
195 project_id = run.project_id
196 db.delete(run)
197 db.flush()
198 provision.remove(db, project_id, current_user)
199 db.commit()