test_timelapse_scan_2704.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. """Timelapse scan reliability (#2704).
  2. A Bambu printer in LAN-only mode never reaches Bambu's NTP server, so the clock
  3. behind both the timelapse filename and the FTP mtime drifts freely — the P1S in
  4. the report was six and a half days out. That is why the automatic scan works by
  5. diffing the printer's ``/timelapse`` listing against a snapshot taken when the
  6. print started, and why nothing in that path may fall back to comparing times.
  7. These tests pin the parts that make the diff dependable:
  8. * the candidate is chosen by exclusion, never by ordering (ordering could only
  9. be done on the printer's clock);
  10. * a download that comes up short never attaches and never triggers a delete —
  11. deleting the printer's copy is only safe because the transfer was verified;
  12. * the baseline persisted at print start is what the manual Scan button uses,
  13. instead of the clock-based strategies that cannot work on a drifted printer.
  14. """
  15. import logging
  16. from unittest.mock import AsyncMock, MagicMock, patch
  17. import pytest
  18. from backend.app.core.printer_scope import ALL_PRINTERS
  19. logger = logging.getLogger(__name__)
  20. def _printer():
  21. p = MagicMock()
  22. p.id = 1
  23. p.name = "TestP1S"
  24. p.ip_address = "192.168.1.100"
  25. p.access_code = "12345678"
  26. p.model = "P1S"
  27. return p
  28. def _video(name: str, size: int = 1000):
  29. return {"name": name, "is_directory": False, "path": f"/timelapse/{name}", "size": size}
  30. def _session(archive=None):
  31. session = AsyncMock()
  32. session.__aenter__ = AsyncMock(return_value=session)
  33. session.__aexit__ = AsyncMock()
  34. if archive is not None:
  35. session.get = AsyncMock(return_value=archive)
  36. return session
  37. class TestCandidateSelection:
  38. """Which of the printer's videos belongs to this print."""
  39. @pytest.fixture
  40. def attach(self):
  41. from backend.app.main import _attach_first_unclaimed_timelapse
  42. return _attach_first_unclaimed_timelapse
  43. @pytest.mark.asyncio
  44. async def test_nothing_new_since_baseline_is_not_an_attach(self, attach):
  45. result = await attach(
  46. 42,
  47. _printer(),
  48. [_video("video_2026-07-21_09-17-37.avi")],
  49. {"video_2026-07-21_09-17-37.avi"},
  50. set(),
  51. 1,
  52. logger,
  53. )
  54. assert result is False
  55. @pytest.mark.asyncio
  56. async def test_attaches_the_one_new_file_and_deletes_it_from_the_printer(self, attach):
  57. download = AsyncMock(return_value=b"x" * 1000)
  58. delete = AsyncMock(return_value=True)
  59. service = MagicMock()
  60. service.attach_timelapse = AsyncMock(return_value=True)
  61. with (
  62. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  63. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  64. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  65. patch("backend.app.main.async_session", return_value=_session()),
  66. patch("backend.app.main.ArchiveService", return_value=service),
  67. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  68. ):
  69. result = await attach(
  70. 42,
  71. _printer(),
  72. [_video("old.avi"), _video("video_2026-07-22_06-18-39.avi")],
  73. {"old.avi"},
  74. set(),
  75. 1,
  76. logger,
  77. )
  78. assert result is True
  79. service.attach_timelapse.assert_awaited_once()
  80. assert service.attach_timelapse.await_args.args[2] == "video_2026-07-22_06-18-39.avi"
  81. delete.assert_awaited_once()
  82. assert delete.await_args.args[2] == "/timelapse/video_2026-07-22_06-18-39.avi"
  83. @pytest.mark.asyncio
  84. async def test_skips_a_previous_prints_late_landing_video(self, attach):
  85. """Two files are new since the baseline because the previous print's
  86. video only landed after this print started. It is already attached to
  87. another archive, so it is excluded by name — no timestamps involved."""
  88. download = AsyncMock(return_value=b"y" * 1000)
  89. service = MagicMock()
  90. service.attach_timelapse = AsyncMock(return_value=True)
  91. with (
  92. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  93. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  94. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  95. patch("backend.app.main.async_session", return_value=_session()),
  96. patch("backend.app.main.ArchiveService", return_value=service),
  97. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  98. ):
  99. result = await attach(
  100. 42,
  101. _printer(),
  102. # Listing order puts the previous print's video first, so a
  103. # naive "take the first new one" would grab the wrong video.
  104. [_video("previous_print.avi"), _video("this_print.avi")],
  105. set(),
  106. {"previous_print"},
  107. 1,
  108. logger,
  109. )
  110. assert result is True
  111. assert service.attach_timelapse.await_args.args[2] == "this_print.avi"
  112. @pytest.mark.asyncio
  113. async def test_claimed_match_survives_the_mp4_conversion(self, attach):
  114. """Attached AVIs are converted to MP4 afterwards, which keeps the stem
  115. but changes the extension — so exclusion has to compare stems."""
  116. result = await attach(
  117. 42,
  118. _printer(),
  119. [_video("video_2026-07-22_06-18-39.avi")],
  120. set(),
  121. {"video_2026-07-22_06-18-39"}, # stored as .mp4 on the archive
  122. 1,
  123. logger,
  124. )
  125. assert result is False
  126. @pytest.mark.asyncio
  127. async def test_all_new_files_claimed_keeps_polling(self, attach):
  128. result = await attach(42, _printer(), [_video("a.avi"), _video("b.avi")], set(), {"a", "b"}, 1, logger)
  129. assert result is False
  130. class TestDownloadVerificationGatesTheDelete:
  131. """The printer's copy is the only other copy — it goes only after the
  132. transfer is verified against the size the listing reported."""
  133. @pytest.fixture
  134. def attach(self):
  135. from backend.app.main import _attach_first_unclaimed_timelapse
  136. return _attach_first_unclaimed_timelapse
  137. @pytest.mark.asyncio
  138. async def test_passes_the_listed_size_to_the_downloader(self, attach):
  139. download = AsyncMock(return_value=b"z" * 4096)
  140. service = MagicMock()
  141. service.attach_timelapse = AsyncMock(return_value=True)
  142. with (
  143. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  144. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  145. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  146. patch("backend.app.main.async_session", return_value=_session()),
  147. patch("backend.app.main.ArchiveService", return_value=service),
  148. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  149. ):
  150. await attach(42, _printer(), [_video("new.avi", size=4096)], set(), set(), 1, logger)
  151. assert download.await_args.kwargs["expected_size"] == 4096
  152. @pytest.mark.asyncio
  153. async def test_short_download_does_not_attach_or_delete(self, attach):
  154. """download_file_bytes_async returns None on a size mismatch. The
  155. printer must keep its copy so the next poll round can retry."""
  156. delete = AsyncMock()
  157. service = MagicMock()
  158. service.attach_timelapse = AsyncMock(return_value=True)
  159. with (
  160. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=None)),
  161. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  162. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  163. patch("backend.app.main.async_session", return_value=_session()),
  164. patch("backend.app.main.ArchiveService", return_value=service),
  165. ):
  166. result = await attach(42, _printer(), [_video("new.avi")], set(), set(), 1, logger)
  167. assert result is False
  168. service.attach_timelapse.assert_not_awaited()
  169. delete.assert_not_awaited()
  170. @pytest.mark.asyncio
  171. async def test_failed_attach_does_not_delete(self, attach):
  172. delete = AsyncMock()
  173. service = MagicMock()
  174. service.attach_timelapse = AsyncMock(return_value=False)
  175. with (
  176. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  177. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  178. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  179. patch("backend.app.main.async_session", return_value=_session()),
  180. patch("backend.app.main.ArchiveService", return_value=service),
  181. ):
  182. result = await attach(42, _printer(), [_video("new.avi")], set(), set(), 1, logger)
  183. assert result is False
  184. delete.assert_not_awaited()
  185. class TestFtpDownloadSizeCheck:
  186. """`download_file` is where a truncated FTPS transfer used to pass for a
  187. complete one — a partial buffer is non-empty, so every caller downstream
  188. treated it as a good file."""
  189. def _client(self, payload: bytes):
  190. from backend.app.services.bambu_ftp import BambuFTPClient
  191. client = BambuFTPClient("192.168.1.100", "12345678")
  192. ftp = MagicMock()
  193. ftp.retrbinary = MagicMock(side_effect=lambda cmd, cb: cb(payload))
  194. client._ftp = ftp
  195. return client
  196. def test_exact_size_passes(self):
  197. assert self._client(b"a" * 500).download_file("/timelapse/v.avi", expected_size=500) == b"a" * 500
  198. def test_short_read_is_a_failure(self):
  199. assert self._client(b"a" * 499).download_file("/timelapse/v.avi", expected_size=500) is None
  200. def test_long_read_is_a_failure(self):
  201. """Not expected in practice, but a mismatch either way means we don't
  202. know what we have, and we're about to delete the original."""
  203. assert self._client(b"a" * 501).download_file("/timelapse/v.avi", expected_size=500) is None
  204. def test_zero_bytes_is_a_failure_even_without_an_expected_size(self):
  205. assert self._client(b"").download_file("/cache/whatever.3mf") is None
  206. def test_unverified_download_still_works_for_callers_that_do_not_pass_a_size(self):
  207. assert self._client(b"abc").download_file("/cache/whatever.3mf") == b"abc"
  208. class TestDeleteIsBestEffort:
  209. """A printer that refuses the delete must not break the flow — the video
  210. is already in the archive, and the diff excludes it by name from then on."""
  211. @pytest.mark.asyncio
  212. async def test_reports_success_on_delete(self):
  213. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  214. with patch(
  215. "backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.DELETED)
  216. ) as d:
  217. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is True
  218. assert d.await_count == 1
  219. @pytest.mark.asyncio
  220. async def test_not_found_is_success_and_is_not_retried(self):
  221. """550 means the printer already cleaned up; waiting cannot change it."""
  222. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  223. with patch(
  224. "backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.NOT_FOUND)
  225. ) as d:
  226. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is True
  227. assert d.await_count == 1
  228. @pytest.mark.asyncio
  229. async def test_failure_retries_then_gives_up_without_raising(self):
  230. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  231. with (
  232. patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.FAILED)),
  233. patch("backend.app.services.bambu_ftp.asyncio.sleep", AsyncMock()),
  234. ):
  235. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is False
  236. @pytest.mark.asyncio
  237. async def test_raising_transport_does_not_propagate(self):
  238. from backend.app.services.bambu_ftp import delete_archived_timelapse
  239. with (
  240. patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock(side_effect=OSError("boom"))),
  241. patch("backend.app.services.bambu_ftp.asyncio.sleep", AsyncMock()),
  242. ):
  243. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is False
  244. class TestBaselineIsPersisted:
  245. """The baseline has to outlive the process: a restart mid-print used to
  246. lose it, and the manual scan never had access to it at all."""
  247. @pytest.mark.asyncio
  248. async def test_written_to_the_archive_row_at_print_start(self):
  249. from backend.app.main import _capture_timelapse_baseline_at_start
  250. archive = MagicMock()
  251. archive.timelapse_baseline = None
  252. session = _session(archive)
  253. with (
  254. patch("backend.app.main.async_session", return_value=session),
  255. patch(
  256. "backend.app.main._list_timelapse_videos",
  257. new=AsyncMock(return_value=([_video("a.avi"), _video("b.avi")], "/timelapse")),
  258. ),
  259. ):
  260. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  261. assert archive.timelapse_baseline == ["a.avi", "b.avi"]
  262. session.commit.assert_awaited()
  263. @pytest.mark.asyncio
  264. async def test_no_archive_id_keeps_it_in_memory_only(self):
  265. from backend.app.main import _capture_timelapse_baseline_at_start, _timelapse_baselines
  266. _timelapse_baselines.pop(1, None)
  267. session = _session(MagicMock())
  268. with (
  269. patch("backend.app.main.async_session", return_value=session),
  270. patch(
  271. "backend.app.main._list_timelapse_videos",
  272. new=AsyncMock(return_value=([_video("a.avi")], "/timelapse")),
  273. ),
  274. ):
  275. await _capture_timelapse_baseline_at_start(_printer(), 1, logger)
  276. assert _timelapse_baselines[1] == {"a.avi"}
  277. session.commit.assert_not_awaited()
  278. _timelapse_baselines.pop(1, None)
  279. @pytest.mark.asyncio
  280. async def test_listing_failure_stores_null_not_an_empty_baseline(self):
  281. """An empty list would make every video on the printer look new; NULL
  282. correctly means "no baseline" and falls back to a fresh snapshot."""
  283. from backend.app.main import _capture_timelapse_baseline_at_start
  284. archive = MagicMock()
  285. session = _session(archive)
  286. with (
  287. patch("backend.app.main.async_session", return_value=session),
  288. patch("backend.app.main._list_timelapse_videos", new=AsyncMock(side_effect=OSError("ftp down"))),
  289. ):
  290. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  291. assert archive.timelapse_baseline is None
  292. class TestManualScanUsesTheBaseline:
  293. """The reporter's second symptom: pressing "Scan for Timelapse" found
  294. nothing. Every strategy the endpoint had was clock-based, and their
  295. printer's clock was days out, so it could not match on any of them."""
  296. def _archive(self, baseline):
  297. from datetime import datetime, timezone
  298. a = MagicMock()
  299. a.id = 64
  300. a.printer_id = 1
  301. a.filename = "mops.3mf"
  302. a.timelapse_path = None
  303. a.timelapse_baseline = baseline
  304. a.started_at = datetime(2026, 7, 28, 20, 30, tzinfo=timezone.utc)
  305. a.completed_at = datetime(2026, 7, 28, 21, 19, tzinfo=timezone.utc)
  306. a.created_at = a.completed_at
  307. return a
  308. async def _scan(self, archive, listing, download=None, delete=None, claimed=()):
  309. from backend.app.api.routes import archives as archives_mod
  310. service = MagicMock()
  311. service.get_archive = AsyncMock(return_value=archive)
  312. service.attach_timelapse = AsyncMock(return_value=True)
  313. session = AsyncMock()
  314. session.__aenter__ = AsyncMock(return_value=session)
  315. session.__aexit__ = AsyncMock()
  316. session.execute = AsyncMock(
  317. return_value=MagicMock(
  318. scalar_one_or_none=MagicMock(return_value=_printer()),
  319. # Videos other archives of this printer hold
  320. scalars=MagicMock(return_value=MagicMock(all=MagicMock(return_value=list(claimed)))),
  321. )
  322. )
  323. with (
  324. patch("backend.app.core.database.async_session", return_value=session),
  325. patch("backend.app.api.routes.archives.ArchiveService", return_value=service),
  326. patch("backend.app.services.bambu_ftp.list_files_async", AsyncMock(return_value=listing)),
  327. patch(
  328. "backend.app.services.bambu_ftp.get_ftp_retry_settings",
  329. AsyncMock(return_value=(False, 3, 2, 30)),
  330. ),
  331. patch(
  332. "backend.app.services.bambu_ftp.download_file_bytes_async",
  333. download or AsyncMock(return_value=b"x" * 1000),
  334. ),
  335. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete or AsyncMock()),
  336. ):
  337. return await archives_mod.scan_timelapse(archive.id, None, ALL_PRINTERS)
  338. @pytest.mark.asyncio
  339. async def test_attaches_the_single_unclaimed_new_file(self):
  340. """The printer's clock is six days out here — exactly the reporter's
  341. case. Nothing in this path looks at a timestamp."""
  342. archive = self._archive(["video_2026-07-21_22-49-47.avi"])
  343. listing = [
  344. _video("video_2026-07-21_22-49-47.avi"),
  345. _video("video_2026-07-22_06-18-39.avi"),
  346. ]
  347. result = await self._scan(archive, listing)
  348. assert result["status"] == "attached"
  349. assert result["filename"] == "video_2026-07-22_06-18-39.avi"
  350. @pytest.mark.asyncio
  351. async def test_deletes_from_the_printer_after_attaching(self):
  352. delete = AsyncMock()
  353. archive = self._archive(["old.avi"])
  354. await self._scan(archive, [_video("old.avi"), _video("new.avi")], delete=delete)
  355. delete.assert_awaited_once()
  356. assert delete.await_args.args[2] == "/timelapse/new.avi"
  357. @pytest.mark.asyncio
  358. async def test_baseline_showing_nothing_new_does_not_guess(self):
  359. """With a baseline saying no new video exists, the clock strategies
  360. must not run — otherwise a coincidental timestamp match attaches
  361. someone else's video and calls it this print's."""
  362. archive = self._archive(["video_2026-07-28_20-30-00.avi"])
  363. # This file's embedded time is minutes from started_at, so the old
  364. # timestamp strategy would have matched it confidently.
  365. listing = [_video("video_2026-07-28_20-30-00.avi")]
  366. result = await self._scan(archive, listing)
  367. assert result["status"] == "not_found"
  368. @pytest.mark.asyncio
  369. async def test_ambiguous_baseline_offers_only_the_plausible_files(self):
  370. archive = self._archive(["old.avi"])
  371. listing = [_video("old.avi"), _video("candidate_a.avi"), _video("candidate_b.avi")]
  372. result = await self._scan(archive, listing)
  373. assert result["status"] == "not_found"
  374. assert {f["name"] for f in result["available_files"]} == {"candidate_a.avi", "candidate_b.avi"}
  375. @pytest.mark.asyncio
  376. async def test_archives_without_a_baseline_keep_the_old_strategies(self):
  377. """Rows predating the persisted baseline still get the best guess the
  378. endpoint can make, rather than nothing at all."""
  379. archive = self._archive(None)
  380. listing = [_video("mops_something.avi")] # matches by print name
  381. result = await self._scan(archive, listing)
  382. assert result["status"] == "attached"
  383. assert result["filename"] == "mops_something.avi"
  384. class TestPollBounds:
  385. """The poll is bounded twice on purpose."""
  386. def test_round_cap_tracks_the_wall_clock_budget(self):
  387. from backend.app.main import (
  388. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS,
  389. _TIMELAPSE_SCAN_TIMEOUT_SECONDS,
  390. _timelapse_scan_max_attempts,
  391. )
  392. assert (
  393. _timelapse_scan_max_attempts()
  394. == int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1
  395. )
  396. def test_zero_interval_does_not_divide_by_zero(self, monkeypatch):
  397. """The deadline alone can't bound the loop once sleeps are shortened to
  398. nothing, which is exactly what a test or a future tweak would do."""
  399. import backend.app.main as main_mod
  400. monkeypatch.setattr(main_mod, "_TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS", 0)
  401. assert main_mod._timelapse_scan_max_attempts() > 1
  402. def test_budget_is_much_longer_than_the_ladder_it_replaced(self):
  403. """The old [5, 10, 20, 30] ladder gave up after ~65 seconds, while the
  404. support bundles showed videos still arriving at the cutoff."""
  405. from backend.app.main import _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  406. assert _TIMELAPSE_SCAN_TIMEOUT_SECONDS >= 300
  407. class TestFinishPhotoUpgrade:
  408. """The print-complete notification waits ~60s for the timelapse, because
  409. holding it for minutes is worse than sending a live grab. On a P1S the
  410. video routinely lands later than that (p90 167s, worst observed 546s), so
  411. the archive kept the live grab — taken after the end G-code dropped the
  412. bed, which is the worse of the two photos. The upgrade runs afterwards."""
  413. @pytest.mark.asyncio
  414. async def test_puts_the_timelapse_frame_first_and_keeps_the_live_grab(self):
  415. """First, because the gallery opens at index 0. Kept, because the
  416. notification that already went out links to that exact file."""
  417. from backend.app.main import _upgrade_finish_photo_from_timelapse
  418. archive = MagicMock()
  419. archive.photos = ["finish_live_grab.jpg"]
  420. session = _session(archive)
  421. with (
  422. patch(
  423. "backend.app.main._capture_finish_photo_from_timelapse",
  424. AsyncMock(return_value=("finish_from_timelapse.jpg", False)),
  425. ),
  426. patch("backend.app.main.async_session", return_value=session),
  427. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())) as ws,
  428. ):
  429. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  430. assert archive.photos == ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  431. session.commit.assert_awaited()
  432. ws.send_archive_updated.assert_awaited_once()
  433. @pytest.mark.asyncio
  434. async def test_waits_far_longer_than_the_notification_can(self):
  435. from backend.app.main import (
  436. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS,
  437. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS,
  438. _upgrade_finish_photo_from_timelapse,
  439. )
  440. capture = AsyncMock(return_value=(None, True))
  441. with patch("backend.app.main._capture_finish_photo_from_timelapse", capture):
  442. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  443. assert capture.await_args.kwargs["timeout"] == _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS
  444. assert _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS > _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS
  445. # Covers the 546s worst case seen in the support bundles.
  446. assert _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS >= 600
  447. @pytest.mark.asyncio
  448. async def test_video_never_arrives_leaves_the_archive_alone(self):
  449. from backend.app.main import _upgrade_finish_photo_from_timelapse
  450. session = _session(MagicMock())
  451. with (
  452. patch("backend.app.main._capture_finish_photo_from_timelapse", AsyncMock(return_value=(None, True))),
  453. patch("backend.app.main.async_session", return_value=session),
  454. ):
  455. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  456. session.commit.assert_not_awaited()
  457. @pytest.mark.asyncio
  458. async def test_is_idempotent(self):
  459. """A second run must not list the same photo twice."""
  460. from backend.app.main import _upgrade_finish_photo_from_timelapse
  461. archive = MagicMock()
  462. archive.photos = ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  463. session = _session(archive)
  464. with (
  465. patch(
  466. "backend.app.main._capture_finish_photo_from_timelapse",
  467. AsyncMock(return_value=("finish_from_timelapse.jpg", False)),
  468. ),
  469. patch("backend.app.main.async_session", return_value=session),
  470. ):
  471. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  472. assert archive.photos == ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  473. session.commit.assert_not_awaited()
  474. @pytest.mark.asyncio
  475. async def test_missing_archive_does_not_raise(self):
  476. from backend.app.main import _upgrade_finish_photo_from_timelapse
  477. session = AsyncMock()
  478. session.__aenter__ = AsyncMock(return_value=session)
  479. session.__aexit__ = AsyncMock()
  480. session.get = AsyncMock(return_value=None)
  481. with (
  482. patch("backend.app.main._capture_finish_photo_from_timelapse", AsyncMock(return_value=("f.jpg", False))),
  483. patch("backend.app.main.async_session", return_value=session),
  484. ):
  485. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  486. session.commit.assert_not_awaited()
  487. @pytest.mark.asyncio
  488. async def test_refuses_to_delete_an_unverified_download(self):
  489. """The safety rule lives with the destructive call, not at the call
  490. sites — an unverified transfer may be a truncated file, and deleting
  491. the source would destroy the only complete copy."""
  492. from backend.app.services.bambu_ftp import delete_archived_timelapse
  493. with patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock()) as d:
  494. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=False) is False
  495. d.assert_not_awaited()
  496. @pytest.mark.asyncio
  497. async def test_verified_is_required_not_defaulted(self):
  498. """A future call site must not be able to silently skip the check."""
  499. import inspect
  500. from backend.app.services.bambu_ftp import delete_archived_timelapse
  501. param = inspect.signature(delete_archived_timelapse).parameters["verified"]
  502. assert param.default is inspect.Parameter.empty
  503. assert param.kind is inspect.Parameter.KEYWORD_ONLY
  504. class TestStaleBaselineCannotSurvive:
  505. """A reprint reuses the archive row, so a baseline left over from the
  506. previous run would have the scan diff this print against the printer's
  507. state before the *last* one — and unlike NULL, a stale list reads as
  508. authoritative and suppresses the fresh-snapshot fallback."""
  509. @pytest.mark.asyncio
  510. async def test_failed_capture_clears_rather_than_leaves_the_old_value(self):
  511. from backend.app.main import _capture_timelapse_baseline_at_start
  512. archive = MagicMock()
  513. archive.timelapse_baseline = ["from_the_previous_run.avi"]
  514. session = _session(archive)
  515. with (
  516. patch("backend.app.main.async_session", return_value=session),
  517. patch("backend.app.main._list_timelapse_videos", new=AsyncMock(side_effect=OSError("ftp down"))),
  518. ):
  519. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  520. assert archive.timelapse_baseline is None
  521. session.commit.assert_awaited()
  522. @pytest.mark.asyncio
  523. async def test_successful_capture_overwrites_the_old_value(self):
  524. from backend.app.main import _capture_timelapse_baseline_at_start
  525. archive = MagicMock()
  526. archive.timelapse_baseline = ["from_the_previous_run.avi"]
  527. session = _session(archive)
  528. with (
  529. patch("backend.app.main.async_session", return_value=session),
  530. patch(
  531. "backend.app.main._list_timelapse_videos",
  532. new=AsyncMock(return_value=([_video("now_on_the_printer.avi")], "/timelapse")),
  533. ),
  534. ):
  535. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  536. assert archive.timelapse_baseline == ["now_on_the_printer.avi"]
  537. class TestFileMustHaveStoppedGrowing:
  538. """Matching the listing's size proves we received what it said, not that
  539. the printer had finished writing. The scan's first look lands seconds after
  540. the print ends — exactly when the video is being written — so a growing
  541. file can be listed short, served short, and pass the length check. That was
  542. survivable while the printer kept its copy; it isn't now that a successful
  543. attach deletes it."""
  544. @pytest.mark.asyncio
  545. async def test_same_size_afterwards_is_settled(self):
  546. from backend.app.services.bambu_ftp import remote_file_settled
  547. with patch(
  548. "backend.app.services.bambu_ftp.list_files_async",
  549. AsyncMock(return_value=[_video("v.avi", size=4096)]),
  550. ):
  551. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is True
  552. @pytest.mark.asyncio
  553. async def test_grown_since_download_is_not_settled(self):
  554. """We hold a prefix of the video, not the video."""
  555. from backend.app.services.bambu_ftp import remote_file_settled
  556. with patch(
  557. "backend.app.services.bambu_ftp.list_files_async",
  558. AsyncMock(return_value=[_video("v.avi", size=9000)]),
  559. ):
  560. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is False
  561. @pytest.mark.asyncio
  562. async def test_vanished_counts_as_settled(self):
  563. """Nothing left that can grow, and nothing left to delete either."""
  564. from backend.app.services.bambu_ftp import remote_file_settled
  565. with patch(
  566. "backend.app.services.bambu_ftp.list_files_async",
  567. AsyncMock(return_value=[_video("something_else.avi")]),
  568. ):
  569. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is True
  570. @pytest.mark.asyncio
  571. async def test_listing_failure_is_not_settled(self):
  572. """ "Could not check" must not read as "safe to delete"."""
  573. from backend.app.services.bambu_ftp import remote_file_settled
  574. with patch("backend.app.services.bambu_ftp.list_files_async", AsyncMock(return_value=[])):
  575. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is False
  576. @pytest.mark.asyncio
  577. async def test_scan_discards_a_still_growing_video_without_deleting(self):
  578. from backend.app.main import _attach_first_unclaimed_timelapse
  579. delete = AsyncMock()
  580. service = MagicMock()
  581. service.attach_timelapse = AsyncMock(return_value=True)
  582. with (
  583. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  584. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=False)),
  585. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  586. patch("backend.app.main.async_session", return_value=_session()),
  587. patch("backend.app.main.ArchiveService", return_value=service),
  588. ):
  589. result = await _attach_first_unclaimed_timelapse(
  590. 42, _printer(), [_video("new.avi", size=1000)], set(), set(), 1, logger
  591. )
  592. assert result is False
  593. service.attach_timelapse.assert_not_awaited()
  594. delete.assert_not_awaited()
  595. @pytest.mark.asyncio
  596. async def test_scan_attaches_once_the_video_has_settled(self):
  597. from backend.app.main import _attach_first_unclaimed_timelapse
  598. settled = AsyncMock(return_value=True)
  599. service = MagicMock()
  600. service.attach_timelapse = AsyncMock(return_value=True)
  601. with (
  602. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  603. patch("backend.app.services.bambu_ftp.remote_file_settled", settled),
  604. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  605. patch("backend.app.main.async_session", return_value=_session()),
  606. patch("backend.app.main.ArchiveService", return_value=service),
  607. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  608. ):
  609. result = await _attach_first_unclaimed_timelapse(
  610. 42, _printer(), [_video("new.avi", size=1000)], set(), set(), 1, logger
  611. )
  612. assert result is True
  613. # Checked against what we actually received, not against the listing.
  614. assert settled.await_args.args[3] == 1000
  615. class TestAScanWithoutABaselineSkipsClaimedVideos:
  616. """An archive from before the baseline was stored is matched on name and
  617. clock, which must not hand it a video another archive already holds
  618. (SN-C7)."""
  619. _archive = TestManualScanUsesTheBaseline._archive
  620. _scan = TestManualScanUsesTheBaseline._scan
  621. @pytest.mark.asyncio
  622. async def test_a_short_name_does_not_take_another_archive_s_video(self):
  623. archive = self._archive(None)
  624. archive.filename = "1.3mf" # "1" is in every video's timestamp
  625. listing = [_video("video_2026-07-28_21-19-10.avi"), _video("video_2026-07-28_21-19-40.avi")]
  626. result = await self._scan(archive, listing, claimed=["archive/1/other/video_2026-07-28_21-19-10.mp4"])
  627. assert result.get("filename") != "video_2026-07-28_21-19-10.avi"
  628. @pytest.mark.asyncio
  629. async def test_a_claimed_video_is_still_offered_for_picking_by_hand(self):
  630. """Picking by hand is how a wrong match is put right."""
  631. archive = self._archive(None)
  632. archive.filename = "mops.3mf"
  633. archive.started_at = archive.completed_at = archive.created_at = None
  634. listing = [_video("video_a.avi"), _video("video_b.avi")]
  635. result = await self._scan(archive, listing, claimed=["archive/1/other/video_a.mp4"])
  636. assert result["status"] == "not_found"
  637. assert {f["name"] for f in result["available_files"]} == {"video_a.avi", "video_b.avi"}