print_batch.py 20 KB

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