pipeline_runs.py 41 KB

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