test_scheduler_nozzle_pick_3536.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. """Nozzle-aware printer pick for "Any <model>" queue items (#3536).
  2. Before #3536 the model-based pick looked at model, filament and state but not
  3. at the nozzle: a file sliced for 0.6 mm could be assigned to a printer with a
  4. 0.4 mm nozzle and then fail in ``_start_print``. These tests cover the pieces
  5. of the fix in order: the sliced diameter carried on each candidate, then the
  6. printer filter built on it.
  7. """
  8. from contextlib import ExitStack
  9. from types import SimpleNamespace
  10. from unittest.mock import AsyncMock, MagicMock, patch
  11. import pytest
  12. from sqlalchemy import select
  13. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  14. from sqlalchemy.orm import selectinload
  15. import backend.app.models # noqa: F401 - populate Base.metadata
  16. from backend.app.core.database import Base
  17. from backend.app.core.printer_scope import ALL_PRINTERS
  18. from backend.app.models.library import LibraryFile
  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. _asks_nothing_new,
  24. _candidates_for,
  25. _ModelCandidate,
  26. _sliced_nozzle,
  27. _wrong_nozzle_label,
  28. )
  29. from backend.tests.unit.test_scheduler_dispatch_order_2915 import PRINTERS as ORDER_PRINTERS, _farm
  30. # --- Sliced diameter per candidate -------------------------------------------
  31. def _item(*, variants=None, archive=None, library_file=None):
  32. return SimpleNamespace(
  33. variants=variants or [],
  34. archive=archive,
  35. archive_id=1 if archive is not None else None,
  36. library_file=library_file,
  37. library_file_id=2 if library_file is not None else None,
  38. target_model="A1",
  39. required_filament_types=None,
  40. filament_overrides=None,
  41. )
  42. def _variant(vid, nozzle):
  43. return SimpleNamespace(
  44. id=vid,
  45. position=vid,
  46. attempt_count=0,
  47. target_model="A1",
  48. required_filament_types=None,
  49. filament_overrides=None,
  50. library_file=SimpleNamespace(deleted_at=None, file_metadata={"nozzle_diameter": nozzle}),
  51. )
  52. def test_sliced_nozzle_from_archive():
  53. assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=0.6), None) == 0.6
  54. def test_sliced_nozzle_from_library_metadata():
  55. assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": 0.6})) == 0.6
  56. def test_sliced_nozzle_unknown():
  57. assert _sliced_nozzle(None, SimpleNamespace(file_metadata=None)) is None
  58. assert _sliced_nozzle(None, SimpleNamespace(file_metadata={})) is None
  59. assert _sliced_nozzle(None, None) is None
  60. def test_sliced_nozzle_rejects_garbage_and_non_positive():
  61. assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=0), None) is None
  62. assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=-0.4), None) is None
  63. assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": "abc"})) is None
  64. assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": [0.4]})) is None
  65. assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": "0.6"})) == 0.6
  66. def test_sliced_nozzle_is_read_without_rounding():
  67. # The tolerance lives in _nozzle_mismatch_message, not here.
  68. meta = SimpleNamespace(file_metadata={"nozzle_diameter": "0.6000001"})
  69. assert _sliced_nozzle(None, meta) == 0.6000001
  70. def test_candidates_carry_their_own_nozzle():
  71. single = _item(library_file=SimpleNamespace(file_metadata={"nozzle_diameter": 0.6}))
  72. assert [c.sliced_nozzle for c in _candidates_for(single)] == [0.6]
  73. multi = _item(variants=[_variant(1, 0.4), _variant(2, 0.6)])
  74. assert sorted(c.sliced_nozzle for c in _candidates_for(multi)) == [0.4, 0.6]
  75. # --- Does this nozzle fit? ---------------------------------------------------
  76. def _state(*diameters: str):
  77. """PrinterState-shaped namespace with the given nozzle diameter strings."""
  78. return SimpleNamespace(nozzles=[SimpleNamespace(nozzle_diameter=d) for d in diameters])
  79. def _h2c(*rack: tuple[int, str], mounted: str = "0.4"):
  80. """H2C-shaped state: one mounted hotend plus docked nozzles (#2885 shape)."""
  81. info = [{"id": 0, "diameter": mounted, "wear": 0, "max_temp": 350, "serial_number": "SN0"}]
  82. info += [
  83. {"id": nozzle_id, "diameter": d, "wear": 0, "max_temp": 350, "serial_number": f"SN{nozzle_id}"}
  84. for nozzle_id, d in rack
  85. ]
  86. return SimpleNamespace(nozzles=[SimpleNamespace(nozzle_diameter=mounted)], nozzle_rack=info)
  87. def test_wrong_nozzle_label_single_and_dual():
  88. assert _wrong_nozzle_label("A1-1", _state("0.4"), 0.6) == "A1-1 (0.4mm)"
  89. assert _wrong_nozzle_label("A1-1", _state("0.6"), 0.6) is None
  90. assert _wrong_nozzle_label("H2D-1", _state("0.4", "0.4"), 0.6) == "H2D-1 (0.4mm)"
  91. assert _wrong_nozzle_label("H2D-1", _state("0.4", "0.6"), 0.6) is None
  92. def test_wrong_nozzle_label_unknown_fits():
  93. assert _wrong_nozzle_label("A1-1", _state("0.4"), None) is None
  94. assert _wrong_nozzle_label("A1-1", _state("0.4"), 0) is None
  95. assert _wrong_nozzle_label("A1-1", None, 0.6) is None
  96. assert _wrong_nozzle_label("A1-1", _state(""), 0.6) is None # nothing reported
  97. def test_wrong_nozzle_label_rack():
  98. assert _wrong_nozzle_label("H2C-1", _h2c((16, "0.6")), 0.6) is None
  99. assert _wrong_nozzle_label("H2C-1", _h2c((16, "0.2"), (18, "0.8")), 0.6) == "H2C-1 (0.4mm, rack 0.2mm / 0.8mm)"
  100. def test_wrong_nozzle_label_rack_without_mounted_nozzle():
  101. status = SimpleNamespace(
  102. nozzles=[SimpleNamespace(nozzle_diameter="")],
  103. nozzle_rack=[{"id": 16, "diameter": "0.2", "max_temp": 350, "serial_number": "SN16"}],
  104. )
  105. assert _wrong_nozzle_label("H2C-1", status, 0.6) == "H2C-1 (no nozzle mounted, rack 0.2mm)"
  106. SIZES = ["0.2", "0.4", "0.6", "0.8"]
  107. @pytest.mark.parametrize("sliced", SIZES)
  108. @pytest.mark.parametrize("installed", SIZES)
  109. def test_only_the_same_size_fits(sliced, installed):
  110. # Same size fits, every other (also the neighbouring one) never does.
  111. label = _wrong_nozzle_label("A1-1", _state(installed), float(sliced))
  112. if sliced == installed:
  113. assert label is None
  114. else:
  115. assert label == f"A1-1 ({installed}mm)"
  116. def test_float_noise_from_metadata_still_fits():
  117. assert _wrong_nozzle_label("A1-1", _state("0.6"), 0.6000001) is None
  118. assert _wrong_nozzle_label("A1-1", _state("0.4"), 0.6000001) == "A1-1 (0.4mm)"
  119. # --- Matcher: passes over a printer with the wrong nozzle --------------------
  120. @pytest.fixture
  121. async def a1_farm():
  122. """Two A1s in "Workshop"; A1-1 is the one with fewer print hours."""
  123. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  124. async with engine.begin() as conn:
  125. await conn.run_sync(Base.metadata.create_all)
  126. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  127. async with session_maker() as db:
  128. db.add_all(
  129. [
  130. Printer(
  131. id=pid,
  132. name=f"A1-{pid}",
  133. serial_number=f"A1000{pid}",
  134. ip_address=f"192.0.2.{pid}",
  135. access_code="x",
  136. model="A1",
  137. is_active=True,
  138. location="Workshop",
  139. runtime_seconds=pid * 3600,
  140. )
  141. for pid in (1, 2)
  142. ]
  143. )
  144. await db.commit()
  145. try:
  146. yield SimpleNamespace(session_maker=session_maker)
  147. finally:
  148. await engine.dispose()
  149. async def _find(ctx, scheduler, states, *, model="A1", exclude=frozenset(), connected=True, idle=None, **kwargs):
  150. """Run the matcher; ``states`` maps printer id to its reported state (or None)."""
  151. idle = idle or {}
  152. with (
  153. patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
  154. patch(
  155. "backend.app.services.print_scheduler.printer_manager.is_connected",
  156. lambda pid: connected if not callable(connected) else connected(pid),
  157. ),
  158. patch.object(scheduler, "_is_printer_idle", lambda pid, *_a, **_k: idle.get(pid, True)),
  159. ):
  160. async with ctx.session_maker() as db:
  161. return await scheduler._find_idle_printer_for_model(db, model, set(exclude), **kwargs)
  162. class TestMatcherNozzle:
  163. @pytest.mark.asyncio
  164. async def test_skips_the_printer_with_the_wrong_nozzle(self, a1_farm):
  165. states = {1: _state("0.4"), 2: _state("0.6")}
  166. assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (2, None)
  167. @pytest.mark.asyncio
  168. async def test_no_printer_fits_names_every_nozzle(self, a1_farm):
  169. states = {1: _state("0.4"), 2: _state("0.4")}
  170. assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (
  171. None,
  172. "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)",
  173. )
  174. @pytest.mark.asyncio
  175. async def test_reason_names_the_location(self, a1_farm):
  176. states = {1: _state("0.4"), 2: _state("0.4")}
  177. _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6, target_location="Workshop")
  178. assert reason.startswith("No A1 in Workshop has a 0.6mm nozzle: ")
  179. @pytest.mark.asyncio
  180. async def test_float_noise_in_the_sliced_size_is_not_shown(self, a1_farm):
  181. states = {1: _state("0.4"), 2: _state("0.4")}
  182. _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6000001)
  183. assert reason.startswith("No A1 has a 0.6mm nozzle: ")
  184. @pytest.mark.asyncio
  185. async def test_unknown_sliced_nozzle_behaves_as_before(self, a1_farm):
  186. states = {1: _state("0.4"), 2: _state("0.6")}
  187. assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=None) == (1, None)
  188. @pytest.mark.asyncio
  189. async def test_printer_without_status_fits(self, a1_farm):
  190. states = {1: None, 2: _state("0.4")}
  191. assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (1, None)
  192. @pytest.mark.asyncio
  193. async def test_wrong_nozzle_printer_does_not_hide_a_busy_matching_one(self, a1_farm):
  194. """The only printer that fits is busy: the job just waits, silently."""
  195. states = {1: _state("0.4"), 2: _state("0.6")}
  196. pick, reason = await _find(a1_farm, PrintScheduler(), states, exclude={2}, sliced_nozzle=0.6)
  197. assert pick is None
  198. assert reason == "Busy: A1-2"
  199. assert PrintScheduler._is_busy_only(reason) is True
  200. @pytest.mark.asyncio
  201. async def test_busy_or_offline_wrong_nozzle_printers_read_as_nozzle_not_busy(self, a1_farm):
  202. """A1-1 is printing, A1-2 offline, both 0.4: waiting would never help."""
  203. states = {1: _state("0.4"), 2: _state("0.4")}
  204. pick, reason = await _find(
  205. a1_farm,
  206. PrintScheduler(),
  207. states,
  208. connected=lambda pid: pid == 1,
  209. idle={1: False},
  210. sliced_nozzle=0.6,
  211. )
  212. assert pick is None
  213. assert reason == "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)"
  214. @pytest.mark.asyncio
  215. async def test_excluded_wrong_nozzle_printer_is_not_listed_as_busy(self, a1_farm):
  216. states = {1: _state("0.4"), 2: _state("0.4")}
  217. _, reason = await _find(a1_farm, PrintScheduler(), states, exclude={1, 2}, sliced_nozzle=0.6)
  218. assert reason.startswith("No A1 has a 0.6mm nozzle: ")
  219. @pytest.mark.asyncio
  220. async def test_nozzle_reason_is_not_busy_only_and_asks_something(self, a1_farm):
  221. states = {1: _state("0.4"), 2: _state("0.4")}
  222. _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6)
  223. assert PrintScheduler._is_busy_only(reason) is False
  224. assert _asks_nothing_new(reason) is False
  225. @pytest.mark.asyncio
  226. async def test_missing_filament_and_wrong_nozzle_mixed(self, a1_farm):
  227. """A1-1 has the wrong nozzle, A1-2 fits but lacks PETG: only the filament is named."""
  228. scheduler = PrintScheduler()
  229. states = {1: _state("0.4"), 2: _state("0.6")}
  230. with patch.object(
  231. scheduler, "_get_missing_filament_types", lambda pid, _types, *_a, **_k: ["PETG"] if pid == 2 else []
  232. ):
  233. pick, reason = await _find(a1_farm, scheduler, states, sliced_nozzle=0.6, required_filament_types=["PETG"])
  234. assert pick is None
  235. assert reason == "Waiting for filament: A1-2 (needs PETG)"
  236. # --- Wake path: does not power on a printer with the wrong nozzle ------------
  237. class TestWakeNozzle:
  238. async def _wake(self, ctx, sliced_nozzle):
  239. scheduler = PrintScheduler()
  240. plug = SimpleNamespace(id=1, auto_on=True, enabled=True, controls_printer_power=True)
  241. power_on = AsyncMock(return_value=True)
  242. # Both printers are off but keep their last status (A1-1 0.4, A1-2 0.6).
  243. states = {1: _state("0.4"), 2: _state("0.6")}
  244. with (
  245. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=False)),
  246. patch(
  247. "backend.app.services.print_scheduler.printer_manager.is_awaiting_plate_clear",
  248. MagicMock(return_value=False),
  249. ),
  250. patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
  251. patch.object(scheduler, "_cached_filament_shortfall", MagicMock(return_value=[])),
  252. patch.object(scheduler, "_get_smart_plugs", AsyncMock(return_value=[plug])),
  253. patch.object(scheduler, "_power_on_and_wait", power_on),
  254. ):
  255. async with ctx.session_maker() as db:
  256. return await scheduler._wake_printer_for_model(
  257. db,
  258. [
  259. _ModelCandidate(
  260. target_model="A1",
  261. sliced_for=None,
  262. required_filament_types=None,
  263. filament_overrides=None,
  264. sliced_nozzle=sliced_nozzle,
  265. )
  266. ],
  267. None,
  268. set(),
  269. {1, 2},
  270. require_plate_clear=False,
  271. )
  272. @pytest.mark.asyncio
  273. async def test_wakes_the_printer_whose_nozzle_fits(self, a1_farm):
  274. assert await self._wake(a1_farm, 0.6) == (2, 2)
  275. @pytest.mark.asyncio
  276. async def test_unknown_sliced_nozzle_wakes_the_least_worn_as_before(self, a1_farm):
  277. assert await self._wake(a1_farm, None) == (1, 1)
  278. # --- Queue pass: end to end ---------------------------------------------------
  279. async def _add_any_a1(ctx, nozzle, **fields):
  280. async with ctx.session_maker() as db:
  281. lib = LibraryFile(
  282. filename="part-a.gcode.3mf",
  283. file_path="/library/part-a.gcode.3mf",
  284. file_size=10,
  285. file_type="gcode.3mf",
  286. file_metadata={"nozzle_diameter": nozzle},
  287. )
  288. db.add(lib)
  289. await db.flush()
  290. values = {"status": "pending", "position": 1, "target_model": "A1", "library_file_id": lib.id}
  291. values.update(fields)
  292. item = PrintQueueItem(**values)
  293. db.add(item)
  294. await db.commit()
  295. return item.id
  296. async def _load(db, item_id):
  297. return (
  298. await db.execute(
  299. select(PrintQueueItem)
  300. .where(PrintQueueItem.id == item_id)
  301. .options(
  302. selectinload(PrintQueueItem.library_file),
  303. selectinload(PrintQueueItem.archive),
  304. selectinload(PrintQueueItem.variants),
  305. )
  306. )
  307. ).scalar_one()
  308. async def _get_item(ctx, item_id):
  309. async with ctx.session_maker() as db:
  310. return await _load(db, item_id)
  311. class TestQueuePassNozzle:
  312. async def _pass(self, ctx, states):
  313. scheduler = PrintScheduler()
  314. launched = MagicMock()
  315. dispatched = AsyncMock()
  316. patches = [
  317. patch("backend.app.services.print_scheduler.async_session", ctx.session_maker),
  318. patch("backend.app.core.database.async_session", ctx.session_maker),
  319. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  320. patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
  321. patch(
  322. "backend.app.services.print_scheduler.ha_sensor_manager.blocked_printers",
  323. AsyncMock(return_value={}),
  324. ),
  325. patch(
  326. "backend.app.services.notification_service.notification_service.on_queue_job_waiting",
  327. AsyncMock(),
  328. ),
  329. patch(
  330. "backend.app.services.notification_service.notification_service.on_queue_job_assigned",
  331. AsyncMock(),
  332. ),
  333. patch("backend.app.services.print_scheduler.compute_deficit_for_queue_item", AsyncMock(return_value=[])),
  334. patch.object(scheduler, "_filament_short_on", AsyncMock(return_value=False)),
  335. patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
  336. patch.object(scheduler, "_check_auto_drying", AsyncMock()),
  337. patch.object(scheduler, "_ensure_ams_mapping", AsyncMock(return_value=None)),
  338. patch.object(scheduler, "_block_on_unmatched_filament", AsyncMock(return_value=False)),
  339. patch.object(scheduler, "_unmatched_on", AsyncMock(return_value=[])),
  340. patch.object(scheduler, "_launch_uploads", launched),
  341. patch.object(scheduler, "_dispatch_one", dispatched),
  342. ]
  343. with ExitStack() as stack:
  344. for p in patches:
  345. stack.enter_context(p)
  346. await scheduler.check_queue()
  347. return launched, dispatched
  348. @pytest.mark.asyncio
  349. async def test_waits_with_the_nozzle_reason_when_no_printer_fits(self, a1_farm):
  350. item_id = await _add_any_a1(a1_farm, 0.6)
  351. launched, dispatched = await self._pass(a1_farm, {1: _state("0.4"), 2: _state("0.4")})
  352. item = await _get_item(a1_farm, item_id)
  353. assert item.status == "pending"
  354. assert item.printer_id is None
  355. assert item.waiting_reason == "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)"
  356. launched.assert_not_called()
  357. dispatched.assert_not_called()
  358. @pytest.mark.asyncio
  359. async def test_goes_to_the_printer_whose_nozzle_fits(self, a1_farm):
  360. item_id = await _add_any_a1(a1_farm, 0.6)
  361. launched, _ = await self._pass(a1_farm, {1: _state("0.4"), 2: _state("0.6")})
  362. launched.assert_called_once()
  363. assert launched.call_args[0][0] == [item_id]
  364. assert launched.call_args[0][1] == {item_id: 2}
  365. assert (await _get_item(a1_farm, item_id)).printer_id == 2
  366. # --- Low-filament hold release -----------------------------------------------
  367. class TestShortHoldNozzle:
  368. """A job held for low filament on A1-1 only moves to a printer whose nozzle fits.
  369. Without the nozzle the move would pin it on a 0.4 mm A1, where the
  370. dispatch guard (#1899) then fails it.
  371. """
  372. async def _release(self, ctx, states):
  373. item_id = await _add_any_a1(ctx, 0.6, printer_id=1, manual_start=True, filament_short=True)
  374. scheduler = PrintScheduler()
  375. async def short_on(db, item, printer_id, *, require_known=False):
  376. return printer_id == 1 # A1-2 has enough filament
  377. with (
  378. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  379. patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
  380. patch.object(scheduler, "_filament_short_on", AsyncMock(side_effect=short_on)),
  381. patch.object(scheduler, "_unmatched_on", AsyncMock(return_value=[])),
  382. patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
  383. ):
  384. async with ctx.session_maker() as db:
  385. item = await _load(db, item_id)
  386. moved = await scheduler._release_short_model_hold(db, item, set(), False, ALL_PRINTERS)
  387. return moved, item.printer_id
  388. @pytest.mark.asyncio
  389. async def test_not_moved_to_a_printer_with_the_wrong_nozzle(self, a1_farm):
  390. assert await self._release(a1_farm, {1: _state("0.6"), 2: _state("0.4")}) == (False, 1)
  391. @pytest.mark.asyncio
  392. async def test_moved_to_a_printer_whose_nozzle_fits(self, a1_farm):
  393. assert await self._release(a1_farm, {1: _state("0.6"), 2: _state("0.6")}) == (True, 2)
  394. # --- Auto-drying: which printers an "Any model" job counts for ---------------
  395. class TestDryingPrinterIds:
  396. """An "Any A1" job that no 0.4 mm A1 can print must not block or trigger drying there."""
  397. async def _ids(self, ctx, nozzle, states):
  398. item_id = await _add_any_a1(ctx, nozzle)
  399. with patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)):
  400. async with ctx.session_maker() as db:
  401. item = await _load(db, item_id)
  402. return await PrintScheduler()._model_job_printer_ids(db, item, ALL_PRINTERS, {})
  403. @pytest.mark.asyncio
  404. async def test_only_printers_whose_nozzle_fits_count(self, a1_farm):
  405. assert await self._ids(a1_farm, 0.6, {1: _state("0.4"), 2: _state("0.6")}) == {2}
  406. @pytest.mark.asyncio
  407. async def test_unknown_sliced_nozzle_counts_every_printer(self, a1_farm):
  408. assert await self._ids(a1_farm, None, {1: _state("0.4"), 2: _state("0.6")}) == {1, 2}
  409. # --- Chosen pick order (#2915) plus nozzle ------------------------------------
  410. class TestPickOrderNozzle:
  411. """The nozzle check passes a printer over whatever order the setting picks in.
  412. Farm from the #2915 tests: X1C-1 most worn (priority 2), X1C-2 priority 1,
  413. X1C-3 fewest hours (no priority).
  414. """
  415. async def _pick(self, setting, nozzles, sliced_nozzle=0.6):
  416. engine, ctx = await _farm(setting, **ORDER_PRINTERS)
  417. try:
  418. states = {pid: _state(d) for pid, d in nozzles.items()}
  419. return await _find(ctx, PrintScheduler(), states, model="X1C", sliced_nozzle=sliced_nozzle)
  420. finally:
  421. await engine.dispose()
  422. @pytest.mark.asyncio
  423. @pytest.mark.parametrize(
  424. ("setting", "nozzles", "expected"),
  425. [
  426. ("priority", {1: "0.6", 2: "0.4", 3: "0.6"}, 1), # priority 1 has the wrong nozzle
  427. ("priority", {1: "0.4", 2: "0.4", 3: "0.6"}, 3), # only the one without priority fits
  428. ("most_hours", {1: "0.4", 2: "0.6", 3: "0.6"}, 2), # the most worn has the wrong nozzle
  429. ("fewest_hours", {1: "0.6", 2: "0.6", 3: "0.4"}, 2), # the least worn has the wrong nozzle
  430. ],
  431. )
  432. async def test_the_next_printer_in_the_chosen_order_whose_nozzle_fits(self, setting, nozzles, expected):
  433. assert await self._pick(setting, nozzles) == (expected, None)
  434. @pytest.mark.asyncio
  435. async def test_the_reason_names_the_printers_in_the_chosen_order(self):
  436. assert await self._pick("priority", {1: "0.4", 2: "0.4", 3: "0.4"}) == (
  437. None,
  438. "No X1C has a 0.6mm nozzle: X1C-2 (0.4mm), X1C-1 (0.4mm), X1C-3 (0.4mm)",
  439. )
  440. @pytest.mark.asyncio
  441. async def test_the_wake_step_passes_over_the_first_in_order_with_the_wrong_nozzle(self):
  442. """All off; X1C-2 (priority 1) last reported 0.4, so X1C-1 is woken instead."""
  443. engine, ctx = await _farm("priority", **ORDER_PRINTERS)
  444. scheduler = PrintScheduler()
  445. plug = SimpleNamespace(id=1, auto_on=True, enabled=True, controls_printer_power=True)
  446. states = {1: _state("0.6"), 2: _state("0.4"), 3: _state("0.6")}
  447. try:
  448. with (
  449. patch(
  450. "backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=False)
  451. ),
  452. patch(
  453. "backend.app.services.print_scheduler.printer_manager.is_awaiting_plate_clear",
  454. MagicMock(return_value=False),
  455. ),
  456. patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
  457. patch.object(scheduler, "_cached_filament_shortfall", MagicMock(return_value=[])),
  458. patch.object(scheduler, "_get_smart_plugs", AsyncMock(return_value=[plug])),
  459. patch.object(scheduler, "_power_on_and_wait", AsyncMock(return_value=True)),
  460. ):
  461. async with ctx.session_maker() as db:
  462. woken = await scheduler._wake_printer_for_model(
  463. db,
  464. [
  465. _ModelCandidate(
  466. target_model="X1C",
  467. sliced_for=None,
  468. required_filament_types=None,
  469. filament_overrides=None,
  470. sliced_nozzle=0.6,
  471. )
  472. ],
  473. None,
  474. set(),
  475. {1, 2, 3},
  476. require_plate_clear=False,
  477. )
  478. finally:
  479. await engine.dispose()
  480. assert woken == (1, 1)