test_github_restore.py 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572
  1. """Unit tests for the Git backup restore service (#2656).
  2. Focus is on the per-category appliers: natural-key matching, the deliberate
  3. refusal to reuse the backup's primary keys, old_id -> new_id remapping for
  4. dependent rows, overwrite-vs-skip, the settings credential blocklist, and the
  5. K-profile paths that depend on live printers.
  6. """
  7. from datetime import datetime
  8. from types import SimpleNamespace
  9. from unittest.mock import AsyncMock, MagicMock, patch
  10. import pytest
  11. from sqlalchemy import select
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.models.settings import Settings
  14. from backend.app.models.spool import Spool
  15. from backend.app.models.spool_usage_history import SpoolUsageHistory
  16. from backend.app.models.user import User
  17. from backend.app.schemas.github_backup import GitHubRestoreRequest, RestoreCategory
  18. from backend.app.services.github_restore import (
  19. _COMPANION_CREDENTIAL_ENV,
  20. _COMPANION_CREDENTIALS,
  21. _COMPANION_EXPOSURE_TOGGLES,
  22. ARCHIVES_PATH,
  23. SETTINGS_PATH,
  24. SPOOL_USAGE_PATH,
  25. SPOOLS_PATH,
  26. GitHubRestoreService,
  27. _CategoryTally,
  28. _is_blocked_setting_key,
  29. _is_protected_setting_key,
  30. _is_usable_credential,
  31. _parse_dt,
  32. _setting_value_is_true,
  33. _SettingsPlan,
  34. )
  35. def _service() -> GitHubRestoreService:
  36. return GitHubRestoreService()
  37. def _messages(tally: _CategoryTally) -> list[str]:
  38. """The English rendering of each note.
  39. Notes are ``{code, params, message}`` since they became translatable
  40. (#2656); asserting on the message keeps these tests readable while
  41. ``_codes`` covers the half a client actually keys on.
  42. """
  43. return [note["message"] for note in tally.notes]
  44. def _codes(tally: _CategoryTally) -> list[str]:
  45. return [note["code"] for note in tally.notes]
  46. class TestParseDt:
  47. def test_parses_str_datetime_the_backup_writes(self):
  48. assert _parse_dt("2026-07-27 06:02:05.123456") == datetime(2026, 7, 27, 6, 2, 5, 123456)
  49. def test_parses_iso_with_t_separator(self):
  50. assert _parse_dt("2026-07-27T06:02:05") == datetime(2026, 7, 27, 6, 2, 5)
  51. @pytest.mark.parametrize("value", ["", None, "not a date", 12345, {}])
  52. def test_returns_none_for_junk(self, value):
  53. assert _parse_dt(value) is None
  54. class TestSettingKeyBlocklist:
  55. @pytest.mark.parametrize(
  56. "key",
  57. [
  58. "bambu_cloud_token",
  59. "auth_secret_key",
  60. "ha_token",
  61. "prometheus_token",
  62. "printer_access_code",
  63. "smtp_password",
  64. "some_api_key",
  65. "ftp_passphrase",
  66. "MQTT_SECRET",
  67. ],
  68. )
  69. def test_credential_like_keys_are_blocked(self, key):
  70. assert _is_blocked_setting_key(key) is True
  71. @pytest.mark.parametrize(
  72. "key",
  73. ["low_stock_threshold", "currency", "theme", "local_backup_enabled", "timezone"],
  74. )
  75. def test_ordinary_keys_are_allowed(self, key):
  76. assert _is_blocked_setting_key(key) is False
  77. @pytest.mark.parametrize(
  78. "key",
  79. ["auth_enabled", "advanced_auth_enabled", "local_login_enabled", "setup_completed"],
  80. )
  81. def test_auth_policy_keys_are_protected(self, key):
  82. # Not credential-shaped, so the secret hints never catch them.
  83. assert _is_blocked_setting_key(key) is False
  84. assert _is_protected_setting_key(key) is True
  85. @pytest.mark.parametrize("key", ["currency", "ldap_enabled", "auth_secret_key"])
  86. def test_protected_set_is_only_the_auth_policy_keys(self, key):
  87. assert _is_protected_setting_key(key) is False
  88. def test_ha_token_from_env_is_deliberately_not_carved_out(self):
  89. """Recorded so the review's question about it is not re-litigated.
  90. ``ha_token_from_env`` looks like a false positive for the ``token`` hint,
  91. but it is only ever constructed in the settings GET response
  92. (``get_homeassistant_settings``). It is absent from ``AppSettingsUpdate``
  93. and so is never a ``Settings`` row — it cannot reach a backup, which
  94. makes an allowlist entry for it dead code.
  95. Carving it out would also be a live hole rather than a tidy-up: an
  96. attacker-authored ``settings/app_settings.json`` could then get a
  97. ``*token*``-named row written simply by choosing that name. This
  98. blocklist's whole job is belt-and-braces, so a name-shaped exception to
  99. it is exactly the wrong shape of fix.
  100. """
  101. assert _is_blocked_setting_key("ha_token_from_env") is True
  102. class TestCategoryTally:
  103. def test_a_note_carries_code_params_and_english(self):
  104. tally = _CategoryTally()
  105. tally.note("noData", "No data of this kind in this backup")
  106. tally.note("spoolUsageUnresolved", "2 usage record(s) skipped", count=2)
  107. assert tally.notes == [
  108. {"code": "noData", "params": {}, "message": "No data of this kind in this backup"},
  109. {"code": "spoolUsageUnresolved", "params": {"count": 2}, "message": "2 usage record(s) skipped"},
  110. ]
  111. def test_notes_are_deduplicated(self):
  112. tally = _CategoryTally()
  113. tally.note("noData", "same")
  114. tally.note("noData", "same")
  115. assert len(tally.notes) == 1
  116. def test_the_same_code_with_different_params_is_kept(self):
  117. """Two printers can both be offline, and the user needs both names."""
  118. tally = _CategoryTally()
  119. tally.note("kprofilesPrinterOffline", "A is not connected", printer="A")
  120. tally.note("kprofilesPrinterOffline", "B is not connected", printer="B")
  121. assert len(tally.notes) == 2
  122. def test_notes_are_bounded(self):
  123. tally = _CategoryTally()
  124. for i in range(50):
  125. tally.note("noData", f"note {i}", index=i)
  126. assert len(tally.notes) == 20
  127. class TestRestoreRequestSchema:
  128. def test_rejects_empty_category_list(self):
  129. with pytest.raises(ValueError):
  130. GitHubRestoreRequest(categories=[])
  131. def test_deduplicates_categories(self):
  132. request = GitHubRestoreRequest(
  133. categories=[RestoreCategory.SPOOLS, RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  134. )
  135. assert request.categories == [RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  136. def test_defaults_to_head(self):
  137. assert GitHubRestoreRequest(categories=[RestoreCategory.SPOOLS]).ref == "HEAD"
  138. @pytest.mark.parametrize("ref", ["HEAD", "abc1234", "a" * 40])
  139. def test_accepts_valid_refs(self, ref):
  140. assert GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS]).ref == ref
  141. @pytest.mark.parametrize("ref", ["abc", "main", "../etc/passwd", "a" * 41, "zzzzzzz", "abc 123"])
  142. def test_rejects_refs_that_are_not_object_names(self, ref):
  143. with pytest.raises(ValueError):
  144. GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS])
  145. class TestRestoreSettings:
  146. @pytest.mark.asyncio
  147. async def test_inserts_missing_keys(self, db_session):
  148. tally = _CategoryTally()
  149. payload = {"version": "1.0", "settings": {"currency": "EUR", "theme": "dark"}}
  150. await _service()._restore_settings(db_session, payload, overwrite=False, tally=tally)
  151. await db_session.commit()
  152. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  153. assert rows == {"currency": "EUR", "theme": "dark"}
  154. assert tally.restored == 2
  155. @pytest.mark.asyncio
  156. async def test_skips_existing_key_when_overwrite_off(self, db_session):
  157. db_session.add(Settings(key="currency", value="USD"))
  158. await db_session.commit()
  159. tally = _CategoryTally()
  160. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=False, tally=tally)
  161. await db_session.commit()
  162. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  163. assert row.value == "USD"
  164. assert tally.skipped == 1
  165. assert tally.restored == 0
  166. @pytest.mark.asyncio
  167. async def test_overwrites_existing_key_when_enabled(self, db_session):
  168. db_session.add(Settings(key="currency", value="USD"))
  169. await db_session.commit()
  170. tally = _CategoryTally()
  171. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=True, tally=tally)
  172. await db_session.commit()
  173. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  174. assert row.value == "EUR"
  175. assert tally.restored == 1
  176. @pytest.mark.asyncio
  177. async def test_credential_keys_are_never_restored(self, db_session):
  178. """A backup predating the collector's denylist can still contain secrets."""
  179. tally = _CategoryTally()
  180. payload = {"settings": {"currency": "EUR", "bambu_cloud_token": "leaked", "ha_token": "leaked"}}
  181. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  182. await db_session.commit()
  183. keys = {s.key for s in (await db_session.execute(select(Settings))).scalars().all()}
  184. assert keys == {"currency"}
  185. # Refusals are notes, not tally rows: the preview never counted these
  186. # keys, so counting them here would put the total above what the user
  187. # was shown before they pressed Restore.
  188. assert tally.skipped == 0
  189. assert any("credential-like" in note for note in _messages(tally))
  190. @pytest.mark.asyncio
  191. async def test_auth_settings_are_never_restored(self, db_session):
  192. """Restoring auth_enabled=false would disable auth behind the cache's back."""
  193. db_session.add(Settings(key="auth_enabled", value="true"))
  194. db_session.add(Settings(key="local_login_enabled", value="true"))
  195. await db_session.commit()
  196. tally = _CategoryTally()
  197. payload = {
  198. "settings": {
  199. "currency": "EUR",
  200. "auth_enabled": "false",
  201. "advanced_auth_enabled": "false",
  202. "local_login_enabled": "false",
  203. "setup_completed": "false",
  204. }
  205. }
  206. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  207. await db_session.commit()
  208. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  209. assert rows["auth_enabled"] == "true"
  210. assert rows["local_login_enabled"] == "true"
  211. assert "advanced_auth_enabled" not in rows
  212. assert "setup_completed" not in rows
  213. assert rows["currency"] == "EUR"
  214. assert tally.restored == 1
  215. # As above: refused keys are outside the preview's count, so outside the
  216. # tally too.
  217. assert tally.skipped == 0
  218. assert any("authentication setting" in note for note in _messages(tally))
  219. @pytest.mark.asyncio
  220. async def test_missing_payload_is_noted_not_fatal(self, db_session):
  221. tally = _CategoryTally()
  222. await _service()._restore_settings(db_session, None, overwrite=True, tally=tally)
  223. assert tally.restored == 0
  224. assert _codes(tally) == ["noData"]
  225. class TestSettingValueIsTrue:
  226. """Only the spellings a reader actually treats as "on" count as on."""
  227. @pytest.mark.parametrize("value", ["true", "TRUE", " True ", True])
  228. def test_on(self, value):
  229. assert _setting_value_is_true(value) is True
  230. @pytest.mark.parametrize("value", ["false", "1", "on", "yes", "", None, False, 0])
  231. def test_off(self, value):
  232. # "1"/"on"/"yes" are deliberately off: no reader in the codebase treats
  233. # them as on, so restoring one cannot switch anything on either.
  234. assert _setting_value_is_true(value) is False
  235. class TestUsableCredential:
  236. @pytest.mark.parametrize("value", ["s3cret", " x "])
  237. def test_present_values_are_usable(self, value):
  238. assert _is_usable_credential(value) is True
  239. @pytest.mark.parametrize("value", [None, "", " "])
  240. def test_absent_or_blank_is_not(self, value):
  241. # A present-but-blank prometheus_token row is exactly the `if token:`
  242. # hole in the metrics route, so it must not count as protection.
  243. assert _is_usable_credential(value) is False
  244. class TestCompanionCredentials:
  245. """Toggles whose safety depends on a credential the restore refuses to write.
  246. ``prometheus_enabled`` is the sharp one. ``/api/v1/metrics`` is a public
  247. route whose only gate is a non-empty ``prometheus_token``, so restoring the
  248. toggle onto an instance that has no token row publishes the entire metrics
  249. body to anyone who can reach the port — and with overwrite *off*, since the
  250. row is missing rather than present. The other four break an integration
  251. rather than open one, but they are the same shape.
  252. """
  253. async def _restore(self, db, tally=None, overwrite=False, **settings) -> _CategoryTally:
  254. tally = tally or _CategoryTally()
  255. await _service()._restore_settings(db, {"settings": settings}, overwrite=overwrite, tally=tally)
  256. await db.commit()
  257. return tally
  258. async def _rows(self, db) -> dict:
  259. return {s.key: s.value for s in (await db.execute(select(Settings))).scalars().all()}
  260. # --- The refusal itself ------------------------------------------------
  261. @pytest.mark.asyncio
  262. async def test_prometheus_toggle_is_refused_when_its_token_was_skipped(self, db_session):
  263. """The headline case: overwrite off, empty database, endpoint stays shut."""
  264. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  265. rows = await self._rows(db_session)
  266. assert rows == {"currency": "EUR"}
  267. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  268. @pytest.mark.asyncio
  269. @pytest.mark.parametrize("toggle,credential", sorted(_COMPANION_CREDENTIALS.items()))
  270. async def test_every_pair_refuses_its_toggle(self, db_session, toggle, credential, monkeypatch):
  271. monkeypatch.delenv("HA_TOKEN", raising=False)
  272. await self._restore(db_session, **{toggle: "true", credential: "s3cret"})
  273. assert toggle not in await self._rows(db_session)
  274. @pytest.mark.asyncio
  275. async def test_ha_toggle_is_refused_when_the_environment_has_no_token(self, db_session, monkeypatch):
  276. monkeypatch.delenv("HA_TOKEN", raising=False)
  277. await self._restore(db_session, ha_enabled="true", ha_token="s3cret", ha_url="http://ha.local")
  278. rows = await self._rows(db_session)
  279. assert "ha_enabled" not in rows
  280. assert rows["ha_url"] == "http://ha.local"
  281. @pytest.mark.asyncio
  282. async def test_a_blank_local_credential_row_is_not_usable(self, db_session):
  283. db_session.add(Settings(key="prometheus_token", value=""))
  284. await db_session.commit()
  285. await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  286. assert "prometheus_enabled" not in await self._rows(db_session)
  287. @pytest.mark.asyncio
  288. @pytest.mark.parametrize("value", ["TRUE", " True ", True])
  289. async def test_true_is_refused_however_it_is_spelled(self, db_session, value):
  290. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  291. assert "prometheus_enabled" not in await self._rows(db_session)
  292. # --- Ruling 3: the tally counts what the preview counted ---------------
  293. @pytest.mark.asyncio
  294. async def test_refusals_are_not_counted_in_the_tally(self, db_session):
  295. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  296. assert (tally.restored, tally.skipped, tally.failed) == (1, 0, 0)
  297. @pytest.mark.asyncio
  298. async def test_tally_total_equals_the_preview_item_count(self, db_session):
  299. """The ruling, encoded: the user is shown a number, and it has to hold.
  300. Off by three before this change — the two name-based refusals and the
  301. companion one were all counted as ``skipped`` despite never being in the
  302. preview's count.
  303. """
  304. db_session.add(Settings(key="theme", value="light"))
  305. await db_session.commit()
  306. values = {
  307. "currency": "EUR", # inserted -> restored
  308. "theme": "dark", # exists, overwrite off -> skipped
  309. "low_stock_threshold": None, # no value -> skipped
  310. "": "junk", # unusable key -> failed
  311. "bambu_cloud_token": "x", # blocked -> refused
  312. "auth_enabled": "false", # protected -> refused
  313. "prometheus_enabled": "true", # companion -> refused
  314. "prometheus_token": "s3cret", # blocked -> refused
  315. }
  316. item_count, _ = await _service()._count_items(
  317. db_session, RestoreCategory.SETTINGS, {SETTINGS_PATH: {"settings": values}}
  318. )
  319. tally = _CategoryTally()
  320. await _service()._restore_settings(db_session, {"settings": values}, overwrite=False, tally=tally)
  321. await db_session.commit()
  322. assert tally.restored + tally.skipped + tally.failed == item_count
  323. assert (tally.restored, tally.skipped, tally.failed) == (1, 2, 1)
  324. @pytest.mark.asyncio
  325. async def test_preview_count_drops_by_one_when_the_local_credential_is_missing(self, db_session):
  326. parsed = {
  327. SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true", "prometheus_token": "s3cret"}}
  328. }
  329. refused_count, refused_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  330. db_session.add(Settings(key="prometheus_token", value="already-set"))
  331. await db_session.commit()
  332. allowed_count, allowed_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  333. assert refused_count == allowed_count - 1
  334. assert refused_detail.code == "settingsCompanionWillSkip"
  335. assert refused_detail.params == {"count": 1, "companion": 1}
  336. # Nothing is being left off now, so the wording drops back to the plain
  337. # credential caveat.
  338. assert allowed_detail.code == "settingsCredentialsWillSkip"
  339. # --- The exposure class: a blank backup credential is the hole ----------
  340. #
  341. # The rule's second condition — "the backup carried a usable credential" —
  342. # is what stops it refusing an anonymous MQTT broker. It does not transfer to
  343. # Prometheus: a backup taken on an instance that enabled Prometheus without a
  344. # token (the field is optional and defaults to "") carries the toggle and no
  345. # usable token, and writing it opens /api/v1/metrics just as wide. That is
  346. # the *more* likely source of the exposure, not the less.
  347. @pytest.mark.asyncio
  348. async def test_prometheus_is_refused_when_the_backup_has_no_token_key_at_all(self, db_session):
  349. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true")
  350. rows = await self._rows(db_session)
  351. assert rows == {"currency": "EUR"}
  352. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  353. @pytest.mark.asyncio
  354. @pytest.mark.parametrize("token", ["", " "])
  355. async def test_prometheus_is_refused_when_the_backup_token_is_blank(self, db_session, token):
  356. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token=token)
  357. assert "prometheus_enabled" not in await self._rows(db_session)
  358. assert "settingsCompanionSkipped" in _codes(tally)
  359. @pytest.mark.asyncio
  360. async def test_the_preview_says_so_with_no_credential_key_to_skip(self, db_session):
  361. """The wording has to survive ``blocked`` being empty.
  362. The shared caveat counts credential-like keys *and* switches; on this
  363. payload there are no credential-like keys, so "0 credential-like key(s)
  364. will be skipped" would be noise.
  365. """
  366. parsed = {SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true"}}}
  367. count, detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  368. assert count == 1
  369. assert detail.code == "settingsCompanionOnlyWillSkip"
  370. assert detail.params == {"companion": 1}
  371. @pytest.mark.asyncio
  372. async def test_the_availability_class_keeps_the_backup_credential_condition(self, db_session):
  373. """The other half of the same change: only Prometheus loses condition 2.
  374. Absent is treated like blank here — an anonymous broker or bind is a
  375. working config, so refusing it would be a false positive.
  376. """
  377. await self._restore(db_session, mqtt_enabled="true", ldap_enabled="true", virtual_printer_enabled="true")
  378. rows = await self._rows(db_session)
  379. assert rows["mqtt_enabled"] == "true"
  380. assert rows["ldap_enabled"] == "true"
  381. assert rows["virtual_printer_enabled"] == "true"
  382. def test_every_exposure_toggle_is_a_companion_toggle(self):
  383. assert _COMPANION_EXPOSURE_TOGGLES.issubset(_COMPANION_CREDENTIALS)
  384. # --- Controls: over-refusal is the real risk here ----------------------
  385. @pytest.mark.asyncio
  386. async def test_a_usable_local_credential_lets_the_toggle_through(self, db_session):
  387. db_session.add(Settings(key="prometheus_token", value="already-set"))
  388. await db_session.commit()
  389. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  390. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  391. assert not any("switched off" in note for note in _messages(tally))
  392. @pytest.mark.asyncio
  393. async def test_the_exposure_route_still_stands_down_for_a_local_token(self, db_session):
  394. """Skipping condition 2 must not skip the local-state pass with it."""
  395. db_session.add(Settings(key="prometheus_token", value="already-set"))
  396. await db_session.commit()
  397. tally = await self._restore(db_session, prometheus_enabled="true")
  398. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  399. assert not any("switched off" in note for note in _messages(tally))
  400. @pytest.mark.asyncio
  401. async def test_the_exposure_route_still_stands_down_when_already_on(self, db_session):
  402. """The exposure pre-dates this restore either way — see ruling 3."""
  403. db_session.add(Settings(key="prometheus_enabled", value="true"))
  404. await db_session.commit()
  405. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true")
  406. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  407. assert not any("switched off" in note for note in _messages(tally))
  408. @pytest.mark.asyncio
  409. async def test_an_anonymous_broker_is_not_a_false_positive(self, db_session):
  410. """mqtt_relay passes an empty password straight through — a real config."""
  411. tally = await self._restore(db_session, mqtt_enabled="true", mqtt_broker="10.0.0.5")
  412. assert (await self._rows(db_session))["mqtt_enabled"] == "true"
  413. assert not any("switched off" in note for note in _messages(tally))
  414. @pytest.mark.asyncio
  415. async def test_an_anonymous_ldap_bind_is_not_a_false_positive(self, db_session):
  416. """Same for a backup that carries the key with a blank value."""
  417. tally = await self._restore(db_session, ldap_enabled="true", ldap_bind_password=" ")
  418. assert (await self._rows(db_session))["ldap_enabled"] == "true"
  419. assert not any("switched off" in note for note in _messages(tally))
  420. @pytest.mark.asyncio
  421. async def test_turning_a_toggle_off_is_always_written(self, db_session):
  422. await self._restore(db_session, prometheus_enabled="false", prometheus_token="s3cret")
  423. assert (await self._rows(db_session))["prometheus_enabled"] == "false"
  424. @pytest.mark.asyncio
  425. @pytest.mark.parametrize("value", ["1", "on", "yes"])
  426. async def test_spellings_no_reader_treats_as_on_are_written(self, db_session, value):
  427. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  428. assert (await self._rows(db_session))["prometheus_enabled"] == value
  429. @pytest.mark.asyncio
  430. async def test_ha_token_in_the_environment_counts_as_usable(self, db_session, monkeypatch):
  431. monkeypatch.setenv("HA_TOKEN", "from-env")
  432. await self._restore(db_session, ha_enabled="true", ha_token="s3cret")
  433. assert (await self._rows(db_session))["ha_enabled"] == "true"
  434. @pytest.mark.asyncio
  435. async def test_a_toggle_already_on_locally_is_written(self, db_session):
  436. """The exposure pre-dates the restore, so "left switched off" would be a lie."""
  437. db_session.add(Settings(key="prometheus_enabled", value="true"))
  438. await db_session.commit()
  439. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true", prometheus_token="s3cret")
  440. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  441. assert not any("switched off" in note for note in _messages(tally))
  442. # --- The map itself ----------------------------------------------------
  443. def test_every_companion_credential_is_blocked_and_no_toggle_is(self):
  444. """Guards the rule against a future edit to _SECRET_KEY_HINTS.
  445. If a credential stopped being blocked, its toggle would travel with it
  446. and the refusal would be pointless; if a toggle started being blocked,
  447. the pair would never be reached at all.
  448. """
  449. for toggle, credential in _COMPANION_CREDENTIALS.items():
  450. assert _is_blocked_setting_key(credential) is True, credential
  451. assert _is_blocked_setting_key(toggle) is False, toggle
  452. assert _is_protected_setting_key(toggle) is False, toggle
  453. def test_every_environment_override_names_a_companion_credential(self):
  454. assert set(_COMPANION_CREDENTIAL_ENV) <= set(_COMPANION_CREDENTIALS.values())
  455. @pytest.mark.asyncio
  456. async def test_plan_leaves_unusable_key_names_in_no_bucket(self, db_session):
  457. """They are the restore's ``failed``, not a refusal."""
  458. plan = await _service()._plan_settings(db_session, {"": "x", 7: "y", "currency": "EUR"})
  459. assert plan == _SettingsPlan()
  460. class TestSpoolTagOverwrite:
  461. """Overwrite must not write the backup's *other* tag key onto a matched spool.
  462. ``tag_uid`` and ``tray_uuid`` are both in the overwrite ``setattr`` loop, and
  463. neither column has a unique constraint, so writing one onto a spool matched
  464. by the other silently creates a duplicate tag rather than erroring. After
  465. that ``_find_spool``'s ``.first()`` is non-deterministic and an AMS tag
  466. lookup resolves to an arbitrary one of the two. The same loop can also clear
  467. a tag the user has scanned since the backup was taken.
  468. """
  469. def _entry(self, **overrides):
  470. entry = {
  471. "id": 41,
  472. "material": "PLA",
  473. "brand": "Bambu Lab",
  474. "created_at": "2026-01-05 12:00:00",
  475. "tag_uid": "TAG-A",
  476. "tray_uuid": None,
  477. }
  478. entry.update(overrides)
  479. return entry
  480. async def _restore(self, db, entry, tally=None):
  481. tally = tally or _CategoryTally()
  482. await _service()._restore_spools(db, {"spools": [entry]}, None, True, tally, {})
  483. await db.commit()
  484. return tally
  485. @pytest.mark.asyncio
  486. async def test_an_empty_incoming_tag_does_not_clear_a_scanned_one(self, db_session):
  487. """The backup predates the scan, so the local tag is the newer fact."""
  488. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  489. await db_session.commit()
  490. tally = await self._restore(db_session, self._entry(tray_uuid=None))
  491. row = (await db_session.execute(select(Spool))).scalar_one()
  492. assert row.tray_uuid == "TRAY-LIVE"
  493. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  494. @pytest.mark.asyncio
  495. async def test_a_tag_another_spool_already_holds_is_not_written(self, db_session):
  496. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  497. db_session.add(Spool(material="PETG", brand="Other", tray_uuid="TRAY-B"))
  498. await db_session.commit()
  499. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-B"))
  500. holders = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-B"))).scalars().all()
  501. assert len(holders) == 1, "a duplicate tray_uuid makes AMS lookups non-deterministic"
  502. assert holders[0].material == "PETG"
  503. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  504. @pytest.mark.asyncio
  505. async def test_the_note_counts_every_column_it_kept(self, db_session):
  506. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  507. db_session.add(Spool(material="PETG", brand="Other", tag_uid="TAG-CLASH"))
  508. await db_session.commit()
  509. # Matched on tray_uuid, so the guard judges tag_uid: it clashes.
  510. tally = await self._restore(db_session, self._entry(tag_uid="TAG-CLASH", tray_uuid="TRAY-LIVE"))
  511. row = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-LIVE"))).scalar_one()
  512. assert row.tag_uid == "TAG-A"
  513. note = next(n for n in tally.notes if n["code"] == "spoolTagKept")
  514. assert note["params"] == {"count": 1}
  515. # --- Controls ----------------------------------------------------------
  516. @pytest.mark.asyncio
  517. async def test_a_free_tag_is_still_written(self, db_session):
  518. """The point of overwrite: a spool that gained a tray_uuid gets it."""
  519. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  520. await db_session.commit()
  521. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-NEW"))
  522. row = (await db_session.execute(select(Spool))).scalar_one()
  523. assert row.tray_uuid == "TRAY-NEW"
  524. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  525. @pytest.mark.asyncio
  526. async def test_an_unchanged_tag_is_not_reported_as_kept(self, db_session):
  527. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-A"))
  528. await db_session.commit()
  529. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-A"))
  530. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  531. @pytest.mark.asyncio
  532. async def test_a_new_spool_keeps_both_tags_from_the_backup(self, db_session):
  533. """The guard is an overwrite-only concern; an insert is unaffected."""
  534. await self._restore(db_session, self._entry(tag_uid="TAG-NEW", tray_uuid="TRAY-NEW"))
  535. row = (await db_session.execute(select(Spool))).scalar_one()
  536. assert (row.tag_uid, row.tray_uuid) == ("TAG-NEW", "TRAY-NEW")
  537. @pytest.mark.asyncio
  538. async def test_find_spool_reports_which_key_matched(self, db_session):
  539. db_session.add(Spool(material="PLA", tag_uid="TAG-A"))
  540. db_session.add(Spool(material="PETG", tray_uuid="TRAY-B"))
  541. await db_session.commit()
  542. service = _service()
  543. assert (await service._find_spool(db_session, {"tag_uid": "TAG-A"}))[1] == "tag_uid"
  544. assert (await service._find_spool(db_session, {"tray_uuid": "TRAY-B"}))[1] == "tray_uuid"
  545. assert await service._find_spool(db_session, {"tag_uid": "NOPE"}) == (None, None)
  546. class TestRestoreSpools:
  547. def _spool_entry(self, **overrides):
  548. entry = {
  549. "id": 41,
  550. "material": "PLA",
  551. "subtype": "Basic",
  552. "color_name": "Jade White",
  553. "brand": "Bambu Lab",
  554. "tag_uid": "AABBCCDD",
  555. "created_at": "2026-01-05 12:00:00",
  556. "weight_used": 120.5,
  557. }
  558. entry.update(overrides)
  559. return entry
  560. @pytest.mark.asyncio
  561. async def test_inserts_without_reusing_backup_id(self, db_session):
  562. """The backup's spool.id belongs to an unrelated row today."""
  563. db_session.add(Spool(material="PETG")) # occupies id 1
  564. await db_session.commit()
  565. tally = _CategoryTally()
  566. payload = {"spools": [self._spool_entry(id=1)]}
  567. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  568. await db_session.commit()
  569. spools = (await db_session.execute(select(Spool))).scalars().all()
  570. assert len(spools) == 2
  571. restored = next(s for s in spools if s.tag_uid == "AABBCCDD")
  572. assert restored.id != 1
  573. assert restored.material == "PLA"
  574. @pytest.mark.asyncio
  575. async def test_matches_existing_spool_by_tag_uid(self, db_session):
  576. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  577. await db_session.commit()
  578. tally = _CategoryTally()
  579. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, False, tally, {})
  580. await db_session.commit()
  581. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  582. assert tally.skipped == 1
  583. @pytest.mark.asyncio
  584. async def test_matches_existing_spool_by_tray_uuid(self, db_session):
  585. db_session.add(Spool(material="PLA", tray_uuid="1234" * 8))
  586. await db_session.commit()
  587. tally = _CategoryTally()
  588. entry = self._spool_entry(tag_uid=None, tray_uuid="1234" * 8)
  589. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  590. await db_session.commit()
  591. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  592. assert tally.skipped == 1
  593. @pytest.mark.asyncio
  594. async def test_matches_tagless_spool_by_descriptive_composite(self, db_session):
  595. """Manually added spools have no tag, so fall back to created_at + description."""
  596. db_session.add(
  597. Spool(
  598. material="PLA",
  599. subtype="Basic",
  600. color_name="Jade White",
  601. brand="Bambu Lab",
  602. created_at=datetime(2026, 1, 5, 12, 0, 0),
  603. )
  604. )
  605. await db_session.commit()
  606. tally = _CategoryTally()
  607. entry = self._spool_entry(tag_uid=None)
  608. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  609. await db_session.commit()
  610. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  611. assert tally.skipped == 1
  612. @pytest.mark.asyncio
  613. async def test_overwrite_updates_matched_spool(self, db_session):
  614. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old", weight_used=0))
  615. await db_session.commit()
  616. tally = _CategoryTally()
  617. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, True, tally, {})
  618. await db_session.commit()
  619. row = (await db_session.execute(select(Spool))).scalar_one()
  620. assert row.color_name == "Jade White"
  621. assert row.weight_used == 120.5
  622. assert tally.restored == 1
  623. @pytest.mark.asyncio
  624. async def test_insert_preserves_created_at_so_repeat_restore_is_idempotent(self, db_session):
  625. """Second restore of the same backup must match, not duplicate."""
  626. service = _service()
  627. payload = {"spools": [self._spool_entry(tag_uid=None)]}
  628. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  629. await db_session.commit()
  630. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  631. await db_session.commit()
  632. spools = (await db_session.execute(select(Spool))).scalars().all()
  633. assert len(spools) == 1
  634. assert spools[0].created_at == datetime(2026, 1, 5, 12, 0, 0)
  635. @pytest.mark.asyncio
  636. async def test_usage_history_spool_id_is_remapped(self, db_session):
  637. """Usage rows must point at the new local spool id, not the backup's."""
  638. tally = _CategoryTally()
  639. inventory = {"spools": [self._spool_entry(id=41)]}
  640. usage = {
  641. "usage_history": [
  642. {
  643. "id": 900,
  644. "spool_id": 41,
  645. "printer_id": None,
  646. "print_name": "benchy.3mf",
  647. "archive_id": None,
  648. "weight_used": 12.0,
  649. "percent_used": 5,
  650. "status": "completed",
  651. "created_at": "2026-02-01 09:00:00",
  652. }
  653. ]
  654. }
  655. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  656. await db_session.commit()
  657. spool = (await db_session.execute(select(Spool))).scalar_one()
  658. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  659. assert row.spool_id == spool.id
  660. assert row.print_name == "benchy.3mf"
  661. @pytest.mark.asyncio
  662. async def test_usage_history_archive_id_is_remapped(self, db_session):
  663. tally = _CategoryTally()
  664. inventory = {"spools": [self._spool_entry(id=41)]}
  665. usage = {
  666. "usage_history": [
  667. {
  668. "spool_id": 41,
  669. "archive_id": 77,
  670. "weight_used": 1.0,
  671. "created_at": "2026-02-01 09:00:00",
  672. }
  673. ]
  674. }
  675. archive = PrintArchive(filename="a.3mf", file_path="", file_size=1)
  676. db_session.add(archive)
  677. await db_session.flush()
  678. await _service()._restore_spools(db_session, inventory, usage, False, tally, {77: archive.id})
  679. await db_session.commit()
  680. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  681. assert row.archive_id == archive.id
  682. @pytest.mark.asyncio
  683. async def test_usage_row_with_unresolvable_spool_is_skipped_and_explained(self, db_session):
  684. tally = _CategoryTally()
  685. usage = {"usage_history": [{"spool_id": 999, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}]}
  686. await _service()._restore_spools(db_session, {"spools": []}, usage, False, tally, {})
  687. await db_session.commit()
  688. assert (await db_session.execute(select(SpoolUsageHistory))).scalars().first() is None
  689. assert tally.skipped == 1
  690. assert any("their spool is not in this backup's spool list" in note for note in _messages(tally))
  691. # No remedy is offered, because none exists: overwrite does not change
  692. # which spools land in the map (a skipped spool is mapped anyway), and
  693. # usage history is always restored alongside the spools category.
  694. assert not any("overwrite" in note.lower() for note in _messages(tally))
  695. @pytest.mark.asyncio
  696. async def test_usage_resolves_against_a_spool_skipped_because_overwrite_is_off(self, db_session):
  697. """A skipped spool is still mapped, so its usage rows are not "unresolved".
  698. This is why the note above offers no remedy: turning overwrite on would
  699. not rescue anything, and saying so misdescribed which records are lost.
  700. """
  701. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  702. await db_session.commit()
  703. tally = _CategoryTally()
  704. inventory = {"spools": [self._spool_entry(id=41)]}
  705. usage = {
  706. "usage_history": [
  707. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  708. ]
  709. }
  710. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  711. await db_session.commit()
  712. spool = (await db_session.execute(select(Spool))).scalar_one()
  713. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  714. assert row.spool_id == spool.id
  715. assert not any("spool list" in note for note in _messages(tally))
  716. @pytest.mark.asyncio
  717. async def test_usage_history_is_not_duplicated_on_repeat_restore(self, db_session):
  718. service = _service()
  719. inventory = {"spools": [self._spool_entry(id=41)]}
  720. usage = {
  721. "usage_history": [
  722. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  723. ]
  724. }
  725. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  726. await db_session.commit()
  727. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  728. await db_session.commit()
  729. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  730. assert len(rows) == 1
  731. @pytest.mark.asyncio
  732. async def test_dropped_archive_link_is_explained(self, db_session):
  733. """Spools without archives nulls every usage -> archive link, silently."""
  734. tally = _CategoryTally()
  735. inventory = {"spools": [self._spool_entry(id=41)]}
  736. usage = {
  737. "usage_history": [
  738. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"},
  739. {"spool_id": 41, "archive_id": 8, "weight_used": 2.0, "created_at": "2026-02-01 10:00:00"},
  740. {"spool_id": 41, "weight_used": 3.0, "created_at": "2026-02-01 11:00:00"},
  741. ]
  742. }
  743. # Empty archive_id_map: the archives category wasn't selected, so its
  744. # payload was never fetched and there is nothing to match against.
  745. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  746. await db_session.commit()
  747. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  748. assert len(rows) == 3
  749. assert all(row.archive_id is None for row in rows)
  750. # Only the two that had a link to lose are counted.
  751. assert any("2 usage record(s) restored without their print-history link" in n for n in _messages(tally))
  752. assert any("select Print archives alongside" in n for n in _messages(tally))
  753. @pytest.mark.asyncio
  754. async def test_no_note_when_every_archive_link_resolves(self, db_session):
  755. tally = _CategoryTally()
  756. inventory = {"spools": [self._spool_entry(id=41)]}
  757. usage = {
  758. "usage_history": [
  759. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  760. ]
  761. }
  762. archive = PrintArchive(filename="linked.3mf", file_path="", file_size=1)
  763. db_session.add(archive)
  764. await db_session.flush()
  765. await _service()._restore_spools(db_session, inventory, usage, False, tally, {7: archive.id})
  766. await db_session.commit()
  767. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  768. assert row.archive_id == archive.id
  769. assert not any("print-history link" in note for note in _messages(tally))
  770. @pytest.mark.asyncio
  771. async def test_dangling_printer_id_is_cleared(self, db_session):
  772. tally = _CategoryTally()
  773. inventory = {"spools": [self._spool_entry(id=41)]}
  774. usage = {
  775. "usage_history": [
  776. {"spool_id": 41, "printer_id": 4242, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  777. ]
  778. }
  779. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  780. await db_session.commit()
  781. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  782. assert row.printer_id is None
  783. class TestRestoreArchives:
  784. def _archive_entry(self, **overrides):
  785. entry = {
  786. "id": 77,
  787. "filename": "benchy.3mf",
  788. "file_size": 2048,
  789. "content_hash": "abc123",
  790. "print_name": "Benchy",
  791. "status": "completed",
  792. "started_at": "2026-03-01 10:00:00",
  793. "completed_at": "2026-03-01 11:00:00",
  794. "created_at": "2026-03-01 10:00:00",
  795. "quantity": 1,
  796. "is_favorite": False,
  797. }
  798. entry.update(overrides)
  799. return entry
  800. @pytest.mark.asyncio
  801. async def test_inserts_metadata_only_row_with_empty_file_path(self, db_session):
  802. """print_archives.file_path is NOT NULL but is not in the backup."""
  803. tally = _CategoryTally()
  804. id_map: dict[int, int] = {}
  805. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, id_map)
  806. await db_session.commit()
  807. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  808. assert row.file_path == ""
  809. assert row.filename == "benchy.3mf"
  810. assert row.id != 77
  811. assert id_map == {77: row.id}
  812. assert any("metadata only" in note for note in _messages(tally))
  813. @pytest.mark.asyncio
  814. async def test_matches_existing_archive_by_hash_and_start(self, db_session):
  815. db_session.add(
  816. PrintArchive(
  817. filename="benchy.3mf",
  818. file_path="/data/benchy.3mf",
  819. file_size=2048,
  820. content_hash="abc123",
  821. started_at=datetime(2026, 3, 1, 10, 0, 0),
  822. )
  823. )
  824. await db_session.commit()
  825. tally = _CategoryTally()
  826. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  827. await db_session.commit()
  828. rows = (await db_session.execute(select(PrintArchive))).scalars().all()
  829. assert len(rows) == 1
  830. assert rows[0].file_path == "/data/benchy.3mf"
  831. assert tally.skipped == 1
  832. @pytest.mark.asyncio
  833. async def test_falls_back_to_filename_and_start_without_hash(self, db_session):
  834. db_session.add(
  835. PrintArchive(
  836. filename="benchy.3mf",
  837. file_path="/data/benchy.3mf",
  838. file_size=2048,
  839. started_at=datetime(2026, 3, 1, 10, 0, 0),
  840. )
  841. )
  842. await db_session.commit()
  843. tally = _CategoryTally()
  844. entry = self._archive_entry(content_hash=None)
  845. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  846. await db_session.commit()
  847. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  848. assert tally.skipped == 1
  849. @pytest.mark.asyncio
  850. async def test_matches_archive_with_no_started_at_by_hash(self, db_session):
  851. """started_at is NULL for re-sliced archives, so it cannot be required.
  852. Gating both match branches on it meant these rows never matched: every
  853. restore re-inserted them and overwrite mode could never update them.
  854. """
  855. db_session.add(
  856. PrintArchive(
  857. filename="benchy.3mf",
  858. file_path="/data/benchy.3mf",
  859. file_size=2048,
  860. content_hash="abc123",
  861. started_at=None,
  862. )
  863. )
  864. await db_session.commit()
  865. tally = _CategoryTally()
  866. entry = self._archive_entry(started_at=None)
  867. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  868. await db_session.commit()
  869. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  870. assert tally.skipped == 1
  871. @pytest.mark.asyncio
  872. async def test_started_at_still_discriminates_when_present(self, db_session):
  873. """A NULL-tolerant match must not collapse rows that do differ."""
  874. db_session.add(
  875. PrintArchive(
  876. filename="benchy.3mf",
  877. file_path="/data/benchy.3mf",
  878. file_size=2048,
  879. content_hash="abc123",
  880. started_at=datetime(2026, 3, 1, 10, 0, 0),
  881. )
  882. )
  883. await db_session.commit()
  884. tally = _CategoryTally()
  885. # Same file, no start time recorded — a different row, not that one.
  886. entry = self._archive_entry(started_at=None)
  887. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  888. await db_session.commit()
  889. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 2
  890. assert tally.restored == 1
  891. @pytest.mark.asyncio
  892. async def test_soft_deleted_archive_is_not_restored_as_visible(self, db_session):
  893. """A backup keeps soft-deleted rows, so the flag has to survive.
  894. Their row is retained on purpose (stats keep counting the filament and
  895. energy), so without carrying deleted_at a restore turns an archive the
  896. user deleted back into a visible one.
  897. """
  898. tally = _CategoryTally()
  899. entry = self._archive_entry(deleted_at="2026-03-02 08:00:00")
  900. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  901. await db_session.commit()
  902. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  903. assert row.deleted_at == datetime(2026, 3, 2, 8, 0, 0)
  904. assert tally.restored == 1
  905. @pytest.mark.asyncio
  906. async def test_locally_deleted_archive_stays_deleted_without_overwrite(self, db_session):
  907. db_session.add(
  908. PrintArchive(
  909. filename="benchy.3mf",
  910. file_path="",
  911. file_size=2048,
  912. content_hash="abc123",
  913. started_at=datetime(2026, 3, 1, 10, 0, 0),
  914. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  915. )
  916. )
  917. await db_session.commit()
  918. tally = _CategoryTally()
  919. # The backup predates the deletion, so its copy is live.
  920. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  921. await db_session.commit()
  922. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  923. assert row.deleted_at == datetime(2026, 3, 5, 9, 0, 0)
  924. assert tally.skipped == 1
  925. @pytest.mark.asyncio
  926. async def test_overwrite_undeletes_a_locally_deleted_archive_and_says_so(self, db_session):
  927. """The entry has to *say* the archive was live — absent no longer means null.
  928. A commit taken before the collector wrote ``deleted_at`` carries no
  929. opinion about it, and overwrite now leaves the column alone in that
  930. case; see ``TestRestoredArchiveOwnership``.
  931. """
  932. db_session.add(
  933. PrintArchive(
  934. filename="benchy.3mf",
  935. file_path="",
  936. file_size=2048,
  937. content_hash="abc123",
  938. started_at=datetime(2026, 3, 1, 10, 0, 0),
  939. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  940. )
  941. )
  942. await db_session.commit()
  943. tally = _CategoryTally()
  944. await _service()._restore_archives(
  945. db_session, {"archives": [self._archive_entry(deleted_at=None)]}, True, tally, {}
  946. )
  947. await db_session.commit()
  948. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  949. assert row.deleted_at is None
  950. assert tally.restored == 1
  951. assert any("visible again" in note for note in _messages(tally))
  952. @pytest.mark.asyncio
  953. async def test_overwrite_updates_metadata_but_keeps_local_file_path(self, db_session):
  954. db_session.add(
  955. PrintArchive(
  956. filename="benchy.3mf",
  957. file_path="/data/benchy.3mf",
  958. file_size=2048,
  959. content_hash="abc123",
  960. started_at=datetime(2026, 3, 1, 10, 0, 0),
  961. notes="old",
  962. )
  963. )
  964. await db_session.commit()
  965. tally = _CategoryTally()
  966. entry = self._archive_entry(notes="restored note")
  967. await _service()._restore_archives(db_session, {"archives": [entry]}, True, tally, {})
  968. await db_session.commit()
  969. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  970. assert row.notes == "restored note"
  971. # The 3MF on disk must not be orphaned by a metadata restore.
  972. assert row.file_path == "/data/benchy.3mf"
  973. assert tally.restored == 1
  974. @pytest.mark.asyncio
  975. async def test_dangling_printer_and_project_links_are_cleared(self, db_session):
  976. tally = _CategoryTally()
  977. entry = self._archive_entry(printer_id=4242, project_id=4343)
  978. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  979. await db_session.commit()
  980. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  981. assert row.printer_id is None
  982. assert row.project_id is None
  983. assert any("no longer exist" in note for note in _messages(tally))
  984. @pytest.mark.asyncio
  985. async def test_valid_printer_link_is_preserved(self, db_session, printer_factory):
  986. printer = await printer_factory()
  987. tally = _CategoryTally()
  988. entry = self._archive_entry(printer_id=printer.id)
  989. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  990. await db_session.commit()
  991. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  992. assert row.printer_id == printer.id
  993. @pytest.mark.asyncio
  994. async def test_non_dict_entry_counts_as_failed(self, db_session):
  995. tally = _CategoryTally()
  996. await _service()._restore_archives(db_session, {"archives": ["nonsense"]}, False, tally, {})
  997. assert tally.failed == 1
  998. class TestRestoreKprofiles:
  999. @staticmethod
  1000. def _live(slot_id, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123", extruder_id=0):
  1001. """One profile as the printer currently reports it.
  1002. ``extruder_id`` mirrors ``KProfile`` (bambu_mqtt.py), which has carried
  1003. it all along; single-nozzle printers report 0.
  1004. """
  1005. return SimpleNamespace(
  1006. slot_id=slot_id,
  1007. filament_id=filament_id,
  1008. name=name,
  1009. setting_id=setting_id,
  1010. extruder_id=extruder_id,
  1011. )
  1012. def _client(self, live=None, sent="7", ack=(True, "")):
  1013. """A connected printer client.
  1014. ``set_kprofiles_batch`` returns the sequence_id it published under, not
  1015. a success flag (#2718), and the verdict arrives separately from
  1016. ``await_cali_ack`` as ``(ok, detail)``.
  1017. """
  1018. client = MagicMock()
  1019. client.state.connected = True
  1020. client.set_kprofiles_batch = MagicMock(return_value=sent)
  1021. client.await_cali_ack = AsyncMock(return_value=ack)
  1022. client.get_kprofiles = AsyncMock(return_value=list(live or []))
  1023. return client
  1024. def _payload(self, serial="00M09A123456789", nozzle="0.4"):
  1025. return {
  1026. f"kprofiles/{serial}/{nozzle}.json": {
  1027. "version": "1.0",
  1028. "printer_serial": serial,
  1029. "nozzle_diameter": nozzle,
  1030. "profiles": [
  1031. {
  1032. "slot_id": 0,
  1033. "name": "Bambu PLA",
  1034. "k_value": "0.020000",
  1035. "filament_id": "GFA00",
  1036. "nozzle_id": "HS00-0.4",
  1037. "extruder_id": 0,
  1038. "setting_id": "PFUS123",
  1039. }
  1040. ],
  1041. }
  1042. }
  1043. @pytest.mark.asyncio
  1044. async def test_sends_batch_to_connected_printer(self, db_session, printer_factory):
  1045. printer = await printer_factory(serial_number="00M09A123456789")
  1046. client = self._client()
  1047. tally = _CategoryTally()
  1048. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1049. manager.get_client = MagicMock(return_value=client)
  1050. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1051. client.set_kprofiles_batch.assert_called_once()
  1052. profiles, nozzle = client.set_kprofiles_batch.call_args.args
  1053. assert nozzle == "0.4"
  1054. assert profiles[0]["name"] == "Bambu PLA"
  1055. assert profiles[0]["filament_id"] == "GFA00"
  1056. assert tally.restored == 1
  1057. assert manager.get_client.call_args.args == (printer.id,)
  1058. @pytest.mark.asyncio
  1059. async def test_always_warns_to_verify_on_the_printer(self, db_session, printer_factory):
  1060. await printer_factory(serial_number="00M09A123456789")
  1061. client = self._client()
  1062. tally = _CategoryTally()
  1063. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1064. manager.get_client = MagicMock(return_value=client)
  1065. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1066. # A refusal is now read and counted failed, so the caveat is narrowed to
  1067. # what is genuinely left uncertain: a printer that never answers.
  1068. assert any("verify the profiles on the printer" in note for note in _messages(tally))
  1069. assert any("does not answer still counts as restored" in note for note in _messages(tally))
  1070. assert not any("without acknowledgement" in note for note in _messages(tally))
  1071. assert any("always overwrite" in note for note in _messages(tally))
  1072. # --- cali_idx is resolved live, never taken from the backup -------------
  1073. #
  1074. # Regression cover for the silent no-op found testing on an X1E: the backup
  1075. # stored cali_idx 8151, a Bambuddy edit re-keyed the profile to 4606, and
  1076. # the restore aimed extrusion_cali_set at 8151. The printer dropped it and
  1077. # the tally still said "1 restored".
  1078. @pytest.mark.asyncio
  1079. async def test_uses_the_live_cali_idx_not_the_backed_up_slot(self, db_session, printer_factory):
  1080. await printer_factory(serial_number="00M09A123456789")
  1081. payload = self._payload()
  1082. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]["slot_id"] = 8151
  1083. client = self._client(live=[self._live(slot_id=4606)])
  1084. tally = _CategoryTally()
  1085. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1086. manager.get_client = MagicMock(return_value=client)
  1087. await _service()._restore_kprofiles(db_session, payload, tally)
  1088. client.get_kprofiles.assert_awaited_once_with(nozzle_diameter="0.4")
  1089. profiles, _ = client.set_kprofiles_batch.call_args.args
  1090. assert profiles[0]["cali_idx"] == 4606, "must address the slot that exists now"
  1091. assert profiles[0]["cali_idx"] != 8151, "must not reuse the backup's cali_idx"
  1092. assert tally.restored == 1
  1093. @pytest.mark.asyncio
  1094. async def test_matches_on_name_when_setting_id_was_regenerated(self, db_session, printer_factory):
  1095. # A delete-then-add edit mints a fresh setting_id, so the name carries
  1096. # the match instead.
  1097. await printer_factory(serial_number="00M09A123456789")
  1098. client = self._client(live=[self._live(slot_id=4606, setting_id="PF9999999999")])
  1099. tally = _CategoryTally()
  1100. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1101. manager.get_client = MagicMock(return_value=client)
  1102. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1103. profiles, _ = client.set_kprofiles_batch.call_args.args
  1104. assert profiles[0]["cali_idx"] == 4606
  1105. # The live setting_id wins: it is what the printer associates with the slot.
  1106. assert profiles[0]["setting_id"] == "PF9999999999"
  1107. @pytest.mark.asyncio
  1108. async def test_unmatched_profile_is_added_rather_than_aimed_at_a_dead_slot(self, db_session, printer_factory):
  1109. await printer_factory(serial_number="00M09A123456789")
  1110. client = self._client(live=[]) # printer has nothing for this nozzle
  1111. tally = _CategoryTally()
  1112. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1113. manager.get_client = MagicMock(return_value=client)
  1114. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1115. profiles, _ = client.set_kprofiles_batch.call_args.args
  1116. assert profiles[0]["cali_idx"] == -1, "-1 tells the printer to add a new profile"
  1117. assert profiles[0]["setting_id"] == "PFUS123", "falls back to the backed-up preset"
  1118. assert any("added as new profiles" in note for note in _messages(tally))
  1119. @pytest.mark.asyncio
  1120. async def test_different_filament_is_not_treated_as_a_match(self, db_session, printer_factory):
  1121. # Same slot, different filament — matching on slot alone would clobber
  1122. # an unrelated profile.
  1123. await printer_factory(serial_number="00M09A123456789")
  1124. client = self._client(live=[self._live(slot_id=4606, filament_id="GFB99", name="Bambu PLA")])
  1125. tally = _CategoryTally()
  1126. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1127. manager.get_client = MagicMock(return_value=client)
  1128. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1129. profiles, _ = client.set_kprofiles_batch.call_args.args
  1130. assert profiles[0]["cali_idx"] == -1
  1131. @pytest.mark.asyncio
  1132. async def test_unreadable_live_index_degrades_to_adding(self, db_session, printer_factory):
  1133. # A failed read must not abort the restore.
  1134. await printer_factory(serial_number="00M09A123456789")
  1135. client = self._client()
  1136. client.get_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt timeout"))
  1137. tally = _CategoryTally()
  1138. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1139. manager.get_client = MagicMock(return_value=client)
  1140. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1141. profiles, _ = client.set_kprofiles_batch.call_args.args
  1142. assert profiles[0]["cali_idx"] == -1
  1143. assert tally.restored == 1
  1144. @pytest.mark.asyncio
  1145. async def test_sole_profile_for_a_filament_matches_without_setting_id_or_name(self, db_session, printer_factory):
  1146. await printer_factory(serial_number="00M09A123456789")
  1147. payload = self._payload()
  1148. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1149. entry["setting_id"] = None
  1150. entry["name"] = ""
  1151. client = self._client(live=[self._live(slot_id=4606, setting_id="PFOTHER", name="Renamed")])
  1152. tally = _CategoryTally()
  1153. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1154. manager.get_client = MagicMock(return_value=client)
  1155. await _service()._restore_kprofiles(db_session, payload, tally)
  1156. profiles, _ = client.set_kprofiles_batch.call_args.args
  1157. assert profiles[0]["cali_idx"] == 4606
  1158. @pytest.mark.asyncio
  1159. async def test_ambiguous_filament_without_discriminator_is_added_not_guessed(self, db_session, printer_factory):
  1160. await printer_factory(serial_number="00M09A123456789")
  1161. payload = self._payload()
  1162. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1163. entry["setting_id"] = None
  1164. entry["name"] = ""
  1165. client = self._client(live=[self._live(slot_id=1, setting_id="A"), self._live(slot_id=2, setting_id="B")])
  1166. tally = _CategoryTally()
  1167. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1168. manager.get_client = MagicMock(return_value=client)
  1169. await _service()._restore_kprofiles(db_session, payload, tally)
  1170. profiles, _ = client.set_kprofiles_batch.call_args.args
  1171. assert profiles[0]["cali_idx"] == -1, "two candidates and nothing to tell them apart"
  1172. @pytest.mark.asyncio
  1173. async def test_two_entries_cannot_claim_the_same_live_slot(self, db_session, printer_factory):
  1174. """One live profile cannot stand in for two backed-up ones (#2656).
  1175. Both entries fell through to the single-candidate arm, both took
  1176. cali_idx 4606, both went into the batch — so the second overwrote the
  1177. first on the printer while the tally counted two restored. Reachable
  1178. whenever the user has deleted one of a pair since the backup, because
  1179. the delete-then-add re-key is what strips the setting_id match.
  1180. """
  1181. await printer_factory(serial_number="00M09A123456789")
  1182. payload = self._payload()
  1183. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1184. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1185. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1186. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1187. tally = _CategoryTally()
  1188. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1189. manager.get_client = MagicMock(return_value=client)
  1190. await _service()._restore_kprofiles(db_session, payload, tally)
  1191. profiles, _ = client.set_kprofiles_batch.call_args.args
  1192. assert [p["cali_idx"] for p in profiles] == [4606, -1], "the displaced entry has to be added, not aliased"
  1193. assert sum(1 for p in profiles if p["cali_idx"] == 4606) == 1
  1194. assert any("added as new profiles" in note for note in _messages(tally))
  1195. @pytest.mark.asyncio
  1196. async def test_the_displaced_entry_does_not_inherit_the_claimed_setting_id(self, db_session, printer_factory):
  1197. """An add-as-new keeps its own preset, or it lands on top of the match anyway.
  1198. cali_idx -1 is only safe if the rest of the payload doesn't point at the
  1199. profile the first entry just claimed — the generated-setting_id fallback
  1200. reads setting_id when cali_idx is -1.
  1201. """
  1202. await printer_factory(serial_number="00M09A123456789")
  1203. payload = self._payload()
  1204. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1205. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1206. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1207. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1208. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1209. manager.get_client = MagicMock(return_value=client)
  1210. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1211. profiles, _ = client.set_kprofiles_batch.call_args.args
  1212. assert profiles[0]["setting_id"] == "PFUS123", "the match prefers the live preset"
  1213. assert profiles[1]["setting_id"] == "PFGONE2", "the displaced entry keeps its own"
  1214. @pytest.mark.asyncio
  1215. async def test_two_entries_matching_two_live_profiles_keep_their_own_slots(self, db_session, printer_factory):
  1216. """Control: the guard must not displace a legitimate second match."""
  1217. await printer_factory(serial_number="00M09A123456789")
  1218. payload = self._payload()
  1219. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1220. entries.append({**entries[0], "setting_id": "PFUS456", "name": "Bambu PETG"})
  1221. client = self._client(
  1222. live=[
  1223. self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA"),
  1224. self._live(slot_id=4607, setting_id="PFUS456", name="Bambu PETG"),
  1225. ]
  1226. )
  1227. tally = _CategoryTally()
  1228. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1229. manager.get_client = MagicMock(return_value=client)
  1230. await _service()._restore_kprofiles(db_session, payload, tally)
  1231. profiles, _ = client.set_kprofiles_batch.call_args.args
  1232. assert [p["cali_idx"] for p in profiles] == [4606, 4607]
  1233. assert not any("added as new profiles" in note for note in _messages(tally))
  1234. @pytest.mark.asyncio
  1235. async def test_a_claimed_slot_does_not_make_an_ambiguous_pair_matchable(self, db_session, printer_factory):
  1236. """Two live profiles for one filament stay ambiguous after one is taken.
  1237. The single-candidate fallback is judged against every candidate, not the
  1238. unclaimed ones — otherwise claiming the first would leave exactly one
  1239. "available" and turn a guess the code deliberately refuses into a match.
  1240. """
  1241. await printer_factory(serial_number="00M09A123456789")
  1242. payload = self._payload()
  1243. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1244. entries[0].update(setting_id="PFUS123", name="Bambu PLA")
  1245. entries.append({**entries[0], "setting_id": None, "name": ""})
  1246. client = self._client(
  1247. live=[
  1248. self._live(slot_id=1, setting_id="PFUS123", name="Bambu PLA"),
  1249. self._live(slot_id=2, setting_id="PFOTHER", name="Renamed"),
  1250. ]
  1251. )
  1252. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1253. manager.get_client = MagicMock(return_value=client)
  1254. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1255. profiles, _ = client.set_kprofiles_batch.call_args.args
  1256. assert [p["cali_idx"] for p in profiles] == [1, -1]
  1257. # --- the match is scoped to the extruder it was calibrated on -----------
  1258. #
  1259. # get_kprofiles reads per nozzle *diameter*, so on a dual-nozzle printer
  1260. # both extruders come back in one list. Scoping candidates on filament_id
  1261. # alone let one extruder's calibration be written over the other's.
  1262. @pytest.mark.asyncio
  1263. async def test_each_extruders_profile_lands_on_its_own_extruder(self, db_session, printer_factory):
  1264. """The same preset calibrated on both extruders of an H2D.
  1265. Both live profiles share a filament_id *and* a setting_id, so the
  1266. setting_id arm matched whichever the printer happened to list first —
  1267. and with an entry per extruder the two swapped slots, each overwriting
  1268. the other's calibration while the tally counted both restored.
  1269. """
  1270. await printer_factory(serial_number="00M09A123456789")
  1271. payload = self._payload()
  1272. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1273. entries.append({**entries[0], "extruder_id": 1, "nozzle_id": "HS00-0.4-R"})
  1274. client = self._client(
  1275. live=[
  1276. # Right extruder first, which is what made the bug bite.
  1277. self._live(slot_id=1001, extruder_id=1),
  1278. self._live(slot_id=1000, extruder_id=0),
  1279. ]
  1280. )
  1281. tally = _CategoryTally()
  1282. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1283. manager.get_client = MagicMock(return_value=client)
  1284. await _service()._restore_kprofiles(db_session, payload, tally)
  1285. profiles, _ = client.set_kprofiles_batch.call_args.args
  1286. assert [(p["extruder_id"], p["cali_idx"]) for p in profiles] == [(0, 1000), (1, 1001)]
  1287. assert tally.restored == 2
  1288. assert not any("added as new profiles" in note for note in _messages(tally))
  1289. @pytest.mark.asyncio
  1290. async def test_the_other_extruders_profile_is_not_a_candidate(self, db_session, printer_factory):
  1291. """One backed-up entry, and the only live profile is the other extruder's.
  1292. Adding as new is the right answer: extruder 0's calibration is not a
  1293. stand-in for extruder 1's, however well the filament and preset line up.
  1294. """
  1295. await printer_factory(serial_number="00M09A123456789")
  1296. client = self._client(live=[self._live(slot_id=1001, extruder_id=1)])
  1297. tally = _CategoryTally()
  1298. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1299. manager.get_client = MagicMock(return_value=client)
  1300. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1301. profiles, _ = client.set_kprofiles_batch.call_args.args
  1302. assert profiles[0]["cali_idx"] == -1
  1303. assert any("added as new profiles" in note for note in _messages(tally))
  1304. @pytest.mark.asyncio
  1305. async def test_an_entry_without_an_extruder_id_still_matches(self, db_session, printer_factory):
  1306. """Control: a pre-#2656 backup carries no extruder_id.
  1307. A missing key must leave the match exactly as it was, not turn every
  1308. entry into an add.
  1309. """
  1310. await printer_factory(serial_number="00M09A123456789")
  1311. payload = self._payload()
  1312. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0].pop("extruder_id")
  1313. client = self._client(live=[self._live(slot_id=4606)])
  1314. tally = _CategoryTally()
  1315. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1316. manager.get_client = MagicMock(return_value=client)
  1317. await _service()._restore_kprofiles(db_session, payload, tally)
  1318. profiles, _ = client.set_kprofiles_batch.call_args.args
  1319. assert profiles[0]["cali_idx"] == 4606
  1320. assert tally.restored == 1
  1321. @pytest.mark.asyncio
  1322. async def test_a_live_index_that_reports_no_extruder_still_matches(self, db_session, printer_factory):
  1323. """Control: the same, for a printer whose profiles carry no extruder_id."""
  1324. await printer_factory(serial_number="00M09A123456789")
  1325. live = SimpleNamespace(slot_id=4606, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123")
  1326. client = self._client(live=[live])
  1327. tally = _CategoryTally()
  1328. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1329. manager.get_client = MagicMock(return_value=client)
  1330. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1331. profiles, _ = client.set_kprofiles_batch.call_args.args
  1332. assert profiles[0]["cali_idx"] == 4606
  1333. assert tally.restored == 1
  1334. @pytest.mark.asyncio
  1335. async def test_unknown_serial_is_skipped_with_reason(self, db_session):
  1336. tally = _CategoryTally()
  1337. with patch("backend.app.services.github_restore.printer_manager"):
  1338. await _service()._restore_kprofiles(db_session, self._payload(serial="NOSUCH"), tally)
  1339. assert tally.restored == 0
  1340. assert tally.skipped == 1
  1341. assert any("No printer with serial NOSUCH" in note for note in _messages(tally))
  1342. @pytest.mark.asyncio
  1343. async def test_offline_printer_is_skipped_not_failed(self, db_session, printer_factory):
  1344. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1345. client = MagicMock()
  1346. client.state.connected = False
  1347. tally = _CategoryTally()
  1348. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1349. manager.get_client = MagicMock(return_value=client)
  1350. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1351. assert tally.skipped == 1
  1352. assert tally.failed == 0
  1353. assert any("not connected" in note for note in _messages(tally))
  1354. @pytest.mark.asyncio
  1355. async def test_no_client_at_all_is_skipped(self, db_session, printer_factory):
  1356. await printer_factory(serial_number="00M09A123456789")
  1357. tally = _CategoryTally()
  1358. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1359. manager.get_client = MagicMock(return_value=None)
  1360. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1361. assert tally.skipped == 1
  1362. @pytest.mark.asyncio
  1363. async def test_publish_failure_counts_as_failed(self, db_session, printer_factory):
  1364. # None is what set_kprofiles_batch returns when it could not publish —
  1365. # a disconnected client. There is no ack to wait for in that case.
  1366. await printer_factory(serial_number="00M09A123456789")
  1367. client = self._client(sent=None)
  1368. tally = _CategoryTally()
  1369. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1370. manager.get_client = MagicMock(return_value=client)
  1371. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1372. assert tally.failed == 1
  1373. assert tally.restored == 0
  1374. assert "kprofilesSendFailed" in _codes(tally)
  1375. assert "kprofilesRefused" not in _codes(tally), "nothing was sent, so the printer refused nothing"
  1376. client.await_cali_ack.assert_not_awaited()
  1377. @pytest.mark.asyncio
  1378. async def test_publish_exception_is_contained(self, db_session, printer_factory):
  1379. await printer_factory(serial_number="00M09A123456789")
  1380. client = MagicMock()
  1381. client.state.connected = True
  1382. client.set_kprofiles_batch = MagicMock(side_effect=RuntimeError("mqtt down"))
  1383. tally = _CategoryTally()
  1384. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1385. manager.get_client = MagicMock(return_value=client)
  1386. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1387. assert tally.failed == 1
  1388. # --- the printer's verdict decides the tally, not the publish ------------
  1389. #
  1390. # #2718 changed set_kprofiles_batch from returning a bool to returning the
  1391. # sequence_id it published under. A sequence_id string is truthy, so a
  1392. # restore that branches on the return value alone reports every refused
  1393. # write as saved — the defect that fix closed in every other caller.
  1394. @pytest.mark.asyncio
  1395. async def test_awaits_the_ack_for_the_sequence_id_it_was_given(self, db_session, printer_factory):
  1396. await printer_factory(serial_number="00M09A123456789")
  1397. client = self._client(sent="4211")
  1398. tally = _CategoryTally()
  1399. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1400. manager.get_client = MagicMock(return_value=client)
  1401. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1402. client.await_cali_ack.assert_awaited_once_with("4211")
  1403. assert tally.restored == 1
  1404. @pytest.mark.asyncio
  1405. async def test_a_refused_batch_counts_failed_not_restored(self, db_session, printer_factory):
  1406. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1407. client = self._client(ack=(False, "invalid tray_id"))
  1408. tally = _CategoryTally()
  1409. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1410. manager.get_client = MagicMock(return_value=client)
  1411. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1412. assert tally.restored == 0
  1413. assert tally.failed == 1
  1414. assert "kprofilesRefused" in _codes(tally)
  1415. assert "kprofilesSendFailed" not in _codes(tally), "it was sent — the printer answered no"
  1416. note = next(n for n in tally.notes if n["code"] == "kprofilesRefused")
  1417. assert note["params"]["reason"] == "invalid tray_id", "the printer's own reason has to survive"
  1418. assert "Shelf Printer" in note["message"] and "invalid tray_id" in note["message"]
  1419. @pytest.mark.asyncio
  1420. async def test_a_silent_printer_still_counts_restored(self, db_session, printer_factory):
  1421. # maziggy's rule, and await_cali_ack's own contract: no answer is not
  1422. # evidence of refusal. Firmware that predates the ack never answers.
  1423. await printer_factory(serial_number="00M09A123456789")
  1424. client = self._client(ack=(True, "no acknowledgement from printer"))
  1425. tally = _CategoryTally()
  1426. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1427. manager.get_client = MagicMock(return_value=client)
  1428. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1429. assert tally.restored == 1
  1430. assert tally.failed == 0
  1431. assert "kprofilesRefused" not in _codes(tally)
  1432. @pytest.mark.asyncio
  1433. async def test_an_unreadable_ack_does_not_fail_the_batch(self, db_session, printer_factory):
  1434. # Same situation one layer up: the write most likely landed, so this
  1435. # degrades the way a timeout does rather than inventing a failure.
  1436. await printer_factory(serial_number="00M09A123456789")
  1437. client = self._client()
  1438. client.await_cali_ack = AsyncMock(side_effect=RuntimeError("mqtt down"))
  1439. tally = _CategoryTally()
  1440. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1441. manager.get_client = MagicMock(return_value=client)
  1442. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1443. assert tally.restored == 1
  1444. assert tally.failed == 0
  1445. @pytest.mark.asyncio
  1446. async def test_one_refused_nozzle_does_not_condemn_the_other(self, db_session, printer_factory):
  1447. await printer_factory(serial_number="00M09A123456789")
  1448. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1449. client = self._client()
  1450. client.await_cali_ack = AsyncMock(side_effect=[(False, "busy"), (True, "")])
  1451. tally = _CategoryTally()
  1452. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1453. manager.get_client = MagicMock(return_value=client)
  1454. await _service()._restore_kprofiles(db_session, payload, tally)
  1455. assert tally.restored == 1
  1456. assert tally.failed == 1
  1457. @pytest.mark.asyncio
  1458. async def test_each_nozzle_is_sent_separately(self, db_session, printer_factory):
  1459. await printer_factory(serial_number="00M09A123456789")
  1460. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1461. client = self._client()
  1462. tally = _CategoryTally()
  1463. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1464. manager.get_client = MagicMock(return_value=client)
  1465. await _service()._restore_kprofiles(db_session, payload, tally)
  1466. assert client.set_kprofiles_batch.call_count == 2
  1467. assert {c.args[1] for c in client.set_kprofiles_batch.call_args_list} == {"0.4", "0.8"}
  1468. assert tally.restored == 2
  1469. @pytest.mark.asyncio
  1470. async def test_empty_payload_is_noted(self, db_session):
  1471. tally = _CategoryTally()
  1472. await _service()._restore_kprofiles(db_session, {}, tally)
  1473. assert _codes(tally) == ["noData"]
  1474. class TestSoftDeletedArchiveRoundTrip:
  1475. """The two halves of the soft-delete fix only work together.
  1476. The collector keeps soft-deleted rows on purpose (their stats still count),
  1477. so if it doesn't write ``deleted_at`` there is nothing for the restore to
  1478. carry across and a deleted archive comes back visible. Covered end to end
  1479. because each half looks harmless on its own.
  1480. """
  1481. @pytest.mark.asyncio
  1482. async def test_deleted_at_survives_collect_then_restore(self, db_session):
  1483. from backend.app.services.github_backup import github_backup_service
  1484. deleted_at = datetime(2026, 3, 5, 9, 0, 0)
  1485. db_session.add(
  1486. PrintArchive(
  1487. filename="trashed.3mf",
  1488. file_path="",
  1489. file_size=1024,
  1490. content_hash="hash-trashed",
  1491. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1492. deleted_at=deleted_at,
  1493. )
  1494. )
  1495. await db_session.commit()
  1496. files: dict = {}
  1497. await github_backup_service._collect_archives(db_session, files)
  1498. payload = files[ARCHIVES_PATH]
  1499. assert payload["archives"][0]["deleted_at"] == str(deleted_at)
  1500. # Restore that payload into an instance where the row is gone entirely.
  1501. await db_session.execute(PrintArchive.__table__.delete())
  1502. await db_session.commit()
  1503. tally = _CategoryTally()
  1504. await _service()._restore_archives(db_session, payload, False, tally, {})
  1505. await db_session.commit()
  1506. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1507. assert row.deleted_at == deleted_at, "a deleted archive must not come back visible"
  1508. class TestRestoredArchiveOwnership:
  1509. """A restored archive without an owner is invisible to the person who owns it.
  1510. ``created_by_id`` is not attribution, it is the column the access check runs
  1511. on: ``_ensure_archive_visible`` fails closed on NULL (404 for any caller
  1512. without ``archives:read_all``) and the list paths filter
  1513. ``created_by_id == user.id``. So on a multi-user instance the tally reported
  1514. archives restored while their owner could neither list nor open them.
  1515. """
  1516. def _entry(self, **overrides):
  1517. entry = {
  1518. "id": 77,
  1519. "filename": "benchy.3mf",
  1520. "file_size": 2048,
  1521. "content_hash": "abc123",
  1522. "started_at": "2026-03-01 10:00:00",
  1523. "created_at": "2026-03-01 10:00:00",
  1524. }
  1525. entry.update(overrides)
  1526. return entry
  1527. async def _user(self, db, username="alice"):
  1528. user = User(username=username, role="operator")
  1529. db.add(user)
  1530. await db.flush()
  1531. return user
  1532. @pytest.mark.asyncio
  1533. async def test_owner_is_carried_across(self, db_session):
  1534. user = await self._user(db_session)
  1535. tally = _CategoryTally()
  1536. await _service()._restore_archives(
  1537. db_session, {"archives": [self._entry(created_by_id=user.id)]}, False, tally, {}
  1538. )
  1539. await db_session.commit()
  1540. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1541. assert row.created_by_id == user.id
  1542. assert not any("owner cleared" in note for note in _messages(tally))
  1543. @pytest.mark.asyncio
  1544. async def test_an_unknown_owner_is_cleared_with_a_note_not_failed(self, db_session):
  1545. """The archive is still worth having; an admin can reassign it."""
  1546. tally = _CategoryTally()
  1547. await _service()._restore_archives(
  1548. db_session, {"archives": [self._entry(created_by_id=4242)]}, False, tally, {}
  1549. )
  1550. await db_session.commit()
  1551. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1552. assert row.created_by_id is None
  1553. assert tally.restored == 1 and tally.failed == 0
  1554. assert any("owner cleared" in note and "archives:read_all" in note for note in _messages(tally))
  1555. @pytest.mark.asyncio
  1556. async def test_the_owner_note_is_emitted_once_for_many_rows(self, db_session):
  1557. tally = _CategoryTally()
  1558. archives = [
  1559. self._entry(id=1, content_hash="h1", filename="a.3mf", created_by_id=4242),
  1560. self._entry(id=2, content_hash="h2", filename="b.3mf", created_by_id=4243),
  1561. ]
  1562. await _service()._restore_archives(db_session, {"archives": archives}, False, tally, {})
  1563. await db_session.commit()
  1564. assert sum(1 for note in _messages(tally) if "owner cleared" in note) == 1
  1565. @pytest.mark.asyncio
  1566. async def test_a_backup_without_the_key_still_restores(self, db_session):
  1567. """Backups taken before the collector recorded it just can't know the owner."""
  1568. tally = _CategoryTally()
  1569. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, False, tally, {})
  1570. await db_session.commit()
  1571. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1572. assert row.created_by_id is None
  1573. assert not any("owner cleared" in note for note in _messages(tally))
  1574. @pytest.mark.asyncio
  1575. async def test_overwrite_makes_the_local_owner_match_the_backup(self, db_session):
  1576. alice = await self._user(db_session, "alice")
  1577. bob = await self._user(db_session, "bob")
  1578. db_session.add(
  1579. PrintArchive(
  1580. filename="benchy.3mf",
  1581. file_path="/data/benchy.3mf",
  1582. file_size=2048,
  1583. content_hash="abc123",
  1584. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1585. created_by_id=bob.id,
  1586. )
  1587. )
  1588. await db_session.commit()
  1589. await _service()._restore_archives(
  1590. db_session, {"archives": [self._entry(created_by_id=alice.id)]}, True, _CategoryTally(), {}
  1591. )
  1592. await db_session.commit()
  1593. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1594. assert row.created_by_id == alice.id
  1595. @pytest.mark.asyncio
  1596. async def test_overwrite_leaves_the_owner_alone_when_the_backup_predates_the_key(self, db_session):
  1597. """A pre-#2656 commit must not blank the owner of a row that was fine.
  1598. The entry carries no ``created_by_id`` at all, so there is nothing to
  1599. write. Treating that as an explicit null inflicted the exact bug the
  1600. column was added to fix — a 404 for the owner — on rows the restore had
  1601. no business touching, silently, while still counting them restored.
  1602. """
  1603. bob = await self._user(db_session, "bob")
  1604. db_session.add(
  1605. PrintArchive(
  1606. filename="benchy.3mf",
  1607. file_path="/data/benchy.3mf",
  1608. file_size=2048,
  1609. content_hash="abc123",
  1610. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1611. created_by_id=bob.id,
  1612. )
  1613. )
  1614. await db_session.commit()
  1615. tally = _CategoryTally()
  1616. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1617. await db_session.commit()
  1618. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1619. assert row.created_by_id == bob.id, "an old backup does not know the owner, so it must not clear one"
  1620. assert tally.restored == 1
  1621. @pytest.mark.asyncio
  1622. async def test_overwrite_leaves_deleted_at_alone_when_the_backup_predates_the_key(self, db_session):
  1623. """The mirror case: an old commit must not un-delete, and must not claim to.
  1624. ``archivesUndeleted`` reads the same absent value, so the un-delete was
  1625. not merely wrong but unannounced.
  1626. """
  1627. db_session.add(
  1628. PrintArchive(
  1629. filename="benchy.3mf",
  1630. file_path="/data/benchy.3mf",
  1631. file_size=2048,
  1632. content_hash="abc123",
  1633. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1634. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1635. )
  1636. )
  1637. await db_session.commit()
  1638. tally = _CategoryTally()
  1639. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1640. await db_session.commit()
  1641. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1642. assert row.deleted_at == datetime(2026, 3, 4, 8, 0, 0), "an old backup must not resurrect a deleted archive"
  1643. assert not any("visible again" in note for note in _messages(tally))
  1644. @pytest.mark.asyncio
  1645. async def test_overwrite_still_clears_an_owner_the_backup_explicitly_nulls(self, db_session):
  1646. """Control: absent is ignored, but an explicit null is still honoured.
  1647. A current-format backup of an unowned archive has to be able to say so,
  1648. or overwrite stops meaning "make the local row match the backup".
  1649. """
  1650. bob = await self._user(db_session, "bob")
  1651. db_session.add(
  1652. PrintArchive(
  1653. filename="benchy.3mf",
  1654. file_path="/data/benchy.3mf",
  1655. file_size=2048,
  1656. content_hash="abc123",
  1657. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1658. created_by_id=bob.id,
  1659. )
  1660. )
  1661. await db_session.commit()
  1662. await _service()._restore_archives(
  1663. db_session, {"archives": [self._entry(created_by_id=None)]}, True, _CategoryTally(), {}
  1664. )
  1665. await db_session.commit()
  1666. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1667. assert row.created_by_id is None
  1668. @pytest.mark.asyncio
  1669. async def test_overwrite_still_undeletes_when_the_backup_explicitly_nulls(self, db_session):
  1670. """Control for the deleted_at half, with the note that goes with it."""
  1671. db_session.add(
  1672. PrintArchive(
  1673. filename="benchy.3mf",
  1674. file_path="/data/benchy.3mf",
  1675. file_size=2048,
  1676. content_hash="abc123",
  1677. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1678. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1679. )
  1680. )
  1681. await db_session.commit()
  1682. tally = _CategoryTally()
  1683. await _service()._restore_archives(db_session, {"archives": [self._entry(deleted_at=None)]}, True, tally, {})
  1684. await db_session.commit()
  1685. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1686. assert row.deleted_at is None
  1687. assert any("visible again" in note for note in _messages(tally))
  1688. @pytest.mark.asyncio
  1689. async def test_owner_survives_collect_then_restore(self, db_session):
  1690. """Both halves, because each looks harmless alone.
  1691. The collector never wrote the key, so there was nothing for the restore
  1692. to carry across even once it wanted to.
  1693. """
  1694. from backend.app.services.github_backup import github_backup_service
  1695. user = await self._user(db_session)
  1696. db_session.add(
  1697. PrintArchive(
  1698. filename="owned.3mf",
  1699. file_path="",
  1700. file_size=1024,
  1701. content_hash="hash-owned",
  1702. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1703. created_by_id=user.id,
  1704. )
  1705. )
  1706. await db_session.commit()
  1707. files: dict = {}
  1708. await github_backup_service._collect_archives(db_session, files)
  1709. payload = files[ARCHIVES_PATH]
  1710. assert payload["archives"][0]["created_by_id"] == user.id
  1711. await db_session.execute(PrintArchive.__table__.delete())
  1712. await db_session.commit()
  1713. await _service()._restore_archives(db_session, payload, False, _CategoryTally(), {})
  1714. await db_session.commit()
  1715. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1716. assert row.created_by_id == user.id, "a restored archive its owner cannot see is not restored"
  1717. class TestCategoryPathMapping:
  1718. def setup_method(self):
  1719. self.service = _service()
  1720. self.available = [
  1721. "backup_metadata.json",
  1722. SETTINGS_PATH,
  1723. SPOOLS_PATH,
  1724. SPOOL_USAGE_PATH,
  1725. ARCHIVES_PATH,
  1726. "kprofiles/SERIAL1/0.4.json",
  1727. "kprofiles/SERIAL1/0.8.json",
  1728. "cloud_profiles/filament.json",
  1729. ]
  1730. def test_spools_includes_usage_history(self):
  1731. paths = self.service._category_paths(RestoreCategory.SPOOLS, self.available)
  1732. assert paths == [SPOOLS_PATH, SPOOL_USAGE_PATH]
  1733. def test_kprofiles_globs_all_serials_and_nozzles(self):
  1734. paths = self.service._category_paths(RestoreCategory.KPROFILES, self.available)
  1735. assert paths == ["kprofiles/SERIAL1/0.4.json", "kprofiles/SERIAL1/0.8.json"]
  1736. def test_absent_paths_are_omitted(self):
  1737. paths = self.service._category_paths(RestoreCategory.SETTINGS, ["backup_metadata.json"])
  1738. assert paths == []
  1739. def test_cloud_profiles_are_not_a_restore_category(self):
  1740. assert "cloud_profiles" not in {c.value for c in RestoreCategory}
  1741. class TestMutex:
  1742. @pytest.mark.asyncio
  1743. async def test_restore_refuses_while_a_backup_is_running(self):
  1744. service = _service()
  1745. with patch("backend.app.services.github_backup.github_backup_service") as backup:
  1746. backup.is_running = True
  1747. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1748. assert result["success"] is False
  1749. assert "backup is currently running" in result["message"]
  1750. @pytest.mark.asyncio
  1751. async def test_restore_refuses_while_another_restore_is_running(self):
  1752. service = _service()
  1753. service._running_restore = True
  1754. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1755. assert result["success"] is False
  1756. assert "restore is already running" in result["message"]
  1757. @pytest.mark.asyncio
  1758. async def test_backup_refuses_while_a_restore_is_running(self):
  1759. from backend.app.services.github_backup import GitHubBackupService
  1760. backup_service = GitHubBackupService()
  1761. with patch("backend.app.services.github_restore.github_restore_service") as restore:
  1762. restore.is_running = True
  1763. result = await backup_service.run_backup(1, trigger="manual")
  1764. assert result["success"] is False
  1765. assert "restore is currently running" in result["message"]
  1766. class TestMqttRelayReconfigure:
  1767. """Restoring mqtt_* rows has to reach the live relay, not just the table."""
  1768. @pytest.mark.asyncio
  1769. async def test_reconfigures_from_the_committed_rows(self, db_session):
  1770. db_session.add(Settings(key="mqtt_enabled", value="true"))
  1771. db_session.add(Settings(key="mqtt_broker", value="restored.local"))
  1772. db_session.add(Settings(key="mqtt_port", value="8883"))
  1773. db_session.add(Settings(key="mqtt_use_tls", value="true"))
  1774. # Never restorable (credential blocklist), so it comes from the row that
  1775. # was already there.
  1776. db_session.add(Settings(key="mqtt_password", value="kept"))
  1777. await db_session.commit()
  1778. tally = _CategoryTally()
  1779. relay = MagicMock()
  1780. relay.configure = AsyncMock(return_value=True)
  1781. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1782. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_broker"}, tally)
  1783. relay.configure.assert_awaited_once()
  1784. sent = relay.configure.await_args.args[0]
  1785. assert sent["mqtt_enabled"] is True
  1786. assert sent["mqtt_broker"] == "restored.local"
  1787. assert sent["mqtt_port"] == 8883
  1788. assert sent["mqtt_use_tls"] is True
  1789. assert sent["mqtt_password"] == "kept"
  1790. assert sent["mqtt_topic_prefix"] == "bambuddy"
  1791. assert tally.notes == []
  1792. @pytest.mark.asyncio
  1793. async def test_no_reconnect_when_no_mqtt_key_was_written(self, db_session):
  1794. """configure() tears the connection down, so don't call it for a theme change."""
  1795. tally = _CategoryTally()
  1796. relay = MagicMock()
  1797. relay.configure = AsyncMock()
  1798. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1799. await _service()._reconfigure_mqtt_relay(db_session, {"currency", "theme"}, tally)
  1800. relay.configure.assert_not_awaited()
  1801. @pytest.mark.asyncio
  1802. async def test_broker_failure_is_noted_not_fatal(self, db_session):
  1803. tally = _CategoryTally()
  1804. relay = MagicMock()
  1805. relay.configure = AsyncMock(side_effect=OSError("no route to broker"))
  1806. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1807. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_enabled"}, tally)
  1808. assert any("restart Bambuddy" in note for note in _messages(tally))
  1809. @pytest.mark.asyncio
  1810. async def test_restore_settings_reports_the_keys_it_wrote(self, db_session):
  1811. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  1812. await db_session.commit()
  1813. written: set[str] = set()
  1814. payload = {
  1815. "settings": {
  1816. "mqtt_broker": "new.local",
  1817. "currency": "EUR",
  1818. "mqtt_password": "leaked",
  1819. "auth_enabled": "false",
  1820. }
  1821. }
  1822. await _service()._restore_settings(
  1823. db_session, payload, overwrite=True, tally=_CategoryTally(), keys_written=written
  1824. )
  1825. # Skipped keys are not "written", or a blocked mqtt_password would
  1826. # trigger a pointless reconnect.
  1827. assert written == {"mqtt_broker", "currency"}
  1828. @pytest.mark.asyncio
  1829. async def test_keys_skipped_for_overwrite_off_are_not_reported(self, db_session):
  1830. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  1831. await db_session.commit()
  1832. written: set[str] = set()
  1833. await _service()._restore_settings(
  1834. db_session,
  1835. {"settings": {"mqtt_broker": "new.local"}},
  1836. overwrite=False,
  1837. tally=_CategoryTally(),
  1838. keys_written=written,
  1839. )
  1840. assert written == set()
  1841. @pytest.mark.asyncio
  1842. async def test_a_refused_mqtt_enabled_is_not_reported_as_written(self, db_session):
  1843. """So the relay reconfigures from the *local* mqtt_enabled, not the backup's.
  1844. The companion rule refuses ``mqtt_enabled`` when the backup's password
  1845. cannot come across and there is none stored locally. It must not then
  1846. appear in ``keys_written``, or _reconfigure_mqtt_relay would be asked to
  1847. bring up a broker connection the restore deliberately declined to enable.
  1848. """
  1849. written: set[str] = set()
  1850. await _service()._restore_settings(
  1851. db_session,
  1852. {"settings": {"mqtt_enabled": "true", "mqtt_password": "refused", "mqtt_broker": "new.local"}},
  1853. overwrite=True,
  1854. tally=_CategoryTally(),
  1855. keys_written=written,
  1856. )
  1857. assert written == {"mqtt_broker"}
  1858. class TestApplyOrdering:
  1859. """_apply must not hold SQLite's write transaction across the MQTT phase."""
  1860. def _recording_service(self, calls: list[str]):
  1861. service = _service()
  1862. # Sync side effects on purpose: an AsyncMock returns a coroutine its
  1863. # side_effect hands back rather than awaiting it, so an async recorder
  1864. # would never run.
  1865. service._restore_archives = AsyncMock(side_effect=lambda *a, **k: calls.append("archives"))
  1866. service._restore_spools = AsyncMock(side_effect=lambda *a, **k: calls.append("spools"))
  1867. service._restore_settings = AsyncMock(side_effect=lambda *a, **k: calls.append("settings"))
  1868. service._restore_kprofiles = AsyncMock(side_effect=lambda *a, **k: calls.append("kprofiles"))
  1869. return service
  1870. @pytest.mark.asyncio
  1871. async def test_commits_database_categories_before_talking_to_printers(self):
  1872. """get_kprofiles is 3 x 5 s per printer/nozzle; busy_timeout is 15 s."""
  1873. calls: list[str] = []
  1874. service = self._recording_service(calls)
  1875. db = MagicMock()
  1876. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  1877. await service._apply(
  1878. db,
  1879. {},
  1880. [RestoreCategory.ARCHIVES, RestoreCategory.SPOOLS, RestoreCategory.KPROFILES],
  1881. False,
  1882. )
  1883. assert calls == ["archives", "spools", "commit", "kprofiles"]
  1884. @pytest.mark.asyncio
  1885. async def test_does_not_split_the_transaction_without_kprofiles(self):
  1886. """A database-only restore stays one transaction, committed by run_restore."""
  1887. calls: list[str] = []
  1888. service = self._recording_service(calls)
  1889. db = MagicMock()
  1890. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  1891. await service._apply(db, {}, [RestoreCategory.ARCHIVES, RestoreCategory.SETTINGS], False)
  1892. assert calls == ["archives", "settings"]
  1893. assert db.commit.await_count == 0
  1894. class TestKprofilePhaseFailure:
  1895. """The K-profile phase runs after _apply has committed everything else.
  1896. So an exception there used to reach run_restore's handler, which reports
  1897. ``success: False`` with an empty ``results`` — over archive, spool and
  1898. settings rows that are durable on disk. The honest-reporting theme of this
  1899. feature inverted on exactly the path where it matters, and the post-commit
  1900. MQTT reconfigure (downstream of the raise, inside the same try) was skipped,
  1901. leaving the relay pointed at the pre-restore broker.
  1902. """
  1903. _SETTINGS = {"version": "1.0", "settings": {"mqtt_broker": "restored.local", "currency": "EUR"}}
  1904. def _payload(self, profiles=None):
  1905. return {
  1906. SETTINGS_PATH: dict(self._SETTINGS),
  1907. "kprofiles/00M09A123456789/0.4.json": {
  1908. "profiles": [{"filament_id": "GFA00", "name": "Bambu PLA"}] if profiles is None else profiles
  1909. },
  1910. }
  1911. def _session_patch(self, db_session):
  1912. cm = AsyncMock()
  1913. cm.__aenter__ = AsyncMock(return_value=db_session)
  1914. cm.__aexit__ = AsyncMock(return_value=None)
  1915. return patch("backend.app.services.github_restore.async_session", return_value=cm)
  1916. async def _configured_service(self, db_session, payload):
  1917. from backend.app.models.github_backup import GitHubBackupConfig
  1918. config = GitHubBackupConfig(repository_url="https://github.com/o/r", access_token="tok", provider="github")
  1919. db_session.add(config)
  1920. await db_session.commit()
  1921. service = _service()
  1922. service._resolve_ref = AsyncMock(return_value=("a" * 40, "", None))
  1923. service._read_categories = AsyncMock(return_value=(payload, ""))
  1924. return service, config.id
  1925. @pytest.mark.asyncio
  1926. async def test_the_committed_categories_are_still_reported(self, db_session):
  1927. service = _service()
  1928. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  1929. results = await service._apply(
  1930. db_session,
  1931. self._payload(),
  1932. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  1933. False,
  1934. )
  1935. assert results[RestoreCategory.SETTINGS.value].restored == 2
  1936. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  1937. assert rows == {"mqtt_broker": "restored.local", "currency": "EUR"}, "committed before the phase that failed"
  1938. @pytest.mark.asyncio
  1939. async def test_the_failure_is_counted_and_explained(self, db_session):
  1940. service = _service()
  1941. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  1942. results = await service._apply(
  1943. db_session,
  1944. self._payload(profiles=[{"filament_id": "GFA00"}, {"filament_id": "GFB99"}]),
  1945. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  1946. False,
  1947. )
  1948. tally = results[RestoreCategory.KPROFILES.value]
  1949. assert tally.failed == 2, "every profile the payload carried is unaccounted for"
  1950. assert tally.restored == 0
  1951. assert _codes(tally) == ["kprofilesStepFailed"]
  1952. assert tally.notes[0]["params"]["reason"] == "mqtt exploded"
  1953. @pytest.mark.asyncio
  1954. async def test_the_relay_is_reconfigured_even_though_the_phase_failed(self, db_session):
  1955. """The reconfigure sits downstream of the raise in run_restore's try."""
  1956. service, config_id = await self._configured_service(db_session, self._payload())
  1957. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  1958. relay = MagicMock()
  1959. relay.configure = AsyncMock(return_value=True)
  1960. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1961. result = await service.run_restore(
  1962. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  1963. )
  1964. assert result["success"] is True
  1965. assert result["results"][RestoreCategory.SETTINGS.value]["restored"] == 2
  1966. assert result["results"][RestoreCategory.KPROFILES.value]["failed"] == 1
  1967. relay.configure.assert_awaited_once()
  1968. assert relay.configure.await_args.args[0]["mqtt_broker"] == "restored.local"
  1969. @pytest.mark.asyncio
  1970. async def test_a_failure_before_the_commit_still_reports_nothing_restored(self, db_session):
  1971. """Control: rolling back and saying so is right when nothing landed."""
  1972. service, config_id = await self._configured_service(db_session, self._payload())
  1973. service._restore_settings = AsyncMock(side_effect=RuntimeError("read failed"))
  1974. relay = MagicMock()
  1975. relay.configure = AsyncMock(return_value=True)
  1976. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1977. result = await service.run_restore(
  1978. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  1979. )
  1980. assert result["success"] is False
  1981. assert result["results"] == {}
  1982. assert (await db_session.execute(select(Settings))).scalars().first() is None
  1983. relay.configure.assert_not_awaited()
  1984. @pytest.mark.asyncio
  1985. async def test_a_malformed_profiles_value_is_a_skipped_category_not_a_raise(self, db_session, printer_factory):
  1986. """Belt-and-braces: the pre-loop count ran ahead of the per-call guards.
  1987. ``sum(len(c.get("profiles") or []) ...)`` raises TypeError on a
  1988. hand-edited or truncated backup whose ``profiles`` is not a list — and it
  1989. raises after the database categories are already on disk.
  1990. """
  1991. await printer_factory(serial_number="00M09A123456789")
  1992. client = MagicMock()
  1993. client.state.connected = True
  1994. client.set_kprofiles_batch = MagicMock(return_value="7")
  1995. client.get_kprofiles = AsyncMock(return_value=[])
  1996. tally = _CategoryTally()
  1997. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1998. manager.get_client = MagicMock(return_value=client)
  1999. await _service()._restore_kprofiles(db_session, self._payload(profiles=5), tally)
  2000. client.set_kprofiles_batch.assert_not_called()
  2001. assert (tally.restored, tally.failed) == (0, 0)
  2002. assert "kprofilesStepFailed" not in _codes(tally)
  2003. class TestResolveRef:
  2004. @pytest.mark.asyncio
  2005. async def test_concrete_sha_passes_through_without_an_api_call(self):
  2006. service = _service()
  2007. service.list_commits = AsyncMock()
  2008. config = MagicMock(branch="main")
  2009. resolved, error, commit = await service._resolve_ref(config, "abc1234")
  2010. assert resolved == "abc1234"
  2011. assert error == ""
  2012. # Nothing was fetched, so there is no entry to describe it with.
  2013. assert commit is None
  2014. service.list_commits.assert_not_awaited()
  2015. @pytest.mark.asyncio
  2016. async def test_head_resolves_to_the_tip_sha(self):
  2017. service = _service()
  2018. service.list_commits = AsyncMock(
  2019. return_value={"success": True, "commits": [{"sha": "tipsha1"}, {"sha": "older"}]}
  2020. )
  2021. config = MagicMock(branch="main")
  2022. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2023. assert resolved == "tipsha1"
  2024. assert error == ""
  2025. # Handed back so preview does not list commits a second time just to
  2026. # describe the one it already fetched.
  2027. assert commit == {"sha": "tipsha1"}
  2028. @pytest.mark.asyncio
  2029. async def test_empty_history_is_an_error(self):
  2030. service = _service()
  2031. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2032. config = MagicMock(branch="main")
  2033. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2034. assert resolved is None
  2035. assert "no commits" in error
  2036. assert commit is None
  2037. class TestDescribeCommit:
  2038. """A preview that says `commit: null` gives the user no idea what they picked."""
  2039. def _config(self):
  2040. return MagicMock(branch="main", provider="github", repository_url="https://github.com/o/r", access_token="t")
  2041. def _entry(self, sha: str):
  2042. return {"sha": sha, "message": "Bambuddy backup", "author": "Bambuddy", "date": "2026-07-01T10:00:00Z"}
  2043. @pytest.mark.asyncio
  2044. async def test_an_abbreviated_ref_matches_a_full_sha_in_the_window(self):
  2045. """REF_PATTERN accepts 7 characters; providers return 40.
  2046. The old exact `==` therefore never matched an abbreviated ref, even when
  2047. the commit was right there in the top 20.
  2048. """
  2049. service = _service()
  2050. full = "abc1234" + "0" * 33
  2051. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry(full)]})
  2052. found = await service._describe_commit(self._config(), "abc1234")
  2053. assert found is not None
  2054. assert found["sha"] == full
  2055. @pytest.mark.asyncio
  2056. async def test_a_full_sha_matches_an_abbreviated_entry(self):
  2057. service = _service()
  2058. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("abc1234")]})
  2059. found = await service._describe_commit(self._config(), "abc1234" + "0" * 33)
  2060. assert found is not None
  2061. @pytest.mark.asyncio
  2062. async def test_a_commit_outside_the_window_is_fetched_directly(self):
  2063. service = _service()
  2064. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("f" * 40)]})
  2065. backend = MagicMock()
  2066. backend.get_commit = AsyncMock(return_value={"success": True, "commit": self._entry("old" + "0" * 37)})
  2067. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2068. found = await service._describe_commit(self._config(), "old" + "0" * 37)
  2069. assert found["sha"] == "old" + "0" * 37
  2070. backend.get_commit.assert_awaited_once()
  2071. @pytest.mark.asyncio
  2072. async def test_a_direct_lookup_failure_is_not_fatal(self):
  2073. """It is a subject line: render the preview without it."""
  2074. service = _service()
  2075. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2076. backend = MagicMock()
  2077. backend.get_commit = AsyncMock(return_value={"success": False, "message": "boom", "commit": None})
  2078. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2079. assert await service._describe_commit(self._config(), "a" * 40) is None
  2080. @pytest.mark.asyncio
  2081. async def test_the_window_scan_is_not_run_twice(self):
  2082. """_resolve_ref already listed commits for HEAD; preview reuses that."""
  2083. service = _service()
  2084. tip = self._entry("t" * 40)
  2085. service.list_commits = AsyncMock(return_value={"success": True, "commits": [tip]})
  2086. resolved, _, commit = await service._resolve_ref(self._config(), "HEAD")
  2087. assert resolved == "t" * 40
  2088. assert commit == tip
  2089. assert service.list_commits.await_count == 1