print_batch.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. """Batch order planning: per-plate targets, progress, and staged dispatch (#342).
  2. A batch stores *intent* in :class:`PrintBatchPlate` rows — "this order wants 3
  3. of plate 2" — while its queue items record what was actually dispatched.
  4. Everything here derives one from the other.
  5. The distinction matters for exactly one reason, and it is the reason the
  6. feature exists: a failed or cancelled run does not count towards the target, so
  7. ``remaining`` goes back up and the order still says it owes a print. A design
  8. that only counted the items it created could not tell "the user cancelled this
  9. deliberately" apart from "this one burned and needs reprinting".
  10. Batches created before targets existed have no plate rows. They still report
  11. progress — the plate breakdown is derived from their queue items and every
  12. target simply equals the number of items dispatched, so ``remaining`` is zero
  13. and the dispatch endpoint has nothing to do. ``has_targets`` tells callers
  14. which kind of batch they are looking at.
  15. """
  16. import logging
  17. from dataclasses import dataclass, field
  18. from datetime import datetime, timezone
  19. from sqlalchemy import func, select, text
  20. from sqlalchemy.ext.asyncio import AsyncSession
  21. from sqlalchemy.orm import selectinload
  22. from backend.app.models.print_batch import PrintBatch, PrintBatchPlate
  23. from backend.app.models.print_log import PrintLogEntry
  24. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  25. logger = logging.getLogger(__name__)
  26. # Statuses that consume a unit of the target. "printing" counts because the
  27. # run is in flight — re-dispatching it would double-print. "failed",
  28. # "cancelled" and "skipped" deliberately do not.
  29. CONSUMING_STATUSES = ("pending", "printing", "completed")
  30. # Queue statuses the roll-up has a counter for. Anything else is ignored rather
  31. # than crashing the page — the queue's status vocabulary is allowed to grow
  32. # without this module having to be updated in lockstep.
  33. COUNTED_STATUSES = ("pending", "printing", "completed", "failed", "cancelled", "skipped")
  34. # Columns copied onto a clone when dispatching more of a plate. This is the
  35. # print *configuration* the user already chose and the API already validated —
  36. # copying the row is what keeps a second dispatch identical to the first
  37. # without re-serialising twenty fields through a template blob that would drift
  38. # from the model the first time someone adds a column.
  39. CLONED_SETTING_COLUMNS = (
  40. "printer_id",
  41. "target_model",
  42. "target_location",
  43. "required_filament_types",
  44. "archive_id",
  45. "library_file_id",
  46. "project_id",
  47. "batch_id",
  48. "ams_mapping",
  49. "filament_overrides",
  50. "plate_id",
  51. "print_time_seconds",
  52. "gcode_injection",
  53. "nozzle_mapping",
  54. "nozzle_rack_choice",
  55. "require_previous_success",
  56. "auto_off_after",
  57. "manual_start",
  58. "bed_levelling",
  59. "flow_cali",
  60. "vibration_cali",
  61. "layer_inspect",
  62. "timelapse",
  63. "use_ams",
  64. "nozzle_offset_cali",
  65. "confirm_outcome",
  66. "preheat_override",
  67. "preheat_chamber_target_override",
  68. "skip_filament_check",
  69. )
  70. CLONED_VARIANT_COLUMNS = (
  71. "position",
  72. "library_file_id",
  73. "target_model",
  74. "plate_id",
  75. "ams_mapping",
  76. "nozzle_mapping",
  77. "nozzle_rack_choice",
  78. "filament_overrides",
  79. "required_filament_types",
  80. "print_time_seconds",
  81. )
  82. class BatchDispatchError(Exception):
  83. """Raised when more runs are owed but nothing can be cloned to produce them."""
  84. @dataclass
  85. class PlateProgress:
  86. """Per-plate roll-up for one batch."""
  87. plate_id: int | None
  88. plate_name: str | None
  89. quantity_target: int
  90. sort_order: int = 0
  91. pending: int = 0
  92. printing: int = 0
  93. completed: int = 0
  94. failed: int = 0
  95. cancelled: int = 0
  96. skipped: int = 0
  97. # Actual material + energy cost of this plate's finished runs. None when no
  98. # run has produced a cost yet — reported as "unknown", never as zero.
  99. actual_cost: float | None = None
  100. filament_used_grams: float | None = None
  101. print_time_seconds: int = 0
  102. # Whether any queue item for this plate still exists, in any status.
  103. # Dispatch clones one to inherit the print configuration, so a plate with
  104. # none cannot be queued however many runs it still owes.
  105. has_source: bool = False
  106. @property
  107. def dispatched(self) -> int:
  108. return self.pending + self.printing + self.completed
  109. @property
  110. def remaining(self) -> int:
  111. return max(0, self.quantity_target - self.dispatched)
  112. @property
  113. def can_dispatch(self) -> bool:
  114. """True when this plate owes runs *and* something can produce them."""
  115. return self.remaining > 0 and self.has_source
  116. @property
  117. def cost_per_run(self) -> float | None:
  118. """Observed mean cost of this plate's completed runs, or None.
  119. Deliberately measured rather than estimated from the file: the file's
  120. estimate ignores what the run actually consumed, and a plate that has
  121. never completed has no honest number to show.
  122. """
  123. if self.completed <= 0 or self.actual_cost is None:
  124. return None
  125. return self.actual_cost / self.completed
  126. @property
  127. def estimated_remaining_cost(self) -> float | None:
  128. per_run = self.cost_per_run
  129. if per_run is None:
  130. return None
  131. return per_run * self.remaining
  132. @dataclass
  133. class BatchProgress:
  134. """Whole-order roll-up, plus the per-plate breakdown it was derived from."""
  135. plates: list[PlateProgress] = field(default_factory=list)
  136. has_targets: bool = False
  137. def _sum(self, attr: str) -> int:
  138. return sum(getattr(p, attr) for p in self.plates)
  139. @property
  140. def pending(self) -> int:
  141. return self._sum("pending")
  142. @property
  143. def printing(self) -> int:
  144. return self._sum("printing")
  145. @property
  146. def completed(self) -> int:
  147. return self._sum("completed")
  148. @property
  149. def failed(self) -> int:
  150. return self._sum("failed")
  151. @property
  152. def cancelled(self) -> int:
  153. return self._sum("cancelled")
  154. @property
  155. def skipped(self) -> int:
  156. return self._sum("skipped")
  157. @property
  158. def target(self) -> int:
  159. return self._sum("quantity_target")
  160. @property
  161. def remaining(self) -> int:
  162. return self._sum("remaining")
  163. @property
  164. def dispatchable_remaining(self) -> int:
  165. """Of the runs still owed, how many can actually be queued.
  166. Lower than ``remaining`` when a plate's last queue item was deleted:
  167. the order still owes the run, but nothing survives to clone its
  168. printer target, AMS mapping and print options from.
  169. """
  170. return sum(p.remaining for p in self.plates if p.has_source)
  171. @property
  172. def actual_cost(self) -> float | None:
  173. costs = [p.actual_cost for p in self.plates if p.actual_cost is not None]
  174. return sum(costs) if costs else None
  175. @property
  176. def estimated_remaining_cost(self) -> float | None:
  177. estimates = [p.estimated_remaining_cost for p in self.plates if p.estimated_remaining_cost is not None]
  178. return sum(estimates) if estimates else None
  179. @property
  180. def filament_used_grams(self) -> float | None:
  181. grams = [p.filament_used_grams for p in self.plates if p.filament_used_grams is not None]
  182. return sum(grams) if grams else None
  183. @property
  184. def print_time_seconds(self) -> int:
  185. return self._sum("print_time_seconds")
  186. @property
  187. def is_fulfilled(self) -> bool:
  188. """True when every target is met and nothing is still in flight.
  189. A zero total target is never "fulfilled". Without that guard a legacy
  190. batch whose items were all cancelled one by one would report itself
  191. completed — its derived target counts only pending/printing/completed
  192. items, so cancelling the lot leaves a target of zero that trivially
  193. satisfies ``remaining == 0``.
  194. """
  195. return self.target > 0 and self.remaining == 0 and self.pending == 0 and self.printing == 0
  196. async def load_progress(db: AsyncSession, batch: PrintBatch) -> BatchProgress:
  197. """Build the per-plate progress roll-up for *batch*.
  198. Two queries plus one for costs, regardless of how many plates the order
  199. has — this runs once per batch in the list endpoint.
  200. """
  201. plate_rows = (await db.execute(select(PrintBatchPlate).where(PrintBatchPlate.batch_id == batch.id))).scalars().all()
  202. # (plate_id, status) -> count, plus the time/weight actually recorded.
  203. item_rows = (
  204. await db.execute(
  205. select(
  206. PrintQueueItem.plate_id,
  207. PrintQueueItem.status,
  208. func.count(PrintQueueItem.id),
  209. func.sum(PrintQueueItem.print_time_seconds),
  210. )
  211. .where(PrintQueueItem.batch_id == batch.id)
  212. .group_by(PrintQueueItem.plate_id, PrintQueueItem.status)
  213. )
  214. ).all()
  215. # Per-run actuals, attributed through the queue item that produced them.
  216. # PrintLogEntry is the authoritative per-run record (#1378) and is already
  217. # scoped to the printed plate (#2614), so a multi-plate order gets each
  218. # plate's own cost rather than the whole file's.
  219. cost_rows = (
  220. await db.execute(
  221. select(
  222. PrintQueueItem.plate_id,
  223. func.sum(func.coalesce(PrintLogEntry.cost, 0.0) + func.coalesce(PrintLogEntry.energy_cost, 0.0)),
  224. func.sum(PrintLogEntry.filament_used_grams),
  225. )
  226. .select_from(PrintLogEntry)
  227. .join(PrintQueueItem, PrintLogEntry.queue_item_id == PrintQueueItem.id)
  228. .where(PrintQueueItem.batch_id == batch.id)
  229. .group_by(PrintQueueItem.plate_id)
  230. )
  231. ).all()
  232. costs = {row[0]: (row[1], row[2]) for row in cost_rows}
  233. progress = BatchProgress(has_targets=bool(plate_rows))
  234. by_plate: dict[int | None, PlateProgress] = {}
  235. for row in plate_rows:
  236. by_plate[row.plate_id] = PlateProgress(
  237. plate_id=row.plate_id,
  238. plate_name=row.plate_name,
  239. quantity_target=row.quantity_target,
  240. sort_order=row.sort_order,
  241. )
  242. for plate_id, status, count, time_sum in item_rows:
  243. plate = by_plate.get(plate_id)
  244. if plate is None:
  245. # A queue item for a plate the order has no target row for: either
  246. # a legacy batch, or an item grouped in by hand after the fact.
  247. # Its own dispatched count becomes its target so it reads as
  248. # complete rather than as owing work nobody asked for.
  249. plate = PlateProgress(plate_id=plate_id, plate_name=None, quantity_target=0, sort_order=plate_id or 0)
  250. by_plate[plate_id] = plate
  251. if status in CONSUMING_STATUSES:
  252. plate.quantity_target += count
  253. elif not progress.has_targets and status in CONSUMING_STATUSES:
  254. plate.quantity_target += count
  255. # Any surviving row is a clone source, whatever its status — a
  256. # cancelled or failed run still carries the configuration a re-queue
  257. # needs. Set before the status filter below so a status this module
  258. # has no counter for still marks the plate dispatchable.
  259. plate.has_source = True
  260. if status in COUNTED_STATUSES:
  261. setattr(plate, status, getattr(plate, status) + count)
  262. else:
  263. logger.debug("Batch %s: ignoring queue item status %r in progress roll-up", batch.id, status)
  264. plate.print_time_seconds += int(time_sum or 0)
  265. for plate_id, (cost_sum, gram_sum) in costs.items():
  266. plate = by_plate.get(plate_id)
  267. if plate is None:
  268. continue
  269. plate.actual_cost = float(cost_sum) if cost_sum else None
  270. plate.filament_used_grams = float(gram_sum) if gram_sum else None
  271. progress.plates = sorted(by_plate.values(), key=lambda p: (p.sort_order, p.plate_id or 0))
  272. return progress
  273. async def refresh_batch_status(db: AsyncSession, batch: PrintBatch) -> bool:
  274. """Flip an ``active`` batch to ``completed`` once its targets are met.
  275. Returns True when the status changed. A ``cancelled`` batch is never
  276. resurrected, and a ``completed`` batch drops back to ``active`` if its
  277. targets grow — raising a target on a finished order reopens it rather than
  278. leaving a "completed" order that still owes prints.
  279. """
  280. progress = await load_progress(db, batch)
  281. if batch.status == "cancelled":
  282. return False
  283. if batch.status == "active" and progress.is_fulfilled:
  284. batch.status = "completed"
  285. batch.completed_at = datetime.now(timezone.utc)
  286. logger.info("Batch %s fulfilled — marked completed", batch.id)
  287. return True
  288. # A grouping whose every item was cancelled one at a time is finished, but
  289. # nothing was produced, so "completed" would be a lie and `is_fulfilled`
  290. # rightly refuses it (its derived target is zero). Left alone it would sit
  291. # on "active" forever. Cancelled is what it is, and matches what the
  292. # batch-level Cancel action would have set had it been used.
  293. #
  294. # Deliberately not applied to orders: an order states its intent
  295. # independently of its runs, so cancelling every run still leaves it owing
  296. # work and offering to re-queue it. A grouping has no such statement — it
  297. # was only ever the sum of its items.
  298. if batch.status == "active" and not progress.has_targets and progress.completed == 0:
  299. settled = progress.pending == 0 and progress.printing == 0
  300. if settled and progress.cancelled > 0 and progress.failed == 0 and progress.skipped == 0:
  301. batch.status = "cancelled"
  302. logger.info("Batch %s had every item cancelled — marked cancelled", batch.id)
  303. return True
  304. if batch.status == "completed" and not progress.is_fulfilled:
  305. batch.status = "active"
  306. batch.completed_at = None
  307. logger.info("Batch %s reopened — targets no longer met", batch.id)
  308. return True
  309. return False
  310. async def backfill_batch_statuses(db: AsyncSession) -> int:
  311. """Close out ``active`` batches that finished before the status existed.
  312. ``completed`` only became reachable with #342. Every batch created since
  313. the feature shipped in April 2026 is therefore still marked ``active``,
  314. however long ago its last run finished — so without this pass the Batches
  315. tab opens on months of accumulated history.
  316. Runs on every startup rather than once behind a marker: it is cheap (only
  317. batches with nothing in flight are even considered), it is idempotent, and
  318. repeating it also closes out any order whose last run landed while the
  319. process was down.
  320. Returns the number of batches whose status changed.
  321. """
  322. candidates = (
  323. (
  324. await db.execute(
  325. select(PrintBatch)
  326. .where(PrintBatch.status == "active")
  327. # Anything still queued or printing is by definition unfinished,
  328. # and re-deriving its progress would change nothing.
  329. .where(
  330. ~select(PrintQueueItem.id)
  331. .where(PrintQueueItem.batch_id == PrintBatch.id)
  332. .where(PrintQueueItem.status.in_(("pending", "printing")))
  333. .exists()
  334. )
  335. )
  336. )
  337. .scalars()
  338. .all()
  339. )
  340. changed = 0
  341. for batch in candidates:
  342. if await refresh_batch_status(db, batch):
  343. changed += 1
  344. if changed:
  345. await db.commit()
  346. logger.info("Marked %d finished batch(es) as completed at startup (#342)", changed)
  347. return changed
  348. async def refresh_batch_status_for_item(db: AsyncSession, queue_item_id: int) -> None:
  349. """Re-evaluate the batch owning *queue_item_id*, if it has one.
  350. Called from the print-completion path so a finished order reports itself
  351. complete the moment its last run lands, rather than whenever someone next
  352. opens the page.
  353. """
  354. batch_id = (
  355. await db.execute(select(PrintQueueItem.batch_id).where(PrintQueueItem.id == queue_item_id))
  356. ).scalar_one_or_none()
  357. if batch_id is None:
  358. return
  359. batch = (await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))).scalar_one_or_none()
  360. if batch is None:
  361. return
  362. await refresh_batch_status(db, batch)
  363. async def _next_position(db: AsyncSession, printer_id: int | None) -> int:
  364. """Next free queue position in the scope a clone will land in.
  365. Positions are per-queue, not global: one sequence per printer plus one
  366. shared sequence for unassigned / model-based items, matching the scope the
  367. add-to-queue route uses. Taking a global MAX here would drop every clone
  368. at the end of whichever printer's queue happens to be longest and scramble
  369. the order the user sees.
  370. """
  371. # Same advisory lock the add-to-queue route takes (#1625-followup): two
  372. # concurrent inserts into an empty scope would otherwise both read
  373. # MAX(position) as 0 and land on position 1. SQLite serialises writes
  374. # implicitly and needs no equivalent.
  375. bind = db.get_bind()
  376. if bind.dialect.name == "postgresql":
  377. await db.execute(
  378. text("SELECT pg_advisory_xact_lock(1625, :k)"), {"k": printer_id if printer_id is not None else 0}
  379. )
  380. scope = PrintQueueItem.printer_id == printer_id if printer_id is not None else PrintQueueItem.printer_id.is_(None)
  381. max_pos = (
  382. await db.execute(
  383. select(func.max(PrintQueueItem.position)).where(scope).where(PrintQueueItem.status == "pending")
  384. )
  385. ).scalar() or 0
  386. return max_pos + 1
  387. def _clone_queue_item(source: PrintQueueItem, *, position: int, created_by_id: int | None) -> PrintQueueItem:
  388. """Copy *source*'s print configuration into a fresh pending item.
  389. Lifecycle state (status, timestamps, retry counters, scheduler flags) is
  390. deliberately not copied — the clone is a new run, not a resurrection.
  391. ``scheduled_time`` is dropped too: dispatching more of a plate is a
  392. "queue this now" action, and replaying the original's scheduled time would
  393. either fire immediately (it is in the past) or silently park the new run
  394. until a moment the user chose for a different print.
  395. ``cleanup_library_after_dispatch`` is forced off. It only ever comes from
  396. the Printers-page direct-print flow, where it deletes the transient library
  397. row after dispatch — replaying that on a clone would delete the source file
  398. out from under the rest of the order.
  399. """
  400. clone = PrintQueueItem(
  401. status="pending",
  402. position=position,
  403. created_by_id=created_by_id if created_by_id is not None else source.created_by_id,
  404. cleanup_library_after_dispatch=False,
  405. )
  406. for column in CLONED_SETTING_COLUMNS:
  407. setattr(clone, column, getattr(source, column))
  408. return clone
  409. def _plate_label(plate: PlateProgress) -> str:
  410. """How a plate is named in an error the user reads.
  411. Prefers the plate name the order stored, because that is what the Batches
  412. tab shows; falls back to the plate number for orders created before names
  413. were recorded.
  414. """
  415. if plate.plate_name:
  416. return plate.plate_name
  417. return f"Plate {plate.plate_id if plate.plate_id is not None else 1}"
  418. async def dispatch_remaining(
  419. db: AsyncSession,
  420. batch: PrintBatch,
  421. *,
  422. plate_id: int | None = None,
  423. only_plate: bool = False,
  424. limit: int | None = None,
  425. created_by_id: int | None = None,
  426. ) -> list[PrintQueueItem]:
  427. """Create queue items for the runs *batch* still owes.
  428. ``only_plate`` restricts the dispatch to the single plate named by
  429. ``plate_id`` (which may legitimately be ``None`` for a single-plate file);
  430. otherwise every plate with work outstanding is dispatched in plate order.
  431. ``limit`` caps the total number of items created across all plates.
  432. Raises :class:`BatchDispatchError` when nothing at all can be produced
  433. because no plate that owes runs has an item to clone — the order can
  434. describe work whose every run has since been deleted, and there is no
  435. configuration to copy in that case. A plate in that state is skipped
  436. rather than aborting the whole order: one unrecoverable plate must not
  437. block the plates that are still perfectly dispatchable.
  438. """
  439. progress = await load_progress(db, batch)
  440. if not progress.has_targets:
  441. return []
  442. targets = [p for p in progress.plates if p.remaining > 0]
  443. if only_plate:
  444. targets = [p for p in targets if p.plate_id == plate_id]
  445. created: list[PrintQueueItem] = []
  446. stranded: list[PlateProgress] = []
  447. for plate in targets:
  448. if limit is not None and len(created) >= limit:
  449. break
  450. source = (
  451. await db.execute(
  452. select(PrintQueueItem)
  453. .options(selectinload(PrintQueueItem.variants))
  454. .where(PrintQueueItem.batch_id == batch.id)
  455. .where(PrintQueueItem.plate_id == plate.plate_id)
  456. .order_by(PrintQueueItem.id.desc())
  457. .limit(1)
  458. )
  459. ).scalar_one_or_none()
  460. if source is None:
  461. stranded.append(plate)
  462. continue
  463. wanted = plate.remaining
  464. if limit is not None:
  465. wanted = min(wanted, limit - len(created))
  466. # One scope per source printer; clones for this plate all land in it,
  467. # appended after whatever is already queued there.
  468. position = await _next_position(db, source.printer_id)
  469. for _ in range(wanted):
  470. clone = _clone_queue_item(source, position=position, created_by_id=created_by_id)
  471. position += 1
  472. db.add(clone)
  473. await db.flush()
  474. for variant in source.variants:
  475. cloned_variant = PrintQueueVariant(queue_item_id=clone.id)
  476. for column in CLONED_VARIANT_COLUMNS:
  477. setattr(cloned_variant, column, getattr(variant, column))
  478. db.add(cloned_variant)
  479. created.append(clone)
  480. if not created and stranded:
  481. names = ", ".join(_plate_label(p) for p in stranded)
  482. raise BatchDispatchError(
  483. f"{names} {'have' if len(stranded) > 1 else 'has'} no queued or finished run to copy settings from. "
  484. "Queue the plate once from the file, then dispatch the rest from here."
  485. )
  486. if created:
  487. # Dispatching more work can only ever un-fulfil an order, but run the
  488. # check anyway so a reopened batch flips back from completed.
  489. await db.flush()
  490. await refresh_batch_status(db, batch)
  491. if stranded:
  492. logger.info("Batch %s: skipped %d plate(s) with no item to clone", batch.id, len(stranded))
  493. logger.info("Dispatched %d item(s) for batch %s", len(created), batch.id)
  494. return created