test_scheduler_cancel_race.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. """Cancel-during-dispatch race regression (#1853).
  2. The user reported: queued a batch of 10 prints, pressed Cancel on a pending
  3. item, the print started anyway. Root cause is a check-then-act race in
  4. ``_start_print``: the snapshot of pending items is taken at the top of
  5. ``check_queue``, then ``_start_print`` does FTP delete + FTP upload (5-30 s)
  6. before flipping the row to ``"printing"`` and sending MQTT. If the user wins
  7. the race and ``/cancel`` lands during that window, the scheduler's stale
  8. in-memory write of ``status="printing"`` silently overwrites the cancellation.
  9. Three guards exercised here:
  10. * Early refresh after the connectivity check — bails before FTP I/O if the
  11. row is already cancelled.
  12. * Atomic CAS at the pending→printing transition — UPDATE WHERE
  13. status='pending'; rowcount==0 means user won, do NOT send MQTT.
  14. * Best-effort delete of the file we just FTP'd up when the CAS aborts.
  15. """
  16. from contextlib import ExitStack
  17. from pathlib import Path
  18. from types import SimpleNamespace
  19. from unittest.mock import AsyncMock, MagicMock, patch
  20. import pytest
  21. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  22. import backend.app.models # noqa: F401 - populate Base.metadata
  23. import backend.app.services.print_scheduler as scheduler_module
  24. from backend.app.core.database import Base
  25. from backend.app.models.archive import PrintArchive
  26. from backend.app.models.print_queue import PrintQueueItem
  27. from backend.app.models.printer import Printer
  28. from backend.app.services.print_scheduler import PrintScheduler
  29. @pytest.fixture
  30. async def queue_factory(tmp_path):
  31. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  32. async with engine.begin() as conn:
  33. await conn.run_sync(Base.metadata.create_all)
  34. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  35. case_counter = 0
  36. async def make_case(*, status="pending"):
  37. nonlocal case_counter
  38. case_counter += 1
  39. base_dir = tmp_path / f"case-{case_counter}"
  40. base_dir.mkdir()
  41. archive_rel = Path("archives") / f"job-{case_counter}.3mf"
  42. archive_abs = base_dir / archive_rel
  43. archive_abs.parent.mkdir(parents=True, exist_ok=True)
  44. archive_abs.write_bytes(b"archive payload")
  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. db.add(printer)
  54. await db.flush()
  55. archive = PrintArchive(
  56. printer_id=printer.id,
  57. filename=f"job-{case_counter}.3mf",
  58. file_path=str(archive_rel),
  59. file_size=archive_abs.stat().st_size,
  60. content_hash=None,
  61. thumbnail_path=None,
  62. timelapse_path=None,
  63. print_time_seconds=120,
  64. status="completed",
  65. )
  66. db.add(archive)
  67. await db.flush()
  68. item = PrintQueueItem(
  69. printer_id=printer.id,
  70. archive_id=archive.id,
  71. status=status,
  72. bed_levelling="on",
  73. flow_cali="off",
  74. vibration_cali=True,
  75. layer_inspect=False,
  76. timelapse=False,
  77. use_ams=True,
  78. nozzle_offset_cali="on",
  79. )
  80. db.add(item)
  81. await db.commit()
  82. return SimpleNamespace(
  83. session_maker=session_maker,
  84. base_dir=base_dir,
  85. archive_path=archive_abs,
  86. printer_id=printer.id,
  87. archive_id=archive.id,
  88. queue_item_id=item.id,
  89. upload=AsyncMock(return_value=True),
  90. start_print=MagicMock(return_value=True),
  91. delete_file=AsyncMock(return_value=True),
  92. )
  93. try:
  94. yield make_case
  95. finally:
  96. await engine.dispose()
  97. async def _dispatch(ctx, *, upload_side_effect=None):
  98. scheduler = PrintScheduler()
  99. if upload_side_effect is not None:
  100. ctx.upload.side_effect = upload_side_effect
  101. patches = [
  102. patch.object(scheduler_module.settings, "base_dir", ctx.base_dir),
  103. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  104. patch("backend.app.services.print_scheduler.printer_manager.get_status", MagicMock(return_value=None)),
  105. patch("backend.app.services.print_scheduler.printer_manager.start_print", ctx.start_print),
  106. patch("backend.app.services.print_scheduler.printer_manager.set_awaiting_plate_clear", MagicMock()),
  107. patch(
  108. "backend.app.services.print_scheduler.get_ftp_retry_settings",
  109. AsyncMock(return_value=(False, 0, 0, 1.0)),
  110. ),
  111. patch("backend.app.services.print_scheduler.delete_file_async", ctx.delete_file),
  112. patch("backend.app.services.print_scheduler.upload_file_async", ctx.upload),
  113. patch("backend.app.services.print_scheduler.cache_3mf_download", MagicMock()),
  114. patch("backend.app.services.print_scheduler.spawn_background_task", MagicMock()),
  115. patch(
  116. "backend.app.services.notification_service.notification_service.on_queue_job_started",
  117. AsyncMock(),
  118. ),
  119. patch(
  120. "backend.app.services.notification_service.notification_service.on_queue_job_failed",
  121. AsyncMock(),
  122. ),
  123. patch("backend.app.services.mqtt_relay.mqtt_relay.on_queue_job_started", AsyncMock()),
  124. patch.object(scheduler, "_propagate_owner_to_printer_manager", AsyncMock()),
  125. patch.object(scheduler, "_power_off_if_needed", AsyncMock()),
  126. patch.object(scheduler, "_preheat_and_soak", AsyncMock()),
  127. ]
  128. with ExitStack() as stack:
  129. for patcher in patches:
  130. stack.enter_context(patcher)
  131. async with ctx.session_maker() as db:
  132. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  133. await scheduler._start_print(db, item)
  134. async def _final_status(ctx):
  135. async with ctx.session_maker() as db:
  136. item = await db.get(PrintQueueItem, ctx.queue_item_id)
  137. return item.status, item.started_at
  138. @pytest.mark.asyncio
  139. async def test_cancel_during_ftp_upload_aborts_before_mqtt(queue_factory):
  140. """User wins the race during the FTP upload — CAS must detect & bail.
  141. This is the headline #1853 scenario: snapshot saw pending, FTP upload
  142. starts, user clicks Cancel, /cancel commits ``cancelled`` to the row,
  143. FTP finishes successfully, scheduler reaches the CAS. CAS rowcount must
  144. be 0; ``printer_manager.start_print`` must NOT be called; row must stay
  145. ``cancelled``; uploaded file must be deleted from the printer's SD.
  146. """
  147. ctx = await queue_factory()
  148. async def cancel_mid_upload(*args, **kwargs):
  149. # Simulate /cancel landing in a separate session while FTP is in
  150. # flight. The endpoint commits status='cancelled' then returns 200.
  151. async with ctx.session_maker() as other_db:
  152. other_item = await other_db.get(PrintQueueItem, ctx.queue_item_id)
  153. other_item.status = "cancelled"
  154. await other_db.commit()
  155. return True
  156. await _dispatch(ctx, upload_side_effect=cancel_mid_upload)
  157. status, started_at = await _final_status(ctx)
  158. assert status == "cancelled", "CAS overwrote the user's cancellation"
  159. assert started_at is None, "started_at must not be stamped on a cancelled row"
  160. ctx.start_print.assert_not_called()
  161. # Two delete calls — the pre-upload sweep and the post-CAS cleanup.
  162. assert ctx.delete_file.await_count == 2
  163. @pytest.mark.asyncio
  164. async def test_cancel_before_ftp_upload_skips_dispatch(queue_factory):
  165. """Early-refresh path: row was cancelled before _start_print resumed.
  166. Mirrors the case where ``/cancel`` lands between the ``check_queue``
  167. snapshot and the time ``_start_print`` runs. The early ``db.refresh``
  168. after the connectivity check sees ``cancelled`` and returns immediately
  169. — no FTP upload, no MQTT send, row unchanged.
  170. """
  171. ctx = await queue_factory()
  172. # Flip to cancelled before _start_print runs; the in-memory snapshot
  173. # the scheduler holds still reads 'pending', exactly the bug shape.
  174. async with ctx.session_maker() as other_db:
  175. item = await other_db.get(PrintQueueItem, ctx.queue_item_id)
  176. item.status = "cancelled"
  177. await other_db.commit()
  178. await _dispatch(ctx)
  179. status, started_at = await _final_status(ctx)
  180. assert status == "cancelled"
  181. assert started_at is None
  182. ctx.upload.assert_not_awaited()
  183. ctx.start_print.assert_not_called()
  184. @pytest.mark.asyncio
  185. async def test_happy_path_still_dispatches(queue_factory):
  186. """Sanity: no cancel, no race — pending row flips to printing, MQTT fires.
  187. Regression guard so the CAS doesn't accidentally block normal dispatch
  188. on a row that was always pending.
  189. """
  190. ctx = await queue_factory()
  191. await _dispatch(ctx)
  192. status, started_at = await _final_status(ctx)
  193. assert status == "printing"
  194. assert started_at is not None
  195. ctx.upload.assert_awaited_once()
  196. ctx.start_print.assert_called_once()