pipeline_runs.py 45 KB

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