test_timelapse_scan_2704.py 34 KB

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