filament_deficit.py 26 KB

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