test_scheduler_concurrent_dispatch.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. """Concurrent queue dispatch as a refillable upload pool (#2555, #2602).
  2. Reported first (#2555) as "prints are sent to the printer one by one, very
  3. slowly" on a 19-printer farm: ``check_queue`` awaited ``_start_print`` inline per
  4. item, and ``_start_print`` performs the FTP upload, so every printer queued
  5. behind every other printer's transfer. #2555 moved the uploads to a parallel
  6. ``asyncio.gather()`` — but that gather was *awaited before check_queue returned*,
  7. so the run loop stayed blocked until the slowest upload in the batch finished. On
  8. a 93-printer farm (#2602) a 513 s upload left 15 of 16 configured slots idle for
  9. 8.5 minutes while other printers came free.
  10. The uploads now run as independent background tasks tracked in
  11. ``scheduler._inflight``; each tick launches at most ``limit - len(_inflight)`` new
  12. ones and returns immediately, so a freed slot refills on the next fast tick.
  13. What must stay true:
  14. * Uploads to different printers overlap in time (the #2555 fix).
  15. * No more than ``queue_max_concurrent_uploads`` run at once — as a *pool*, across
  16. ticks, not just within one batch (#2602).
  17. * A freed slot is refilled by a later tick (#2602).
  18. * An item whose upload is in flight — and its printer — are excluded from the
  19. next pass, so a still-`pending` row is never dispatched twice (#2602).
  20. * check_queue returns *without* waiting for the uploads (#2602), reporting a
  21. productive/in-flight pass so ``run()`` re-checks on the fast interval.
  22. * Setting the cap to 1 restores serial behaviour; one printer failing must not
  23. cancel its siblings' in-flight uploads.
  24. Test model: the scheduler now launches uploads via ``spawn_background_task``, so
  25. the harness swaps in a real task-spawning shim and drains ``_inflight`` explicitly
  26. (inside the patched context, so the upload/session patches are still active while
  27. the pool workers run). ``_run_to_completion`` loops check_queue + drain to model
  28. the run loop draining a queue that exceeds the cap.
  29. """
  30. import asyncio
  31. from contextlib import ExitStack, asynccontextmanager
  32. from pathlib import Path
  33. from types import SimpleNamespace
  34. from unittest.mock import AsyncMock, MagicMock, patch
  35. import pytest
  36. from sqlalchemy import func, select
  37. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  38. import backend.app.models # noqa: F401 - populate Base.metadata
  39. import backend.app.services.archive as archive_module
  40. import backend.app.services.print_scheduler as scheduler_module
  41. from backend.app.core.database import Base
  42. from backend.app.models.archive import PrintArchive
  43. from backend.app.models.library import LibraryFile
  44. from backend.app.models.print_queue import PrintQueueItem
  45. from backend.app.models.printer import Printer
  46. from backend.app.models.settings import Settings
  47. from backend.app.services.print_scheduler import PrintScheduler
  48. UPLOAD_SECONDS = 0.15
  49. @pytest.fixture
  50. async def farm(tmp_path):
  51. """Build a farm of N printers, each with one pending queue item."""
  52. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  53. async with engine.begin() as conn:
  54. await conn.run_sync(Base.metadata.create_all)
  55. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  56. async def make_farm(printer_count: int, *, max_concurrent: int | None = None):
  57. base_dir = tmp_path / "farm"
  58. (base_dir / "archives").mkdir(parents=True, exist_ok=True)
  59. async with session_maker() as db:
  60. if max_concurrent is not None:
  61. db.add(Settings(key="queue_max_concurrent_uploads", value=str(max_concurrent)))
  62. printer_ids = []
  63. for n in range(printer_count):
  64. archive_rel = Path("archives") / f"job-{n}.3mf"
  65. (base_dir / archive_rel).write_bytes(b"archive payload")
  66. printer = Printer(
  67. name=f"Printer {n}",
  68. serial_number=f"SERIAL-{n}",
  69. ip_address=f"10.0.0.{n + 1}",
  70. access_code="access-code",
  71. model="A1",
  72. )
  73. db.add(printer)
  74. await db.flush()
  75. archive = PrintArchive(
  76. printer_id=printer.id,
  77. filename=f"job-{n}.3mf",
  78. file_path=str(archive_rel),
  79. file_size=15,
  80. print_time_seconds=120,
  81. status="completed",
  82. )
  83. db.add(archive)
  84. await db.flush()
  85. db.add(
  86. PrintQueueItem(
  87. printer_id=printer.id,
  88. archive_id=archive.id,
  89. status="pending",
  90. position=n,
  91. )
  92. )
  93. printer_ids.append(printer.id)
  94. await db.commit()
  95. return SimpleNamespace(
  96. session_maker=session_maker,
  97. base_dir=base_dir,
  98. printer_ids=printer_ids,
  99. )
  100. try:
  101. yield make_farm
  102. finally:
  103. await engine.dispose()
  104. class _UploadRecorder:
  105. """Stands in for ``upload_file_async``; records overlap.
  106. Each call sleeps, so genuinely concurrent uploads have overlapping
  107. lifetimes. ``peak`` is the high-water mark of simultaneous in-flight
  108. uploads — the number the pool cap turns on.
  109. """
  110. def __init__(self, *, fail_for_ip: str | None = None):
  111. self.in_flight = 0
  112. self.peak = 0
  113. self.order: list[str] = []
  114. self.fail_for_ip = fail_for_ip
  115. async def __call__(self, ip_address, access_code, local_path, remote_path, **kwargs):
  116. self.in_flight += 1
  117. self.peak = max(self.peak, self.in_flight)
  118. self.order.append(ip_address)
  119. try:
  120. await asyncio.sleep(UPLOAD_SECONDS)
  121. if self.fail_for_ip is not None and ip_address == self.fail_for_ip:
  122. raise OSError(f"simulated FTP failure for {ip_address}")
  123. return True
  124. finally:
  125. self.in_flight -= 1
  126. @asynccontextmanager
  127. async def _scheduler_ctx(ctx, upload, job_started=None):
  128. """Yield a scheduler with all I/O patched, and a real task-spawning shim.
  129. The scheduler launches uploads through ``spawn_background_task`` (#2602), so
  130. the harness gives it a real ``create_task`` shim rather than the no-op mock
  131. used before — otherwise the pool workers never run and rows stay ``pending``.
  132. The watchdog (also spawned per dispatch) is stubbed so it doesn't poll for
  133. the whole test. Drain ``_inflight`` *inside* this context so the workers run
  134. while the upload/session patches are still active.
  135. """
  136. scheduler = PrintScheduler()
  137. job_started = job_started or AsyncMock()
  138. def _real_spawn(coro, *, name=None):
  139. return asyncio.create_task(coro, name=name)
  140. patches = [
  141. patch.object(scheduler_module.settings, "base_dir", ctx.base_dir),
  142. patch.object(archive_module.settings, "base_dir", ctx.base_dir),
  143. patch.object(archive_module.settings, "archive_dir", ctx.base_dir / "archive"),
  144. patch("backend.app.services.print_scheduler.async_session", ctx.session_maker),
  145. patch("backend.app.core.database.async_session", ctx.session_maker),
  146. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  147. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=None)),
  148. patch("backend.app.services.print_scheduler.printer_manager.start_print", MagicMock(return_value=True)),
  149. patch("backend.app.services.print_scheduler.printer_manager.set_awaiting_plate_clear", MagicMock()),
  150. patch("backend.app.services.print_scheduler.upload_file_async", upload),
  151. patch("backend.app.services.print_scheduler.delete_file_async", AsyncMock(return_value=True)),
  152. patch(
  153. "backend.app.services.print_scheduler.get_ftp_retry_settings",
  154. AsyncMock(return_value=(False, 0, 0, 1.0)),
  155. ),
  156. patch("backend.app.services.print_scheduler.cache_3mf_download", MagicMock()),
  157. patch("backend.app.services.print_scheduler.spawn_background_task", _real_spawn),
  158. patch("backend.app.services.notification_service.notification_service.on_queue_job_started", job_started),
  159. patch("backend.app.services.notification_service.notification_service.on_queue_job_failed", AsyncMock()),
  160. patch("backend.app.services.mqtt_relay.mqtt_relay.on_queue_job_started", AsyncMock()),
  161. patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
  162. patch.object(scheduler, "_propagate_owner_to_printer_manager", AsyncMock()),
  163. patch.object(scheduler, "_power_off_if_needed", AsyncMock()),
  164. patch.object(scheduler, "_preheat_and_soak", AsyncMock()),
  165. patch.object(scheduler, "_check_auto_drying", AsyncMock()),
  166. patch.object(scheduler, "_watchdog_print_start", AsyncMock()),
  167. ]
  168. with ExitStack() as stack:
  169. for patcher in patches:
  170. stack.enter_context(patcher)
  171. yield scheduler
  172. async def _drain(scheduler):
  173. """Run the currently in-flight pool workers to completion."""
  174. tasks = [task for (task, _pid) in scheduler._inflight.values()]
  175. if tasks:
  176. await asyncio.gather(*tasks, return_exceptions=True)
  177. async def _run_check_queue(ctx, upload, job_started=None, *, drain=True):
  178. """Run one check_queue pass; by default also drain the launched uploads.
  179. Returns the check_queue result (True if the pass was productive / has uploads
  180. still in flight).
  181. """
  182. async with _scheduler_ctx(ctx, upload, job_started) as scheduler:
  183. result = await scheduler.check_queue()
  184. if drain:
  185. await _drain(scheduler)
  186. return result
  187. async def _run_to_completion(ctx, upload, job_started=None, *, max_ticks: int = 50) -> int:
  188. """Model the run loop: check_queue + drain until the queue is empty.
  189. Draining fully between ticks makes each tick a fresh batch of at most the cap,
  190. which is enough to prove the cap holds across the whole drain and every item
  191. eventually goes out. Returns the number of ticks it took.
  192. """
  193. ticks = 0
  194. async with _scheduler_ctx(ctx, upload, job_started) as scheduler:
  195. while ticks < max_ticks:
  196. await scheduler.check_queue()
  197. await _drain(scheduler)
  198. ticks += 1
  199. if await _pending_count(ctx) == 0 and not scheduler._inflight:
  200. break
  201. return ticks
  202. async def _statuses(ctx):
  203. async with ctx.session_maker() as db:
  204. rows = (await db.execute(select(PrintQueueItem).order_by(PrintQueueItem.position))).scalars().all()
  205. return [r.status for r in rows]
  206. async def _pending_count(ctx) -> int:
  207. async with ctx.session_maker() as db:
  208. return await db.scalar(
  209. select(func.count()).select_from(PrintQueueItem).where(PrintQueueItem.status == "pending")
  210. )
  211. @pytest.mark.asyncio
  212. async def test_uploads_to_different_printers_overlap(farm):
  213. """The #2555 headline: six printers must not queue behind each other.
  214. Pre-fix this recorded peak == 1 no matter how many printers were pending.
  215. """
  216. ctx = await farm(6, max_concurrent=6)
  217. upload = _UploadRecorder()
  218. await _run_check_queue(ctx, upload)
  219. assert upload.peak == 6, (
  220. f"expected all 6 printers to be uploaded to concurrently, but the "
  221. f"high-water mark was {upload.peak} — uploads are still serialized"
  222. )
  223. assert await _statuses(ctx) == ["printing"] * 6
  224. @pytest.mark.asyncio
  225. async def test_pool_cap_holds_across_refills(farm):
  226. """Eight pending printers, cap of 3 — never more than 3 uploads at once.
  227. Under the pool model (#2602) one tick launches at most 3; the queue drains
  228. over several ticks. The cap must hold across the *whole* drain, and every
  229. item must still go out.
  230. """
  231. ctx = await farm(8, max_concurrent=3)
  232. upload = _UploadRecorder()
  233. ticks = await _run_to_completion(ctx, upload)
  234. assert upload.peak == 3, f"cap of 3 not honoured across the drain — peak was {upload.peak}"
  235. assert len(upload.order) == 8, "every pending item must still be dispatched, just not all at once"
  236. assert await _statuses(ctx) == ["printing"] * 8
  237. assert ticks >= 3, "8 items at a cap of 3 must take at least 3 ticks to drain"
  238. @pytest.mark.asyncio
  239. async def test_freed_slot_is_refilled_on_the_next_tick(farm):
  240. """The #2602 fix: a busy pool doesn't block, and a freed slot refills.
  241. Cap of 1, two printers. Tick 1 launches printer A. A second tick while A is
  242. still in flight must launch nothing (pool full) rather than block. Once A
  243. finishes, the next tick fills the freed slot with printer B.
  244. """
  245. ctx = await farm(2, max_concurrent=1)
  246. upload = _UploadRecorder()
  247. async with _scheduler_ctx(ctx, upload) as scheduler:
  248. # Tick 1: one slot, one launch. Don't drain — A is now "in flight".
  249. assert await scheduler.check_queue() is True
  250. assert len(scheduler._inflight) == 1
  251. # Tick 2 while A is in flight: pool full → no new launch, no blocking.
  252. assert await scheduler.check_queue() is True
  253. assert len(scheduler._inflight) == 1, "a full pool must not launch a second upload"
  254. # A completes, freeing the slot.
  255. await _drain(scheduler)
  256. assert not scheduler._inflight
  257. # Tick 3: the freed slot is refilled with the second printer.
  258. assert await scheduler.check_queue() is True
  259. assert len(scheduler._inflight) == 1
  260. await _drain(scheduler)
  261. assert await _statuses(ctx) == ["printing", "printing"]
  262. assert upload.peak == 1, "cap of 1 must never overlap two uploads"
  263. @pytest.mark.asyncio
  264. async def test_inflight_item_and_printer_are_excluded_from_reselection(farm):
  265. """A still-`pending` in-flight row must not be dispatched a second time (#2602).
  266. The row flips pending -> printing only after its upload completes, so the
  267. reservation that stops a fast tick re-dispatching it is the in-flight
  268. exclusion, not the DB status.
  269. """
  270. ctx = await farm(1, max_concurrent=4)
  271. upload = _UploadRecorder()
  272. async with _scheduler_ctx(ctx, upload) as scheduler:
  273. await scheduler.check_queue()
  274. inflight_before = set(scheduler._inflight)
  275. assert len(inflight_before) == 1
  276. # Second tick while the upload is in flight (row still pending): the item
  277. # and its printer must be excluded — no new task, pool unchanged.
  278. await scheduler.check_queue()
  279. assert set(scheduler._inflight) == inflight_before, "an in-flight item was re-selected"
  280. await _drain(scheduler)
  281. assert await _statuses(ctx) == ["printing"]
  282. assert len(upload.order) == 1, "the item must be uploaded exactly once, not twice"
  283. @pytest.mark.asyncio
  284. async def test_inflight_printer_is_kept_out_of_auto_drying(farm):
  285. """A printer with an upload in flight must not be auto-dried in the gap (#2602).
  286. Once check_queue returns while the upload runs, the only pending row is the
  287. in-flight one — so the pass takes the "no dispatchable items" path. That path
  288. must still exclude the in-flight printer from auto-drying, because its print
  289. is imminent (the row flips to printing the moment the upload finishes).
  290. """
  291. ctx = await farm(1, max_concurrent=4)
  292. printer_id = ctx.printer_ids[0]
  293. upload = _UploadRecorder()
  294. async with _scheduler_ctx(ctx, upload) as scheduler:
  295. await scheduler.check_queue() # launch the only item; now in flight
  296. scheduler._check_auto_drying.reset_mock()
  297. # Second tick: the sole pending row is in flight, so this hits the
  298. # empty-items path. It must report the in-flight printer as busy.
  299. result = await scheduler.check_queue()
  300. assert result is True, "in-flight uploads keep the loop on the fast interval"
  301. assert scheduler._check_auto_drying.await_count == 1
  302. busy_arg = scheduler._check_auto_drying.await_args.args[2]
  303. assert printer_id in busy_arg, "the in-flight printer must be excluded from auto-drying"
  304. await _drain(scheduler)
  305. @pytest.mark.asyncio
  306. async def test_limit_of_one_restores_serial_behaviour(farm):
  307. """An escape hatch for weak networks: 1 == one upload at a time."""
  308. ctx = await farm(4, max_concurrent=1)
  309. upload = _UploadRecorder()
  310. await _run_to_completion(ctx, upload)
  311. assert upload.peak == 1
  312. assert await _statuses(ctx) == ["printing"] * 4
  313. @pytest.mark.asyncio
  314. async def test_default_concurrency_applies_when_setting_absent(farm):
  315. """No Settings row (every existing install) must still dispatch in parallel.
  316. Default cap is 4.
  317. """
  318. ctx = await farm(5, max_concurrent=None)
  319. upload = _UploadRecorder()
  320. await _run_to_completion(ctx, upload)
  321. assert upload.peak == 4, f"expected the default cap of 4, got {upload.peak}"
  322. assert await _statuses(ctx) == ["printing"] * 5
  323. @pytest.mark.asyncio
  324. async def test_one_failing_upload_does_not_cancel_the_others(farm):
  325. """A dead printer must not take its siblings' in-flight uploads down with it.
  326. Each upload is an independent task, so one raising cannot cancel the others;
  327. _start_print marks that one item failed and the rest proceed.
  328. """
  329. ctx = await farm(4, max_concurrent=4)
  330. upload = _UploadRecorder(fail_for_ip="10.0.0.2") # printer index 1
  331. await _run_check_queue(ctx, upload)
  332. statuses = await _statuses(ctx)
  333. assert statuses[1] == "failed", "the unreachable printer's item should be marked failed"
  334. assert [s for i, s in enumerate(statuses) if i != 1] == ["printing"] * 3, (
  335. "the other three printers must have started despite the failure"
  336. )
  337. @pytest.mark.asyncio
  338. async def test_check_queue_reports_it_dispatched(farm):
  339. """A productive pass returns True so ``run()`` re-checks quickly (#2555)."""
  340. ctx = await farm(3, max_concurrent=3)
  341. dispatched = await _run_check_queue(ctx, _UploadRecorder())
  342. assert dispatched is True, "check_queue dispatched 3 items but did not report it"
  343. @pytest.mark.asyncio
  344. async def test_check_queue_reports_nothing_dispatched_when_empty(farm):
  345. """An empty queue returns False so ``run()`` falls back to the idle interval."""
  346. ctx = await farm(0, max_concurrent=3)
  347. dispatched = await _run_check_queue(ctx, _UploadRecorder())
  348. assert dispatched is False, "an empty pass must not trigger a fast re-tick"
  349. @pytest.mark.asyncio
  350. async def test_check_queue_returns_without_awaiting_the_uploads(farm):
  351. """The pass must return *before* the uploads finish (#2602).
  352. This is the inversion of the old contract: check_queue no longer blocks on
  353. the batch. It launches the uploads as tracked background tasks, leaves the
  354. rows ``pending`` (they flip to ``printing`` only when each upload completes),
  355. and returns True so the run loop keeps ticking fast while they drain.
  356. """
  357. ctx = await farm(3, max_concurrent=3)
  358. upload = _UploadRecorder()
  359. async with _scheduler_ctx(ctx, upload) as scheduler:
  360. result = await scheduler.check_queue()
  361. # Uploads are tracked but have not been awaited: rows are still pending.
  362. assert result is True
  363. assert len(scheduler._inflight) == 3
  364. assert await _statuses(ctx) == ["pending"] * 3
  365. await _drain(scheduler)
  366. assert await _statuses(ctx) == ["printing"] * 3
  367. assert upload.peak == 3
  368. class TestSharedLibraryRow:
  369. """Dispatching in parallel means two items can reach the same library row at
  370. the same time — impossible when dispatch was serial.
  371. Only the ``cleanup_library_after_dispatch`` flow (printer-card "upload and
  372. print") *mutates* that row: it deletes it and unlinks the 3MF once the print
  373. is away. Two of those against one row would race. An ordinary library print
  374. only reads the row, and the reporter's own batch was one File Manager file
  375. fanned out across his farm, so a blanket "never share a library row" guard
  376. would re-serialize the exact workload this exists to fix.
  377. """
  378. @staticmethod
  379. async def _library_farm(session_maker, tmp_path, printer_count, *, cleanup: bool):
  380. """One shared library file, one queue item per printer, all pointing at it."""
  381. base_dir = tmp_path / "libfarm"
  382. (base_dir / "library").mkdir(parents=True, exist_ok=True)
  383. shared = base_dir / "library" / "shared.3mf"
  384. shared.write_bytes(b"shared payload")
  385. async with session_maker() as db:
  386. db.add(Settings(key="queue_max_concurrent_uploads", value=str(printer_count)))
  387. library_file = LibraryFile(
  388. filename="shared.3mf",
  389. file_path=str(shared),
  390. file_type="3mf",
  391. file_size=shared.stat().st_size,
  392. )
  393. db.add(library_file)
  394. await db.flush()
  395. for n in range(printer_count):
  396. printer = Printer(
  397. name=f"Printer {n}",
  398. serial_number=f"LIB-SERIAL-{n}",
  399. ip_address=f"10.1.0.{n + 1}",
  400. access_code="access-code",
  401. model="A1",
  402. )
  403. db.add(printer)
  404. await db.flush()
  405. db.add(
  406. PrintQueueItem(
  407. printer_id=printer.id,
  408. library_file_id=library_file.id,
  409. cleanup_library_after_dispatch=cleanup,
  410. status="pending",
  411. position=n,
  412. )
  413. )
  414. await db.commit()
  415. return SimpleNamespace(session_maker=session_maker, base_dir=base_dir, printer_ids=None)
  416. @pytest.mark.asyncio
  417. async def test_plain_library_file_still_fans_out_in_parallel(self, tmp_path):
  418. """The reporter's actual workload: one File Manager file, four printers.
  419. Nothing here mutates the library row, so all four must upload at once.
  420. """
  421. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  422. async with engine.begin() as conn:
  423. await conn.run_sync(Base.metadata.create_all)
  424. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  425. try:
  426. ctx = await self._library_farm(session_maker, tmp_path, 4, cleanup=False)
  427. upload = _UploadRecorder()
  428. await _run_check_queue(ctx, upload)
  429. assert upload.peak == 4, f"a shared library file must not re-serialize the fan-out — peak was {upload.peak}"
  430. assert await _statuses(ctx) == ["printing"] * 4
  431. finally:
  432. await engine.dispose()
  433. @pytest.mark.asyncio
  434. async def test_cleanup_items_never_share_a_row_in_one_pass(self, tmp_path):
  435. """The mutating flow must be held to one dispatch per pass.
  436. Each of these deletes the library row and unlinks the 3MF when done.
  437. Exactly one may go per pass; the rest stay pending for a later one.
  438. """
  439. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  440. async with engine.begin() as conn:
  441. await conn.run_sync(Base.metadata.create_all)
  442. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  443. try:
  444. ctx = await self._library_farm(session_maker, tmp_path, 3, cleanup=True)
  445. upload = _UploadRecorder()
  446. await _run_check_queue(ctx, upload)
  447. assert upload.peak <= 1, (
  448. f"{upload.peak} dispatches raced over one consumable library row — "
  449. f"the loser's DELETE finds nothing and its 3MF can be unlinked mid-upload"
  450. )
  451. statuses = await _statuses(ctx)
  452. assert statuses.count("printing") == 1, "exactly one item should have gone out"
  453. assert statuses.count("pending") == 2, "the rest must stay queued, not fail"
  454. finally:
  455. await engine.dispose()
  456. @pytest.mark.asyncio
  457. async def test_library_print_without_a_parseable_print_time_does_not_crash(tmp_path):
  458. """Regression: `_start_print` read `library_file.print_time_seconds`, a column
  459. LibraryFile does not have.
  460. It only fired when the archive carried no print time — a plain .gcode, or a 3MF
  461. the parser could not read — and it fired *after* the printer had been sent the
  462. job. The started-notification was lost and the AttributeError unwound the
  463. dispatch. Two printers here: if the first one's dispatch blows up, the second
  464. must still go out.
  465. """
  466. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  467. async with engine.begin() as conn:
  468. await conn.run_sync(Base.metadata.create_all)
  469. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  470. try:
  471. base_dir = tmp_path / "nolibtime"
  472. (base_dir / "library").mkdir(parents=True, exist_ok=True)
  473. async with session_maker() as db:
  474. db.add(Settings(key="queue_max_concurrent_uploads", value="2"))
  475. for n in range(2):
  476. src = base_dir / "library" / f"job-{n}.gcode"
  477. src.write_bytes(b"G28\n")
  478. lib = LibraryFile(
  479. filename=f"job-{n}.gcode",
  480. file_path=str(src),
  481. file_type="gcode",
  482. file_size=src.stat().st_size,
  483. )
  484. db.add(lib)
  485. printer = Printer(
  486. name=f"Printer {n}",
  487. serial_number=f"NT-{n}",
  488. ip_address=f"10.2.0.{n + 1}",
  489. access_code="access-code",
  490. model="A1",
  491. )
  492. db.add(printer)
  493. await db.flush()
  494. db.add(
  495. PrintQueueItem(
  496. printer_id=printer.id,
  497. library_file_id=lib.id,
  498. status="pending",
  499. position=n,
  500. print_time_seconds=None, # nothing cached either — the crashing shape
  501. )
  502. )
  503. await db.commit()
  504. ctx = SimpleNamespace(session_maker=session_maker, base_dir=base_dir, printer_ids=None)
  505. job_started = AsyncMock()
  506. await _run_check_queue(ctx, _UploadRecorder(), job_started=job_started)
  507. assert await _statuses(ctx) == ["printing", "printing"]
  508. assert job_started.await_count == 2, (
  509. "the job-started notification was lost — _start_print raised after the "
  510. "printer had already been sent the job"
  511. )
  512. finally:
  513. await engine.dispose()