print_batch.py 20 KB

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