test_scheduler_cross_model_variants.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. """Cross-model queue items — one job, several sliced files (#671).
  2. The reporter has an H2S and an H2C and does not care which one runs the job.
  3. He slices it twice; both slices become variants of a single queue item, and the
  4. scheduler takes the first whose model has an idle printer.
  5. The design constraint that shapes everything here: the many-to-many must never
  6. escape the selection loop. Once a candidate wins, its file and settings are
  7. folded onto the queue row, so the upload, archive creation, print history and
  8. reprint paths keep seeing an ordinary single-file item. These tests assert both
  9. halves — that the right candidate is picked, and that the row afterwards looks
  10. like it was queued for that file all along.
  11. """
  12. from contextlib import ExitStack
  13. from types import SimpleNamespace
  14. from unittest.mock import AsyncMock, MagicMock, patch
  15. import pytest
  16. from sqlalchemy import select
  17. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  18. import backend.app.models # noqa: F401 - populate Base.metadata
  19. from backend.app.core.database import Base
  20. from backend.app.models.library import LibraryFile
  21. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  22. from backend.app.models.printer import Printer
  23. from backend.app.services.print_scheduler import (
  24. PrintScheduler,
  25. _candidate_model_label,
  26. _candidates_for,
  27. _collapse_waiting_reasons,
  28. )
  29. # ---------------------------------------------------------------------------
  30. # Candidate ordering — pure
  31. # ---------------------------------------------------------------------------
  32. def _fake_variant(*, vid, position, model, attempts=0, trashed=False, file_missing=False):
  33. return SimpleNamespace(
  34. id=vid,
  35. position=position,
  36. target_model=model,
  37. attempt_count=attempts,
  38. library_file=None
  39. if file_missing
  40. else SimpleNamespace(
  41. file_metadata={"sliced_for_model": model},
  42. deleted_at="2026-01-01" if trashed else None,
  43. ),
  44. required_filament_types=None,
  45. filament_overrides=None,
  46. )
  47. def _fake_item(variants):
  48. return SimpleNamespace(
  49. variants=variants,
  50. target_model=None,
  51. archive=None,
  52. archive_id=None,
  53. library_file=None,
  54. library_file_id=None,
  55. required_filament_types=None,
  56. filament_overrides=None,
  57. )
  58. def test_no_variants_yields_the_items_own_columns():
  59. """The pre-#671 path must be provably unchanged: one candidate, built from
  60. the item itself."""
  61. item = SimpleNamespace(
  62. variants=[],
  63. target_model="H2D",
  64. archive=None,
  65. archive_id=None,
  66. library_file_id=7,
  67. library_file=SimpleNamespace(file_metadata={"sliced_for_model": "H2D"}),
  68. required_filament_types='["PLA"]',
  69. filament_overrides=None,
  70. )
  71. candidates = _candidates_for(item)
  72. assert len(candidates) == 1
  73. assert candidates[0].target_model == "H2D"
  74. assert candidates[0].sliced_for == "H2D"
  75. assert candidates[0].required_filament_types == '["PLA"]'
  76. assert candidates[0].variant is None
  77. def test_variants_come_back_in_user_priority_order():
  78. item = _fake_item(
  79. [
  80. _fake_variant(vid=2, position=1, model="H2C"),
  81. _fake_variant(vid=1, position=0, model="H2S"),
  82. ]
  83. )
  84. assert [c.target_model for c in _candidates_for(item)] == ["H2S", "H2C"]
  85. def test_least_attempted_candidate_is_tried_first():
  86. """A printer that accepts the file and never starts must not eat the item's
  87. whole retry budget — the alternative gets the next lap."""
  88. item = _fake_item(
  89. [
  90. _fake_variant(vid=1, position=0, model="H2S", attempts=1),
  91. _fake_variant(vid=2, position=1, model="H2C", attempts=0),
  92. ]
  93. )
  94. assert [c.target_model for c in _candidates_for(item)] == ["H2C", "H2S"]
  95. def test_trashed_candidate_is_skipped():
  96. """Library deletes are soft: the row survives with deleted_at set, which no
  97. foreign key can express. Dispatching a file the user put in the bin would be
  98. a genuine surprise."""
  99. item = _fake_item(
  100. [
  101. _fake_variant(vid=1, position=0, model="H2S", trashed=True),
  102. _fake_variant(vid=2, position=1, model="H2C"),
  103. ]
  104. )
  105. assert [c.target_model for c in _candidates_for(item)] == ["H2C"]
  106. def test_orphaned_candidate_is_skipped():
  107. """SQLite runs with PRAGMA foreign_keys off, so a hard delete can leave a
  108. candidate row pointing at nothing."""
  109. item = _fake_item(
  110. [
  111. _fake_variant(vid=1, position=0, model="H2S", file_missing=True),
  112. _fake_variant(vid=2, position=1, model="H2C"),
  113. ]
  114. )
  115. assert [c.target_model for c in _candidates_for(item)] == ["H2C"]
  116. def test_item_with_no_usable_candidates_yields_none():
  117. item = _fake_item([_fake_variant(vid=1, position=0, model="H2S", trashed=True)])
  118. assert _candidates_for(item) == []
  119. def test_equal_attempts_fall_back_to_priority():
  120. """Once every candidate has failed equally often they cycle in the user's
  121. order, so the item still reaches its DISPATCH_MAX_ATTEMPTS ceiling."""
  122. item = _fake_item(
  123. [
  124. _fake_variant(vid=1, position=0, model="H2S", attempts=2),
  125. _fake_variant(vid=2, position=1, model="H2C", attempts=2),
  126. ]
  127. )
  128. assert [c.target_model for c in _candidates_for(item)] == ["H2S", "H2C"]
  129. # ---------------------------------------------------------------------------
  130. # Waiting reasons — pure
  131. # ---------------------------------------------------------------------------
  132. def test_single_candidate_reason_is_unprefixed():
  133. """One candidate means the card already shows the model; prefixing it would
  134. just be noise."""
  135. assert _collapse_waiting_reasons([("H2D", "Busy: H2D-1 (Printing)")]) == "Busy: H2D-1 (Printing)"
  136. def test_identical_reasons_collapse_to_one_clause():
  137. collapsed = _collapse_waiting_reasons([("H2S", "Busy: shared-1 (Printing)"), ("H2C", "Busy: shared-1 (Printing)")])
  138. assert collapsed == "Busy: shared-1 (Printing)"
  139. def test_all_busy_stays_busy_only_so_no_notification_fires():
  140. """Two models busy on differently-named printers still has to read as
  141. busy-only. Labelling the clauses would make every pass over a cross-model
  142. item look like it needs the user, when it just needs a printer to finish."""
  143. scheduler = PrintScheduler()
  144. collapsed = _collapse_waiting_reasons([("H2S", "Busy: H2S-1 (Printing)"), ("H2C", "Busy: H2C-1 (Printing)")])
  145. assert collapsed == "Busy: H2S-1 (Printing) | Busy: H2C-1 (Printing)"
  146. assert scheduler._is_busy_only(collapsed)
  147. def test_differing_reasons_are_labelled_by_model():
  148. collapsed = _collapse_waiting_reasons([("H2S", "No PETG loaded"), ("H2C", "Busy: H2C-1 (Printing)")])
  149. assert collapsed == "H2S: No PETG loaded; H2C: Busy: H2C-1 (Printing)"
  150. assert not PrintScheduler._is_busy_only(collapsed), "a real blocker must still notify"
  151. def test_empty_reasons_are_dropped():
  152. assert _collapse_waiting_reasons([("H2S", "")]) is None
  153. assert _collapse_waiting_reasons([]) is None
  154. def test_model_label_names_every_candidate():
  155. item = _fake_item(
  156. [
  157. _fake_variant(vid=1, position=0, model="H2S"),
  158. _fake_variant(vid=2, position=1, model="H2C"),
  159. ]
  160. )
  161. assert _candidate_model_label(_candidates_for(item)) == "H2S or H2C"
  162. # ---------------------------------------------------------------------------
  163. # Scheduler behaviour
  164. # ---------------------------------------------------------------------------
  165. @pytest.fixture
  166. async def queue_db():
  167. """In-memory DB with one H2S and one H2C."""
  168. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  169. async with engine.begin() as conn:
  170. await conn.run_sync(Base.metadata.create_all)
  171. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  172. async with session_maker() as db:
  173. db.add_all(
  174. [
  175. Printer(
  176. id=1,
  177. name="H2S-1",
  178. serial_number="H2S0001",
  179. ip_address="10.0.0.1",
  180. access_code="x",
  181. model="H2S",
  182. is_active=True,
  183. ),
  184. Printer(
  185. id=2,
  186. name="H2C-1",
  187. serial_number="H2C0001",
  188. ip_address="10.0.0.2",
  189. access_code="x",
  190. model="H2C",
  191. is_active=True,
  192. ),
  193. ]
  194. )
  195. await db.commit()
  196. try:
  197. yield SimpleNamespace(session_maker=session_maker)
  198. finally:
  199. await engine.dispose()
  200. async def _add_variant_item(ctx, specs):
  201. """Seed one pending queue item with a variant per (model, overrides) spec."""
  202. async with ctx.session_maker() as db:
  203. item = PrintQueueItem(
  204. status="pending",
  205. position=1,
  206. target_model=specs[0]["model"],
  207. )
  208. db.add(item)
  209. await db.flush()
  210. for position, spec in enumerate(specs):
  211. lib = LibraryFile(
  212. filename=f"job_{spec['model']}.gcode.3mf",
  213. file_path=f"/library/job_{spec['model']}.gcode.3mf",
  214. file_size=10,
  215. file_type="gcode.3mf",
  216. file_metadata={"sliced_for_model": spec.get("sliced_for", spec["model"])},
  217. )
  218. db.add(lib)
  219. await db.flush()
  220. db.add(
  221. PrintQueueVariant(
  222. queue_item_id=item.id,
  223. position=position,
  224. library_file_id=lib.id,
  225. target_model=spec["model"],
  226. plate_id=spec.get("plate_id"),
  227. ams_mapping=spec.get("ams_mapping"),
  228. nozzle_mapping=spec.get("nozzle_mapping"),
  229. print_time_seconds=spec.get("print_time_seconds"),
  230. attempt_count=spec.get("attempts", 0),
  231. )
  232. )
  233. await db.commit()
  234. return item.id
  235. async def _run_check_queue(ctx, scheduler, finder, waiting_notification=None):
  236. patches = [
  237. patch("backend.app.services.print_scheduler.async_session", ctx.session_maker),
  238. patch("backend.app.core.database.async_session", ctx.session_maker),
  239. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  240. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=None)),
  241. patch(
  242. "backend.app.services.notification_service.notification_service.on_queue_job_waiting",
  243. waiting_notification or AsyncMock(),
  244. ),
  245. patch(
  246. "backend.app.services.notification_service.notification_service.on_queue_job_assigned",
  247. AsyncMock(),
  248. ),
  249. patch.object(scheduler, "_find_idle_printer_for_model", finder),
  250. patch.object(scheduler, "_check_auto_drying", AsyncMock()),
  251. # Selection is what's under test — keep AMS recomputation and the
  252. # filament-deficit probe out of the way, and never actually dispatch.
  253. # None is the mapping-resolved answer; a bare AsyncMock returns a truthy
  254. # sentinel, which the unmappable guard (#2771) reads as "this job can
  255. # never print" and fails the item on.
  256. patch.object(scheduler, "_ensure_ams_mapping", AsyncMock(return_value=None)),
  257. patch.object(scheduler, "_block_on_filament_deficit", AsyncMock(return_value=False)),
  258. patch.object(scheduler, "_launch_uploads", MagicMock()),
  259. ]
  260. with ExitStack() as stack:
  261. for p in patches:
  262. stack.enter_context(p)
  263. return await scheduler.check_queue()
  264. async def _get_item(ctx, item_id):
  265. async with ctx.session_maker() as db:
  266. return (await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))).scalar_one()
  267. def _finder_for(available: dict[str, int]):
  268. """Matcher that offers a printer only for the listed models."""
  269. async def _find(db, model, exclude_ids, *args, **kwargs):
  270. if model in available:
  271. return available[model], None
  272. return None, f"No idle {model} printer"
  273. return AsyncMock(side_effect=_find)
  274. @pytest.mark.asyncio
  275. async def test_first_matching_variant_wins_and_is_folded_onto_the_row(queue_db):
  276. """The H2C is free, the H2S is not — the item runs the H2C slice, and every
  277. downstream consumer sees a plain single-file item pointing at it."""
  278. item_id = await _add_variant_item(
  279. queue_db,
  280. [
  281. {"model": "H2S", "plate_id": 1, "ams_mapping": "[1]", "print_time_seconds": 900},
  282. {
  283. "model": "H2C",
  284. "plate_id": 3,
  285. "ams_mapping": "[4, 5]",
  286. "nozzle_mapping": "[0, 1]",
  287. "print_time_seconds": 1200,
  288. },
  289. ],
  290. )
  291. scheduler = PrintScheduler()
  292. await _run_check_queue(queue_db, scheduler, _finder_for({"H2C": 2}))
  293. item = await _get_item(queue_db, item_id)
  294. assert item.printer_id == 2, "assigned to the H2C"
  295. assert item.target_model == "H2C"
  296. assert item.plate_id == 3
  297. assert item.ams_mapping == "[4, 5]"
  298. assert item.nozzle_mapping == "[0, 1]"
  299. assert item.print_time_seconds == 1200, "the estimate now describes what will actually run"
  300. assert item.waiting_reason is None
  301. assert item.archive_id is None
  302. async with queue_db.session_maker() as db:
  303. chosen = (
  304. await db.execute(select(PrintQueueVariant).where(PrintQueueVariant.target_model == "H2C"))
  305. ).scalar_one()
  306. assert item.library_file_id == chosen.library_file_id
  307. @pytest.mark.asyncio
  308. async def test_priority_order_decides_when_both_are_free(queue_db):
  309. """Both printers idle in the same pass: the user's first choice runs, so the
  310. outcome is reproducible rather than whichever match came back first."""
  311. item_id = await _add_variant_item(queue_db, [{"model": "H2S"}, {"model": "H2C"}])
  312. scheduler = PrintScheduler()
  313. await _run_check_queue(queue_db, scheduler, _finder_for({"H2S": 1, "H2C": 2}))
  314. item = await _get_item(queue_db, item_id)
  315. assert item.printer_id == 1
  316. assert item.target_model == "H2S"
  317. @pytest.mark.asyncio
  318. async def test_cross_model_gate_is_applied_per_candidate(queue_db):
  319. """A variant whose file disagrees with its own model is skipped, and the
  320. other one still runs — the gate must not condemn the whole item."""
  321. item_id = await _add_variant_item(
  322. queue_db,
  323. [
  324. {"model": "H2S", "sliced_for": "X1C"},
  325. {"model": "H2C"},
  326. ],
  327. )
  328. scheduler = PrintScheduler()
  329. finder = _finder_for({"H2S": 1, "H2C": 2})
  330. await _run_check_queue(queue_db, scheduler, finder)
  331. assert [c.args[1] for c in finder.await_args_list] == ["H2C"], "the mismatched variant never reaches the matcher"
  332. item = await _get_item(queue_db, item_id)
  333. assert item.printer_id == 2
  334. assert item.target_model == "H2C"
  335. @pytest.mark.asyncio
  336. async def test_no_match_reports_every_model_it_tried(queue_db):
  337. """Nothing is free: the user must be able to tell which machines were
  338. considered, not just that "a printer" was unavailable."""
  339. item_id = await _add_variant_item(queue_db, [{"model": "H2S"}, {"model": "H2C"}])
  340. scheduler = PrintScheduler()
  341. waiting = AsyncMock()
  342. await _run_check_queue(queue_db, scheduler, _finder_for({}), waiting)
  343. item = await _get_item(queue_db, item_id)
  344. assert item.printer_id is None
  345. assert item.status == "pending"
  346. assert "H2S: No idle H2S printer" in item.waiting_reason
  347. assert "H2C: No idle H2C printer" in item.waiting_reason
  348. assert waiting.await_args.kwargs["target_model"] == "H2S or H2C"
  349. # The item holds no file of its own yet — the alert still has to name the job.
  350. assert waiting.await_args.kwargs["job_name"] == "job_H2S"
  351. @pytest.mark.asyncio
  352. async def test_item_with_no_files_left_is_held_with_an_actionable_reason(queue_db):
  353. """Deleting a library file takes its variant with it. An item stripped of
  354. every candidate used to sail into dispatch and die there on "No archive_id
  355. or library_file_id"; hold it where the user can see why."""
  356. async with queue_db.session_maker() as db:
  357. db.add(PrintQueueItem(status="pending", position=1, target_model="H2S"))
  358. await db.commit()
  359. scheduler = PrintScheduler()
  360. finder = _finder_for({"H2S": 1})
  361. await _run_check_queue(queue_db, scheduler, finder)
  362. finder.assert_not_awaited()
  363. async with queue_db.session_maker() as db:
  364. item = (await db.execute(select(PrintQueueItem))).scalar_one()
  365. assert item.status == "pending"
  366. assert item.printer_id is None
  367. assert "has been deleted" in item.waiting_reason
  368. @pytest.mark.asyncio
  369. async def test_plain_model_based_item_is_untouched(queue_db):
  370. """Regression guard: an item with no variants takes exactly the path it took
  371. before variants existed."""
  372. async with queue_db.session_maker() as db:
  373. lib = LibraryFile(
  374. filename="job.gcode.3mf",
  375. file_path="/library/job.gcode.3mf",
  376. file_size=10,
  377. file_type="gcode.3mf",
  378. file_metadata={"sliced_for_model": "H2S"},
  379. )
  380. db.add(lib)
  381. await db.flush()
  382. db.add(
  383. PrintQueueItem(
  384. status="pending",
  385. position=1,
  386. target_model="H2S",
  387. library_file_id=lib.id,
  388. plate_id=2,
  389. )
  390. )
  391. await db.commit()
  392. scheduler = PrintScheduler()
  393. await _run_check_queue(queue_db, scheduler, _finder_for({"H2S": 1}))
  394. async with queue_db.session_maker() as db:
  395. item = (await db.execute(select(PrintQueueItem))).scalar_one()
  396. assert item.printer_id == 1
  397. assert item.target_model == "H2S"
  398. assert item.plate_id == 2, "nothing overwrote the item's own settings"
  399. @pytest.mark.asyncio
  400. async def test_failed_candidate_steps_aside_for_the_alternative(queue_db):
  401. """The H2S burned an attempt on the last lap. Both are free now — the H2C
  402. goes first, which is the entire point of queueing an alternative."""
  403. item_id = await _add_variant_item(
  404. queue_db,
  405. [
  406. {"model": "H2S", "attempts": 1},
  407. {"model": "H2C", "attempts": 0},
  408. ],
  409. )
  410. scheduler = PrintScheduler()
  411. await _run_check_queue(queue_db, scheduler, _finder_for({"H2S": 1, "H2C": 2}))
  412. item = await _get_item(queue_db, item_id)
  413. assert item.printer_id == 2
  414. assert item.target_model == "H2C"