pipeline_runs.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. """API routes for Slicer Pipeline runs (#1425 PR B + PR C).
  2. PR B implemented single-target dispatch: one Run-pipeline click =
  3. slice the source once → enqueue ONE print on ``target_printer_id``.
  4. PR C extends this with:
  5. * ``copies > 1`` — slice once, enqueue N copies.
  6. * ``target_kind='printer_class'`` — pipeline targets a Bambu model code
  7. (X1C / P1S / H2D / …); orchestrator distributes copies across matching
  8. printers using the pipeline's ``fanout_strategy``.
  9. * Retry-failed runs that re-attempt only the failed/cancelled copies of
  10. a partial-failure run.
  11. * Dashboard list endpoint (``GET /pipeline-runs``) with status + pipeline
  12. filters and pagination.
  13. * WebSocket ``pipeline_run_updated`` events on state transitions so the
  14. dashboard refreshes live without polling.
  15. The slice itself runs through ``slice_dispatch`` (same path as the manual
  16. SliceModal), so the ``Slicing X — Generating G-code 75%`` toast renders
  17. end-to-end. The slice job's id rides on the run response so the frontend
  18. can call ``trackJob`` directly.
  19. """
  20. from __future__ import annotations
  21. import json
  22. import logging
  23. from datetime import datetime, timezone
  24. from pathlib import Path
  25. from typing import Literal
  26. from fastapi import APIRouter, Depends, HTTPException
  27. from sqlalchemy import delete, desc, func, select
  28. from sqlalchemy.ext.asyncio import AsyncSession
  29. from backend.app.api.routes.cloud import resolve_api_key_cloud_owner
  30. from backend.app.core.auth import (
  31. ApiKeyActor,
  32. QueueReviewRequired,
  33. RequestActor,
  34. RequestPrinterScope,
  35. RequirePermissionIfAuthEnabled,
  36. is_auth_enabled,
  37. )
  38. from backend.app.core.config import settings as app_settings
  39. from backend.app.core.database import async_session, get_db
  40. from backend.app.core.permissions import Permission
  41. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, ensure_model_target_allowed
  42. from backend.app.core.websocket import ws_manager
  43. from backend.app.models.archive import PrintArchive
  44. from backend.app.models.library import LibraryFile
  45. from backend.app.models.pipeline_run import PipelineJob, PipelineRun
  46. from backend.app.models.print_queue import PrintQueueItem
  47. from backend.app.models.printer import Printer
  48. from backend.app.models.slicer_pipeline import SlicerPipeline
  49. from backend.app.models.user import User
  50. from backend.app.schemas.pipeline_run import (
  51. CheckEligibilityRequest,
  52. EligibilityIssueResponse,
  53. EligibilityReportResponse,
  54. PerPrinterReport as PerPrinterReportResponse,
  55. PipelineJobResponse,
  56. PipelineRunCreateRequest,
  57. PipelineRunListResponse,
  58. PipelineRunResponse,
  59. )
  60. from backend.app.schemas.slicer import PresetRef, SliceRequest
  61. from backend.app.services.pipeline_eligibility import (
  62. EligibilityReport,
  63. check_pipeline_eligibility,
  64. )
  65. from backend.app.services.print_confirmation import confirm_outcome_for_new_queue_item
  66. from backend.app.services.print_defaults import default_print_options
  67. from backend.app.services.queue_announcements import announce_queue_jobs_added
  68. logger = logging.getLogger(__name__)
  69. pipeline_run_create_router = APIRouter(prefix="/slicer-pipelines", tags=["Slicer Pipelines"])
  70. pipeline_run_router = APIRouter(prefix="/pipeline-runs", tags=["Slicer Pipelines"])
  71. # ---------------------------------------------------------------------------
  72. # Helpers
  73. # ---------------------------------------------------------------------------
  74. def _serialise_status(report: EligibilityReport) -> EligibilityReportResponse:
  75. return EligibilityReportResponse(
  76. ok=report.ok,
  77. target_kind=report.target_kind,
  78. target_printer_id=report.target_printer_id,
  79. target_printer_name=report.target_printer_name,
  80. target_model_class=report.target_model_class,
  81. issues=[
  82. EligibilityIssueResponse(
  83. kind=issue.kind,
  84. slot_index=issue.slot_index,
  85. expected=issue.expected,
  86. actual=issue.actual,
  87. )
  88. for issue in report.issues
  89. ],
  90. printer_reports=[
  91. PerPrinterReportResponse(
  92. printer_id=r.printer_id,
  93. printer_name=r.printer_name,
  94. ok=r.ok,
  95. issues=[
  96. EligibilityIssueResponse(
  97. kind=i.kind,
  98. slot_index=i.slot_index,
  99. expected=i.expected,
  100. actual=i.actual,
  101. )
  102. for i in r.issues
  103. ],
  104. )
  105. for r in report.printer_reports
  106. ],
  107. )
  108. async def _load_pipeline(db: AsyncSession, pipeline_id: int) -> SlicerPipeline:
  109. pipeline = (
  110. await db.execute(
  111. select(SlicerPipeline).where(
  112. SlicerPipeline.id == pipeline_id,
  113. SlicerPipeline.is_deleted.is_(False),
  114. )
  115. )
  116. ).scalar_one_or_none()
  117. if pipeline is None:
  118. raise HTTPException(404, "Pipeline not found")
  119. return pipeline
  120. async def _load_printer_status(printer_id: int | None) -> dict | None:
  121. """Snapshot the printer_manager's live PrinterState for the eligibility
  122. matcher. Returns ``None`` when the printer has no MQTT client."""
  123. if printer_id is None:
  124. return None
  125. from backend.app.services.printer_manager import printer_manager
  126. state = printer_manager.get_status(printer_id)
  127. if state is None:
  128. return None
  129. return {"connected": state.connected, "raw_data": state.raw_data}
  130. def _make_status_lookup():
  131. """Closure that snapshots the printer_manager once per printer_id call.
  132. Passed to the matcher's class-targeting branch so it can read live state
  133. for every candidate printer."""
  134. def _lookup(printer_id: int) -> dict | None:
  135. from backend.app.services.printer_manager import printer_manager
  136. state = printer_manager.get_status(printer_id)
  137. if state is None:
  138. return None
  139. return {"connected": state.connected, "raw_data": state.raw_data}
  140. return _lookup
  141. def _slice_request_from_pipeline(pipeline: SlicerPipeline) -> SliceRequest:
  142. try:
  143. raw_filaments = json.loads(pipeline.filament_presets_json or "[]")
  144. except (json.JSONDecodeError, TypeError):
  145. raw_filaments = []
  146. filament_presets = [
  147. PresetRef(source=r["source"], id=r["id"])
  148. for r in raw_filaments
  149. if isinstance(r, dict) and "source" in r and "id" in r
  150. ]
  151. return SliceRequest(
  152. printer_preset=PresetRef(source=pipeline.printer_preset_source, id=pipeline.printer_preset_id),
  153. process_preset=PresetRef(source=pipeline.process_preset_source, id=pipeline.process_preset_id),
  154. filament_presets=filament_presets,
  155. bed_type=pipeline.bed_type,
  156. export_3mf=True,
  157. )
  158. def _compute_job_status(
  159. persisted: str,
  160. queue_entry: PrintQueueItem | None,
  161. ) -> str:
  162. if persisted in ("failed", "cancelled", "completed"):
  163. return persisted
  164. if queue_entry is None:
  165. # Dispatched, but its queue entry is gone without a final status stored
  166. # (deleted before jobs stored it, or removed by the database itself):
  167. # printed or not cannot be told, so neither failed nor cancelled.
  168. return "unknown" if persisted in ("queued", "printing") else persisted
  169. qs = queue_entry.status
  170. if qs == "completed":
  171. return "completed"
  172. if qs in ("failed", "aborted"):
  173. return "failed"
  174. if qs == "cancelled":
  175. return "cancelled"
  176. if qs == "printing":
  177. return "printing"
  178. return "queued"
  179. def _roll_up_run_status(
  180. persisted: str,
  181. job_statuses: list[str],
  182. ) -> str:
  183. """Compute the run-level status from the per-job statuses.
  184. Terminal-persisted always wins for explicit cancels / hard failures so
  185. the dashboard doesn't flicker when one job's queue entry hasn't caught
  186. up. Otherwise:
  187. - all completed → completed
  188. - any in_progress / printing / queued / dispatching → in_progress
  189. - any failed alongside any completed → partial_failure
  190. - all failed/cancelled → failed
  191. """
  192. if persisted in ("cancelled",):
  193. return persisted
  194. if not job_statuses:
  195. return persisted
  196. completed = sum(1 for s in job_statuses if s == "completed")
  197. # A copy whose outcome is unknown ended without failing anything to retry.
  198. unknown = sum(1 for s in job_statuses if s == "unknown")
  199. failed = sum(1 for s in job_statuses if s == "failed")
  200. cancelled = sum(1 for s in job_statuses if s == "cancelled")
  201. in_flight = sum(1 for s in job_statuses if s in ("printing", "queued", "awaiting_printer", "pending"))
  202. total = len(job_statuses)
  203. if completed + unknown == total:
  204. return "completed"
  205. if in_flight > 0:
  206. return "in_progress" if persisted not in ("queued", "slicing", "dispatching") else persisted
  207. # All copies are in terminal states.
  208. if failed == 0 and cancelled == total:
  209. return "cancelled"
  210. if completed + unknown > 0 and (failed > 0 or cancelled > 0):
  211. return "partial_failure"
  212. if failed > 0:
  213. return "failed"
  214. return persisted
  215. async def _materialise_run(db: AsyncSession, run: PipelineRun) -> PipelineRunResponse:
  216. pipeline_name: str | None = None
  217. target_kind = None
  218. target_printer_id = None
  219. target_model_class = None
  220. fanout_strategy = None
  221. if run.pipeline_id:
  222. pipeline = (
  223. await db.execute(select(SlicerPipeline).where(SlicerPipeline.id == run.pipeline_id))
  224. ).scalar_one_or_none()
  225. if pipeline:
  226. pipeline_name = pipeline.name
  227. target_kind = pipeline.target_kind # type: ignore[assignment]
  228. target_printer_id = pipeline.target_printer_id
  229. target_model_class = pipeline.target_model_class
  230. fanout_strategy = pipeline.fanout_strategy # type: ignore[assignment]
  231. source_filename: str | None = None
  232. if run.source_library_file_id:
  233. src = (
  234. await db.execute(select(LibraryFile).where(LibraryFile.id == run.source_library_file_id))
  235. ).scalar_one_or_none()
  236. source_filename = src.filename if src else None
  237. elif run.source_archive_id:
  238. arc = (
  239. await db.execute(select(PrintArchive).where(PrintArchive.id == run.source_archive_id))
  240. ).scalar_one_or_none()
  241. source_filename = (arc.print_name or arc.filename) if arc else None
  242. job_rows = (
  243. (
  244. await db.execute(
  245. select(PipelineJob).where(PipelineJob.pipeline_run_id == run.id).order_by(PipelineJob.copy_index)
  246. )
  247. )
  248. .scalars()
  249. .all()
  250. )
  251. job_responses: list[PipelineJobResponse] = []
  252. job_live_statuses: list[str] = []
  253. for job in job_rows:
  254. queue_entry = None
  255. if job.queue_entry_id:
  256. queue_entry = (
  257. await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == job.queue_entry_id))
  258. ).scalar_one_or_none()
  259. printer_name: str | None = None
  260. if job.assigned_printer_id:
  261. p = (await db.execute(select(Printer).where(Printer.id == job.assigned_printer_id))).scalar_one_or_none()
  262. printer_name = p.name if p else None
  263. live_job_status = _compute_job_status(job.status, queue_entry)
  264. job_live_statuses.append(live_job_status)
  265. job_responses.append(
  266. PipelineJobResponse(
  267. id=job.id,
  268. pipeline_run_id=job.pipeline_run_id,
  269. copy_index=job.copy_index,
  270. assigned_printer_id=job.assigned_printer_id,
  271. assigned_printer_name=printer_name,
  272. queue_entry_id=job.queue_entry_id,
  273. status=live_job_status, # type: ignore[arg-type]
  274. error_message=job.error_message,
  275. dispatched_at=job.dispatched_at,
  276. completed_at=job.completed_at,
  277. )
  278. )
  279. rolled_up = _roll_up_run_status(run.status, job_live_statuses)
  280. return PipelineRunResponse(
  281. id=run.id,
  282. pipeline_id=run.pipeline_id,
  283. pipeline_name=pipeline_name,
  284. source_library_file_id=run.source_library_file_id,
  285. source_archive_id=run.source_archive_id,
  286. source_filename=source_filename,
  287. parent_run_id=run.parent_run_id,
  288. copies=run.copies,
  289. copies_completed=sum(1 for s in job_live_statuses if s == "completed"),
  290. copies_failed=sum(1 for s in job_live_statuses if s == "failed"),
  291. copies_cancelled=sum(1 for s in job_live_statuses if s == "cancelled"),
  292. copies_in_progress=sum(
  293. 1 for s in job_live_statuses if s in ("printing", "queued", "awaiting_printer", "pending")
  294. ),
  295. status=rolled_up, # type: ignore[arg-type]
  296. slice_job_id=run.slice_job_id,
  297. sliced_library_file_id=run.sliced_library_file_id,
  298. eligibility_overridden=run.eligibility_overridden,
  299. error_message=run.error_message,
  300. created_by=run.created_by,
  301. created_at=run.created_at,
  302. started_at=run.started_at,
  303. completed_at=run.completed_at,
  304. jobs=job_responses,
  305. target_kind=target_kind,
  306. target_printer_id=target_printer_id,
  307. target_model_class=target_model_class,
  308. fanout_strategy=fanout_strategy,
  309. )
  310. async def _publish_run_event(db: AsyncSession, run: PipelineRun) -> None:
  311. """Broadcast a ``pipeline_run_updated`` event with the full materialised
  312. run. Per-user routing via ``broadcast_to_user`` falls back to a global
  313. broadcast when ``created_by`` is None on auth-disabled installs."""
  314. try:
  315. # Without a user, broadcast_to_user would send it to everyone. With auth
  316. # on, a run whose user was deleted is nobody's to watch (the runs page polls).
  317. if run.created_by is None and await is_auth_enabled(db):
  318. return
  319. payload = await _materialise_run(db, run)
  320. await ws_manager.broadcast_to_user(
  321. run.created_by,
  322. {
  323. "type": "pipeline_run_updated",
  324. "run": payload.model_dump(mode="json"),
  325. },
  326. )
  327. except Exception:
  328. logger.exception("Failed to broadcast pipeline_run_updated for run %d", run.id)
  329. # ---------------------------------------------------------------------------
  330. # Source resolution + orchestration
  331. # ---------------------------------------------------------------------------
  332. SourceKind = Literal["library_file", "archive"]
  333. async def _resolve_source(
  334. db: AsyncSession,
  335. *,
  336. library_file_id: int | None,
  337. archive_id: int | None,
  338. user: User | ApiKeyActor | None,
  339. printer_scope: PrinterScope,
  340. ) -> tuple[SourceKind, int, str, Path]:
  341. # Per-row ownership gate (IDOR fix): a caller may only run a pipeline on a
  342. # source they can see. Without this a READ_OWN caller could reference
  343. # another user's library file / archive by raw id and have it sliced (and,
  344. # via /run, printed) even though a direct GET on that id returned 404.
  345. # Only auth off (user is None) keeps can_read_all=True. An API key arrives
  346. # as its owner's RequestActor, matching the library/archive read helpers.
  347. from backend.app.api.routes.archives import _ensure_archive_visible
  348. from backend.app.api.routes.library import _ensure_library_file_visible
  349. if library_file_id is not None:
  350. lib = (await db.execute(select(LibraryFile).where(LibraryFile.id == library_file_id))).scalar_one_or_none()
  351. can_read_all = user is None or user.has_permission(Permission.LIBRARY_READ_ALL.value)
  352. lib = _ensure_library_file_visible(lib, user, can_read_all)
  353. src_path = (
  354. Path(app_settings.base_dir) / lib.file_path
  355. ) # SEC-PATH-OK: lib.file_path is a LibraryFile DB column set only by the upload route, which writes a UUID-named file under base_dir/library_files/.
  356. if not src_path.exists():
  357. raise HTTPException(404, "Source library file missing on disk")
  358. return ("library_file", lib.id, lib.filename, src_path)
  359. assert archive_id is not None
  360. arc = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  361. can_read_all = user is None or user.has_permission(Permission.ARCHIVES_READ_ALL.value)
  362. arc = _ensure_archive_visible(arc, user, can_read_all, printer_scope)
  363. # Running a pipeline on an archive prints it again: the same rules as
  364. # queueing it, including the right to reprint it.
  365. from backend.app.api.routes.print_queue import _assert_can_queue_archive
  366. _assert_can_queue_archive(arc, user, printer_scope)
  367. rel = arc.source_3mf_path or arc.file_path
  368. if not rel:
  369. raise HTTPException(400, "Archive has no source file to slice")
  370. src_path = (
  371. Path(app_settings.base_dir) / rel
  372. ) # SEC-PATH-OK: rel is archive.source_3mf_path / archive.file_path, both set by upload-time validators that already do resolve+relative_to containment.
  373. if not src_path.exists():
  374. raise HTTPException(404, "Archive source file missing on disk")
  375. name = arc.filename or arc.print_name or src_path.name
  376. return ("archive", arc.id, name, src_path)
  377. async def _pick_assignments(
  378. db: AsyncSession,
  379. pipeline: SlicerPipeline,
  380. copies: int,
  381. printer_scope: PrinterScope = ALL_PRINTERS,
  382. ) -> list[tuple[int | None, str | None]]:
  383. """Return ``[(printer_id_or_None, target_model_or_None), ...]`` of length
  384. ``copies`` per the pipeline's fanout strategy. ``target_model_class``
  385. items leave ``printer_id`` None so the scheduler picks any free matching
  386. printer; specific assignments fill ``printer_id``. Class targeting only
  387. pins copies to printers in the runner's ``printer_scope`` (#1727)."""
  388. target_kind = pipeline.target_kind or "specific_printer"
  389. if target_kind == "specific_printer" or pipeline.target_printer_id is not None:
  390. assert pipeline.target_printer_id is not None
  391. return [(pipeline.target_printer_id, None)] * copies
  392. # Class-targeting. Enumerate matching printers + apply the strategy.
  393. matching = (
  394. (
  395. await db.execute(
  396. select(Printer)
  397. .where(func.lower(Printer.model) == (pipeline.target_model_class or "").lower())
  398. .where(Printer.is_active.is_(True))
  399. .order_by(Printer.id)
  400. )
  401. )
  402. .scalars()
  403. .all()
  404. )
  405. matching = [p for p in matching if printer_scope.allows(p.id)]
  406. if not matching:
  407. # Shouldn't reach here when eligibility passes, but failing gracefully
  408. # is better than a TypeError on next-slot pick.
  409. return [(None, pipeline.target_model_class)] * copies
  410. strategy = pipeline.fanout_strategy or "max_parallel"
  411. if strategy == "fill_one_first":
  412. # Pin every copy to the first match. Scheduler dispatches them serially
  413. # to that printer. If the printer breaks, copies wait; that's the
  414. # documented trade-off.
  415. return [(matching[0].id, None)] * copies
  416. if strategy == "round_robin":
  417. # Cycle through eligible printers — copy ``i`` lands on
  418. # ``matching[i % len(matching)]``. Each item gets a fixed printer_id.
  419. return [(matching[i % len(matching)].id, None) for i in range(copies)]
  420. # max_parallel — leave printer_id=None, set target_model so the scheduler
  421. # picks any free X1C / P1S / … for each item independently. In the
  422. # printers' own spelling: the class is matched without regard to case.
  423. return [(None, matching[0].model)] * copies
  424. def _make_orchestration_callable(
  425. *,
  426. run_id: int,
  427. pipeline_id: int,
  428. src_kind: SourceKind,
  429. src_id: int,
  430. src_filename: str,
  431. src_path: Path,
  432. creator_user_id: int | None,
  433. copies: int,
  434. printer_scope: PrinterScope = ALL_PRINTERS,
  435. review_required: bool = False,
  436. ):
  437. """Returns the async callable that ``slice_dispatch.enqueue`` runs as the
  438. background slice job. Wraps slice + multi-copy enqueue + state update."""
  439. async def _orchestrate(slice_job_id: int) -> dict:
  440. from backend.app.api.routes.library import slice_and_persist
  441. async with async_session() as session:
  442. run = (await session.execute(select(PipelineRun).where(PipelineRun.id == run_id))).scalar_one_or_none()
  443. pipeline = (
  444. await session.execute(select(SlicerPipeline).where(SlicerPipeline.id == pipeline_id))
  445. ).scalar_one_or_none()
  446. if run is None or pipeline is None:
  447. logger.warning("pipeline_run %d or pipeline %d disappeared mid-orchestration", run_id, pipeline_id)
  448. return {}
  449. # Honour a cancel that landed between ``POST /run`` returning and
  450. # this background task starting. If the run was cancelled while
  451. # still in ``queued`` we must NOT flip it back to ``slicing`` —
  452. # the operator's intent was to stop, and overwriting status here
  453. # was the bug that left runs stuck at ``dispatching`` after a
  454. # user-side cancel (#1425 PR C bug report).
  455. if run.status == "cancelled":
  456. logger.info("pipeline_run %d was cancelled before slicing started", run_id)
  457. return {}
  458. run.status = "slicing"
  459. run.started_at = datetime.now(timezone.utc)
  460. await session.commit()
  461. await _publish_run_event(session, run)
  462. slice_request = _slice_request_from_pipeline(pipeline)
  463. model_bytes = src_path.read_bytes()
  464. folder_id: int | None = None
  465. if src_kind == "library_file":
  466. lib = (await session.execute(select(LibraryFile).where(LibraryFile.id == src_id))).scalar_one_or_none()
  467. if lib is not None:
  468. folder_id = lib.folder_id
  469. try:
  470. slice_response = await slice_and_persist(
  471. session,
  472. model_bytes=model_bytes,
  473. model_filename=src_filename,
  474. folder_id=folder_id,
  475. extra_metadata={
  476. f"sliced_from_{src_kind}_id": src_id,
  477. "sliced_via_pipeline_id": pipeline.id,
  478. "sliced_via_pipeline_run_id": run.id,
  479. },
  480. request=slice_request,
  481. current_user_id=creator_user_id,
  482. job_id=slice_job_id,
  483. )
  484. except HTTPException as exc:
  485. run.status = "failed"
  486. run.error_message = f"Slice failed: {exc.detail}"
  487. run.completed_at = datetime.now(timezone.utc)
  488. await session.commit()
  489. await _publish_run_event(session, run)
  490. raise
  491. except Exception as exc:
  492. logger.exception("Pipeline run %d slice raised unexpectedly", run_id)
  493. run.status = "failed"
  494. run.error_message = f"Slice failed: {exc}"
  495. run.completed_at = datetime.now(timezone.utc)
  496. await session.commit()
  497. await _publish_run_event(session, run)
  498. raise
  499. run.sliced_library_file_id = slice_response.library_file_id
  500. # Re-check cancellation: the slice can take minutes, and the
  501. # operator may have hit Cancel during that window. Refresh from
  502. # the DB rather than trusting our in-memory `run` (the cancel
  503. # route writes via a separate session). When cancelled, don't
  504. # enqueue print queue items — that's the whole point of cancel.
  505. await session.refresh(run)
  506. if run.status == "cancelled":
  507. logger.info("pipeline_run %d cancelled mid-slice; skipping queue enqueue", run_id)
  508. await session.commit()
  509. return slice_response.model_dump()
  510. # PR C: enqueue N copies per the picked assignment strategy.
  511. assignments = await _pick_assignments(session, pipeline, copies, printer_scope)
  512. jobs = (
  513. (
  514. await session.execute(
  515. select(PipelineJob)
  516. .where(PipelineJob.pipeline_run_id == run_id)
  517. .order_by(PipelineJob.copy_index)
  518. )
  519. )
  520. .scalars()
  521. .all()
  522. )
  523. if len(jobs) != copies:
  524. logger.warning("pipeline_run %d expected %d jobs, found %d", run_id, copies, len(jobs))
  525. # No per-job ask-for-outcome toggle on a pipeline run either (#1898).
  526. confirm_outcome = await confirm_outcome_for_new_queue_item(session)
  527. # Nor print options: the install's defaults.
  528. print_options = await default_print_options(session)
  529. for job, (printer_id, target_model) in zip(jobs, assignments, strict=False):
  530. queue_item = PrintQueueItem(
  531. printer_id=printer_id,
  532. target_model=target_model,
  533. library_file_id=slice_response.library_file_id,
  534. # From the run as refreshed after the slice, not the id the
  535. # request started with: a user deleted meanwhile is gone
  536. # from it, and SQLite may have given the id to someone else.
  537. created_by_id=run.created_by,
  538. status="pending",
  539. confirm_outcome=confirm_outcome,
  540. # The copies wait for review like any other job of theirs (#1620)
  541. # A restricted user deleted while it sliced: as delete_user
  542. # stages their ownerless "any model" jobs, or these would run
  543. # on every printer of the model, not only on theirs (#1727).
  544. manual_start=review_required
  545. or (
  546. run.created_by is None
  547. and creator_user_id is not None
  548. and printer_id is None
  549. and not printer_scope.is_unrestricted
  550. ),
  551. **print_options,
  552. )
  553. session.add(queue_item)
  554. await session.flush()
  555. job.queue_entry_id = queue_item.id
  556. job.assigned_printer_id = printer_id # may be None for max_parallel
  557. # Don't write job.status yet — final cancellation check below
  558. # may flip it to 'cancelled' instead. dispatched_at is fine to
  559. # set unconditionally since the orchestration actually got here.
  560. job.dispatched_at = datetime.now(timezone.utc)
  561. # Final cancellation check before committing 'dispatching'. The
  562. # cancel route writes via a separate session so we have to refresh
  563. # to see the latest. If the cancel landed in this narrow window —
  564. # AFTER the post-slice refresh but BEFORE this commit — the queue
  565. # entries we just created would otherwise pick up and print. Mark
  566. # them + the per-copy jobs cancelled so the user's intent sticks.
  567. await session.refresh(run)
  568. if run.status == "cancelled":
  569. logger.info(
  570. "pipeline_run %d cancelled in the dispatch window; cancelling its %d queue entries",
  571. run_id,
  572. len(jobs),
  573. )
  574. for job in jobs:
  575. if job.queue_entry_id:
  576. qe = (
  577. await session.execute(select(PrintQueueItem).where(PrintQueueItem.id == job.queue_entry_id))
  578. ).scalar_one_or_none()
  579. if qe is not None and qe.status in ("pending", "queued"):
  580. qe.status = "cancelled"
  581. qe.completed_at = datetime.now(timezone.utc)
  582. if job.status not in ("completed", "failed", "cancelled"):
  583. job.status = "cancelled"
  584. job.completed_at = datetime.now(timezone.utc)
  585. await session.commit()
  586. await _publish_run_event(session, run)
  587. return slice_response.model_dump()
  588. for job in jobs:
  589. job.status = "queued"
  590. run.status = "dispatching"
  591. await session.commit()
  592. await announce_queue_jobs_added(session, [job.queue_entry_id for job in jobs if job.queue_entry_id])
  593. await _publish_run_event(session, run)
  594. return slice_response.model_dump()
  595. return _orchestrate
  596. # ---------------------------------------------------------------------------
  597. # /slicer-pipelines/{id}/check-eligibility
  598. # ---------------------------------------------------------------------------
  599. @pipeline_run_create_router.post("/{pipeline_id}/check-eligibility", response_model=EligibilityReportResponse)
  600. async def check_eligibility(
  601. pipeline_id: int,
  602. body: CheckEligibilityRequest,
  603. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_READ),
  604. printer_scope: PrinterScope = RequestPrinterScope,
  605. db: AsyncSession = Depends(get_db),
  606. actor: User | ApiKeyActor | None = RequestActor,
  607. ):
  608. pipeline = await _load_pipeline(db, pipeline_id)
  609. printer_scope.ensure(pipeline.target_printer_id)
  610. await _resolve_source(
  611. db,
  612. library_file_id=body.source_library_file_id,
  613. archive_id=body.source_archive_id,
  614. user=actor,
  615. printer_scope=printer_scope,
  616. )
  617. if pipeline.target_kind == "printer_class" and pipeline.target_printer_id is None:
  618. report = await check_pipeline_eligibility(db, pipeline, status_lookup=_make_status_lookup())
  619. else:
  620. status = await _load_printer_status(pipeline.target_printer_id)
  621. report = await check_pipeline_eligibility(db, pipeline, status)
  622. return _serialise_status(report)
  623. # ---------------------------------------------------------------------------
  624. # /slicer-pipelines/{id}/run
  625. # ---------------------------------------------------------------------------
  626. @pipeline_run_create_router.post("/{pipeline_id}/run", response_model=PipelineRunResponse, status_code=202)
  627. async def run_pipeline(
  628. pipeline_id: int,
  629. body: PipelineRunCreateRequest,
  630. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_RUN),
  631. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  632. printer_scope: PrinterScope = RequestPrinterScope,
  633. review_required: bool = QueueReviewRequired,
  634. db: AsyncSession = Depends(get_db),
  635. actor: User | ApiKeyActor | None = RequestActor,
  636. ):
  637. from backend.app.api.routes.settings import get_setting
  638. from backend.app.services.slice_dispatch import slice_dispatch
  639. pipeline = await _load_pipeline(db, pipeline_id)
  640. # The pipeline is shared config; running it is limited to what the caller
  641. # may print on (#1727)
  642. printer_scope.ensure(pipeline.target_printer_id)
  643. # An API key is checked as its owner (RequestActor), like its owner's own
  644. # session; ``creator`` below is a separate question.
  645. src_kind, src_id, src_filename, src_path = await _resolve_source(
  646. db,
  647. library_file_id=body.source_library_file_id,
  648. archive_id=body.source_archive_id,
  649. user=actor,
  650. printer_scope=printer_scope,
  651. )
  652. # The permission gate answers an API-keyed request with current_user=None,
  653. # so a pipeline built on Bambu/Orca Cloud presets would have nobody whose
  654. # stored cloud token could resolve them. Fall back to the key's owner, the
  655. # same fallback POST /library/files/{id}/slice makes (#1182 follow-up).
  656. # Only keys with the cloud scope resolve to an owner here; everything else
  657. # stays None and slices against local presets exactly as before.
  658. creator = current_user or api_key_cloud_owner
  659. # Copies left to the scheduler run within their creator's printers. A
  660. # limited API key can't be held to its own printers that way -- its cloud
  661. # owner may see more -- and even a pinning strategy falls back to "any
  662. # printer of the class" when none of the class is in scope, so a limited
  663. # key may only run pipelines aimed at one printer (#1727).
  664. if pipeline.target_printer_id is None:
  665. ensure_model_target_allowed(current_user, printer_scope)
  666. # Cap copies against the configured ceiling.
  667. raw_cap = await get_setting(db, "pipeline_max_copies")
  668. try:
  669. cap = int(raw_cap) if raw_cap else 50
  670. except (TypeError, ValueError):
  671. cap = 50
  672. if body.copies > cap:
  673. raise HTTPException(
  674. 422,
  675. f"copies={body.copies} exceeds pipeline_max_copies setting ({cap})",
  676. )
  677. # Eligibility pre-flight.
  678. if pipeline.target_kind == "printer_class" and pipeline.target_printer_id is None:
  679. report = await check_pipeline_eligibility(db, pipeline, status_lookup=_make_status_lookup())
  680. else:
  681. status = await _load_printer_status(pipeline.target_printer_id)
  682. report = await check_pipeline_eligibility(db, pipeline, status)
  683. if not report.ok and not body.force:
  684. raise HTTPException(status_code=409, detail=_serialise_status(report).model_dump())
  685. # Need a target — specific or class — to dispatch.
  686. if pipeline.target_printer_id is None and not pipeline.target_model_class:
  687. raise HTTPException(
  688. 400,
  689. "Pipeline has no target. Open the pipeline in Settings → Workflow → Pipelines and choose a target printer or printer class.",
  690. )
  691. run = PipelineRun(
  692. pipeline_id=pipeline.id,
  693. source_library_file_id=src_id if src_kind == "library_file" else None,
  694. source_archive_id=src_id if src_kind == "archive" else None,
  695. copies=body.copies,
  696. status="queued",
  697. eligibility_overridden=(not report.ok and body.force),
  698. created_by=creator.id if creator else None,
  699. )
  700. db.add(run)
  701. await db.flush()
  702. # One PipelineJob per copy. PR B was copies=1, PR C generalises.
  703. for i in range(body.copies):
  704. db.add(
  705. PipelineJob(
  706. pipeline_run_id=run.id,
  707. copy_index=i,
  708. status="pending",
  709. )
  710. )
  711. await db.commit()
  712. await db.refresh(run)
  713. await _publish_run_event(db, run)
  714. orchestrate = _make_orchestration_callable(
  715. run_id=run.id,
  716. pipeline_id=pipeline.id,
  717. src_kind=src_kind,
  718. src_id=src_id,
  719. src_filename=src_filename,
  720. src_path=src_path,
  721. creator_user_id=creator.id if creator else None,
  722. copies=body.copies,
  723. printer_scope=printer_scope,
  724. review_required=review_required,
  725. )
  726. slice_job = await slice_dispatch.enqueue(
  727. kind="library_file" if src_kind == "library_file" else "archive",
  728. source_id=src_id,
  729. source_name=src_filename,
  730. owner_id=creator.id if creator else None,
  731. run=orchestrate,
  732. )
  733. run.slice_job_id = slice_job.id
  734. await db.commit()
  735. await db.refresh(run)
  736. return await _materialise_run(db, run)
  737. # ---------------------------------------------------------------------------
  738. # Lists, reads, cancel, retry-failed
  739. # ---------------------------------------------------------------------------
  740. def _run_scope_clause(printer_scope: PrinterScope):
  741. """Runs the caller may see (#1727): their pipeline targets no printer out of
  742. scope, and no copy was assigned to one. None when unrestricted."""
  743. if printer_scope.is_unrestricted:
  744. return None
  745. allowed = printer_scope.printer_ids
  746. hidden_by_job = select(PipelineJob.pipeline_run_id).where(
  747. PipelineJob.assigned_printer_id.is_not(None), PipelineJob.assigned_printer_id.not_in(allowed)
  748. )
  749. hidden_pipelines = select(SlicerPipeline.id).where(
  750. SlicerPipeline.target_printer_id.is_not(None), SlicerPipeline.target_printer_id.not_in(allowed)
  751. )
  752. return PipelineRun.id.not_in(hidden_by_job) & (
  753. PipelineRun.pipeline_id.is_(None) | PipelineRun.pipeline_id.not_in(hidden_pipelines)
  754. )
  755. async def _load_run_in_scope(db: AsyncSession, run_id: int, printer_scope: PrinterScope) -> PipelineRun:
  756. query = select(PipelineRun).where(PipelineRun.id == run_id)
  757. if (clause := _run_scope_clause(printer_scope)) is not None:
  758. query = query.where(clause)
  759. run = (await db.execute(query)).scalar_one_or_none()
  760. if run is None:
  761. raise HTTPException(404, "Pipeline run not found")
  762. return run
  763. @pipeline_run_create_router.get("/{pipeline_id}/runs", response_model=PipelineRunListResponse)
  764. async def list_runs_for_pipeline(
  765. pipeline_id: int,
  766. limit: int = 10,
  767. _: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_READ),
  768. db: AsyncSession = Depends(get_db),
  769. printer_scope: PrinterScope = RequestPrinterScope,
  770. ):
  771. limit = max(1, min(limit, 100))
  772. conditions = [PipelineRun.pipeline_id == pipeline_id]
  773. if (clause := _run_scope_clause(printer_scope)) is not None:
  774. conditions.append(clause)
  775. rows = (
  776. (await db.execute(select(PipelineRun).where(*conditions).order_by(PipelineRun.id.desc()).limit(limit)))
  777. .scalars()
  778. .all()
  779. )
  780. total = (await db.execute(select(func.count()).select_from(PipelineRun).where(*conditions))).scalar() or 0
  781. return PipelineRunListResponse(
  782. runs=[await _materialise_run(db, r) for r in rows],
  783. total=total,
  784. )
  785. @pipeline_run_router.get("", response_model=PipelineRunListResponse)
  786. async def list_all_runs(
  787. limit: int = 25,
  788. offset: int = 0,
  789. pipeline_id: int | None = None,
  790. status: str | None = None,
  791. target_printer_id: int | None = None,
  792. target_model_class: str | None = None,
  793. _: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_READ),
  794. db: AsyncSession = Depends(get_db),
  795. printer_scope: PrinterScope = RequestPrinterScope,
  796. ):
  797. """Dashboard list. Newest first; filters on pipeline_id + status +
  798. target_printer_id + target_model_class. The ``status`` filter matches
  799. the persisted snapshot, not the live roll-up — in-progress runs may
  800. appear under ``dispatching`` until the next state transition writes
  801. through. ``target_*`` filters JOIN to the pipeline so runs whose
  802. pipeline currently points at the printer / class are returned."""
  803. limit = max(1, min(limit, 100))
  804. offset = max(0, offset)
  805. stmt = select(PipelineRun)
  806. count_stmt = select(func.count()).select_from(PipelineRun)
  807. if (clause := _run_scope_clause(printer_scope)) is not None:
  808. stmt = stmt.where(clause)
  809. count_stmt = count_stmt.where(clause)
  810. if pipeline_id is not None:
  811. stmt = stmt.where(PipelineRun.pipeline_id == pipeline_id)
  812. count_stmt = count_stmt.where(PipelineRun.pipeline_id == pipeline_id)
  813. if status:
  814. stmt = stmt.where(PipelineRun.status == status)
  815. count_stmt = count_stmt.where(PipelineRun.status == status)
  816. if target_printer_id is not None or target_model_class is not None:
  817. stmt = stmt.join(SlicerPipeline, SlicerPipeline.id == PipelineRun.pipeline_id)
  818. count_stmt = count_stmt.join(SlicerPipeline, SlicerPipeline.id == PipelineRun.pipeline_id)
  819. if target_printer_id is not None:
  820. stmt = stmt.where(SlicerPipeline.target_printer_id == target_printer_id)
  821. count_stmt = count_stmt.where(SlicerPipeline.target_printer_id == target_printer_id)
  822. if target_model_class is not None:
  823. stmt = stmt.where(SlicerPipeline.target_model_class == target_model_class)
  824. count_stmt = count_stmt.where(SlicerPipeline.target_model_class == target_model_class)
  825. rows = (await db.execute(stmt.order_by(desc(PipelineRun.id)).offset(offset).limit(limit))).scalars().all()
  826. total = (await db.execute(count_stmt)).scalar() or 0
  827. return PipelineRunListResponse(
  828. runs=[await _materialise_run(db, r) for r in rows],
  829. total=total,
  830. )
  831. _TERMINAL_RUN_STATUSES = ("completed", "failed", "cancelled", "partial_failure")
  832. @pipeline_run_router.post("/clear")
  833. async def clear_terminal_runs(
  834. _: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_WRITE),
  835. db: AsyncSession = Depends(get_db),
  836. printer_scope: PrinterScope = RequestPrinterScope,
  837. ):
  838. """Delete every terminal pipeline run (completed / failed / cancelled /
  839. partial_failure). In-flight runs (queued / slicing / dispatching /
  840. in_progress) are preserved — clearing those mid-flight would lose the
  841. operator's intent. Cascades to PipelineJob via the ondelete='CASCADE'
  842. relationship; the linked PrintQueueItem rows stay (they have their own
  843. lifecycle on the queue page)."""
  844. # Count first so the response can report how many got cleared. Done
  845. # under the same session/transaction as the delete so the numbers can't
  846. # drift if another caller races in.
  847. # Runs on printers the caller can't see are left alone (#1727)
  848. conditions = [PipelineRun.status.in_(_TERMINAL_RUN_STATUSES)]
  849. if (clause := _run_scope_clause(printer_scope)) is not None:
  850. conditions.append(clause)
  851. count_stmt = select(func.count()).select_from(PipelineRun).where(*conditions)
  852. n = (await db.execute(count_stmt)).scalar() or 0
  853. if n > 0:
  854. await db.execute(delete(PipelineRun).where(*conditions))
  855. await db.commit()
  856. return {"deleted": n}
  857. @pipeline_run_router.get("/{run_id}", response_model=PipelineRunResponse)
  858. async def get_run(
  859. run_id: int,
  860. _: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_READ),
  861. db: AsyncSession = Depends(get_db),
  862. printer_scope: PrinterScope = RequestPrinterScope,
  863. ):
  864. run = await _load_run_in_scope(db, run_id, printer_scope)
  865. return await _materialise_run(db, run)
  866. @pipeline_run_router.post("/{run_id}/cancel", response_model=PipelineRunResponse)
  867. async def cancel_run(
  868. run_id: int,
  869. _: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_RUN),
  870. db: AsyncSession = Depends(get_db),
  871. printer_scope: PrinterScope = RequestPrinterScope,
  872. ):
  873. """Cancel a queued / in-flight run. Cascades to all non-terminal queue
  874. entries; in-flight prints continue on the printer (operator must Stop)."""
  875. run = await _load_run_in_scope(db, run_id, printer_scope)
  876. if run.status in ("completed", "failed", "cancelled", "partial_failure"):
  877. return await _materialise_run(db, run)
  878. run.status = "cancelled"
  879. run.completed_at = datetime.now(timezone.utc)
  880. if not run.error_message:
  881. run.error_message = "Cancelled by user"
  882. from backend.app.services.finance_budget import release_budget_reservation
  883. cancelled_entries: list[int] = []
  884. job_rows = (await db.execute(select(PipelineJob).where(PipelineJob.pipeline_run_id == run.id))).scalars().all()
  885. for job in job_rows:
  886. queue_entry = None
  887. if job.queue_entry_id:
  888. queue_entry = (
  889. await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == job.queue_entry_id))
  890. ).scalar_one_or_none()
  891. if queue_entry is not None and queue_entry.status in ("pending", "queued"):
  892. queue_entry.status = "cancelled"
  893. queue_entry.completed_at = datetime.now(timezone.utc)
  894. # As a cancel from the queue does: its budget hold is freed
  895. await release_budget_reservation(
  896. db, source_type="print_queue", source_id=queue_entry.id, status="released"
  897. )
  898. cancelled_entries.append(queue_entry.id)
  899. if job.status in ("queued", "printing") and queue_entry is None:
  900. # Dispatched, its entry gone: whether it printed is unknown, and
  901. # calling it cancelled would make retry print it again.
  902. continue
  903. if job.status not in ("completed", "failed", "cancelled"):
  904. job.status = "cancelled"
  905. job.completed_at = datetime.now(timezone.utc)
  906. await db.commit()
  907. if cancelled_entries:
  908. from backend.app.services.print_batch import refresh_batches_after
  909. from backend.app.services.print_scheduler import scheduler
  910. await refresh_batches_after(cancelled_entries)
  911. # A preheating entry's dispatch is parked in a sleep and cannot see the
  912. # status written above (#2727): told, it stops heating the printer.
  913. for entry_id in cancelled_entries:
  914. scheduler.notify_dispatch_cancelled(entry_id)
  915. await db.refresh(run)
  916. await _publish_run_event(db, run)
  917. return await _materialise_run(db, run)
  918. @pipeline_run_router.post("/{run_id}/retry-failed", response_model=PipelineRunResponse, status_code=202)
  919. async def retry_failed(
  920. run_id: int,
  921. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.PIPELINES_RUN),
  922. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  923. printer_scope: PrinterScope = RequestPrinterScope,
  924. review_required: bool = QueueReviewRequired,
  925. db: AsyncSession = Depends(get_db),
  926. actor: User | ApiKeyActor | None = RequestActor,
  927. ):
  928. """Create a new run with copies = (failed + cancelled count) from the
  929. parent. Same pipeline, same source. Eligibility re-checked at run time
  930. (it might pass this time — operator may have fixed the issue)."""
  931. parent = await _load_run_in_scope(db, run_id, printer_scope)
  932. if parent.pipeline_id is None:
  933. raise HTTPException(400, "Original pipeline was deleted; cannot retry")
  934. if parent.source_library_file_id is None and parent.source_archive_id is None:
  935. raise HTTPException(400, "Original source was deleted; cannot retry")
  936. # Count the parent's failed + cancelled jobs.
  937. parent_jobs = (
  938. (await db.execute(select(PipelineJob).where(PipelineJob.pipeline_run_id == parent.id))).scalars().all()
  939. )
  940. fail_count = 0
  941. for j in parent_jobs:
  942. queue_entry = None
  943. if j.queue_entry_id:
  944. queue_entry = (
  945. await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == j.queue_entry_id))
  946. ).scalar_one_or_none()
  947. live = _compute_job_status(j.status, queue_entry)
  948. if live in ("failed", "cancelled"):
  949. fail_count += 1
  950. if fail_count == 0:
  951. raise HTTPException(400, "No failed copies to retry")
  952. # Build the request payload the same way the user would have via /run.
  953. body = PipelineRunCreateRequest(
  954. source_library_file_id=parent.source_library_file_id,
  955. source_archive_id=parent.source_archive_id,
  956. copies=fail_count,
  957. force=True, # operator already accepted eligibility on the parent
  958. )
  959. # Reuse the run_pipeline route logic via a direct call — keeps the
  960. # orchestration single-sourced. The result inherits parent_run_id. Every
  961. # dependency it declares has to be forwarded explicitly: FastAPI resolves
  962. # those only for a routed request, so an omitted one would arrive as the
  963. # Depends() marker object itself rather than as None.
  964. new_run_response = await run_pipeline(
  965. parent.pipeline_id,
  966. body,
  967. current_user=current_user,
  968. api_key_cloud_owner=api_key_cloud_owner,
  969. actor=actor,
  970. printer_scope=printer_scope,
  971. review_required=review_required,
  972. db=db,
  973. )
  974. # Stamp parent_run_id on the freshly-created run.
  975. new_row = (await db.execute(select(PipelineRun).where(PipelineRun.id == new_run_response.id))).scalar_one_or_none()
  976. if new_row is not None:
  977. new_row.parent_run_id = parent.id
  978. await db.commit()
  979. await db.refresh(new_row)
  980. return await _materialise_run(db, new_row)
  981. return new_run_response