test_scheduler_nozzle_mismatch.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. """Tests for the nozzle-diameter mismatch guard (#1899).
  2. A file sliced for one nozzle size dispatched to a printer with a different
  3. nozzle installed is rejected by the firmware with a cryptic HMS ("Failed to get
  4. AMS mapping table" 0700_8012). The scheduler catches this before upload and
  5. fails the queue item with an actionable message instead.
  6. These cover the two pure helpers that make the decision. The guard is fail-safe
  7. by construction: it only blocks on a POSITIVE mismatch, never on missing data.
  8. """
  9. from contextlib import ExitStack
  10. from pathlib import Path
  11. from types import SimpleNamespace
  12. from unittest.mock import AsyncMock, MagicMock, patch
  13. import pytest
  14. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  15. import backend.app.models # noqa: F401 - populate Base.metadata
  16. import backend.app.services.print_scheduler as scheduler_module
  17. from backend.app.core.database import Base
  18. from backend.app.models.archive import PrintArchive
  19. from backend.app.models.print_queue import PrintQueueItem
  20. from backend.app.models.printer import Printer
  21. from backend.app.services.print_scheduler import (
  22. PrintScheduler,
  23. _installed_nozzle_diameters,
  24. _nozzle_mismatch_message,
  25. _rack_nozzle_diameters,
  26. )
  27. from backend.tests._fixtures.background_tasks import discarding_spawn_patch
  28. def _state(*diameters: str):
  29. """PrinterState-shaped namespace with the given nozzle diameter strings."""
  30. return SimpleNamespace(nozzles=[SimpleNamespace(nozzle_diameter=d) for d in diameters])
  31. # ---------------------------------------------------------------------------
  32. # _installed_nozzle_diameters
  33. # ---------------------------------------------------------------------------
  34. def test_installed_parses_single_nozzle():
  35. assert _installed_nozzle_diameters(_state("0.6")) == [0.6]
  36. def test_installed_parses_dual_nozzle():
  37. assert _installed_nozzle_diameters(_state("0.4", "0.6")) == [0.4, 0.6]
  38. def test_installed_skips_empty_default_stub():
  39. # Single-nozzle printers still emit a 2-entry array; the second is an
  40. # empty-string default until MQTT fills it in.
  41. assert _installed_nozzle_diameters(_state("0.4", "")) == [0.4]
  42. def test_installed_skips_unparseable_and_zero():
  43. assert _installed_nozzle_diameters(_state("", "abc", "0", "0.4")) == [0.4]
  44. def test_installed_handles_no_status_or_no_nozzles():
  45. assert _installed_nozzle_diameters(None) == []
  46. assert _installed_nozzle_diameters(SimpleNamespace()) == []
  47. assert _installed_nozzle_diameters(SimpleNamespace(nozzles=[])) == []
  48. # ---------------------------------------------------------------------------
  49. # _nozzle_mismatch_message
  50. # ---------------------------------------------------------------------------
  51. def test_mismatch_blocks_single_nozzle():
  52. msg = _nozzle_mismatch_message(0.6, [0.4])
  53. assert msg is not None
  54. assert "0.6mm" in msg
  55. assert "0.4mm" in msg
  56. def test_match_single_nozzle_passes():
  57. assert _nozzle_mismatch_message(0.4, [0.4]) is None
  58. def test_match_within_float_tolerance_passes():
  59. # 0.4 slice vs a 0.40000001 reported diameter must not trip.
  60. assert _nozzle_mismatch_message(0.4, [0.40000001]) is None
  61. def test_dual_nozzle_match_on_either_passes():
  62. # 0.6 slice on a printer with a 0.4 and a 0.6 hotend is fine.
  63. assert _nozzle_mismatch_message(0.6, [0.4, 0.6]) is None
  64. def test_dual_nozzle_mismatch_on_both_blocks():
  65. msg = _nozzle_mismatch_message(0.8, [0.4, 0.6])
  66. assert msg is not None
  67. assert "0.4mm / 0.6mm" in msg
  68. def test_no_sliced_diameter_is_failsafe_none():
  69. # Slice didn't declare a nozzle diameter → never block.
  70. assert _nozzle_mismatch_message(None, [0.4]) is None
  71. assert _nozzle_mismatch_message(0.0, [0.4]) is None
  72. def test_no_installed_nozzles_is_failsafe_none():
  73. # Printer hasn't reported nozzles → unknown, never block.
  74. assert _nozzle_mismatch_message(0.6, []) is None
  75. def test_adjacent_sizes_are_distinguished():
  76. # 0.2 gap between adjacent sizes stays well outside the 0.05 tolerance.
  77. assert _nozzle_mismatch_message(0.4, [0.6]) is not None
  78. assert _nozzle_mismatch_message(0.6, [0.8]) is not None
  79. # ---------------------------------------------------------------------------
  80. # Tool-changer rack (#2885)
  81. #
  82. # H2C-1's live telemetry, captured while it was sitting in the state that
  83. # reproduces the bug: both hotends read 0.4, R2 (id 17) is an empty dock and so
  84. # absent from the payload, and id 1 is a hotend whose nozzle is parked back in
  85. # the rack -- it still reports diameter "0.4", but max_temp 0 / serial "N/A"
  86. # say nothing is mounted.
  87. # ---------------------------------------------------------------------------
  88. H2C_NOZZLE_INFO = [
  89. {"id": 0, "diameter": "0.4", "wear": 128, "max_temp": 350, "serial_number": "20D06A611826266"},
  90. {"id": 1, "diameter": "0.4", "wear": 0, "max_temp": 0, "serial_number": "N/A"},
  91. {"id": 16, "diameter": "0.4", "wear": 128, "max_temp": 350, "serial_number": "20D06A630222856"},
  92. {"id": 18, "diameter": "0.4", "wear": 128, "max_temp": 350, "serial_number": "20D06A630227749"},
  93. {"id": 19, "diameter": "0.4", "wear": 128, "max_temp": 350, "serial_number": "20D06A630222810"},
  94. {"id": 20, "diameter": "0.6", "wear": 128, "max_temp": 350, "serial_number": "20D06A610707022"},
  95. {"id": 21, "diameter": "0.2", "wear": 128, "max_temp": 350, "serial_number": "20D06A5C2913952"},
  96. ]
  97. def _h2c_state():
  98. return SimpleNamespace(
  99. nozzles=[SimpleNamespace(nozzle_diameter="0.4"), SimpleNamespace(nozzle_diameter="0.4")],
  100. nozzle_rack=H2C_NOZZLE_INFO,
  101. )
  102. def test_rack_reads_dock_positions_only():
  103. # ids 16-21 are the docks; 0/1 are the hotends and must not leak in.
  104. assert _rack_nozzle_diameters(_h2c_state()) == [0.4, 0.4, 0.4, 0.6, 0.2]
  105. def test_rack_empty_dock_is_absent_not_zero():
  106. # R2 (id 17) held no nozzle and the printer simply omitted it, so five
  107. # entries come back for a six-position rack.
  108. assert len(_rack_nozzle_diameters(_h2c_state())) == 5
  109. def test_rack_empty_on_printers_without_one():
  110. assert _rack_nozzle_diameters(_state("0.4")) == []
  111. assert _rack_nozzle_diameters(None) == []
  112. assert _rack_nozzle_diameters(SimpleNamespace(nozzle_rack=[])) == []
  113. def test_rack_ignores_unparseable_entries():
  114. status = SimpleNamespace(
  115. nozzle_rack=[
  116. {"id": 16, "diameter": ""},
  117. {"id": 17, "diameter": "0"},
  118. {"id": 18, "diameter": "abc"},
  119. {"id": 19, "diameter": "0.4"},
  120. "not-a-dict",
  121. {"id": "x", "diameter": "0.6"},
  122. ]
  123. )
  124. assert _rack_nozzle_diameters(status) == [0.4]
  125. def test_rack_accepts_the_serialised_key_name():
  126. # PrinterState says "diameter"; the REST schema says "nozzle_diameter".
  127. status = SimpleNamespace(nozzle_rack=[{"id": 21, "nozzle_diameter": "0.2"}])
  128. assert _rack_nozzle_diameters(status) == [0.2]
  129. def test_installed_drops_a_hotend_with_no_nozzle_mounted():
  130. # id 1's "0.4" is stale -- the carriage is empty (max_temp 0, serial N/A).
  131. assert _installed_nozzle_diameters(_h2c_state()) == [0.4]
  132. def test_installed_keeps_hotends_when_no_nozzle_info_is_reported():
  133. # Printers that never send nozzle_info behave exactly as before.
  134. assert _installed_nozzle_diameters(_state("0.4", "0.6")) == [0.4, 0.6]
  135. def test_installed_keeps_a_hotend_when_only_one_signal_says_empty():
  136. # Conservative: the explicit "N/A" serial and a missing temperature rating
  137. # must BOTH be present before we discard a reported diameter, so a partial
  138. # payload can never invent a mismatch.
  139. only_serial_says_empty = SimpleNamespace(
  140. nozzles=[SimpleNamespace(nozzle_diameter="0.4")],
  141. nozzle_rack=[{"id": 0, "diameter": "0.4", "max_temp": 350, "serial_number": "N/A"}],
  142. )
  143. only_temp_says_empty = SimpleNamespace(
  144. nozzles=[SimpleNamespace(nozzle_diameter="0.4")],
  145. nozzle_rack=[{"id": 0, "diameter": "0.4", "max_temp": 0, "serial_number": "SN123"}],
  146. )
  147. assert _installed_nozzle_diameters(only_serial_says_empty) == [0.4]
  148. assert _installed_nozzle_diameters(only_temp_says_empty) == [0.4]
  149. def test_installed_keeps_a_hotend_when_the_firmware_reports_neither_field():
  150. # A firmware that sends nozzle_info without max_temp/serial normalises to
  151. # max_temp 0 + serial "". That is "didn't say", not "empty" -- reading it as
  152. # empty would silently switch the #1899 guard off on that machine.
  153. quiet = SimpleNamespace(
  154. nozzles=[SimpleNamespace(nozzle_diameter="0.4"), SimpleNamespace(nozzle_diameter="0.6")],
  155. nozzle_rack=[
  156. {"id": 0, "diameter": "0.4", "max_temp": 0, "serial_number": ""},
  157. {"id": 1, "diameter": "0.6", "max_temp": 0, "serial_number": ""},
  158. ],
  159. )
  160. assert _installed_nozzle_diameters(quiet) == [0.4, 0.6]
  161. # ...and the guard therefore still blocks a genuinely wrong slice.
  162. assert _nozzle_mismatch_message(0.2, _installed_nozzle_diameters(quiet), []) is not None
  163. def test_installed_tolerates_a_non_numeric_max_temp():
  164. odd = SimpleNamespace(
  165. nozzles=[SimpleNamespace(nozzle_diameter="0.4")],
  166. nozzle_rack=[{"id": 0, "diameter": "0.4", "max_temp": "hot", "serial_number": "N/A"}],
  167. )
  168. assert _installed_nozzle_diameters(odd) == [0.4]
  169. def test_docked_nozzle_counts_as_reachable():
  170. # The bug: a 0.2 slice was blocked while a 0.2 sat in R6.
  171. assert _nozzle_mismatch_message(0.2, [0.4], [0.4, 0.6, 0.2]) is None
  172. # And it was never only about 0.2 -- a 0.6 in R5 was blocked the same way.
  173. assert _nozzle_mismatch_message(0.6, [0.4], [0.4, 0.6, 0.2]) is None
  174. def test_h2c_live_state_no_longer_blocks_any_stocked_diameter():
  175. status = _h2c_state()
  176. installed = _installed_nozzle_diameters(status)
  177. rack = _rack_nozzle_diameters(status)
  178. for sliced in (0.2, 0.4, 0.6):
  179. assert _nozzle_mismatch_message(sliced, installed, rack) is None, sliced
  180. def test_diameter_in_neither_hotend_nor_rack_still_blocks():
  181. msg = _nozzle_mismatch_message(0.8, [0.4], [0.4, 0.6, 0.2])
  182. assert msg is not None
  183. assert "0.8mm" in msg
  184. assert "0.4mm installed" in msg
  185. # Deduplicated and rack-labelled, so the user can see what is actually there.
  186. assert "0.4mm / 0.6mm / 0.2mm in the nozzle rack" in msg
  187. def test_message_names_an_empty_carriage_rather_than_claiming_a_size():
  188. msg = _nozzle_mismatch_message(0.8, [], [0.4])
  189. assert msg is not None
  190. assert "no nozzle mounted" in msg
  191. def test_rack_only_still_fail_safe_when_nothing_is_known():
  192. # No hotend and no rack -> unknown, never block.
  193. assert _nozzle_mismatch_message(0.8, [], []) is None
  194. # ---------------------------------------------------------------------------
  195. # End-to-end: the guard fires inside _start_print BEFORE upload
  196. # ---------------------------------------------------------------------------
  197. @pytest.fixture
  198. async def archive_case(tmp_path):
  199. """Build an archive-based queue item on a real in-memory DB + on-disk 3MF."""
  200. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  201. async with engine.begin() as conn:
  202. await conn.run_sync(Base.metadata.create_all)
  203. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  204. async def make_case(*, sliced_nozzle: float | None):
  205. base_dir = tmp_path / "case"
  206. base_dir.mkdir(exist_ok=True)
  207. archive_rel = Path("archives") / "job.3mf"
  208. archive_abs = base_dir / archive_rel
  209. archive_abs.parent.mkdir(parents=True, exist_ok=True)
  210. archive_abs.write_bytes(b"sliced 3mf")
  211. async with session_maker() as db:
  212. printer = Printer(
  213. name="H2S",
  214. serial_number="SN-H2S",
  215. ip_address="127.0.0.1",
  216. access_code="ac",
  217. model="H2S",
  218. )
  219. db.add(printer)
  220. await db.flush()
  221. archive = PrintArchive(
  222. printer_id=printer.id,
  223. filename="job.3mf",
  224. file_path=str(archive_rel),
  225. file_size=archive_abs.stat().st_size,
  226. nozzle_diameter=sliced_nozzle,
  227. status="completed",
  228. )
  229. db.add(archive)
  230. await db.flush()
  231. item = PrintQueueItem(
  232. printer_id=printer.id,
  233. archive_id=archive.id,
  234. status="pending",
  235. bed_levelling="on",
  236. flow_cali="off",
  237. vibration_cali=True,
  238. layer_inspect=False,
  239. timelapse=False,
  240. use_ams=True,
  241. nozzle_offset_cali="on",
  242. )
  243. db.add(item)
  244. await db.commit()
  245. return SimpleNamespace(
  246. session_maker=session_maker,
  247. base_dir=base_dir,
  248. archive_abs=archive_abs,
  249. printer_id=printer.id,
  250. queue_item_id=item.id,
  251. start_print=MagicMock(return_value=True),
  252. upload=AsyncMock(return_value=True),
  253. )
  254. try:
  255. yield make_case
  256. finally:
  257. await engine.dispose()
  258. async def _run_start_print(ctx, *, installed_nozzles, nozzle_rack=None):
  259. scheduler = PrintScheduler()
  260. status = SimpleNamespace(
  261. nozzles=[SimpleNamespace(nozzle_diameter=d) for d in installed_nozzles],
  262. nozzle_rack=nozzle_rack or [],
  263. )
  264. # The mismatch case returns before the upload path; the match case drives it
  265. # to start_print, so mirror the post-guard dependency patches the
  266. # cleanup-library harness uses (get_ftp_retry_settings et al. open their own
  267. # DB session, not our in-memory one, so they must be stubbed).
  268. patches = [
  269. patch.object(scheduler_module.settings, "base_dir", ctx.base_dir),
  270. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  271. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=status)),
  272. patch("backend.app.services.print_scheduler.printer_manager.start_print", ctx.start_print),
  273. patch("backend.app.services.print_scheduler.printer_manager.set_awaiting_plate_clear", MagicMock()),
  274. patch("backend.app.services.print_scheduler.upload_file_async", ctx.upload),
  275. patch("backend.app.services.print_scheduler.delete_file_async", AsyncMock(return_value=True)),
  276. patch("backend.app.services.print_scheduler.cache_3mf_download", MagicMock()),
  277. discarding_spawn_patch(),
  278. patch(
  279. "backend.app.services.print_scheduler.get_ftp_retry_settings", AsyncMock(return_value=(False, 0, 0, 1.0))
  280. ),
  281. patch("backend.app.services.notification_service.notification_service.on_queue_job_started", AsyncMock()),
  282. patch("backend.app.services.notification_service.notification_service.on_queue_job_failed", AsyncMock()),
  283. patch("backend.app.services.mqtt_relay.mqtt_relay.on_queue_job_started", AsyncMock()),
  284. patch("backend.app.services.print_scheduler.ws_manager.send_queue_item_failed", AsyncMock()),
  285. patch.object(scheduler, "_preheat_and_soak", AsyncMock()),
  286. patch.object(scheduler, "_propagate_owner_to_printer_manager", AsyncMock()),
  287. patch.object(scheduler, "_power_off_if_needed", AsyncMock()),
  288. ]
  289. with ExitStack() as stack:
  290. for p in patches:
  291. stack.enter_context(p)
  292. async with ctx.session_maker() as db:
  293. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  294. await scheduler._start_print(db, item)
  295. @pytest.mark.asyncio
  296. async def test_start_print_blocks_on_nozzle_mismatch_before_upload(archive_case):
  297. """0.6 slice on a 0.4-only printer: item fails with an actionable message,
  298. and neither upload nor start_print is reached."""
  299. ctx = await archive_case(sliced_nozzle=0.6)
  300. await _run_start_print(ctx, installed_nozzles=["0.4"])
  301. async with ctx.session_maker() as db:
  302. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  303. assert item.status == "failed"
  304. assert "0.6mm" in item.error_message and "0.4mm" in item.error_message
  305. ctx.upload.assert_not_called()
  306. ctx.start_print.assert_not_called()
  307. @pytest.mark.asyncio
  308. async def test_start_print_proceeds_when_nozzle_matches(archive_case):
  309. """0.6 slice on a 0.6 printer: the guard is a no-op and dispatch proceeds
  310. (item leaves 'pending', start_print is reached)."""
  311. ctx = await archive_case(sliced_nozzle=0.6)
  312. await _run_start_print(ctx, installed_nozzles=["0.6"])
  313. async with ctx.session_maker() as db:
  314. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  315. assert item.status != "failed"
  316. ctx.start_print.assert_called_once()
  317. @pytest.mark.asyncio
  318. async def test_start_print_proceeds_when_the_nozzle_is_in_the_rack(archive_case):
  319. """#2885: a 0.2 slice dispatched to an H2C whose hotends both read 0.4 but
  320. whose rack holds a 0.2 must reach start_print. Before the fix the guard
  321. failed the item here, so the rack picker further down never ran and the
  322. user had to fetch the nozzle by hand on the printer's own UI."""
  323. ctx = await archive_case(sliced_nozzle=0.2)
  324. await _run_start_print(ctx, installed_nozzles=["0.4", "0.4"], nozzle_rack=H2C_NOZZLE_INFO)
  325. async with ctx.session_maker() as db:
  326. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  327. assert item.status != "failed"
  328. ctx.start_print.assert_called_once()
  329. @pytest.mark.asyncio
  330. async def test_start_print_still_blocks_a_diameter_the_rack_lacks(archive_case):
  331. """The rack widens the guard, it does not disable it: 0.8 is in neither a
  332. hotend nor a dock, so the item still fails before upload."""
  333. ctx = await archive_case(sliced_nozzle=0.8)
  334. await _run_start_print(ctx, installed_nozzles=["0.4", "0.4"], nozzle_rack=H2C_NOZZLE_INFO)
  335. async with ctx.session_maker() as db:
  336. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  337. assert item.status == "failed"
  338. assert "nozzle rack" in item.error_message
  339. ctx.upload.assert_not_called()
  340. ctx.start_print.assert_not_called()