filament_deficit.py 32 KB

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