pipeline_runs.py 38 KB

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