print_batch.py 24 KB

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