filament_deficit.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. """Filament-deficit check used by every queue dispatch path.
  2. The PrintModal warns when an assigned spool can't satisfy a print's per-slot
  3. filament weight (``Pre-print checks now also warn when the spool has
  4. insufficient material`` — #720). That check only runs when the user clicks
  5. "Print" inside PrintModal; ``QueuePage`` Play button, ``start_queue_item``
  6. route, and the VP intake + scheduler auto-dispatch path all skip it (#1496).
  7. This module is the single source of truth for the check. Both the route
  8. handler (``POST /print-queue/{id}/start``) and the dispatch scheduler call
  9. ``compute_deficit_for_queue_item`` against live spool state.
  10. Design notes:
  11. * The 3MF parser is the same one used by PrintModal: per-slot ``used_grams``
  12. comes from ``extract_filament_requirements`` (#1188's filament-overrides
  13. pipeline) or — when the item points at an unsliced library file — falls
  14. through to the file's archive copy. Anything that yields no requirements
  15. is treated as "no deficit" so a malformed or stripped 3MF never blocks.
  16. * Both internal-inventory and Spoolman modes are covered. Internal mode
  17. resolves via ``SpoolAssignment`` joined to ``Spool`` (``label_weight``
  18. minus ``weight_used``). Spoolman mode resolves via
  19. ``SpoolmanSlotAssignment`` then ``SpoolmanClient.get_spool`` for the live
  20. remaining weight; if Spoolman is unreachable we return no deficit rather
  21. than wedge the queue on a flaky network call.
  22. * The ``disable_filament_warnings`` user setting is respected at the
  23. service boundary — callers do not have to know about it.
  24. """
  25. from __future__ import annotations
  26. import json
  27. import logging
  28. from collections import defaultdict
  29. from dataclasses import dataclass
  30. from pathlib import Path
  31. from sqlalchemy import select
  32. from sqlalchemy.ext.asyncio import AsyncSession
  33. from sqlalchemy.orm import selectinload
  34. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool, spoolman_net_weight
  35. from backend.app.core.config import settings as app_settings
  36. from backend.app.models.print_queue import PrintQueueItem
  37. from backend.app.models.spool_assignment import SpoolAssignment
  38. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  39. from backend.app.services.filament_requirements import extract_filament_requirements
  40. from backend.app.services.printer_manager import printer_tray_layout
  41. from backend.app.utils.filament_ids import normalize_slicer_filament
  42. from backend.app.utils.tray_ids import TrayLayout
  43. logger = logging.getLogger(__name__)
  44. @dataclass(frozen=True)
  45. class FilamentDeficit:
  46. """One slot's filament shortfall."""
  47. slot_id: int
  48. ams_id: int | None
  49. tray_id: int | None
  50. filament_type: str
  51. required_grams: float
  52. remaining_grams: float | None # None = could not determine
  53. def to_dict(self) -> dict:
  54. return {
  55. "slot_id": self.slot_id,
  56. "ams_id": self.ams_id,
  57. "tray_id": self.tray_id,
  58. "filament_type": self.filament_type,
  59. "required_grams": self.required_grams,
  60. "remaining_grams": self.remaining_grams,
  61. }
  62. def _resolve_source_3mf(item: PrintQueueItem) -> Path | None:
  63. """Locate the 3MF file backing this queue item (archive or library).
  64. ``LibraryFile.file_path`` is stored relative to ``base_dir`` (rows written
  65. before that convention hold absolute paths, which is why every reader
  66. guards on ``is_absolute``). Resolving a relative one against the process
  67. working directory finds nothing, and a source that cannot be found is
  68. treated as "nothing to verify" — so this check silently passed every
  69. library-backed item, which is every Slicer Pipeline job and everything
  70. queued from the Library page (#2779).
  71. """
  72. if item.archive is not None and item.archive.file_path:
  73. return app_settings.base_dir / item.archive.file_path
  74. if item.library_file is not None and item.library_file.file_path:
  75. library_path = Path(item.library_file.file_path)
  76. if library_path.is_absolute():
  77. return library_path
  78. # SEC-PATH-OK: file_path is DB-stored and generated by the Library
  79. # ingest (archive/library/files/<uuid>.<ext>), never request input. The
  80. # same value already resolves the file for upload in print_queue.py and
  81. # print_scheduler.py — this check reads what the printer is about to be
  82. # sent, so it must resolve it identically.
  83. return app_settings.base_dir / item.library_file.file_path
  84. return None
  85. async def _spoolman_remaining_grams(spoolman_spool_id: int) -> float | None:
  86. """Live remaining grams for a Spoolman spool, or None if unavailable."""
  87. try:
  88. from backend.app.services.spoolman import (
  89. SpoolmanClientError,
  90. SpoolmanNotFoundError,
  91. get_spoolman_client,
  92. )
  93. except ImportError:
  94. return None
  95. try:
  96. client = await get_spoolman_client()
  97. if client is None:
  98. return None
  99. spool = await client.get_spool(spoolman_spool_id)
  100. except (SpoolmanNotFoundError, SpoolmanClientError):
  101. return None
  102. except Exception as e:
  103. logger.debug("Spoolman fetch failed for spool %s: %s", spoolman_spool_id, e)
  104. return None
  105. if not spool:
  106. return None
  107. # Spoolman exposes either an absolute remaining_weight, or used_weight +
  108. # the spool's net weight (initial_weight, else filament.weight; #3194).
  109. # Either is sufficient — prefer remaining_weight when present (the user
  110. # may have overridden it).
  111. remaining = spool.get("remaining_weight")
  112. if isinstance(remaining, (int, float)) and remaining >= 0:
  113. return float(remaining)
  114. used = spool.get("used_weight")
  115. total = spoolman_net_weight(spool)
  116. if isinstance(used, (int, float)) and isinstance(total, (int, float)) and total > 0:
  117. return max(0.0, float(total) - float(used))
  118. return None
  119. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  120. """Check whether the user has opted in to Spoolman inventory mode."""
  121. try:
  122. from backend.app.api.routes.settings import get_setting
  123. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  124. return bool(spoolman_enabled) and spoolman_enabled.lower() == "true"
  125. except Exception:
  126. return False
  127. async def _warnings_disabled(db: AsyncSession) -> bool:
  128. """Honour the ``disable_filament_warnings`` setting (#720)."""
  129. try:
  130. from backend.app.api.routes.settings import get_setting
  131. disabled = await get_setting(db, "disable_filament_warnings")
  132. return bool(disabled) and disabled.lower() == "true"
  133. except Exception:
  134. return False
  135. def _normalize_color_for_id(raw: str | None) -> str:
  136. """Canonicalise a hex colour for identity comparison.
  137. Strips the leading ``#``, uppercases, and drops the alpha channel when
  138. the hex is 8 chars long (``RRGGBBAA``) so a fully-opaque 8-char hex
  139. matches a 6-char hex of the same RGB. Empty / None → empty string.
  140. Anything that is not a string reads as "no colour" rather than raising.
  141. In Spoolman mode ``raw`` comes straight off the wire as
  142. ``filament.color_hex``, and this runs on the dispatch path — a record
  143. holding a number there would otherwise fail a queue start rather than
  144. merely fail to pool.
  145. """
  146. if not isinstance(raw, str):
  147. raw = None
  148. s = (raw or "").strip().lstrip("#").upper()
  149. if len(s) == 8: # RRGGBBAA → strip alpha
  150. s = s[:6]
  151. return s
  152. def _material_identity_internal(spool) -> str:
  153. """Strict same-material key for backup-peer matching in internal mode.
  154. Requires a Bambu filament preset ID (``slicer_filament``, e.g. ``GFA00``)
  155. AND a matching colour. The preset identifies the filament profile (PETG
  156. HF, PLA Basic, etc.) — same hot-end behaviour — but the firmware's
  157. switch logic also requires the spool to be the same colour (otherwise
  158. every PETG HF spool would back every other PETG HF spool regardless of
  159. colour, which would dye prints mid-run). Spools without a preset
  160. (user-tagged / non-Bambu) get a per-spool unique key so they NEVER
  161. pair with anything else; without the Bambu preset the firmware can't
  162. trust the backup decision.
  163. """
  164. preset = (spool.slicer_filament or "").strip() if spool else ""
  165. if preset:
  166. # The field holds a filament_id from an RFID scan ("GFA10") or a
  167. # setting_id from the preset picker ("GFSA10_02"); both name the same
  168. # filament, so compare the filament_id (#1824).
  169. filament_id = normalize_slicer_filament(preset)[0] or preset
  170. color = _normalize_color_for_id(spool.rgba if spool else None)
  171. return f"preset:{filament_id}|color:{color}"
  172. # Unique-per-spool key prevents grouping. Use the spool's primary key so
  173. # the same spool always resolves to the same key within a request.
  174. spool_id = getattr(spool, "id", None) if spool else None
  175. return f"unmatched:{spool_id}"
  176. def _material_identity_spoolman(spool: dict | None) -> str:
  177. """Strict same-material key for backup-peer matching in Spoolman mode.
  178. Two spools pair only when they reference the same Spoolman ``filament``
  179. catalog entry (same ``filament.id``) AND share the same colour. The
  180. catalog entry pins the profile (PETG HF / PLA Basic / ...); the colour
  181. pins the variant. Spools without a resolvable filament id get a
  182. per-spool unique key so they never pair.
  183. """
  184. if not isinstance(spool, dict) or not spool:
  185. return "unmatched:none"
  186. # Both are free-form JSON off the Spoolman API, and this is the dispatch
  187. # path: a wrongly-typed member must cost the slot its pool, never the
  188. # queue its start.
  189. filament = spool.get("filament") or {}
  190. if not isinstance(filament, dict):
  191. filament = {}
  192. fil_id = filament.get("id")
  193. if isinstance(fil_id, (int, str)) and str(fil_id).strip():
  194. # Prefer the per-spool override colour when set (Spoolman lets the user
  195. # tag a spool with a colour distinct from the filament catalog
  196. # default); fall back to the filament catalog colour.
  197. color = _normalize_color_for_id(
  198. (spool.get("color_hex") if isinstance(spool.get("color_hex"), str) else None) or filament.get("color_hex")
  199. )
  200. return f"filament:{fil_id}|color:{color}"
  201. spool_id = spool.get("id")
  202. return f"unmatched:{spool_id}"
  203. def _live_tray_keys(printer_id: int) -> dict[int, str]:
  204. """Pooling key per ``global_tray_id``, from what the printer reports per tray.
  205. AMS Filament Backup is the firmware's decision, and it makes it on the
  206. tray's own ``tray_info_idx`` and colour. The spool rows bound to two slots
  207. can disagree about that while the printer does not: an RFID-created spool
  208. stores "GFA10", one set up from a user preset "PFUS..." (#1824). So a slot
  209. the printer reports is keyed on the report, in the same format
  210. ``_material_identity_internal`` uses; a tray with nothing in it or no
  211. preset gets a key of its own, so it never pairs. Slots missing from the
  212. report fall back to the bound spool.
  213. """
  214. try:
  215. from backend.app.services.printer_manager import printer_manager
  216. except ImportError:
  217. return {}
  218. state = printer_manager.get_status(printer_id)
  219. raw = getattr(state, "raw_data", None) if state is not None else None
  220. if not isinstance(raw, dict):
  221. return {}
  222. keys: dict[int, str] = {}
  223. def _add(global_tray_id: int, tray: dict) -> None:
  224. preset = tray.get("tray_info_idx")
  225. preset = preset.strip() if isinstance(preset, str) else ""
  226. if tray.get("tray_type") and preset:
  227. keys[global_tray_id] = f"preset:{preset}|color:{_normalize_color_for_id(tray.get('tray_color'))}"
  228. else:
  229. keys[global_tray_id] = f"unmatched:tray:{global_tray_id}"
  230. # Free-form MQTT payload on the dispatch path: a malformed unit or tray
  231. # costs that slot its live key, never the check.
  232. units = raw.get("ams") or []
  233. if isinstance(units, dict): # also stored as the push's {"ams": [...]}
  234. units = units.get("ams") or []
  235. layout = TrayLayout.from_state(state)
  236. for unit in units:
  237. if not isinstance(unit, dict):
  238. continue
  239. for tray in unit.get("tray") or []:
  240. if not isinstance(tray, dict):
  241. continue
  242. try:
  243. ams_id, tray_id = int(unit.get("id", "")), int(tray.get("id", ""))
  244. except (TypeError, ValueError):
  245. continue
  246. _add(layout.tray_from_slot_key(ams_id, tray_id), tray)
  247. vt_trays = raw.get("vt_tray") or []
  248. for tray in [vt_trays] if isinstance(vt_trays, dict) else vt_trays:
  249. if not isinstance(tray, dict):
  250. continue
  251. try:
  252. global_tray_id = int(tray.get("id", 254))
  253. except (TypeError, ValueError):
  254. continue
  255. _add(global_tray_id, tray)
  256. return keys
  257. def _extruder_side_for_ams(
  258. ams_id: int,
  259. ams_extruder_map: dict[str, int],
  260. is_dual_extruder: bool,
  261. ) -> int:
  262. """Resolve the extruder index (0=right, 1=left) for a given AMS unit.
  263. Single-extruder printers collapse everything to 0. On dual-extruder
  264. printers (H2D / H2C / X2D), the firmware can't cross extruders even with
  265. AMS Filament Backup ON, so the pool must be scoped per-side.
  266. """
  267. if not is_dual_extruder:
  268. return 0
  269. return int(ams_extruder_map.get(str(ams_id), 0))
  270. def _parse_ams_mapping(raw: str | None) -> list[int] | None:
  271. if not raw:
  272. return None
  273. try:
  274. parsed = json.loads(raw)
  275. except (json.JSONDecodeError, TypeError):
  276. return None
  277. if not isinstance(parsed, list):
  278. return None
  279. return [v for v in parsed if isinstance(v, int)]
  280. async def _get_printer_backup_context(
  281. printer_id: int,
  282. ) -> tuple[bool, dict[str, int], bool]:
  283. """Return ``(backup_on, ams_extruder_map, is_dual_extruder)`` for the printer.
  284. Read from the live MQTT state via ``printer_manager`` (no DB round-trip).
  285. Defaults conservatively to ``backup_on=False`` when the state is missing
  286. or the printer is offline — same fallback as today (per-slot deficit
  287. accounting), so an offline printer is never treated as backup-capable.
  288. """
  289. try:
  290. from backend.app.services.printer_manager import printer_manager
  291. from backend.app.utils.printer_models import is_dual_nozzle_model
  292. except ImportError:
  293. return False, {}, False
  294. state = printer_manager.get_status(printer_id)
  295. if state is None:
  296. return False, {}, False
  297. backup_on = state.ams_filament_backup is True
  298. ams_extruder_map = dict(state.ams_extruder_map or {})
  299. model = printer_manager.get_model(printer_id)
  300. is_dual = bool(model and is_dual_nozzle_model(model))
  301. return backup_on, ams_extruder_map, is_dual
  302. @dataclass(frozen=True)
  303. class SlotSpoolIdentity:
  304. """How the spool bound to a slot should be *named*, as opposed to matched.
  305. The printer cannot supply this and never will. A tray record carries no
  306. brand field at all, and ``tray_sub_brands`` stays empty for anything that
  307. isn't a Bambu spool, so a client naming a slot from telemetry alone has
  308. only the type and the colour hex to work with — and turns that hex into
  309. whichever catalogue colour happens to share it. A Devil Design PLA Basic
  310. Orange the operator assigned in Bambuddy reads back as "PLA (Sunflower
  311. Yellow)", because Bambu sell a Sunflower Yellow at the same ``FEC600``.
  312. Only the assignment knows the answer, which is why it is served alongside
  313. the pooling key rather than left to the client to resolve: the identity
  314. rule differs per inventory mode, and the printer card and the print dialog
  315. disagreeing about what is in a slot is the bug this exists to close.
  316. Purely descriptive — nothing here takes part in matching, which stays on
  317. the printer's own telemetry so the dialog and the dispatcher cannot draw
  318. different conclusions from the same slot.
  319. """
  320. brand: str | None
  321. material: str | None
  322. subtype: str | None
  323. color_name: str | None
  324. rgba: str | None
  325. # The rest of the spool's colour, for drawing it rather than naming it
  326. # (#3159). A tray record carries one hex and nothing else, so a two-tone
  327. # or glittery spool renders as its base colour unless the binding says
  328. # otherwise -- and on a farm of third-party spools that is exactly the
  329. # swatch somebody is comparing against the slicer's colour. Same shape the
  330. # inventory row stores: ``extra_colors`` a comma-separated hex list,
  331. # ``effect_type`` one of the client's FilamentEffect names.
  332. extra_colors: str | None = None
  333. effect_type: str | None = None
  334. def to_dict(self) -> dict:
  335. return {
  336. "brand": self.brand,
  337. "material": self.material,
  338. "subtype": self.subtype,
  339. "color_name": self.color_name,
  340. "rgba": self.rgba,
  341. "extra_colors": self.extra_colors,
  342. "effect_type": self.effect_type,
  343. }
  344. def _clean(value) -> str | None:
  345. """Trim a display field, collapsing blanks to None so the client can skip it."""
  346. text = str(value).strip() if value is not None else ""
  347. return text or None
  348. def _identity_from_internal(spool) -> SlotSpoolIdentity:
  349. """Display identity from an internal-inventory ``Spool`` row."""
  350. return SlotSpoolIdentity(
  351. brand=_clean(spool.brand),
  352. material=_clean(spool.material),
  353. subtype=_clean(spool.subtype),
  354. color_name=_clean(spool.color_name),
  355. rgba=_clean(spool.rgba),
  356. extra_colors=_clean(spool.extra_colors),
  357. effect_type=_clean(spool.effect_type),
  358. )
  359. def _identity_from_spoolman(spool_dict: dict) -> SlotSpoolIdentity | None:
  360. """Display identity from a raw Spoolman spool dict, or None if unreadable.
  361. Goes through ``_map_spoolman_spool`` rather than reading the dict directly:
  362. brand lives on the nested vendor, subtype is the filament name with its
  363. material prefix stripped, and ``color_name`` has a three-step read order
  364. Spoolman itself has no field for. Re-deriving any of that here is how the
  365. two modes would drift apart.
  366. """
  367. # Broad on purpose. This is a name for a dropdown, and the caller is on the
  368. # dispatch path -- ``compute_deficit_for_queue_item`` runs it before every
  369. # queue start. ``_map_spoolman_spool`` walks a dozen nested fields off the
  370. # wire (``filament.vendor.name``, ``extra.tag``, ``filament.color_hex``) and
  371. # any of them arriving as the wrong type raises AttributeError rather than
  372. # ValueError, so a narrow catch here would turn one malformed Spoolman
  373. # record into a failed dispatch. Losing the name costs a fallback to
  374. # telemetry, which is what every slot did before this existed.
  375. try:
  376. mapped = _map_spoolman_spool(spool_dict)
  377. except Exception as exc: # noqa: BLE001 - display-only, must never block a dispatch
  378. logger.debug(
  379. "Spoolman spool %r has no usable display identity: %s",
  380. spool_dict.get("id") if isinstance(spool_dict, dict) else spool_dict,
  381. exc,
  382. )
  383. return None
  384. # Spoolman has no colour-name field, so `_map_spoolman_spool` synthesises
  385. # one from the subtype when nothing is stored -- which reads fine in an
  386. # inventory list ("PLA Basic") and badly as a colour ("Devil Design PLA
  387. # Basic (Basic)"). Drop it and let the client's catalogue lookup name the
  388. # hex, which is what an unnamed slot got before this existed.
  389. color_name = None if mapped.get("color_name_is_synthesized") else _clean(mapped.get("color_name"))
  390. return SlotSpoolIdentity(
  391. brand=_clean(mapped.get("brand")),
  392. material=_clean(mapped.get("material")),
  393. subtype=_clean(mapped.get("subtype")),
  394. color_name=color_name,
  395. rgba=_clean(mapped.get("rgba")),
  396. # `_map_spoolman_spool` builds `extra_colors` from Spoolman's own
  397. # multi-colour hexes and pins `effect_type` to None, because Spoolman
  398. # has no field for it -- see the note there.
  399. extra_colors=_clean(mapped.get("extra_colors")),
  400. effect_type=_clean(mapped.get("effect_type")),
  401. )
  402. @dataclass(frozen=True)
  403. class SlotMaterial:
  404. """One inventory-bound AMS slot: what's in it, how much is left, which side."""
  405. ams_id: int
  406. tray_id: int
  407. global_tray_id: int
  408. # Opaque grouping key. Two slots pool for AMS Filament Backup only when
  409. # their keys AND extruder sides match. Never parse it — the format is an
  410. # implementation detail of ``_live_tray_keys`` / ``_material_identity_*``.
  411. material_key: str
  412. remaining_grams: float
  413. extruder: int
  414. # Display-only; see SlotSpoolIdentity. None when the binding resolves to a
  415. # spool we cannot describe, which callers render from telemetry as before.
  416. spool: SlotSpoolIdentity | None = None
  417. # Per-kg rate a print off this spool is charged at; None when unpriced,
  418. # which the charge prices at the default rate. Display-only: the print
  419. # dialog's estimate, which priced Spoolman slots from the built-in table.
  420. cost_per_kg: float | None = None
  421. def to_dict(self) -> dict:
  422. return {
  423. "ams_id": self.ams_id,
  424. "tray_id": self.tray_id,
  425. "global_tray_id": self.global_tray_id,
  426. "material_key": self.material_key,
  427. "remaining_g": self.remaining_grams,
  428. "extruder": self.extruder,
  429. "spool": self.spool.to_dict() if self.spool else None,
  430. "cost_per_kg": self.cost_per_kg,
  431. }
  432. async def build_slot_materials(
  433. db: AsyncSession,
  434. printer_id: int,
  435. *,
  436. live_keys: dict[int, str] | None = None,
  437. ) -> list[SlotMaterial]:
  438. """Every inventory-bound slot on ``printer_id``, with identity and remaining grams.
  439. Mode-agnostic: internal inventory resolves via ``SpoolAssignment`` joined to
  440. ``Spool`` (``label_weight`` minus ``weight_used``), Spoolman mode via
  441. ``SpoolmanSlotAssignment`` plus a live ``get_spool`` fetch. Slots whose
  442. remaining weight can't be determined — no spool row, zero label weight,
  443. Spoolman unreachable — are omitted entirely rather than reported as zero, so
  444. a missing binding never manufactures a shortfall.
  445. This is the pool the AMS-Filament-Backup accounting draws on (#1762), and
  446. the same data the PrintModal pre-flight check consumes through
  447. ``GET /printers/{id}/inventory-remain``. Both sides share it so the modal's
  448. warning and the dispatcher's 409 can't disagree about what backs what up.
  449. """
  450. _, ams_extruder_map, is_dual = await _get_printer_backup_context(printer_id)
  451. # ``live_keys``: a caller that has keyed its own slots passes the same read,
  452. # so a status push in between cannot put them in different pools.
  453. if live_keys is None:
  454. live_keys = _live_tray_keys(printer_id)
  455. layout = printer_tray_layout(printer_id)
  456. materials: list[SlotMaterial] = []
  457. def _append(
  458. ams_id: int,
  459. tray_id: int,
  460. material_key: str,
  461. remaining: float,
  462. spool: SlotSpoolIdentity | None = None,
  463. cost_per_kg: float | None = None,
  464. ) -> None:
  465. global_tray_id = layout.tray_from_slot_key(ams_id, tray_id)
  466. materials.append(
  467. SlotMaterial(
  468. ams_id=ams_id,
  469. tray_id=tray_id,
  470. global_tray_id=global_tray_id,
  471. material_key=live_keys.get(global_tray_id, material_key),
  472. remaining_grams=remaining,
  473. extruder=_extruder_side_for_ams(ams_id, ams_extruder_map, is_dual),
  474. spool=spool,
  475. cost_per_kg=cost_per_kg,
  476. )
  477. )
  478. if await _is_spoolman_mode(db):
  479. from backend.app.services.spoolman_tracking import _spool_cost_per_gram
  480. sm_all = await db.execute(select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id))
  481. from backend.app.services.spoolman import (
  482. SpoolmanClientError,
  483. SpoolmanNotFoundError,
  484. get_spoolman_client,
  485. )
  486. try:
  487. client = await get_spoolman_client()
  488. except Exception:
  489. client = None
  490. if client is None:
  491. return []
  492. for sa in sm_all.scalars().all():
  493. try:
  494. spool_dict = await client.get_spool(sa.spoolman_spool_id)
  495. except (SpoolmanNotFoundError, SpoolmanClientError):
  496. continue
  497. except Exception as e:
  498. logger.debug("Spoolman pool fetch failed for spool %s: %s", sa.spoolman_spool_id, e)
  499. continue
  500. if not spool_dict:
  501. continue
  502. remaining: float | None = None
  503. rw = spool_dict.get("remaining_weight")
  504. if isinstance(rw, (int, float)) and rw >= 0:
  505. remaining = float(rw)
  506. else:
  507. used = spool_dict.get("used_weight")
  508. total = spoolman_net_weight(spool_dict)
  509. if isinstance(used, (int, float)) and isinstance(total, (int, float)) and total > 0:
  510. remaining = max(0.0, float(total) - float(used))
  511. if remaining is None:
  512. continue
  513. per_gram = _spool_cost_per_gram(spool_dict)
  514. _append(
  515. sa.ams_id,
  516. sa.tray_id,
  517. _material_identity_spoolman(spool_dict),
  518. remaining,
  519. _identity_from_spoolman(spool_dict),
  520. per_gram * 1000.0 if per_gram is not None else None,
  521. )
  522. return materials
  523. internal_all = await db.execute(
  524. select(SpoolAssignment)
  525. .options(selectinload(SpoolAssignment.spool))
  526. .where(SpoolAssignment.printer_id == printer_id)
  527. )
  528. for assignment in internal_all.scalars().all():
  529. spool = assignment.spool
  530. if spool is None:
  531. continue
  532. label_weight = float(spool.label_weight or 0)
  533. weight_used = float(spool.weight_used or 0)
  534. if label_weight <= 0:
  535. continue
  536. _append(
  537. assignment.ams_id,
  538. assignment.tray_id,
  539. _material_identity_internal(spool),
  540. max(0.0, label_weight - weight_used),
  541. _identity_from_internal(spool),
  542. spool.cost_per_kg,
  543. )
  544. return materials
  545. async def compute_deficit_for_queue_item(
  546. db: AsyncSession,
  547. item: PrintQueueItem,
  548. *,
  549. printer_id: int | None = None,
  550. ams_mapping: list[int] | None = None,
  551. require_known: bool = False,
  552. ) -> list[FilamentDeficit]:
  553. """Return per-slot filament shortfalls for ``item``, or [] when it's safe to dispatch.
  554. ``printer_id`` and ``ams_mapping`` ask about a printer the item is not
  555. assigned to yet, with the mapping it would get there: the model-based
  556. matcher uses them to pass over a printer that would be short (#3137)
  557. before it commits the item to one. Without them, the item's own columns
  558. are read.
  559. ``require_known`` also reports every printed slot whose remaining amount
  560. cannot be determined (no tray mapped, no spool assigned, no label weight,
  561. Spoolman not answering), with ``remaining_grams=None``. Everywhere else an
  562. unknown amount lets the print through; a caller about to *start* a held
  563. job on its own uses this so it only does so on a positive finding.
  564. Returns an empty list whenever any of the following hold:
  565. * The ``disable_filament_warnings`` setting is on.
  566. * The item has no resolved ``printer_id`` (model-based assignment not
  567. yet picked a printer — the scheduler re-runs the check after it does).
  568. * No source 3MF is available, or the 3MF carries no per-slot
  569. requirements (treated as "nothing to verify" rather than an error,
  570. matching the PrintModal behaviour).
  571. * No AMS mapping is set yet — the scheduler computes the mapping just
  572. before dispatch; until it does we cannot map slot → tray.
  573. * Spoolman mode is on but the Spoolman server is unreachable. We do not
  574. wedge the queue on a network blip.
  575. #1762: when the printer reports ``ams_filament_backup=True`` in MQTT
  576. status, available material is pooled across ALL same-material spools on
  577. the printer (within the same extruder side for dual-nozzle models, since
  578. firmware can't cross extruders even with the backup bit set). Per-slot
  579. shortfalls are then only emitted if the POOL is too small for the
  580. print's total required of that material — matching how the printer
  581. actually behaves with Filament Backup ON.
  582. """
  583. if await _warnings_disabled(db):
  584. return []
  585. if printer_id is None:
  586. printer_id = item.printer_id
  587. if printer_id is None:
  588. return []
  589. # Refresh the relationships we need without assuming the caller eagerly
  590. # loaded them — both the route and the scheduler call this from contexts
  591. # with different loading strategies.
  592. refreshed = await db.execute(
  593. select(PrintQueueItem)
  594. .options(
  595. selectinload(PrintQueueItem.archive),
  596. selectinload(PrintQueueItem.library_file),
  597. )
  598. .where(PrintQueueItem.id == item.id)
  599. )
  600. item = refreshed.scalar_one_or_none() or item
  601. source_path = _resolve_source_3mf(item)
  602. if source_path is None:
  603. # No archive and no library file — nothing was ever attached to check.
  604. return []
  605. if not source_path.exists():
  606. # Dispatch is not blocked: the upload that follows needs the same file
  607. # and fails within seconds, where wedging the queue here would strand
  608. # it. But skipping a safety check must leave a trace — a silent skip is
  609. # what hid #2779 for every library-backed item.
  610. logger.warning(
  611. "Filament check skipped for queue item %s: source 3MF not found at %s",
  612. item.id,
  613. source_path,
  614. )
  615. return []
  616. requirements = extract_filament_requirements(source_path, item.plate_id)
  617. if not requirements:
  618. return []
  619. mapping = ams_mapping if ams_mapping is not None else _parse_ams_mapping(item.ams_mapping)
  620. if not mapping:
  621. return []
  622. spoolman_mode = await _is_spoolman_mode(db)
  623. backup_on, ams_extruder_map, is_dual = await _get_printer_backup_context(printer_id)
  624. live_keys = _live_tray_keys(printer_id) if backup_on else {}
  625. layout = printer_tray_layout(printer_id)
  626. # ------------------------------------------------------------------ phase 1
  627. # Resolve each requirement to (ams_id, tray_id, identity, remaining_grams).
  628. # Slot identity is what the printer reports for the tray, else the spool
  629. # *assigned to that slot* (see ``_live_tray_keys``). A
  630. # ``None`` remaining means "couldn't determine" — treated as "no deficit"
  631. # below (preserved from pre-#1762 behaviour for non-backup paths too).
  632. @dataclass
  633. class _ReqRow:
  634. slot_id: int
  635. ams_id: int
  636. tray_id: int
  637. global_tray_id: int
  638. required: float
  639. identity: str
  640. remaining: float | None
  641. filament_type: str
  642. extruder: int
  643. resolved: list[_ReqRow] = []
  644. # Printed slots whose remaining amount is unknown; only returned with
  645. # ``require_known``.
  646. undetermined: list[FilamentDeficit] = []
  647. def _undetermined(req: dict, ams_id: int | None = None, tray_id: int | None = None) -> None:
  648. undetermined.append(
  649. FilamentDeficit(
  650. slot_id=req["slot_id"],
  651. ams_id=ams_id,
  652. tray_id=tray_id,
  653. filament_type=str(req.get("type", "")),
  654. required_grams=float(req["used_grams"]),
  655. remaining_grams=None,
  656. )
  657. )
  658. for req in requirements:
  659. slot_id = req.get("slot_id")
  660. used_grams = req.get("used_grams")
  661. if not isinstance(slot_id, int) or slot_id <= 0:
  662. continue
  663. if not isinstance(used_grams, (int, float)) or used_grams <= 0:
  664. continue
  665. idx = slot_id - 1
  666. if idx >= len(mapping):
  667. _undetermined(req)
  668. continue
  669. global_tray_id = mapping[idx]
  670. if global_tray_id is None or global_tray_id < 0:
  671. _undetermined(req)
  672. continue
  673. ams_id, tray_id = layout.slot_key(global_tray_id)
  674. identity = "attrs:|||"
  675. remaining: float | None = None
  676. if spoolman_mode:
  677. sm_result = await db.execute(
  678. select(SpoolmanSlotAssignment).where(
  679. SpoolmanSlotAssignment.printer_id == printer_id,
  680. SpoolmanSlotAssignment.ams_id == ams_id,
  681. SpoolmanSlotAssignment.tray_id == tray_id,
  682. )
  683. )
  684. sm_assignment = sm_result.scalar_one_or_none()
  685. if sm_assignment is None:
  686. _undetermined(req, ams_id, tray_id)
  687. continue
  688. # Live remaining_weight from Spoolman. The fetch also resolves the
  689. # filament identity for pooling (material + colour + name).
  690. from backend.app.services.spoolman import (
  691. SpoolmanClientError,
  692. SpoolmanNotFoundError,
  693. get_spoolman_client,
  694. )
  695. try:
  696. client = await get_spoolman_client()
  697. spool_dict = await client.get_spool(sm_assignment.spoolman_spool_id) if client else None
  698. except (SpoolmanNotFoundError, SpoolmanClientError):
  699. spool_dict = None
  700. except Exception as e:
  701. logger.debug("Spoolman fetch failed for spool %s: %s", sm_assignment.spoolman_spool_id, e)
  702. spool_dict = None
  703. if spool_dict:
  704. identity = _material_identity_spoolman(spool_dict)
  705. rw = spool_dict.get("remaining_weight")
  706. if isinstance(rw, (int, float)) and rw >= 0:
  707. remaining = float(rw)
  708. else:
  709. used = spool_dict.get("used_weight")
  710. total = spoolman_net_weight(spool_dict)
  711. if isinstance(used, (int, float)) and isinstance(total, (int, float)) and total > 0:
  712. remaining = max(0.0, float(total) - float(used))
  713. else:
  714. internal_result = await db.execute(
  715. select(SpoolAssignment)
  716. .options(selectinload(SpoolAssignment.spool))
  717. .where(
  718. SpoolAssignment.printer_id == printer_id,
  719. SpoolAssignment.ams_id == ams_id,
  720. SpoolAssignment.tray_id == tray_id,
  721. )
  722. )
  723. assignment = internal_result.scalar_one_or_none()
  724. if assignment is None or assignment.spool is None:
  725. _undetermined(req, ams_id, tray_id)
  726. continue
  727. spool = assignment.spool
  728. identity = _material_identity_internal(spool)
  729. label_weight = float(spool.label_weight or 0)
  730. weight_used = float(spool.weight_used or 0)
  731. if label_weight <= 0:
  732. _undetermined(req, ams_id, tray_id)
  733. continue
  734. remaining = max(0.0, label_weight - weight_used)
  735. if remaining is None:
  736. # Unable to determine remaining grams — preserve pre-#1762 behaviour
  737. # (don't block on undetermined data).
  738. _undetermined(req, ams_id, tray_id)
  739. continue
  740. resolved.append(
  741. _ReqRow(
  742. slot_id=slot_id,
  743. ams_id=ams_id,
  744. tray_id=tray_id,
  745. global_tray_id=global_tray_id,
  746. required=float(used_grams),
  747. # Must key the same way as ``build_slot_materials``, or the
  748. # slot's demand lands in a pool its own grams are not in.
  749. identity=live_keys.get(global_tray_id, identity),
  750. remaining=remaining,
  751. filament_type=str(req.get("type", "")),
  752. extruder=_extruder_side_for_ams(ams_id, ams_extruder_map, is_dual),
  753. )
  754. )
  755. # ------------------------------------------------------------------ phase 2
  756. # When backup is OFF, fall back to today's per-slot accounting (one-line
  757. # equivalence of the original loop), so this path is a strict no-op
  758. # behaviour-wise vs. the pre-#1762 code.
  759. unknown = undetermined if require_known else []
  760. if not backup_on:
  761. return unknown + [
  762. FilamentDeficit(
  763. slot_id=row.slot_id,
  764. ams_id=row.ams_id,
  765. tray_id=row.tray_id,
  766. filament_type=row.filament_type,
  767. required_grams=row.required,
  768. remaining_grams=row.remaining,
  769. )
  770. for row in resolved
  771. if row.remaining is not None and row.remaining < row.required
  772. ]
  773. # ------------------------------------------------------------------ phase 3
  774. # Backup ON: build (identity, extruder)-keyed pool and required-sum maps
  775. # from EVERY assigned spool on the printer (not just the slots in the
  776. # print's mapping). Then emit deficits only when the pool for a slot's
  777. # material is too small for the print's total required of that material.
  778. pool_by_key: dict[tuple[str, int], float] = defaultdict(float)
  779. required_by_key: dict[tuple[str, int], float] = defaultdict(float)
  780. for slot in await build_slot_materials(db, printer_id, live_keys=live_keys):
  781. pool_by_key[(slot.material_key, slot.extruder)] += slot.remaining_grams
  782. for row in resolved:
  783. required_by_key[(row.identity, row.extruder)] += row.required
  784. deficits: list[FilamentDeficit] = []
  785. for row in resolved:
  786. key = (row.identity, row.extruder)
  787. # Pool insufficient for the print's TOTAL required of this material on
  788. # this extruder side → real deficit. The per-slot remaining still gets
  789. # surfaced so the UI can point at the slot the user assigned.
  790. if pool_by_key[key] < required_by_key[key]:
  791. deficits.append(
  792. FilamentDeficit(
  793. slot_id=row.slot_id,
  794. ams_id=row.ams_id,
  795. tray_id=row.tray_id,
  796. filament_type=row.filament_type,
  797. required_grams=row.required,
  798. remaining_grams=row.remaining,
  799. )
  800. )
  801. return unknown + deficits
  802. # Re-export the most useful pieces for callers that just want the data.
  803. __all__ = [
  804. "FilamentDeficit",
  805. "compute_deficit_for_queue_item",
  806. ]