test_ams_mapping_per_printer_2799.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. """Regression tests for the cross-printer AMS mapping bug (#2799).
  2. One model queued to three P2S at once produced three queue items carrying a
  3. byte-identical ``ams_mapping``. That mapping was correct for the printer it was
  4. computed against and wrong for the other two, whose AMS held the same spools in
  5. different slots — so two of the three printed the lettering in ASA where the 3MF
  6. strictly requires PETG. An explicit ``ams_mapping`` bypasses the firmware's own
  7. type check, so nothing downstream caught it.
  8. The reproduction below is the real incident: the 3MF needs light-blue PETG in
  9. slot 1 and dark-blue PETG in slot 3; P2S-4 holds them in trays 2 and 1, while
  10. P2S-5 holds them in trays 0 and 2 with ASA in tray 1. ``[2, -1, 1]`` is right on
  11. the first and feeds ASA into slot 3 on the second.
  12. """
  13. import json
  14. from unittest.mock import AsyncMock, MagicMock, patch
  15. import pytest
  16. from backend.app.services.print_scheduler import PrintScheduler
  17. # 3MF requirements: slot 1 light-blue PETG (body), slot 3 dark-blue PETG (text).
  18. REQUIREMENTS = [
  19. {"slot_id": 1, "type": "PETG", "color": "#76D9F4", "tray_info_idx": "GFG99"},
  20. {"slot_id": 3, "type": "PETG", "color": "#2850E0", "tray_info_idx": "GFG99"},
  21. ]
  22. # AMS layouts as reported over MQTT, same spools in a different slot order.
  23. P2S_4_TRAYS = [
  24. {"global_tray_id": 0, "type": "ASA", "color": "161616FF"},
  25. {"global_tray_id": 1, "type": "PETG", "color": "2850E0FF"},
  26. {"global_tray_id": 2, "type": "PETG", "color": "76D9F4FF"},
  27. {"global_tray_id": 3, "type": "ASA", "color": "898989FF"},
  28. ]
  29. P2S_5_TRAYS = [
  30. {"global_tray_id": 0, "type": "PETG", "color": "76D9F4FF"},
  31. {"global_tray_id": 1, "type": "ASA", "color": "161616FF"},
  32. {"global_tray_id": 2, "type": "PETG", "color": "2850E0FF"},
  33. {"global_tray_id": 3, "type": "ASA", "color": "898989FF"},
  34. ]
  35. # The mapping the print dialog stamped onto all three items.
  36. SHARED_MAPPING = [2, -1, 1]
  37. def _item(**overrides):
  38. item = MagicMock()
  39. item.id = 276
  40. item.printer_id = 8
  41. item.created_by_id = None # no creator: unrestricted filament scope (#3522)
  42. item.ams_mapping = json.dumps(SHARED_MAPPING)
  43. item.skip_filament_check = False
  44. item.filament_overrides = None
  45. item.required_filament_types = None
  46. item.manual_start = False
  47. item.filament_short = False
  48. for key, value in overrides.items():
  49. setattr(item, key, value)
  50. return item
  51. def _scheduler(trays, requirements=REQUIREMENTS):
  52. scheduler = PrintScheduler()
  53. scheduler._build_loaded_filaments = MagicMock(return_value=list(trays))
  54. scheduler._get_filament_requirements = AsyncMock(
  55. return_value=[dict(r) for r in requirements] if requirements else None
  56. )
  57. return scheduler
  58. class TestStoredMappingConflict:
  59. """The stored mapping is re-checked against the printer about to run it."""
  60. @pytest.mark.asyncio
  61. async def test_mapping_fits_the_printer_it_was_computed_for(self):
  62. scheduler = _scheduler(P2S_4_TRAYS)
  63. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  64. pm.get_status.return_value = MagicMock()
  65. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), SHARED_MAPPING)
  66. assert conflict is None
  67. @pytest.mark.asyncio
  68. async def test_same_mapping_on_a_differently_loaded_printer_conflicts(self):
  69. """The incident: slot 3 would have printed in ASA."""
  70. scheduler = _scheduler(P2S_5_TRAYS)
  71. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  72. pm.get_status.return_value = MagicMock()
  73. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), SHARED_MAPPING)
  74. assert conflict is not None
  75. assert "slot 3" in conflict
  76. assert "ASA" in conflict
  77. @pytest.mark.asyncio
  78. async def test_tray_not_loaded_conflicts(self):
  79. scheduler = _scheduler(P2S_4_TRAYS[:2]) # trays 2 and 3 removed
  80. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  81. pm.get_status.return_value = MagicMock()
  82. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), SHARED_MAPPING)
  83. assert conflict is not None
  84. assert "does not have loaded" in conflict
  85. @pytest.mark.asyncio
  86. async def test_mapping_too_short_for_the_plate_conflicts(self):
  87. scheduler = _scheduler(P2S_4_TRAYS)
  88. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  89. pm.get_status.return_value = MagicMock()
  90. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [2])
  91. assert conflict is not None
  92. assert "slot 3" in conflict
  93. @pytest.mark.asyncio
  94. async def test_unreported_external_feed_is_not_a_conflict(self):
  95. """An external spool we have not heard about is absence of evidence."""
  96. scheduler = _scheduler(P2S_4_TRAYS)
  97. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  98. pm.get_status.return_value = MagicMock()
  99. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [254, -1, 255])
  100. assert conflict is None
  101. @pytest.mark.asyncio
  102. async def test_external_feed_is_type_checked_like_any_tray(self):
  103. """Two printers with different filament in the external feed is the same
  104. failure this check exists for, so >=254 is not a free pass."""
  105. trays = P2S_4_TRAYS + [{"global_tray_id": 254, "type": "ASA", "color": "161616FF"}]
  106. scheduler = _scheduler(trays)
  107. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  108. pm.get_status.return_value = MagicMock()
  109. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [254, -1, 1])
  110. assert conflict is not None
  111. assert "ASA" in conflict
  112. @pytest.mark.asyncio
  113. async def test_an_external_feed_does_not_excuse_the_rest_of_the_mapping(self):
  114. """An unrecognised >=254 entry is absence of evidence about that slot
  115. only. Bailing out of the whole pass on it let a foreign tray later in
  116. the mapping through unexamined."""
  117. scheduler = _scheduler(P2S_4_TRAYS)
  118. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  119. pm.get_status.return_value = MagicMock()
  120. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [254, -1, 7])
  121. assert conflict is not None
  122. assert "slot 3" in conflict
  123. @pytest.mark.asyncio
  124. async def test_unresolved_required_slot_is_not_a_conflict(self):
  125. """-1 says the matcher had nothing, not that the mapping is foreign.
  126. Recomputing on it would discard the slots the user did resolve by hand;
  127. _block_on_unmatched_filament owns this case instead."""
  128. scheduler = _scheduler(P2S_4_TRAYS)
  129. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  130. pm.get_status.return_value = MagicMock()
  131. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [2, -1, -1])
  132. assert conflict is None
  133. @pytest.mark.asyncio
  134. async def test_foreign_tray_is_caught_without_reading_the_3mf(self):
  135. """The cheap pass runs on live status alone, so a foreign mapping is
  136. rejected without opening the 3MF."""
  137. scheduler = _scheduler(P2S_4_TRAYS)
  138. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  139. pm.get_status.return_value = MagicMock()
  140. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 9, _item(), [7, -1, 1])
  141. assert conflict is not None
  142. assert "does not have loaded" in conflict
  143. scheduler._get_filament_requirements.assert_not_awaited()
  144. @pytest.mark.asyncio
  145. async def test_no_status_is_not_a_conflict(self):
  146. """Absence of evidence never triggers a recompute."""
  147. scheduler = _scheduler(P2S_5_TRAYS)
  148. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  149. pm.get_status.return_value = None
  150. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), SHARED_MAPPING)
  151. assert conflict is None
  152. @pytest.mark.asyncio
  153. async def test_no_trays_reported_yet_is_not_a_conflict(self):
  154. scheduler = _scheduler([])
  155. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  156. pm.get_status.return_value = MagicMock()
  157. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), SHARED_MAPPING)
  158. assert conflict is None
  159. @pytest.mark.asyncio
  160. async def test_unreadable_requirements_is_not_a_conflict(self):
  161. scheduler = _scheduler(P2S_5_TRAYS, requirements=None)
  162. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  163. pm.get_status.return_value = MagicMock()
  164. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), SHARED_MAPPING)
  165. assert conflict is None
  166. @pytest.mark.asyncio
  167. async def test_a_mapping_that_is_not_a_list_is_not_a_conflict(self):
  168. """A corrupted row is not evidence about the printer, and the guard that
  169. keeps it from being indexed was the one thing here without a test."""
  170. scheduler = _scheduler(P2S_5_TRAYS)
  171. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  172. pm.get_status.return_value = MagicMock()
  173. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), {"1": 2})
  174. assert conflict is None
  175. @pytest.mark.asyncio
  176. async def test_a_boolean_is_not_read_as_tray_one(self):
  177. """`true` is an int in Python, so it would otherwise be judged against
  178. whatever tray 1 holds — here ASA, i.e. a conflict reported for a slot
  179. nothing is actually known about."""
  180. scheduler = _scheduler(P2S_5_TRAYS)
  181. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  182. pm.get_status.return_value = MagicMock()
  183. conflict = await scheduler._stored_mapping_conflict(AsyncMock(), 8, _item(), [True, -1, 2])
  184. assert conflict is None
  185. class TestEnsureAmsMappingRevalidates:
  186. """``_ensure_ams_mapping`` acts on the conflict verdict."""
  187. @pytest.mark.asyncio
  188. async def test_conflicting_mapping_is_recomputed(self):
  189. scheduler = _scheduler(P2S_5_TRAYS)
  190. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  191. item = _item()
  192. db = AsyncMock()
  193. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  194. pm.get_status.return_value = MagicMock()
  195. await scheduler._ensure_ams_mapping(db, 8, item)
  196. assert json.loads(item.ams_mapping) == [0, -1, 2]
  197. scheduler._compute_ams_mapping_for_printer.assert_awaited_once()
  198. @pytest.mark.asyncio
  199. async def test_fitting_mapping_is_left_untouched(self):
  200. scheduler = _scheduler(P2S_4_TRAYS)
  201. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  202. item = _item(printer_id=9)
  203. db = AsyncMock()
  204. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  205. pm.get_status.return_value = MagicMock()
  206. await scheduler._ensure_ams_mapping(db, 9, item)
  207. assert json.loads(item.ams_mapping) == SHARED_MAPPING
  208. scheduler._compute_ams_mapping_for_printer.assert_not_awaited()
  209. @pytest.mark.asyncio
  210. async def test_print_anyway_keeps_the_users_mapping(self):
  211. """skip_filament_check is the user overriding exactly this judgement."""
  212. scheduler = _scheduler(P2S_5_TRAYS)
  213. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  214. item = _item(skip_filament_check=True)
  215. db = AsyncMock()
  216. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  217. pm.get_status.return_value = MagicMock()
  218. await scheduler._ensure_ams_mapping(db, 8, item)
  219. assert json.loads(item.ams_mapping) == SHARED_MAPPING
  220. scheduler._compute_ams_mapping_for_printer.assert_not_awaited()
  221. @pytest.mark.asyncio
  222. async def test_failed_recompute_does_not_fall_back_to_the_bad_mapping(self):
  223. scheduler = _scheduler(P2S_5_TRAYS)
  224. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=None)
  225. scheduler._unmappable_without_ams_message = AsyncMock(return_value=None)
  226. item = _item()
  227. db = AsyncMock()
  228. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  229. pm.get_status.return_value = MagicMock()
  230. await scheduler._ensure_ams_mapping(db, 8, item)
  231. assert item.ams_mapping is None
  232. class TestBlockOnUnmatchedFilament:
  233. """A slot the plate prints with no tray on this printer holds the job."""
  234. @pytest.mark.asyncio
  235. async def test_unresolved_required_slot_holds(self):
  236. scheduler = _scheduler(P2S_5_TRAYS)
  237. scheduler._get_job_name = AsyncMock(return_value="body1")
  238. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  239. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  240. db = AsyncMock()
  241. blocked = await scheduler._block_on_unmatched_filament(db, item)
  242. assert blocked is True
  243. assert item.manual_start is True
  244. # The reason names the filament, not a machine token, because it renders
  245. # on the queue row.
  246. assert item.waiting_reason.startswith("Needs ")
  247. assert "PETG" in item.waiting_reason
  248. assert "#2850E0" in item.waiting_reason
  249. @pytest.mark.asyncio
  250. async def test_padding_for_a_slot_this_plate_skips_does_not_hold(self):
  251. """-1 at slot 2, which this plate never prints, is not a missing filament.
  252. This is why the hold intersects with the requirement list rather than
  253. reading the mapping array on its own."""
  254. scheduler = _scheduler(P2S_5_TRAYS)
  255. item = _item(ams_mapping=json.dumps([0, -1, 2]))
  256. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  257. assert blocked is False
  258. assert item.manual_start is False
  259. @pytest.mark.asyncio
  260. async def test_mapping_too_short_for_the_plate_holds(self):
  261. scheduler = _scheduler(P2S_5_TRAYS)
  262. scheduler._get_job_name = AsyncMock(return_value="body1")
  263. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  264. item = _item(ams_mapping=json.dumps([0]))
  265. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  266. assert blocked is True
  267. @pytest.mark.asyncio
  268. async def test_print_anyway_dispatches(self):
  269. scheduler = _scheduler(P2S_5_TRAYS)
  270. item = _item(ams_mapping=json.dumps([0, -1, -1]), skip_filament_check=True)
  271. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  272. assert blocked is False
  273. @pytest.mark.asyncio
  274. async def test_a_mapping_that_resolved_nothing_at_all_holds(self):
  275. """The complete miss used to fall out of this gate and into the ugly path.
  276. `_ensure_ams_mapping` clears a rejected mapping the recompute could not
  277. replace, and bailing on `not item.ams_mapping` then dispatched the item
  278. with no mapping at all: several megabytes uploaded, 0700_8012 from the
  279. firmware, retries burned. Live status reporting loaded trays while the
  280. matcher resolved none of them is a positive finding, so it holds.
  281. """
  282. scheduler = _scheduler(P2S_5_TRAYS)
  283. scheduler._get_job_name = AsyncMock(return_value="body1")
  284. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  285. item = _item(ams_mapping=None)
  286. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  287. pm.get_status.return_value = MagicMock()
  288. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  289. assert blocked is True
  290. assert item.manual_start is True
  291. assert item.waiting_reason.startswith("Needs ")
  292. @pytest.mark.asyncio
  293. async def test_a_cleared_mapping_on_a_printer_with_no_trays_reported_dispatches(self):
  294. """#2589 is the same shape and must stay untouched: there the mapping is
  295. bogus because the AMS was not known yet, and an empty loaded list is
  296. exactly that ignorance. Holding on it would hold on absence of
  297. evidence."""
  298. scheduler = _scheduler([])
  299. item = _item(ams_mapping=None)
  300. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  301. pm.get_status.return_value = MagicMock()
  302. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  303. assert blocked is False
  304. assert item.manual_start is False
  305. @pytest.mark.asyncio
  306. async def test_a_cleared_mapping_with_no_status_dispatches(self):
  307. scheduler = _scheduler(P2S_5_TRAYS)
  308. item = _item(ams_mapping=None)
  309. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  310. pm.get_status.return_value = None
  311. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  312. assert blocked is False
  313. assert item.manual_start is False
  314. @pytest.mark.asyncio
  315. async def test_a_boolean_tray_id_holds_rather_than_reading_as_tray_one(self):
  316. """`true` is an int in Python. A hand-written payload carrying it would
  317. otherwise be read as tray 1 and dispatched as whatever sits there."""
  318. scheduler = _scheduler(P2S_5_TRAYS)
  319. scheduler._get_job_name = AsyncMock(return_value="body1")
  320. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  321. item = _item(ams_mapping=json.dumps([True, -1, 2]))
  322. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  323. assert blocked is True
  324. assert "#76D9F4" in item.waiting_reason
  325. class TestHoldOnTheModelBasedPath:
  326. """A held "any P2S" job must not stay pinned to the P2S that held it.
  327. The model-based path commits `item.printer_id` before the gates run, so a
  328. hold would otherwise leave an unpinned job pinned to the one printer that
  329. could not run it, and the next press of the start button retries the same
  330. dead end. The printer-assigned path keeps its printer: that one was the
  331. user's choice, not the scheduler's.
  332. """
  333. @pytest.mark.asyncio
  334. async def test_a_model_based_hold_releases_the_printer_and_its_mapping(self):
  335. scheduler = _scheduler(P2S_5_TRAYS)
  336. scheduler._get_job_name = AsyncMock(return_value="body1")
  337. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  338. item = _item(
  339. ams_mapping=json.dumps([0, -1, -1]),
  340. nozzle_mapping=json.dumps([16, -1]),
  341. nozzle_rack_choice=json.dumps({"0": 16}),
  342. )
  343. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item, release_assignment=True)
  344. assert blocked is True
  345. assert item.printer_id is None
  346. # So do the nozzle positions, which name that printer's rack.
  347. assert item.nozzle_mapping is None and item.nozzle_rack_choice is None
  348. # The mapping goes with the assignment: its tray IDs were resolved
  349. # against the printer just released, so leaving it would hold the job
  350. # again on the next printer even when that one has the filament.
  351. assert item.ams_mapping is None
  352. assert item.waiting_reason.startswith("Needs ")
  353. @pytest.mark.asyncio
  354. async def test_the_notification_still_names_the_printer_that_held_it(self):
  355. scheduler = _scheduler(P2S_5_TRAYS)
  356. scheduler._get_job_name = AsyncMock(return_value="body1")
  357. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  358. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  359. await scheduler._block_on_unmatched_filament(AsyncMock(), item, release_assignment=True)
  360. # Looked up before the release, or it would be looked up as None.
  361. assert scheduler._get_printer.await_args.args[1] == 8
  362. @pytest.mark.asyncio
  363. async def test_a_printer_assigned_hold_keeps_both(self):
  364. scheduler = _scheduler(P2S_5_TRAYS)
  365. scheduler._get_job_name = AsyncMock(return_value="body1")
  366. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  367. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  368. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  369. assert blocked is True
  370. assert item.printer_id == 8
  371. assert json.loads(item.ams_mapping) == [0, -1, -1]
  372. @pytest.mark.asyncio
  373. async def test_unreadable_requirements_dispatches(self):
  374. scheduler = _scheduler(P2S_5_TRAYS, requirements=None)
  375. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  376. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  377. assert blocked is False
  378. @pytest.mark.asyncio
  379. async def test_nozzle_bound_filament_on_the_wrong_side_holds(self):
  380. """The H2D case the type-only scan waved through: PETG is loaded, but on
  381. the other nozzle's AMS, so the nozzle-aware matcher left the slot at -1.
  382. Reading the mapping inherits that restriction for free."""
  383. scheduler = _scheduler(P2S_5_TRAYS)
  384. scheduler._get_job_name = AsyncMock(return_value="body1")
  385. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="H2D"))
  386. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  387. blocked = await scheduler._block_on_unmatched_filament(AsyncMock(), item)
  388. assert blocked is True
  389. class TestModelBasedVirtualPrinterMapping:
  390. """A model-based Virtual Printer stamps a mapping nothing can attribute.
  391. `virtual_printer/manager.py` writes the slicer's own AMS pick onto the queue
  392. item it creates, on the line below `printer_id=self.target_printer_id` —
  393. which is None for an "Any P2S" VP. So the tray IDs the slicer resolved are
  394. carried by an item the scheduler will hand to whichever printer of that
  395. model happens to be free, and the row itself records no printer they could
  396. be checked against. Same failure as the print dialog's, arriving from a
  397. different direction, and reachable whenever the per-VP `save_ams_mapping`
  398. opt-in is on without `queue_force_color_match`.
  399. The item has no `printer_id` until the model-based path assigns one, so
  400. these go through `_ensure_ams_mapping`'s `printer_id` argument rather than
  401. `item.printer_id` — which is how that path calls it.
  402. """
  403. @pytest.mark.asyncio
  404. async def test_slicer_mapping_is_rechecked_against_the_printer_chosen_for_it(self):
  405. scheduler = _scheduler(P2S_5_TRAYS)
  406. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  407. # Fresh from the VP: no printer_id, mapping resolved by the slicer.
  408. item = _item(printer_id=None)
  409. db = AsyncMock()
  410. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  411. pm.get_status.return_value = MagicMock()
  412. await scheduler._ensure_ams_mapping(db, 10, item)
  413. assert json.loads(item.ams_mapping) == [0, -1, 2]
  414. # Judged against the printer the scheduler picked, not the row's own
  415. # (absent) one.
  416. scheduler._compute_ams_mapping_for_printer.assert_awaited_once()
  417. assert scheduler._compute_ams_mapping_for_printer.await_args.args[1] == 10
  418. @pytest.mark.asyncio
  419. async def test_slicer_mapping_survives_on_a_printer_it_happens_to_fit(self):
  420. """Not every VP mapping is wrong — one that fits the chosen printer is
  421. kept, so the slicer's deliberate slot pick is not thrown away."""
  422. scheduler = _scheduler(P2S_4_TRAYS)
  423. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  424. item = _item(printer_id=None)
  425. db = AsyncMock()
  426. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  427. pm.get_status.return_value = MagicMock()
  428. await scheduler._ensure_ams_mapping(db, 9, item)
  429. assert json.loads(item.ams_mapping) == SHARED_MAPPING
  430. scheduler._compute_ams_mapping_for_printer.assert_not_awaited()
  431. class TestFilamentRequirementMemo:
  432. """The two gates parse the same 3MF per dispatch attempt (#2799 review).
  433. A one-file fan-out to many idle printers repeats that for every one of them
  434. inside a single pass, each time a DB lookup plus a zip open and XML parse.
  435. The memo is scoped to the pass so a file re-sliced between ticks is re-read.
  436. """
  437. @staticmethod
  438. def _db_returning(archive):
  439. result = MagicMock()
  440. result.scalar_one_or_none.return_value = archive
  441. db = AsyncMock()
  442. db.execute = AsyncMock(return_value=result)
  443. return db
  444. @pytest.fixture
  445. def parsed(self, tmp_path, monkeypatch):
  446. from backend.app.services import print_scheduler as ps
  447. (tmp_path / "plate.3mf").write_bytes(b"")
  448. monkeypatch.setattr(ps.settings, "base_dir", tmp_path)
  449. calls = []
  450. def fake_extract(path, plate_id=None):
  451. calls.append((path, plate_id))
  452. return [{"slot_id": 1, "type": "PETG", "color": "#76D9F4", "tray_info_idx": ""}]
  453. monkeypatch.setattr(
  454. "backend.app.services.filament_requirements.extract_filament_requirements",
  455. fake_extract,
  456. )
  457. return calls
  458. @pytest.mark.asyncio
  459. async def test_the_same_plate_is_parsed_once_per_pass(self, parsed):
  460. scheduler = PrintScheduler()
  461. db = self._db_returning(MagicMock(file_path="plate.3mf"))
  462. item = _item(archive_id=731, library_file_id=None, plate_id=22)
  463. await scheduler._get_filament_requirements(db, item)
  464. await scheduler._get_filament_requirements(db, item)
  465. assert len(parsed) == 1
  466. @pytest.mark.asyncio
  467. async def test_each_caller_gets_its_own_copy(self, parsed):
  468. """`_apply_filament_overrides` rewrites these dicts in place, so handing
  469. out the cached list would leak one item's overrides into the next."""
  470. scheduler = PrintScheduler()
  471. db = self._db_returning(MagicMock(file_path="plate.3mf"))
  472. item = _item(archive_id=731, library_file_id=None, plate_id=22)
  473. first = await scheduler._get_filament_requirements(db, item)
  474. first[0]["type"] = "ASA" # an override applied by one caller
  475. second = await scheduler._get_filament_requirements(db, item)
  476. assert second[0]["type"] == "PETG"
  477. @pytest.mark.asyncio
  478. async def test_a_different_plate_is_parsed_separately(self, parsed):
  479. scheduler = PrintScheduler()
  480. db = self._db_returning(MagicMock(file_path="plate.3mf"))
  481. await scheduler._get_filament_requirements(db, _item(archive_id=731, library_file_id=None, plate_id=22))
  482. await scheduler._get_filament_requirements(db, _item(archive_id=731, library_file_id=None, plate_id=23))
  483. assert len(parsed) == 2
  484. @pytest.mark.asyncio
  485. async def test_the_memo_does_not_outlive_the_pass(self, parsed):
  486. """check_queue clears it at the top of every pass."""
  487. scheduler = PrintScheduler()
  488. db = self._db_returning(MagicMock(file_path="plate.3mf"))
  489. item = _item(archive_id=731, library_file_id=None, plate_id=22)
  490. await scheduler._get_filament_requirements(db, item)
  491. scheduler._filament_req_memo.clear()
  492. await scheduler._get_filament_requirements(db, item)
  493. assert len(parsed) == 2
  494. @pytest.mark.asyncio
  495. async def test_an_unreadable_file_is_remembered_too(self, parsed):
  496. """The miss is worth caching as well — otherwise a missing file costs a
  497. DB lookup per gate per attempt for nothing."""
  498. scheduler = PrintScheduler()
  499. db = self._db_returning(None)
  500. item = _item(archive_id=999, library_file_id=None, plate_id=1)
  501. assert await scheduler._get_filament_requirements(db, item) is None
  502. assert await scheduler._get_filament_requirements(db, item) is None
  503. assert db.execute.await_count == 1
  504. class TestTheHoldReasonSurvivesTheNextPass:
  505. """The reason is the hold's whole explanation, so a later pass must keep it.
  506. Since #3074 the scheduler clears the reason of every staged item on each
  507. pass, because a reason left from before staging would otherwise stand
  508. forever. The unmatched-filament hold writes its reason at the moment it
  509. stages the item, so clearing it would leave a job that waits for a start
  510. press with nothing on the row saying which spool to load.
  511. """
  512. @pytest.fixture
  513. async def session_maker(self):
  514. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  515. import backend.app.models # noqa: F401 - populate Base.metadata
  516. from backend.app.core.database import Base
  517. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  518. async with engine.begin() as conn:
  519. await conn.run_sync(Base.metadata.create_all)
  520. try:
  521. yield async_sessionmaker(engine, expire_on_commit=False)
  522. finally:
  523. await engine.dispose()
  524. async def _staged_item(self, session_maker, reason):
  525. from backend.app.models.print_queue import PrintQueueItem
  526. from backend.app.models.printer import Printer
  527. async with session_maker() as db:
  528. printer = Printer(
  529. name="P2S-5", serial_number="SERIAL", ip_address="10.0.0.1", access_code="code", model="P2S"
  530. )
  531. db.add(printer)
  532. await db.flush()
  533. item = PrintQueueItem(
  534. printer_id=printer.id, status="pending", position=0, manual_start=True, waiting_reason=reason
  535. )
  536. db.add(item)
  537. await db.commit()
  538. return item.id
  539. async def _reason_after_a_pass(self, session_maker, item_id):
  540. from backend.app.models.print_queue import PrintQueueItem
  541. scheduler = PrintScheduler()
  542. with (
  543. patch("backend.app.services.print_scheduler.async_session", session_maker),
  544. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  545. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=None)),
  546. patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
  547. patch.object(scheduler, "_check_auto_drying", AsyncMock()),
  548. ):
  549. await scheduler.check_queue()
  550. async with session_maker() as db:
  551. return (await db.get(PrintQueueItem, item_id)).waiting_reason
  552. @pytest.mark.asyncio
  553. async def test_the_hold_reason_stays_on_a_staged_item(self, session_maker):
  554. item_id = await self._staged_item(session_maker, "Needs PETG #2850E0")
  555. assert await self._reason_after_a_pass(session_maker, item_id) == "Needs PETG #2850E0"
  556. @pytest.mark.asyncio
  557. async def test_any_other_reason_on_a_staged_item_is_still_cleared(self, session_maker):
  558. """#3074's rule for everything else is unchanged."""
  559. item_id = await self._staged_item(session_maker, "Busy: P2S-5")
  560. assert await self._reason_after_a_pass(session_maker, item_id) is None
  561. def _matching_scheduler(trays):
  562. """A scheduler whose real matcher runs against ``trays``."""
  563. scheduler = _scheduler(trays)
  564. scheduler._get_bool_setting = AsyncMock(return_value=False)
  565. scheduler._get_job_name = AsyncMock(return_value="body1")
  566. scheduler._get_printer = AsyncMock(return_value=MagicMock(model="P2S"))
  567. return scheduler
  568. class TestUnresolvedSlotsAreMatchedAgain:
  569. """A fitting mapping keeps its resolved slots and has only its gaps matched again.
  570. The hold keeps a pinned item's mapping, and an unresolved slot is not a
  571. conflict, so without this nothing would look at the gap again: loading the
  572. missing spool and pressing Start would hold the job again, every time.
  573. """
  574. @pytest.mark.asyncio
  575. async def test_a_spool_loaded_after_the_hold_is_found(self):
  576. # Held with slot 3 unresolved; dark-blue PETG has since gone into tray 2.
  577. scheduler = _matching_scheduler(P2S_5_TRAYS)
  578. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  579. db = AsyncMock()
  580. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  581. pm.get_status.return_value = MagicMock()
  582. await scheduler._ensure_ams_mapping(db, 8, item)
  583. blocked = await scheduler._block_on_unmatched_filament(db, item)
  584. assert json.loads(item.ams_mapping) == [0, -1, 2]
  585. assert blocked is False
  586. @pytest.mark.asyncio
  587. async def test_a_tray_the_user_picked_is_kept_and_not_handed_out_twice(self):
  588. """The user put slot 1 on tray 2 by hand. Slot 3's best match is that same
  589. tray, but it is taken, so slot 3 gets the other PETG instead of sharing."""
  590. scheduler = _matching_scheduler(P2S_5_TRAYS)
  591. item = _item(ams_mapping=json.dumps([2, -1, -1]))
  592. db = AsyncMock()
  593. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  594. pm.get_status.return_value = MagicMock()
  595. await scheduler._ensure_ams_mapping(db, 8, item)
  596. assert json.loads(item.ams_mapping) == [2, -1, 0]
  597. @pytest.mark.asyncio
  598. async def test_still_missing_leaves_the_mapping_and_holds(self):
  599. trays = [
  600. {"global_tray_id": 0, "type": "PETG", "color": "76D9F4FF"},
  601. {"global_tray_id": 1, "type": "ASA", "color": "161616FF"},
  602. ]
  603. scheduler = _matching_scheduler(trays)
  604. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  605. db = AsyncMock()
  606. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  607. pm.get_status.return_value = MagicMock()
  608. await scheduler._ensure_ams_mapping(db, 8, item)
  609. blocked = await scheduler._block_on_unmatched_filament(db, item)
  610. assert json.loads(item.ams_mapping) == [0, -1, -1]
  611. assert blocked is True
  612. @pytest.mark.asyncio
  613. async def test_print_anyway_leaves_the_gap_alone(self):
  614. scheduler = _matching_scheduler(P2S_5_TRAYS)
  615. item = _item(ams_mapping=json.dumps([0, -1, -1]), skip_filament_check=True)
  616. db = AsyncMock()
  617. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  618. pm.get_status.return_value = MagicMock()
  619. await scheduler._ensure_ams_mapping(db, 8, item)
  620. assert json.loads(item.ams_mapping) == [0, -1, -1]
  621. @pytest.mark.asyncio
  622. async def test_a_complete_mapping_is_not_matched_again(self):
  623. scheduler = _matching_scheduler(P2S_5_TRAYS)
  624. scheduler._compute_ams_mapping_for_printer = AsyncMock(return_value=[0, -1, 2])
  625. item = _item(ams_mapping=json.dumps([0, -1, 2]))
  626. db = AsyncMock()
  627. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  628. pm.get_status.return_value = MagicMock()
  629. await scheduler._ensure_ams_mapping(db, 8, item)
  630. scheduler._compute_ams_mapping_for_printer.assert_not_awaited()
  631. class TestMissingFilamentForStart:
  632. """The Start button's question: would this item be held again right now?"""
  633. @pytest.mark.asyncio
  634. async def test_names_a_filament_that_is_still_not_loaded(self):
  635. trays = [
  636. {"global_tray_id": 0, "type": "PETG", "color": "76D9F4FF"},
  637. {"global_tray_id": 1, "type": "ASA", "color": "161616FF"},
  638. ]
  639. scheduler = _matching_scheduler(trays)
  640. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  641. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  642. pm.get_status.return_value = MagicMock()
  643. missing = await scheduler.missing_filament_for_start(AsyncMock(), item)
  644. assert missing is not None and len(missing) == 1
  645. assert "PETG" in missing[0] and "#2850E0" in missing[0]
  646. # Asking is not acting: the stored mapping is the scheduler's to change.
  647. assert json.loads(item.ams_mapping) == [0, -1, -1]
  648. @pytest.mark.asyncio
  649. async def test_nothing_missing_once_the_spool_is_loaded(self):
  650. scheduler = _matching_scheduler(P2S_5_TRAYS)
  651. item = _item(ams_mapping=json.dumps([0, -1, -1]))
  652. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  653. pm.get_status.return_value = MagicMock()
  654. assert await scheduler.missing_filament_for_start(AsyncMock(), item) is None
  655. @pytest.mark.asyncio
  656. async def test_a_mapping_from_another_printer_is_judged_by_a_fresh_match(self):
  657. """The #2799 mapping on P2S-5 conflicts, so Start judges a fresh match,
  658. which finds both filaments."""
  659. scheduler = _matching_scheduler(P2S_5_TRAYS)
  660. item = _item()
  661. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  662. pm.get_status.return_value = MagicMock()
  663. assert await scheduler.missing_filament_for_start(AsyncMock(), item) is None
  664. @pytest.mark.asyncio
  665. async def test_no_mapping_and_nothing_matching_is_missing(self):
  666. trays = [{"global_tray_id": 0, "type": "ASA", "color": "161616FF"}]
  667. scheduler = _matching_scheduler(trays)
  668. item = _item(ams_mapping=None)
  669. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  670. pm.get_status.return_value = MagicMock()
  671. missing = await scheduler.missing_filament_for_start(AsyncMock(), item)
  672. assert missing is not None and len(missing) == 2
  673. @pytest.mark.asyncio
  674. @pytest.mark.parametrize(
  675. "overrides",
  676. [
  677. {"skip_filament_check": True},
  678. # A model-based item picks its printer at dispatch.
  679. {"printer_id": None},
  680. ],
  681. )
  682. async def test_does_not_judge_what_dispatch_would_not(self, overrides):
  683. trays = [{"global_tray_id": 0, "type": "ASA", "color": "161616FF"}]
  684. scheduler = _matching_scheduler(trays)
  685. item = _item(ams_mapping=None, **overrides)
  686. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  687. pm.get_status.return_value = MagicMock()
  688. assert await scheduler.missing_filament_for_start(AsyncMock(), item) is None
  689. @pytest.mark.asyncio
  690. async def test_no_status_is_not_a_finding(self):
  691. scheduler = _matching_scheduler(P2S_5_TRAYS)
  692. item = _item(ams_mapping=None)
  693. with patch("backend.app.services.print_scheduler.printer_manager") as pm:
  694. pm.get_status.return_value = None
  695. assert await scheduler.missing_filament_for_start(AsyncMock(), item) is None