print_batch.py 21 KB

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