print_batch.py 22 KB

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