pipeline_runs.py 40 KB

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