test_scheduler_cleanup_library.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. from contextlib import ExitStack
  2. from pathlib import Path
  3. from types import SimpleNamespace
  4. from unittest.mock import AsyncMock, MagicMock, patch
  5. import pytest
  6. from sqlalchemy import select
  7. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  8. import backend.app.models # noqa: F401 - populate Base.metadata
  9. import backend.app.services.print_scheduler as scheduler_module
  10. from backend.app.core.database import Base
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.library import LibraryFile
  13. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  14. from backend.app.models.printer import Printer
  15. from backend.app.services.print_scheduler import PrintScheduler
  16. @pytest.fixture
  17. async def queue_factory(tmp_path):
  18. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  19. async with engine.begin() as conn:
  20. await conn.run_sync(Base.metadata.create_all)
  21. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  22. case_counter = 0
  23. async def make_case(*, cleanup=True, is_external=False, thumbnail_path=None, siblings=()):
  24. nonlocal case_counter
  25. case_counter += 1
  26. base_dir = tmp_path / f"case-{case_counter}"
  27. base_dir.mkdir()
  28. source_path = base_dir / "library" / f"source-{case_counter}.3mf"
  29. source_path.parent.mkdir()
  30. source_path.write_bytes(b"library source")
  31. thumbnail_actual_path = None
  32. thumbnail_db_path = None
  33. if thumbnail_path == "relative":
  34. thumbnail_db_path = f"thumbs/preview-{case_counter}.png"
  35. thumbnail_actual_path = base_dir / thumbnail_db_path
  36. elif thumbnail_path == "absolute":
  37. thumbnail_actual_path = tmp_path / f"absolute-preview-{case_counter}.png"
  38. thumbnail_db_path = str(thumbnail_actual_path)
  39. elif thumbnail_path is not None:
  40. thumbnail_actual_path = Path(thumbnail_path)
  41. thumbnail_db_path = str(thumbnail_path)
  42. if thumbnail_actual_path:
  43. thumbnail_actual_path.parent.mkdir(parents=True, exist_ok=True)
  44. thumbnail_actual_path.write_bytes(b"thumbnail")
  45. async with session_maker() as db:
  46. printer = Printer(
  47. name=f"Printer {case_counter}",
  48. serial_number=f"SERIAL-{case_counter}",
  49. ip_address="127.0.0.1",
  50. access_code="access-code",
  51. model="X1C",
  52. )
  53. library_file = LibraryFile(
  54. filename=f"source-{case_counter}.3mf",
  55. file_path=str(source_path),
  56. file_type="3mf",
  57. file_size=source_path.stat().st_size,
  58. file_hash=None,
  59. thumbnail_path=thumbnail_db_path,
  60. file_metadata=None,
  61. is_external=is_external,
  62. )
  63. db.add_all([printer, library_file])
  64. await db.flush()
  65. item = PrintQueueItem(
  66. printer_id=printer.id,
  67. library_file_id=library_file.id,
  68. status="pending",
  69. cleanup_library_after_dispatch=cleanup,
  70. bed_levelling="on",
  71. flow_cali="off",
  72. vibration_cali=True,
  73. layer_inspect=False,
  74. timelapse=False,
  75. use_ams=True,
  76. nozzle_offset_cali="on",
  77. )
  78. db.add(item)
  79. await db.flush()
  80. # The other copies of a quantity>1 dispatch (#2819). Each entry is a
  81. # dict of overrides: `status`, `own_archive` for a copy that already
  82. # holds one, and `extra_variant` for a cross-model copy that keeps a
  83. # candidate this cleanup does not consume.
  84. sibling_ids = []
  85. other_file = None
  86. for spec in siblings:
  87. sibling = PrintQueueItem(
  88. printer_id=printer.id,
  89. library_file_id=None if spec.get("variants") else library_file.id,
  90. status=spec.get("status", "pending"),
  91. cleanup_library_after_dispatch=cleanup,
  92. )
  93. if spec.get("own_archive"):
  94. own = PrintArchive(
  95. printer_id=printer.id,
  96. filename="already-dispatched.3mf",
  97. file_path="archives/already-dispatched.3mf",
  98. file_size=1,
  99. status="printing",
  100. )
  101. db.add(own)
  102. await db.flush()
  103. sibling.archive_id = own.id
  104. db.add(sibling)
  105. await db.flush()
  106. if spec.get("variants"):
  107. db.add(
  108. PrintQueueVariant(
  109. queue_item_id=sibling.id,
  110. library_file_id=library_file.id,
  111. target_model="X1C",
  112. position=0,
  113. )
  114. )
  115. if spec.get("extra_variant"):
  116. if other_file is None:
  117. other_path = base_dir / "library" / f"other-{case_counter}.3mf"
  118. other_path.write_bytes(b"other source")
  119. other_file = LibraryFile(
  120. filename=f"other-{case_counter}.3mf",
  121. file_path=str(other_path),
  122. file_type="3mf",
  123. file_size=other_path.stat().st_size,
  124. )
  125. db.add(other_file)
  126. await db.flush()
  127. db.add(
  128. PrintQueueVariant(
  129. queue_item_id=sibling.id,
  130. library_file_id=other_file.id,
  131. target_model="P1S",
  132. position=1,
  133. )
  134. )
  135. sibling_ids.append(sibling.id)
  136. await db.commit()
  137. return SimpleNamespace(
  138. session_maker=session_maker,
  139. base_dir=base_dir,
  140. source_path=source_path,
  141. thumbnail_path=thumbnail_actual_path,
  142. printer_id=printer.id,
  143. library_file_id=library_file.id,
  144. queue_item_id=item.id,
  145. sibling_ids=sibling_ids,
  146. other_library_file_id=other_file.id if other_file is not None else None,
  147. archive_path=None,
  148. upload=AsyncMock(return_value=True),
  149. start_print=MagicMock(return_value=True),
  150. )
  151. try:
  152. yield make_case
  153. finally:
  154. await engine.dispose()
  155. async def _dispatch_library_item(ctx, *, archive_failure=False, unlink_side_effect=None):
  156. scheduler = PrintScheduler()
  157. async def archive_print(
  158. self,
  159. *,
  160. printer_id,
  161. source_file,
  162. original_filename,
  163. created_by_id=None,
  164. project_id=None,
  165. cost_center_id=None,
  166. plate_id=None,
  167. library_file_id=None,
  168. ):
  169. if archive_failure:
  170. raise RuntimeError("archive copy failed")
  171. archive_rel_path = Path("archives") / f"archive-{ctx.queue_item_id}.3mf"
  172. ctx.archive_path = ctx.base_dir / archive_rel_path
  173. ctx.archive_path.parent.mkdir(parents=True, exist_ok=True)
  174. ctx.archive_path.write_bytes(Path(source_file).read_bytes())
  175. archive = PrintArchive(
  176. printer_id=printer_id,
  177. filename=original_filename,
  178. file_path=str(archive_rel_path),
  179. file_size=ctx.archive_path.stat().st_size,
  180. content_hash=None,
  181. thumbnail_path=None,
  182. timelapse_path=None,
  183. print_time_seconds=120,
  184. status="completed",
  185. project_id=project_id,
  186. library_file_id=library_file_id,
  187. created_by_id=created_by_id,
  188. )
  189. self.db.add(archive)
  190. await self.db.flush()
  191. return archive
  192. patches = [
  193. patch.object(scheduler_module.settings, "base_dir", ctx.base_dir),
  194. patch("backend.app.services.archive.ArchiveService.archive_print", new=archive_print),
  195. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  196. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=None)),
  197. patch("backend.app.services.print_scheduler.printer_manager.start_print", ctx.start_print),
  198. patch("backend.app.services.print_scheduler.printer_manager.set_awaiting_plate_clear", MagicMock()),
  199. patch(
  200. "backend.app.services.print_scheduler.get_ftp_retry_settings", AsyncMock(return_value=(False, 0, 0, 1.0))
  201. ),
  202. patch("backend.app.services.print_scheduler.delete_file_async", AsyncMock(return_value=True)),
  203. patch("backend.app.services.print_scheduler.upload_file_async", ctx.upload),
  204. patch("backend.app.services.print_scheduler.cache_3mf_download", MagicMock()),
  205. patch("backend.app.services.print_scheduler.spawn_background_task", MagicMock()),
  206. patch("backend.app.services.notification_service.notification_service.on_queue_job_started", AsyncMock()),
  207. patch("backend.app.services.notification_service.notification_service.on_queue_job_failed", AsyncMock()),
  208. patch("backend.app.services.mqtt_relay.mqtt_relay.on_queue_job_started", AsyncMock()),
  209. patch.object(scheduler, "_propagate_owner_to_printer_manager", AsyncMock()),
  210. patch.object(scheduler, "_power_off_if_needed", AsyncMock()),
  211. ]
  212. if unlink_side_effect:
  213. patches.append(patch.object(type(ctx.source_path), "unlink", unlink_side_effect))
  214. with ExitStack() as stack:
  215. for patcher in patches:
  216. stack.enter_context(patcher)
  217. async with ctx.session_maker() as db:
  218. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  219. await scheduler._start_print(db, item)
  220. async def _queue_snapshot(ctx):
  221. async with ctx.session_maker() as db:
  222. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  223. library_file = await db.get(LibraryFile, ctx.library_file_id)
  224. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id else None
  225. return item, library_file, archive
  226. @pytest.mark.asyncio
  227. async def test_cleanup_unlinks_library_file_and_removes_db_row(queue_factory):
  228. ctx = await queue_factory(cleanup=True)
  229. await _dispatch_library_item(ctx)
  230. item, library_file, archive = await _queue_snapshot(ctx)
  231. assert item.status == "printing"
  232. assert item.library_file_id is None
  233. assert item.archive_id == archive.id
  234. assert library_file is None
  235. assert not ctx.source_path.exists()
  236. @pytest.mark.asyncio
  237. async def test_external_library_file_skips_cleanup(queue_factory):
  238. ctx = await queue_factory(cleanup=True, is_external=True)
  239. await _dispatch_library_item(ctx)
  240. item, library_file, archive = await _queue_snapshot(ctx)
  241. assert item.status == "printing"
  242. assert item.library_file_id == ctx.library_file_id
  243. assert item.archive_id == archive.id
  244. assert library_file is not None
  245. assert ctx.source_path.exists()
  246. @pytest.mark.asyncio
  247. async def test_archive_creation_failure_skips_cleanup_and_dispatch(queue_factory):
  248. ctx = await queue_factory(cleanup=True, thumbnail_path="relative")
  249. await _dispatch_library_item(ctx, archive_failure=True)
  250. item, library_file, archive = await _queue_snapshot(ctx)
  251. assert item.status == "failed"
  252. assert item.error_message == "Failed to create archive from library file"
  253. assert item.archive_id is None
  254. assert archive is None
  255. assert library_file is not None
  256. assert ctx.source_path.exists()
  257. assert ctx.thumbnail_path.exists()
  258. ctx.upload.assert_not_awaited()
  259. ctx.start_print.assert_not_called()
  260. @pytest.mark.parametrize("thumbnail_path", ["absolute", "relative"])
  261. @pytest.mark.asyncio
  262. async def test_cleanup_resolves_absolute_and_relative_thumbnail_paths(queue_factory, thumbnail_path):
  263. ctx = await queue_factory(cleanup=True, thumbnail_path=thumbnail_path)
  264. await _dispatch_library_item(ctx)
  265. item, library_file, archive = await _queue_snapshot(ctx)
  266. assert item.status == "printing"
  267. assert item.archive_id == archive.id
  268. assert library_file is None
  269. assert not ctx.source_path.exists()
  270. assert not ctx.thumbnail_path.exists()
  271. @pytest.mark.asyncio
  272. async def test_archive_copy_survives_library_cleanup(queue_factory):
  273. ctx = await queue_factory(cleanup=True)
  274. await _dispatch_library_item(ctx)
  275. assert not ctx.source_path.exists()
  276. assert ctx.archive_path.exists()
  277. assert ctx.archive_path.read_bytes() == b"library source"
  278. uploaded_path = ctx.upload.await_args.args[2]
  279. assert uploaded_path == ctx.archive_path
  280. async def _sibling_snapshot(ctx):
  281. async with ctx.session_maker() as db:
  282. return [await db.get(PrintQueueItem, sid) for sid in ctx.sibling_ids]
  283. async def _variant_files(ctx, sibling_id):
  284. async with ctx.session_maker() as db:
  285. rows = await db.execute(
  286. select(PrintQueueVariant.library_file_id).where(PrintQueueVariant.queue_item_id == sibling_id)
  287. )
  288. return sorted(rows.scalars().all())
  289. # ---------------------------------------------------------------------------
  290. # Sibling copies of the same library row (#2819)
  291. #
  292. # `quantity > 1` on the printer-card upload-and-print flow puts the cleanup flag
  293. # on every copy, and batch clones inherit `library_file_id`. Consuming the row
  294. # for the first copy used to leave the others pointing at it, which failed with
  295. # "Library file not found" on SQLite and deleted the rows outright on
  296. # PostgreSQL, where the FK cascade is enforced.
  297. #
  298. # These run on SQLite, so they cover the orphan half directly. The cascade half
  299. # was verified by hand against a real PostgreSQL 16, building this same fixture
  300. # on both backends and comparing every row: without the fix the copies were gone
  301. # after the delete -- including the finished ones a batch order counts its
  302. # progress from, and a copy already printing from its own archive. With it, the
  303. # two backends agree row for row. `print_archives.library_file_id` is SET NULL,
  304. # so it is cleared by the same delete, which is why looking the archive up by
  305. # the consumed library id -- the obvious alternative fix -- cannot work there.
  306. # ---------------------------------------------------------------------------
  307. @pytest.mark.asyncio
  308. async def test_pending_copies_are_repointed_at_the_archive(queue_factory):
  309. ctx = await queue_factory(cleanup=True, siblings=({}, {}))
  310. await _dispatch_library_item(ctx)
  311. item, library_file, archive = await _queue_snapshot(ctx)
  312. assert library_file is None
  313. for sibling in await _sibling_snapshot(ctx):
  314. # Still queued -- the point is that they can now run, not that they run now.
  315. assert sibling.status == "pending"
  316. assert sibling.archive_id == archive.id
  317. assert sibling.library_file_id is None
  318. # Their file is already consumed; leaving this armed would delete
  319. # whatever library row they were next given.
  320. assert sibling.cleanup_library_after_dispatch is False
  321. @pytest.mark.asyncio
  322. async def test_copy_that_already_has_its_own_archive_keeps_it(queue_factory):
  323. ctx = await queue_factory(cleanup=True, siblings=({"own_archive": True, "status": "printing"},))
  324. await _dispatch_library_item(ctx)
  325. _, _, archive = await _queue_snapshot(ctx)
  326. (sibling,) = await _sibling_snapshot(ctx)
  327. # It is mid-print from its own archive and does not need the library file.
  328. # Re-pointing it would swap the file under a job already running.
  329. assert sibling.archive_id != archive.id
  330. assert sibling.status == "printing"
  331. # Cleared all the same: on PostgreSQL a row still naming the file goes with
  332. # it, and this one is a job that is currently printing.
  333. assert sibling.library_file_id is None
  334. @pytest.mark.parametrize("status", ["completed", "failed", "cancelled", "aborted"])
  335. @pytest.mark.asyncio
  336. async def test_finished_copies_keep_their_outcome_and_survive_the_delete(queue_factory, status):
  337. ctx = await queue_factory(cleanup=True, siblings=({"status": status},))
  338. await _dispatch_library_item(ctx)
  339. (sibling,) = await _sibling_snapshot(ctx)
  340. # A finished row is a record of what happened, not a spare part -- it keeps
  341. # its outcome and is not handed the archive.
  342. assert sibling.status == status
  343. assert sibling.archive_id is None
  344. # But the reference has to go: it is the only thing tying the row to the
  345. # cascade that would otherwise delete it, and a batch order counts its
  346. # progress from rows exactly like this one.
  347. assert sibling.library_file_id is None
  348. @pytest.mark.asyncio
  349. async def test_skipped_copy_is_repointed_because_it_can_come_back(queue_factory):
  350. ctx = await queue_factory(cleanup=True, siblings=({"status": "skipped"},))
  351. await _dispatch_library_item(ctx)
  352. _, _, archive = await _queue_snapshot(ctx)
  353. (sibling,) = await _sibling_snapshot(ctx)
  354. # Clearing the printer's previous-success gate puts skipped items back to
  355. # pending, so this one is only waiting -- not finished.
  356. assert sibling.status == "skipped"
  357. assert sibling.archive_id == archive.id
  358. assert sibling.library_file_id is None
  359. @pytest.mark.asyncio
  360. async def test_copies_are_untouched_when_the_dispatch_does_not_consume_the_file(queue_factory):
  361. ctx = await queue_factory(cleanup=False, siblings=({},))
  362. await _dispatch_library_item(ctx)
  363. item, library_file, _ = await _queue_snapshot(ctx)
  364. assert library_file is not None
  365. (sibling,) = await _sibling_snapshot(ctx)
  366. assert sibling.library_file_id == ctx.library_file_id
  367. assert sibling.archive_id is None
  368. @pytest.mark.asyncio
  369. async def test_cross_model_copy_keeps_its_other_candidate_instead_of_the_archive(queue_factory):
  370. ctx = await queue_factory(cleanup=True, siblings=({"variants": True, "extra_variant": True},))
  371. await _dispatch_library_item(ctx)
  372. (sibling,) = await _sibling_snapshot(ctx)
  373. # It still has somewhere to go, and that candidate carries its own target
  374. # model -- pointing it at this archive would print a file the matcher never
  375. # chose.
  376. assert sibling.archive_id is None
  377. assert sibling.library_file_id is None
  378. assert await _variant_files(ctx, sibling.id) == [ctx.other_library_file_id]
  379. @pytest.mark.asyncio
  380. async def test_copy_whose_only_candidate_was_consumed_is_repointed(queue_factory):
  381. ctx = await queue_factory(cleanup=True, siblings=({"variants": True},))
  382. await _dispatch_library_item(ctx)
  383. _, _, archive = await _queue_snapshot(ctx)
  384. (sibling,) = await _sibling_snapshot(ctx)
  385. # Its one candidate is gone. Without the re-point the resolver would hold it
  386. # pending forever with nothing left to dispatch.
  387. assert sibling.archive_id == archive.id
  388. assert sibling.library_file_id is None
  389. assert await _variant_files(ctx, sibling.id) == []
  390. @pytest.mark.asyncio
  391. async def test_oserror_during_unlink_logs_orphan_path_and_does_not_crash_dispatch(queue_factory, caplog):
  392. ctx = await queue_factory(cleanup=True, thumbnail_path="relative")
  393. original_unlink = type(ctx.source_path).unlink
  394. def unlink_with_source_failure(path, *args, **kwargs):
  395. if Path(path) == ctx.source_path:
  396. raise OSError("permission denied")
  397. return original_unlink(path, *args, **kwargs)
  398. with caplog.at_level("WARNING", logger="backend.app.services.print_scheduler"):
  399. await _dispatch_library_item(ctx, unlink_side_effect=unlink_with_source_failure)
  400. item, library_file, archive = await _queue_snapshot(ctx)
  401. assert item.status == "printing"
  402. assert item.archive_id == archive.id
  403. assert item.library_file_id is None
  404. assert library_file is None
  405. assert ctx.source_path.exists()
  406. assert not ctx.thumbnail_path.exists()
  407. assert ctx.archive_path.exists()
  408. assert "TRANSIENT_LIBRARY_FILE_ORPHAN" in caplog.text
  409. assert str(ctx.source_path) in caplog.text
  410. assert "permission denied" in caplog.text