test_finish_photo_moment_sync.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. """Regression tests for the #1790 producer-consumer synchronization.
  2. `on_finish_photo_moment` (producer) and `_background_finish_photo`
  3. (consumer) are dispatched back-to-back on the FINISH-state fallback path
  4. (`bambu_mqtt.py:3258-3297`). Before #1790, the consumer ran a single
  5. `pop()` on `_stage22_finish_frames` with no wait — racing past the
  6. producer with an empty result, then doing its own RTSP grab that
  7. collided with the producer's still-in-flight grab (Bambu printers allow
  8. one RTSP client). Net result: a captured frame was logged, the cache
  9. was populated ~1s later, but the notification went text-only.
  10. The fix is an `asyncio.Event` per printer registered in
  11. `_stage22_finish_in_flight` by the producer and awaited (with timeout)
  12. by the consumer. These tests pin the producer side of that contract.
  13. """
  14. import asyncio
  15. import logging
  16. from contextlib import asynccontextmanager
  17. from types import SimpleNamespace
  18. from unittest.mock import AsyncMock
  19. import pytest
  20. from backend.app import main as main_module
  21. from backend.app.main import on_finish_photo_moment
  22. from backend.app.services import print_dispatch_context
  23. @asynccontextmanager
  24. async def _fake_session(printer):
  25. """Async-session stub that returns `printer` from scalar_one_or_none()."""
  26. result = SimpleNamespace(scalar_one_or_none=lambda: printer)
  27. session = SimpleNamespace(execute=AsyncMock(return_value=result))
  28. yield session
  29. @pytest.fixture
  30. def fake_printer():
  31. return SimpleNamespace(
  32. id=7,
  33. ip_address="192.0.2.7",
  34. access_code="x",
  35. model="X1C",
  36. external_camera_enabled=False,
  37. external_camera_url=None,
  38. external_camera_type=None,
  39. external_camera_snapshot_url=None,
  40. )
  41. @pytest.fixture(autouse=True)
  42. def _clean_state():
  43. """Don't leak event/cache dict entries across tests."""
  44. main_module._stage22_finish_in_flight.clear()
  45. main_module._stage22_finish_frames.clear()
  46. main_module._inprint_frame_bank.clear()
  47. main_module._inprint_frame_bank_ts.clear()
  48. print_dispatch_context.clear(7)
  49. yield
  50. main_module._stage22_finish_in_flight.clear()
  51. main_module._stage22_finish_frames.clear()
  52. main_module._inprint_frame_bank.clear()
  53. main_module._inprint_frame_bank_ts.clear()
  54. print_dispatch_context.clear(7)
  55. @pytest.fixture
  56. def patched_env(fake_printer, monkeypatch):
  57. monkeypatch.setattr(main_module, "async_session", lambda: _fake_session(fake_printer))
  58. async def _get_setting(_db, key):
  59. if key == "capture_finish_photo":
  60. return "true"
  61. return None
  62. monkeypatch.setattr(
  63. "backend.app.api.routes.settings.get_setting",
  64. _get_setting,
  65. )
  66. monkeypatch.setattr(
  67. "backend.app.api.routes.camera.get_buffered_frame",
  68. lambda _pid: None,
  69. )
  70. # #2547: default the plate restore to "print height unknown", so tests that
  71. # aren't about the restore never reach the G-code path. Tests that ARE about
  72. # it override these two.
  73. async def _no_height(_printer_id, _data, _logger):
  74. return None
  75. async def _not_blocked(_printer_id):
  76. return False
  77. monkeypatch.setattr(main_module, "_max_z_for_current_print", _no_height)
  78. monkeypatch.setattr(main_module, "_plate_restore_is_blocked_by_queue", _not_blocked)
  79. return fake_printer
  80. async def test_event_registered_before_first_await(patched_env, monkeypatch):
  81. """The consumer needs to find the event the moment it polls — that
  82. means registration must complete BEFORE any `await` yields control
  83. back to the loop."""
  84. # Slow the first await (DB session entry) so we can observe the dict
  85. # before the producer makes any real progress.
  86. seen_during_capture = {}
  87. async def _slow_capture(**_kwargs):
  88. seen_during_capture["registered"] = patched_env.id in main_module._stage22_finish_in_flight
  89. await asyncio.sleep(0)
  90. return b"\xff\xd8frame"
  91. monkeypatch.setattr(
  92. "backend.app.services.camera.capture_camera_frame_bytes",
  93. _slow_capture,
  94. )
  95. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  96. assert seen_during_capture["registered"] is True
  97. async def test_event_set_after_successful_capture(patched_env, monkeypatch):
  98. async def _capture(**_kwargs):
  99. return b"\xff\xd8frame"
  100. monkeypatch.setattr(
  101. "backend.app.services.camera.capture_camera_frame_bytes",
  102. _capture,
  103. )
  104. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  105. event = main_module._stage22_finish_in_flight[patched_env.id]
  106. assert event.is_set()
  107. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8frame"
  108. async def test_event_set_when_capture_returns_no_frame(patched_env, monkeypatch):
  109. """Producer gives up (RTSP timeout, no buffered frame, no external
  110. camera) — consumer must NOT wait the full 20s for nothing."""
  111. async def _capture(**_kwargs):
  112. return None
  113. monkeypatch.setattr(
  114. "backend.app.services.camera.capture_camera_frame_bytes",
  115. _capture,
  116. )
  117. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  118. event = main_module._stage22_finish_in_flight[patched_env.id]
  119. assert event.is_set()
  120. assert patched_env.id not in main_module._stage22_finish_frames
  121. async def test_event_set_even_when_capture_raises(patched_env, monkeypatch):
  122. """Producer hit a bug or network error — `finally` still has to
  123. release the consumer."""
  124. async def _capture(**_kwargs):
  125. raise RuntimeError("camera went away")
  126. monkeypatch.setattr(
  127. "backend.app.services.camera.capture_camera_frame_bytes",
  128. _capture,
  129. )
  130. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  131. event = main_module._stage22_finish_in_flight[patched_env.id]
  132. assert event.is_set()
  133. async def test_no_event_when_timelapse_was_active(patched_env):
  134. """On the timelapse-on path the consumer takes the
  135. `_capture_finish_photo_from_timelapse` branch and shouldn't be
  136. blocked by a producer wait — the producer doesn't enter the
  137. lifecycle."""
  138. await on_finish_photo_moment(
  139. patched_env.id,
  140. {"trigger": "stage_22", "timelapse_was_active": True},
  141. )
  142. assert patched_env.id not in main_module._stage22_finish_in_flight
  143. async def test_event_set_when_capture_setting_disabled(patched_env, monkeypatch):
  144. """Even on the early-return-before-capture path, the event must be
  145. released so the consumer doesn't hang on a no-op producer."""
  146. async def _disabled_setting(_db, _key):
  147. return "false"
  148. monkeypatch.setattr(
  149. "backend.app.api.routes.settings.get_setting",
  150. _disabled_setting,
  151. )
  152. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  153. event = main_module._stage22_finish_in_flight[patched_env.id]
  154. assert event.is_set()
  155. async def test_consumer_wait_unblocked_when_producer_completes(patched_env, monkeypatch):
  156. """End-to-end sync check: a consumer-style waiter awaiting the
  157. event finishes promptly once the producer's finally fires."""
  158. async def _capture(**_kwargs):
  159. await asyncio.sleep(0.05)
  160. return b"\xff\xd8frame"
  161. monkeypatch.setattr(
  162. "backend.app.services.camera.capture_camera_frame_bytes",
  163. _capture,
  164. )
  165. producer = asyncio.create_task(on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"}))
  166. await asyncio.sleep(0) # let the producer register
  167. event = main_module._stage22_finish_in_flight[patched_env.id]
  168. await asyncio.wait_for(event.wait(), timeout=1.0)
  169. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8frame"
  170. await producer
  171. async def test_finish_state_prefers_banked_frame_when_end_gcode_was_injected(patched_env, monkeypatch):
  172. """#1867: when Bambuddy injected End G-code, a SwapMod snippet may already
  173. have ejected the plate by FINISH — so the banked in-print frame is used and
  174. the live grab must not run."""
  175. print_dispatch_context.mark_pending(patched_env.id)
  176. print_dispatch_context.adopt(patched_env.id)
  177. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  178. live_called = {"n": 0}
  179. async def _live(**_kwargs):
  180. live_called["n"] += 1
  181. return b"\xff\xd8live-post-swap"
  182. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  183. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  184. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8banked"
  185. assert live_called["n"] == 0
  186. async def test_finish_state_grabs_live_when_no_end_gcode_was_injected(patched_env, monkeypatch):
  187. """#2547: the ordinary case. Nothing moved the plate, the toolhead is
  188. parked, and the print is still sitting there — so the live frame is the
  189. finished print, and a banked mid-print frame must NOT win over it.
  190. Preferring the bank here unconditionally, which is what this code used to
  191. do, is how the H2C shipped a photo with the toolhead over the part."""
  192. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked-midprint"
  193. async def _live(**_kwargs):
  194. return b"\xff\xd8live-finished-print"
  195. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  196. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  197. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live-finished-print"
  198. async def test_finish_state_falls_back_to_live_when_bank_is_empty(patched_env, monkeypatch):
  199. """End G-code was injected but nothing was ever banked (feature just
  200. enabled, tiny print, capture failures). Degrade to a live grab rather than
  201. sending a text-only notification."""
  202. print_dispatch_context.mark_pending(patched_env.id)
  203. print_dispatch_context.adopt(patched_env.id)
  204. async def _live(**_kwargs):
  205. return b"\xff\xd8live"
  206. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  207. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  208. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live"
  209. async def test_stage_22_trigger_ignores_bank(patched_env, monkeypatch):
  210. """The `stage_22` trigger fires before any End G-code and gives cleaner
  211. (parked-toolhead, plate-still-up) framing via a live grab — the bank is only
  212. for the post-swap `finish_state` path, so it must be ignored here."""
  213. print_dispatch_context.mark_pending(patched_env.id)
  214. print_dispatch_context.adopt(patched_env.id)
  215. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  216. async def _live(**_kwargs):
  217. return b"\xff\xd8live"
  218. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  219. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  220. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live"
  221. # --- #1867 banking helper (_maybe_bank_inprint_frame) --------------------
  222. def _bank_env(monkeypatch, *, state="RUNNING", sub_stage=0, total_layers=10, printer=object()):
  223. """Wire printer_manager.get_client + the snapshot capture for the bank
  224. helper. Capture returns a distinct frame per call so updates are visible."""
  225. client = SimpleNamespace(
  226. state=SimpleNamespace(state=state, mc_print_sub_stage=sub_stage, total_layers=total_layers)
  227. )
  228. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: client)
  229. monkeypatch.setattr(main_module, "async_session", lambda: _fake_session(printer))
  230. counter = {"n": 0}
  231. async def _capture(_pid, _printer, _logger):
  232. counter["n"] += 1
  233. return f"frame-{counter['n']}".encode()
  234. monkeypatch.setattr(main_module, "_capture_snapshot_for_notification", _capture)
  235. return counter
  236. async def test_bank_stores_frame_while_printing(monkeypatch):
  237. _bank_env(monkeypatch)
  238. await main_module._maybe_bank_inprint_frame(3, 5)
  239. assert main_module._inprint_frame_bank[3] == b"frame-1"
  240. async def test_bank_throttles_within_interval(monkeypatch):
  241. counter = _bank_env(monkeypatch)
  242. await main_module._maybe_bank_inprint_frame(3, 5) # banks frame-1
  243. await main_module._maybe_bank_inprint_frame(3, 6) # within 25s -> skipped
  244. assert counter["n"] == 1
  245. assert main_module._inprint_frame_bank[3] == b"frame-1"
  246. async def test_bank_throttles_on_the_last_layer_too(monkeypatch):
  247. """#2547: the last layer used to bypass the throttle so it always got a
  248. fresh frame. Now that progress advances also drive banking, that exemption
  249. would fire a camera grab on every percent tick of a multi-minute last layer
  250. — and each grab contends with the live view for the single RTSP slot."""
  251. counter = _bank_env(monkeypatch, total_layers=10)
  252. await main_module._maybe_bank_inprint_frame(3, 5) # banks frame-1
  253. await main_module._maybe_bank_inprint_frame(3, 10) # last layer, within 25s
  254. assert counter["n"] == 1
  255. assert main_module._inprint_frame_bank[3] == b"frame-1"
  256. async def test_bank_refreshes_on_the_last_layer_once_the_throttle_elapses(monkeypatch):
  257. """The point of banking on progress: a three-minute last layer keeps
  258. refreshing instead of freezing at the moment that layer began."""
  259. counter = _bank_env(monkeypatch, total_layers=10)
  260. await main_module._maybe_bank_inprint_frame(3, 10) # banks frame-1
  261. # Pretend the throttle window has passed, as it does mid-last-layer.
  262. main_module._inprint_frame_bank_ts[3] -= main_module._INPRINT_BANK_MIN_INTERVAL + 1
  263. await main_module._maybe_bank_inprint_frame(3, 10)
  264. assert counter["n"] == 2
  265. assert main_module._inprint_frame_bank[3] == b"frame-2"
  266. async def test_bank_skips_when_not_running(monkeypatch):
  267. """End G-code (plate swap) runs after RUNNING ends — the bank must not
  268. update then, which is what freezes it on the finished print."""
  269. _bank_env(monkeypatch, state="FINISH")
  270. await main_module._maybe_bank_inprint_frame(3, 10)
  271. assert 3 not in main_module._inprint_frame_bank
  272. async def test_bank_skips_during_calibration_substage(monkeypatch):
  273. """layer_num ticks during pre-print calibration (non-zero sub-stage) —
  274. banking then would capture an empty bed."""
  275. _bank_env(monkeypatch, sub_stage=14)
  276. await main_module._maybe_bank_inprint_frame(3, 2)
  277. assert 3 not in main_module._inprint_frame_bank
  278. class TestStage22CacheHoldsExactlyOneRotation:
  279. """#2708. `_stage22_finish_frames` is fed from two kinds of source: live
  280. grabs, which are raw, and the #1867 in-print bank, whose bytes came from
  281. `_capture_snapshot_for_notification` and are therefore ALREADY rotated.
  282. The consumer cannot tell them apart, so the producer normalises: every
  283. entry in the cache has had the rotation applied exactly once.
  284. Rotating on the consumer side instead put two rotations on the banked
  285. path — at 180 degrees that is the reported bug reproduced exactly, and at
  286. 90/270 it lands the photo 180 degrees out.
  287. """
  288. @staticmethod
  289. def _jpeg(width, height):
  290. import io
  291. from PIL import Image
  292. buf = io.BytesIO()
  293. Image.new("RGB", (width, height), (0, 0, 255)).save(buf, format="JPEG")
  294. return buf.getvalue()
  295. @staticmethod
  296. def _size(data):
  297. import io
  298. from PIL import Image
  299. return Image.open(io.BytesIO(data)).size
  300. async def test_a_live_grab_is_rotated_before_caching(self, patched_env, monkeypatch):
  301. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  302. raw = self._jpeg(64, 32)
  303. async def _capture(**_kwargs):
  304. return raw
  305. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  306. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  307. cached = main_module._stage22_finish_frames[patched_env.id]
  308. assert self._size(cached) == (32, 64)
  309. async def test_the_banked_frame_is_cached_verbatim(self, patched_env, monkeypatch):
  310. """The bank is filled by `_capture_snapshot_for_notification`, which
  311. rotates before it returns — so the producer must pass those bytes
  312. through untouched rather than rotating them a second time.
  313. Note this pins the invariant forward; it does not on its own prove the
  314. bug fixed, because the old producer didn't rotate anything either. The
  315. pair that discriminates is `test_a_live_grab_is_rotated_before_caching`
  316. (producer now rotates) plus the source guard below (consumer no longer
  317. does).
  318. """
  319. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  320. # #2547: the bank is only preferred when End G-code was injected.
  321. print_dispatch_context.mark_pending(patched_env.id)
  322. print_dispatch_context.adopt(patched_env.id)
  323. already_rotated = self._jpeg(32, 64) # what one rotation of a 64x32 frame looks like
  324. main_module._inprint_frame_bank[patched_env.id] = already_rotated
  325. async def _capture(**_kwargs): # pragma: no cover - must not be reached
  326. raise AssertionError("the banked frame should have been preferred")
  327. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  328. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  329. cached = main_module._stage22_finish_frames[patched_env.id]
  330. assert cached is already_rotated
  331. assert self._size(cached) == (32, 64)
  332. async def test_a_stage22_grab_is_rotated_even_though_the_bank_is_full(self, patched_env, monkeypatch):
  333. """Only the `finish_state` trigger reads the bank. The `stage_22` and
  334. `last_layer` triggers take a live grab, which still needs rotating —
  335. a shared "did we use the bank" flag must not latch on the bank merely
  336. existing."""
  337. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  338. main_module._inprint_frame_bank[patched_env.id] = self._jpeg(999, 1)
  339. async def _capture(**_kwargs):
  340. return self._jpeg(64, 32)
  341. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  342. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  343. cached = main_module._stage22_finish_frames[patched_env.id]
  344. assert self._size(cached) == (32, 64)
  345. async def test_no_rotation_configured_caches_the_bytes_as_captured(self, patched_env, monkeypatch):
  346. raw = self._jpeg(64, 32)
  347. async def _capture(**_kwargs):
  348. return raw
  349. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  350. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  351. assert main_module._stage22_finish_frames[patched_env.id] is raw
  352. def test_the_consumer_does_not_rotate_the_cached_frame():
  353. """The other half of the #2708 invariant, and the half with no runtime
  354. harness: `_background_finish_photo` is a closure nested inside
  355. `on_print_complete`, so nothing can drive its cached-frame branch
  356. directly. What it must NOT do is rotate what it pops from
  357. `_stage22_finish_frames` — the producer has already done that, and doing
  358. it again upside-downs the banked path, which is the bug this fixed.
  359. Checked against the source because the alternative is no check at all.
  360. """
  361. import ast
  362. from pathlib import Path
  363. main_py = Path(__file__).resolve().parents[2] / "app" / "main.py"
  364. assert main_py.exists(), f"guard is looking in the wrong place: {main_py}"
  365. tree = ast.parse(main_py.read_text())
  366. offenders = [
  367. node.lineno
  368. for node in ast.walk(tree)
  369. if isinstance(node, ast.Call)
  370. and isinstance(node.func, ast.Name)
  371. and node.func.id == "_apply_camera_rotation"
  372. and node.args
  373. and isinstance(node.args[0], ast.Name)
  374. and node.args[0].id == "cached_frame"
  375. ]
  376. assert not offenders, (
  377. f"main.py:{offenders} rotates the frame popped from _stage22_finish_frames. "
  378. "Those bytes are already rotated by on_finish_photo_moment (#2708); rotating "
  379. "again returns a 180-degree print to upside-down."
  380. )
  381. class TestPlateRestore:
  382. """#2547 / #1145 / #1397 / #1565: put the plate back into camera framing.
  383. Bambu's end G-code drops the plate ~100mm as the last thing it does, so by
  384. FINISH the finished print sits well below where the camera frames it. The
  385. restore commands an ABSOLUTE Z back to just above the last printed layer.
  386. Absolute is the safety argument, and these tests pin it: the target is a
  387. height the toolhead was physically at seconds earlier, so it is inside the
  388. travel limits and leaves the nozzle above the part. It is also unambiguous
  389. across model families — Z is the nozzle-to-bed gap whether the bed moves or
  390. the toolhead does — so there is no sign to get wrong the way the relative
  391. bed-jog path had (#1334).
  392. """
  393. @pytest.fixture
  394. def printer_client(self, monkeypatch):
  395. sent: list[str] = []
  396. client = SimpleNamespace(
  397. state=SimpleNamespace(state="FINISH"),
  398. send_gcode=lambda gcode: (sent.append(gcode), True)[1],
  399. )
  400. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: client)
  401. monkeypatch.setattr(main_module.asyncio, "sleep", AsyncMock())
  402. client.sent = sent
  403. return client
  404. async def test_commands_an_absolute_move_above_the_print(self, printer_client):
  405. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  406. assert ok is True
  407. assert printer_client.sent == ["G90\nG1 Z26.00 F600"]
  408. async def test_never_touches_m211(self, printer_client):
  409. """#2579: disabling soft endstops is what let a jog drive the nozzle
  410. into the bed. This path must not reintroduce it."""
  411. await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  412. assert not any("M211" in line for line in printer_client.sent)
  413. async def test_skipped_when_the_printer_is_no_longer_in_finish(self, printer_client):
  414. """The queue dispatches the next job the instant a print completes.
  415. Commanding a plate move into a starting print is not a race worth
  416. having, so state is re-read immediately before the move."""
  417. printer_client.state.state = "RUNNING"
  418. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  419. assert ok is False
  420. assert printer_client.sent == []
  421. async def test_skipped_when_the_printer_is_gone(self, monkeypatch):
  422. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: None)
  423. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  424. assert ok is False
  425. async def test_reports_failure_when_the_send_fails(self, printer_client, monkeypatch):
  426. """A failed send means the plate never moved — the caller must not go on
  427. to owe it a move back down."""
  428. monkeypatch.setattr(printer_client, "send_gcode", lambda _g: False)
  429. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  430. assert ok is False
  431. def test_park_lowers_the_plate_again(self, printer_client):
  432. main_module._park_plate_after_finish_photo(7, 16.0, logging.getLogger(__name__))
  433. assert printer_client.sent == ["G90\nG1 Z116.00 F600"]
  434. def test_park_skipped_once_the_next_print_has_started(self, printer_client):
  435. printer_client.state.state = "RUNNING"
  436. main_module._park_plate_after_finish_photo(7, 16.0, logging.getLogger(__name__))
  437. assert printer_client.sent == []
  438. class TestPlateRestoreWiring:
  439. """The restore only runs in the one situation it is correct for, and the
  440. plate always comes back down afterwards."""
  441. @pytest.fixture
  442. def restore_env(self, patched_env, monkeypatch):
  443. calls = {"restore": [], "park": [], "blocked": False, "height": 16.0}
  444. async def _height(_printer_id, _data, _logger):
  445. return calls["height"]
  446. async def _blocked(_printer_id):
  447. return calls["blocked"]
  448. async def _restore(printer_id, max_z, _logger):
  449. calls["restore"].append((printer_id, max_z))
  450. return True
  451. def _park(printer_id, max_z, _logger):
  452. calls["park"].append((printer_id, max_z))
  453. monkeypatch.setattr(main_module, "_max_z_for_current_print", _height)
  454. monkeypatch.setattr(main_module, "_plate_restore_is_blocked_by_queue", _blocked)
  455. monkeypatch.setattr(main_module, "_restore_plate_for_finish_photo", _restore)
  456. monkeypatch.setattr(main_module, "_park_plate_after_finish_photo", _park)
  457. async def _live(**_kwargs):
  458. return b"\xff\xd8live"
  459. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  460. return calls
  461. async def test_restores_then_parks_on_the_finish_state_path(self, patched_env, restore_env):
  462. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  463. assert restore_env["restore"] == [(patched_env.id, 16.0)]
  464. assert restore_env["park"] == [(patched_env.id, 16.0)]
  465. async def test_not_restored_on_the_stage_22_path(self, patched_env, restore_env):
  466. """Stage 22 fires before the end G-code drops the plate — it is already
  467. where we want it, and moving it would only cost the settle delay."""
  468. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  469. assert restore_env["restore"] == []
  470. assert restore_env["park"] == []
  471. async def test_not_restored_when_the_banked_frame_is_used(self, patched_env, restore_env):
  472. """The plate has been swapped out — no move brings the print back."""
  473. print_dispatch_context.mark_pending(patched_env.id)
  474. print_dispatch_context.adopt(patched_env.id)
  475. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  476. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  477. assert restore_env["restore"] == []
  478. assert restore_env["park"] == []
  479. async def test_not_restored_when_end_gcode_was_injected_but_the_bank_is_empty(self, patched_env, restore_env):
  480. """A plate-swap machine may have just ejected its plate. Even with no
  481. banked frame to fall back on, driving Z into whatever a swap mechanism
  482. is doing is not worth a photo of a bed we know may be bare."""
  483. print_dispatch_context.mark_pending(patched_env.id)
  484. print_dispatch_context.adopt(patched_env.id)
  485. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  486. assert restore_env["restore"] == []
  487. assert restore_env["park"] == []
  488. async def test_not_restored_when_the_print_height_is_unknown(self, patched_env, restore_env):
  489. restore_env["height"] = None
  490. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  491. assert restore_env["restore"] == []
  492. assert restore_env["park"] == []
  493. async def test_not_restored_when_another_job_is_queued(self, patched_env, restore_env):
  494. restore_env["blocked"] = True
  495. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  496. assert restore_env["restore"] == []
  497. assert restore_env["park"] == []
  498. async def test_not_restored_when_the_setting_is_off(self, patched_env, restore_env, monkeypatch):
  499. async def _get_setting(_db, key):
  500. if key == "capture_finish_photo":
  501. return "true"
  502. if key == "finish_photo_restore_plate":
  503. return "false"
  504. return None
  505. monkeypatch.setattr("backend.app.api.routes.settings.get_setting", _get_setting)
  506. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  507. assert restore_env["restore"] == []
  508. assert restore_env["park"] == []
  509. async def test_plate_is_parked_even_when_the_capture_throws(self, patched_env, restore_env, monkeypatch):
  510. """We raised it, so we owe the move back down — including when the grab
  511. between the two fails. Otherwise the user finds the print pinned under
  512. the nozzle."""
  513. async def _boom(**_kwargs):
  514. raise RuntimeError("camera gone")
  515. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _boom)
  516. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  517. assert restore_env["restore"] == [(patched_env.id, 16.0)]
  518. assert restore_env["park"] == [(patched_env.id, 16.0)]
  519. async def test_producer_event_is_still_set_after_a_restore(self, patched_env, restore_env):
  520. """#1790: the consumer's bounded wait must be released on every exit,
  521. and the restore added a new path through the producer."""
  522. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  523. assert main_module._stage22_finish_in_flight[patched_env.id].is_set()
  524. async def test_producer_wait_budget_covers_the_restore():
  525. """The consumer's wait has to outlast settle + a worst-case RTSP grab, and
  526. still finish inside the notification's own photo budget — otherwise the
  527. restore path is cut off by a timeout somewhere above it."""
  528. assert main_module._FINISH_PHOTO_PRODUCER_WAIT_SECONDS > main_module._PLATE_RESTORE_SETTLE_SECONDS + 15
  529. class TestMaxZResolution:
  530. """#2547 safety: the height that becomes a Z-move target must provably
  531. belong to the print that just finished.
  532. A height from another print is the one failure mode that could drive the
  533. nozzle into the model — 20mm carried onto a 200mm print commands the plate
  534. up through the part. So the resolver refuses on every ambiguity rather than
  535. falling back to "whatever ran last on this printer".
  536. """
  537. @staticmethod
  538. def _archive(**overrides):
  539. base = {
  540. "id": 11,
  541. "file_path": "/data/archive/1/job/job.3mf",
  542. "plate_id": 1,
  543. "total_layers": 30,
  544. }
  545. base.update(overrides)
  546. return SimpleNamespace(**base)
  547. @pytest.fixture
  548. def resolver_env(self, monkeypatch):
  549. env = {"archive": self._archive(), "reported_layers": 30, "height": 16.0, "where": None}
  550. @asynccontextmanager
  551. async def _session():
  552. async def _execute(stmt):
  553. env["where"] = str(stmt)
  554. return SimpleNamespace(scalar_one_or_none=lambda: env["archive"])
  555. yield SimpleNamespace(execute=_execute)
  556. monkeypatch.setattr(main_module, "async_session", _session)
  557. monkeypatch.setattr(
  558. main_module.printer_manager,
  559. "get_client",
  560. lambda _pid: SimpleNamespace(state=SimpleNamespace(total_layers=env["reported_layers"])),
  561. )
  562. monkeypatch.setattr(
  563. "backend.app.utils.threemf_tools.extract_max_z_height_from_3mf",
  564. lambda _path, _plate: env["height"],
  565. )
  566. return env
  567. async def test_returns_the_height_when_name_and_layers_agree(self, resolver_env):
  568. height = await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__))
  569. assert height == 16.0
  570. async def test_refuses_when_the_print_has_no_name_to_match_on(self, resolver_env):
  571. """Without an identifier there is nothing to bind the archive to, and
  572. the query would degrade to 'the newest row for this printer'."""
  573. height = await main_module._max_z_for_current_print(1, {}, logging.getLogger(__name__))
  574. assert height is None
  575. assert resolver_env["where"] is None # refused before touching the DB
  576. async def test_refuses_when_no_archive_matches_the_name(self, resolver_env):
  577. resolver_env["archive"] = None
  578. height = await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__))
  579. assert height is None
  580. async def test_refuses_when_the_layer_counts_disagree(self, resolver_env):
  581. """The corroboration check. The archive's layer count comes from the
  582. 3MF; the printer's comes from MQTT. If two independent sources disagree,
  583. the row is not this print whatever its name says."""
  584. resolver_env["reported_layers"] = 240
  585. height = await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__))
  586. assert height is None
  587. async def test_proceeds_when_a_layer_count_is_simply_unknown(self, resolver_env):
  588. """Absent is not the same as contradictory — a print Bambuddy has no
  589. layer count for still gets its height, because the name matched."""
  590. resolver_env["reported_layers"] = 0
  591. assert (
  592. await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__)) == 16.0
  593. )
  594. resolver_env["reported_layers"] = 30
  595. resolver_env["archive"] = self._archive(total_layers=None)
  596. assert (
  597. await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__)) == 16.0
  598. )
  599. async def test_matches_by_equality_not_substring(self, resolver_env):
  600. """`LIKE %name%` would let "Cube" resolve to "Cube v2" — a different
  601. print, quite possibly a much taller one."""
  602. await main_module._max_z_for_current_print(1, {"subtask_name": "Cube"}, logging.getLogger(__name__))
  603. assert "LIKE" not in resolver_env["where"].upper()
  604. async def test_refuses_when_the_archive_has_no_file(self, resolver_env):
  605. resolver_env["archive"] = self._archive(file_path=None)
  606. height = await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__))
  607. assert height is None
  608. async def test_refuses_when_the_3mf_has_no_height(self, resolver_env):
  609. resolver_env["height"] = None
  610. height = await main_module._max_z_for_current_print(1, {"subtask_name": "job"}, logging.getLogger(__name__))
  611. assert height is None
  612. class TestTimelapsePathPlateRestore:
  613. """#2547: the timelapse path falls through to a live grab whenever the
  614. video hasn't landed yet — the documented usual outcome on P1-series.
  615. `on_finish_photo_moment` returns early for those prints without raising the
  616. plate, so the photo that actually ships in the notification would be of an
  617. already-dropped plate. The consumer therefore does the restore itself, but
  618. only on that path — everywhere else the producer has already done it.
  619. """
  620. def test_notification_budget_outlasts_the_video_poll_plus_a_restore(self):
  621. """The wait has to cover polling for the video AND the restore that
  622. follows when it doesn't arrive. At the old flat 75s the fallback was
  623. cut off mid-settle, so the plate would have moved for a photo nobody
  624. was still waiting for."""
  625. assert (
  626. main_module._FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + main_module._FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  627. > main_module._FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + main_module._PLATE_RESTORE_SETTLE_SECONDS + 15
  628. )
  629. async def test_producer_skips_the_restore_when_a_timelapse_was_recording(self, patched_env, monkeypatch):
  630. """The producer returns before any of the restore code — the consumer
  631. owns it on this path, and doing it in both would move the plate twice."""
  632. moved = []
  633. async def _restore(printer_id, max_z, _logger):
  634. moved.append((printer_id, max_z))
  635. return True
  636. async def _height(_printer_id, _data, _logger):
  637. return 16.0
  638. monkeypatch.setattr(main_module, "_restore_plate_for_finish_photo", _restore)
  639. monkeypatch.setattr(main_module, "_max_z_for_current_print", _height)
  640. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state", "timelapse_was_active": True})
  641. assert moved == []