test_scheduler_auto_drying.py 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496
  1. """Tests for the auto-drying feature in the print scheduler.
  2. Covers:
  3. - Conservative drying parameter selection (mixed filaments)
  4. - Drying preset loading (user-configured vs defaults)
  5. - Auto-drying lifecycle: start, humidity stop, minimum drying time
  6. - Auto-drying stop conditions: feature disabled, no scheduled items, per-printer
  7. - Sync drying state after restart
  8. """
  9. import re
  10. import time
  11. from unittest.mock import AsyncMock, MagicMock, patch
  12. import pytest
  13. from backend.app.services.print_scheduler import (
  14. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES,
  15. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  16. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS,
  17. PrintScheduler,
  18. )
  19. class TestConservativeDryingParams:
  20. """Test _get_conservative_drying_params — picks safest temp/duration for mixed filaments."""
  21. @pytest.fixture
  22. def scheduler(self):
  23. return PrintScheduler()
  24. def test_single_filament_pla(self, scheduler):
  25. """Single PLA tray uses PLA preset."""
  26. trays = [{"tray_type": "PLA"}]
  27. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  28. result = scheduler._get_conservative_drying_params(trays, "n3f", presets)
  29. assert result == (45, 12, "PLA")
  30. def test_mixed_filaments_lowest_temp(self, scheduler):
  31. """Mixed PLA + ABS: should use PLA's 45°C (lowest), ABS's 12h (longest for n3f)."""
  32. trays = [{"tray_type": "PLA"}, {"tray_type": "ABS"}]
  33. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  34. result = scheduler._get_conservative_drying_params(trays, "n3f", presets)
  35. temp, hours, _ = result
  36. assert temp == 45 # PLA is lowest
  37. assert hours == 12
  38. def test_mixed_filaments_longest_duration(self, scheduler):
  39. """Mixed ABS (8h) + PVA (18h) on n3s: should use longest duration."""
  40. trays = [{"tray_type": "ABS"}, {"tray_type": "PVA"}]
  41. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  42. result = scheduler._get_conservative_drying_params(trays, "n3s", presets)
  43. temp, hours, _ = result
  44. assert temp == 80 # ABS n3s=80, PVA n3s=85 → lowest=80
  45. assert hours == 18 # ABS n3s_hours=8, PVA n3s_hours=18 → longest=18
  46. def test_empty_trays_returns_none(self, scheduler):
  47. """No loaded trays returns None."""
  48. result = scheduler._get_conservative_drying_params([], "n3f", PrintScheduler.DEFAULT_DRYING_PRESETS)
  49. assert result is None
  50. def test_unknown_filament_skipped(self, scheduler):
  51. """Unknown filament types are ignored."""
  52. trays = [{"tray_type": "EXOTIC_WOOD"}]
  53. result = scheduler._get_conservative_drying_params(trays, "n3f", PrintScheduler.DEFAULT_DRYING_PRESETS)
  54. assert result is None
  55. def test_filament_type_normalization(self, scheduler):
  56. """'PLA Basic' should normalize to 'PLA'."""
  57. trays = [{"tray_type": "PLA Basic"}]
  58. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  59. result = scheduler._get_conservative_drying_params(trays, "n3f", presets)
  60. assert result is not None
  61. assert result[0] == 45 # PLA temp
  62. def test_empty_tray_type_skipped(self, scheduler):
  63. """Trays with empty tray_type are skipped."""
  64. trays = [{"tray_type": ""}, {"tray_type": "PETG"}]
  65. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  66. result = scheduler._get_conservative_drying_params(trays, "n3f", presets)
  67. assert result is not None
  68. assert result[2] == "PETG"
  69. def test_n3s_uses_n3s_keys(self, scheduler):
  70. """AMS-HT (n3s) should use n3s temp and n3s_hours."""
  71. trays = [{"tray_type": "TPU"}]
  72. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  73. result = scheduler._get_conservative_drying_params(trays, "n3s", presets)
  74. assert result == (75, 18, "TPU") # n3s=75, n3s_hours=18
  75. def test_n3f_uses_n3f_keys(self, scheduler):
  76. """AMS 2 Pro (n3f) should use n3f temp and n3f_hours."""
  77. trays = [{"tray_type": "TPU"}]
  78. presets = PrintScheduler.DEFAULT_DRYING_PRESETS
  79. result = scheduler._get_conservative_drying_params(trays, "n3f", presets)
  80. assert result == (65, 12, "TPU") # n3f=65, n3f_hours=12
  81. def test_custom_presets(self, scheduler):
  82. """Custom presets override defaults."""
  83. trays = [{"tray_type": "PLA"}]
  84. custom = {"PLA": {"n3f": 50, "n3s": 50, "n3f_hours": 6, "n3s_hours": 6}}
  85. result = scheduler._get_conservative_drying_params(trays, "n3f", custom)
  86. assert result == (50, 6, "PLA")
  87. class TestCompositesResolveToTheirBaseMaterial:
  88. """#3067: a composite spool was skipped by auto-drying entirely.
  89. The preset key came from ``tray_type.split()[0].upper()``, which splits on
  90. spaces only -- so "PA6-CF" stayed "PA6-CF", found no row in an 8-key table,
  91. and the tray contributed nothing. Every caller reads "no row" as "nothing to
  92. dry here", so the AMS was passed over on every scheduler pass, silently.
  93. It was never only PA. Of the 41 types a printer can report, 33 had no row
  94. under that rule and 20 of them have a base material sitting right there:
  95. every -CF, -GF and -AERO variant of PLA, PETG, ABS, ASA, PC and PA.
  96. The reporter could still dry the same spool by hand, because the drying
  97. popover has resolved composites since #2774 -- these tests pin the two ends
  98. to the same answer.
  99. """
  100. @pytest.fixture
  101. def scheduler(self):
  102. return PrintScheduler()
  103. @pytest.mark.parametrize(
  104. ("tray_type", "expected_key"),
  105. [
  106. # The reported spool, and the rest of the polyamide spellings. Bambu
  107. # labels nylon "PA" and spells its own composites out, so none of
  108. # these match a PA row without the alias map.
  109. ("PA6-CF", "PA"),
  110. ("PA6-GF", "PA"),
  111. ("PA12-CF", "PA"),
  112. ("PAHT-CF", "PA"),
  113. ("PA-CF", "PA"),
  114. ("Nylon", "PA"),
  115. # Polyphthalamide is a distinct polymer, not a nylon grade, so this
  116. # one is a judgement: an aromatic polyamide that takes up moisture
  117. # the same way, dried on the hottest row the table has.
  118. ("PPA-CF", "PA"),
  119. ("PPA-GF", "PA"),
  120. # ...and the variants of everything else, which were equally skipped.
  121. ("PLA-CF", "PLA"),
  122. ("PLA-GF", "PLA"),
  123. ("PLA-AERO", "PLA"),
  124. ("PLA-S", "PLA"),
  125. ("PETG-CF", "PETG"),
  126. ("ABS-GF", "ABS"),
  127. ("ASA-CF", "ASA"),
  128. ("ASA-AERO", "ASA"),
  129. ("PC-CF", "PC"),
  130. # Already worked, and must keep working.
  131. ("PLA", "PLA"),
  132. ("PLA Basic", "PLA"),
  133. ("TPU for AMS", "TPU"),
  134. ],
  135. )
  136. def test_the_tray_reaches_its_base_materials_preset(self, scheduler, tray_type, expected_key):
  137. result = scheduler._get_conservative_drying_params(
  138. [{"tray_type": tray_type}], "n3s", PrintScheduler.DEFAULT_DRYING_PRESETS
  139. )
  140. assert result is not None, f"{tray_type} is still skipped by auto-drying"
  141. assert result[2] == expected_key
  142. assert result[0] == PrintScheduler.DEFAULT_DRYING_PRESETS[expected_key]["n3s"]
  143. def test_the_reported_spool_gets_nylons_temperature(self, scheduler):
  144. """The whole point of resolving it rather than defaulting: PA6-CF wants
  145. PA's 85C on an AMS-HT. Landing on PLA's 45 would run a cycle that dries
  146. nothing, which is worse than the skip it replaces -- it looks like it
  147. worked."""
  148. result = scheduler._get_conservative_drying_params(
  149. [{"tray_type": "PA6-CF"}], "n3s", PrintScheduler.DEFAULT_DRYING_PRESETS
  150. )
  151. assert result == (85, 12, "PA")
  152. @pytest.mark.parametrize("tray_type", ["PPS-CF", "PET-CF", "PEEK", "PP", "PE", "wildly unknown"])
  153. def test_a_material_with_no_base_row_is_still_skipped(self, scheduler, tray_type):
  154. """Nothing here invents a drying profile. A material with no row and no
  155. alias keeps the behaviour it has today rather than being dried at a
  156. number nobody chose.
  157. This is deliberately where the backend parts company with the drying
  158. popover, which falls back to PLA because a dropdown has to show
  159. something. A scheduler does not.
  160. """
  161. result = scheduler._get_conservative_drying_params(
  162. [{"tray_type": tray_type}], "n3s", PrintScheduler.DEFAULT_DRYING_PRESETS
  163. )
  164. assert result is None
  165. def test_a_user_row_for_the_exact_type_wins_over_the_base(self, scheduler):
  166. """Someone who has added PA6-CF to their own table meant it."""
  167. custom = {
  168. **PrintScheduler.DEFAULT_DRYING_PRESETS,
  169. "PA6-CF": {"n3f": 70, "n3s": 90, "n3f_hours": 10, "n3s_hours": 10},
  170. }
  171. result = scheduler._get_conservative_drying_params([{"tray_type": "PA6-CF"}], "n3s", custom)
  172. assert result == (90, 10, "PA6-CF")
  173. def test_a_mixed_load_still_takes_the_coolest_row(self, scheduler):
  174. """Resolving more types must not disturb the conservative choice: a
  175. PA6-CF spool sharing the unit with PLA still gets PLA's 45C, because
  176. 85 would deform the PLA."""
  177. result = scheduler._get_conservative_drying_params(
  178. [{"tray_type": "PA6-CF"}, {"tray_type": "PLA"}], "n3s", PrintScheduler.DEFAULT_DRYING_PRESETS
  179. )
  180. assert result[0] == 45
  181. def test_an_empty_preset_row_still_means_skip(self, scheduler):
  182. """The table is user-editable JSON and nothing validates a row, so one
  183. can be present and empty. Resolving the key is not the same as having a
  184. preset: the temp/hours reads each fall back to 55C/12h, which would dry
  185. a PLA spool at 55 degrees because somebody left a row blank."""
  186. custom = {**PrintScheduler.DEFAULT_DRYING_PRESETS, "PLA": {}}
  187. assert scheduler._get_conservative_drying_params([{"tray_type": "PLA"}], "n3s", custom) is None
  188. # And it does not quietly fall through to some other row either.
  189. assert scheduler._get_conservative_drying_params([{"tray_type": "PLA-CF"}], "n3s", custom) is None
  190. def test_a_zero_valued_row_is_a_row(self, scheduler):
  191. """The resolver tests key presence, not truthiness. It is shared with the
  192. chamber-preheat map, where 0 is the correct target for PLA, PETG, TPU and
  193. PVA -- reading those as "no row" would send every one of them to the
  194. catch-all."""
  195. targets = PrintScheduler._bundled_preheat_targets()
  196. assert targets["PLA"] == 0
  197. assert PrintScheduler._resolve_filament_key("PLA", targets) == "PLA"
  198. assert scheduler._target_for_tray_type("PLA", targets) == 0
  199. assert scheduler._target_for_tray_type("PLA-CF", targets) == 0
  200. def test_a_whitespace_only_tray_type_is_not_a_material(self, scheduler):
  201. """Truthy, and splits to nothing. The old normaliser indexed the split
  202. after testing the string, so this raised IndexError rather than reading
  203. as an empty tray."""
  204. assert PrintScheduler._normalize_filament_type(" ") == ""
  205. result = scheduler._get_conservative_drying_params(
  206. [{"tray_type": " "}], "n3s", PrintScheduler.DEFAULT_DRYING_PRESETS
  207. )
  208. assert result is None
  209. class TestDryingPresets:
  210. """Test _get_drying_presets — loads user presets from DB or falls back to defaults."""
  211. @pytest.fixture
  212. def scheduler(self):
  213. return PrintScheduler()
  214. @pytest.mark.asyncio
  215. async def test_default_presets_when_no_setting(self, scheduler):
  216. """Returns built-in defaults when no DB setting exists."""
  217. db = AsyncMock()
  218. result_mock = MagicMock()
  219. result_mock.scalar_one_or_none.return_value = None
  220. db.execute = AsyncMock(return_value=result_mock)
  221. presets = await scheduler._get_drying_presets(db)
  222. assert presets == PrintScheduler.DEFAULT_DRYING_PRESETS
  223. @pytest.mark.asyncio
  224. async def test_user_presets_from_db(self, scheduler):
  225. """Returns user-configured presets when saved in DB."""
  226. db = AsyncMock()
  227. setting = MagicMock()
  228. setting.value = '{"PLA": {"n3f": 50, "n3s": 50, "n3f_hours": 6, "n3s_hours": 6}}'
  229. result_mock = MagicMock()
  230. result_mock.scalar_one_or_none.return_value = setting
  231. db.execute = AsyncMock(return_value=result_mock)
  232. presets = await scheduler._get_drying_presets(db)
  233. assert presets["PLA"]["n3f"] == 50
  234. @pytest.mark.asyncio
  235. async def test_invalid_json_falls_back(self, scheduler):
  236. """Invalid JSON in DB falls back to defaults."""
  237. db = AsyncMock()
  238. setting = MagicMock()
  239. setting.value = "not valid json{{"
  240. result_mock = MagicMock()
  241. result_mock.scalar_one_or_none.return_value = setting
  242. db.execute = AsyncMock(return_value=result_mock)
  243. presets = await scheduler._get_drying_presets(db)
  244. assert presets == PrintScheduler.DEFAULT_DRYING_PRESETS
  245. @pytest.mark.asyncio
  246. async def test_empty_string_falls_back(self, scheduler):
  247. """Empty string in DB falls back to defaults."""
  248. db = AsyncMock()
  249. setting = MagicMock()
  250. setting.value = ""
  251. result_mock = MagicMock()
  252. result_mock.scalar_one_or_none.return_value = setting
  253. db.execute = AsyncMock(return_value=result_mock)
  254. presets = await scheduler._get_drying_presets(db)
  255. assert presets == PrintScheduler.DEFAULT_DRYING_PRESETS
  256. class TestSyncDryingState:
  257. """Test _sync_drying_state — syncs in-memory state with actual printer status."""
  258. @pytest.fixture
  259. def scheduler(self):
  260. return PrintScheduler()
  261. @patch("backend.app.services.print_scheduler.printer_manager")
  262. def test_removes_stopped_printers(self, mock_pm, scheduler):
  263. """Printers that stopped drying are removed from tracking."""
  264. scheduler._drying_in_progress = {1: time.monotonic()}
  265. state = MagicMock()
  266. state.raw_data = {"ams": [{"dry_time": 0}]}
  267. mock_pm.get_status.return_value = state
  268. scheduler._sync_drying_state()
  269. assert 1 not in scheduler._drying_in_progress
  270. @patch("backend.app.services.print_scheduler.printer_manager")
  271. def test_keeps_active_printers(self, mock_pm, scheduler):
  272. """Printers still drying remain in tracking."""
  273. ts = time.monotonic()
  274. scheduler._drying_in_progress = {1: ts}
  275. state = MagicMock()
  276. state.raw_data = {"ams": [{"dry_time": 120}]}
  277. mock_pm.get_status.return_value = state
  278. scheduler._sync_drying_state()
  279. assert scheduler._drying_in_progress[1] == ts
  280. @patch("backend.app.services.print_scheduler.printer_manager")
  281. def test_removes_disconnected_printers(self, mock_pm, scheduler):
  282. """Disconnected printers are removed from tracking."""
  283. scheduler._drying_in_progress = {1: time.monotonic()}
  284. mock_pm.get_status.return_value = None
  285. scheduler._sync_drying_state()
  286. assert 1 not in scheduler._drying_in_progress
  287. class TestPlateHoldDoesNotGateDrying:
  288. """#2801 — an unacknowledged plate must not stop the AMS heating.
  289. Plate-clear answers "is the bed ready for the next job". It says nothing
  290. about whether filament may be dried, and the gap between a finished print
  291. and the acknowledgment is exactly when drying is most useful: the printer
  292. is free and nobody is waiting on it. Leaving the plate unacknowledged is
  293. also how people hold the queue by hand.
  294. Before this, such a printer landed in the dispatch set, was read as
  295. "currently printing", took the mid-print path -- capped temperature,
  296. (mid-print) in the log -- and bypassed the very gate that was meant to
  297. hold it, while the queue loop tore the cycle down once a tick.
  298. """
  299. @pytest.fixture
  300. def scheduler(self):
  301. return PrintScheduler()
  302. @staticmethod
  303. def _finished_printer_state():
  304. state = MagicMock()
  305. state.state = "FINISH"
  306. state.firmware_version = "01.03.00.00"
  307. state.raw_data = {
  308. "ams": [
  309. {
  310. "id": 0,
  311. "module_type": "n3f",
  312. "dry_time": 0,
  313. "humidity_raw": "75",
  314. "dry_sf_reason": [],
  315. "tray": [{"tray_type": "PLA"}],
  316. }
  317. ]
  318. }
  319. return state
  320. def _db(self):
  321. db = AsyncMock()
  322. db.execute = AsyncMock(
  323. side_effect=TestAmbientDrying._make_db_side_effect(
  324. {
  325. "queue_drying_enabled": TestAmbientDrying._make_setting("false"),
  326. "ambient_drying_enabled": TestAmbientDrying._make_setting("true"),
  327. "print_drying_enabled": TestAmbientDrying._make_setting("true"),
  328. "ams_humidity_fair": TestAmbientDrying._make_setting("60"),
  329. "queue_drying_block": TestAmbientDrying._make_setting("false"),
  330. "drying_presets": None,
  331. }
  332. )
  333. )
  334. return db
  335. @pytest.mark.asyncio
  336. @patch("backend.app.services.print_scheduler.printer_manager")
  337. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  338. async def test_finished_printer_with_dirty_plate_dries_at_full_temperature(self, mock_sd, mock_pm, scheduler):
  339. mock_pm.get_status.return_value = self._finished_printer_state()
  340. mock_pm.is_connected.return_value = True
  341. mock_pm.get_model.return_value = "P2S"
  342. mock_pm.send_drying_command.return_value = True
  343. scheduler._is_printer_idle = MagicMock(return_value=True)
  344. await scheduler._check_auto_drying(self._db(), [], set())
  345. # 45 degC is the uncapped PLA preset: mid-print would have sent 40.
  346. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  347. @pytest.mark.asyncio
  348. @patch("backend.app.services.print_scheduler.printer_manager")
  349. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  350. async def test_idleness_is_judged_without_the_plate_gate(self, mock_sd, mock_pm, scheduler):
  351. mock_pm.get_status.return_value = self._finished_printer_state()
  352. mock_pm.is_connected.return_value = True
  353. mock_pm.get_model.return_value = "P2S"
  354. mock_pm.send_drying_command.return_value = True
  355. scheduler._is_printer_idle = MagicMock(return_value=True)
  356. await scheduler._check_auto_drying(self._db(), [], set())
  357. scheduler._is_printer_idle.assert_called_with(1, require_plate_clear=False)
  358. @pytest.mark.asyncio
  359. @patch("backend.app.services.print_scheduler.printer_manager")
  360. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  361. async def test_a_printer_about_to_print_is_still_left_alone(self, mock_sd, mock_pm, scheduler):
  362. """The narrow set keeps its job: an imminent print must not be dried into."""
  363. mock_pm.get_status.return_value = self._finished_printer_state()
  364. mock_pm.is_connected.return_value = True
  365. mock_pm.get_model.return_value = "P2S"
  366. mock_pm.send_drying_command.return_value = True
  367. scheduler._is_printer_idle = MagicMock(return_value=True)
  368. await scheduler._check_auto_drying(self._db(), [], {1})
  369. assert not mock_pm.send_drying_command.called
  370. class TestStopDrying:
  371. """Test _stop_drying — sends stop commands and clears tracking."""
  372. @pytest.fixture
  373. def scheduler(self):
  374. return PrintScheduler()
  375. @pytest.mark.asyncio
  376. @patch("backend.app.services.print_scheduler.printer_manager")
  377. async def test_stops_all_ams_units(self, mock_pm, scheduler):
  378. """Sends stop command to each auto-armed AMS unit that is drying."""
  379. scheduler._drying_in_progress = {1: time.monotonic()}
  380. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  381. scheduler._auto_dry_units[(1, 128)] = {"ended_at": None}
  382. state = MagicMock()
  383. state.raw_data = {
  384. "ams": [
  385. {"id": 0, "dry_time": 120},
  386. {"id": 1, "dry_time": 0},
  387. {"id": 128, "dry_time": 60},
  388. ]
  389. }
  390. mock_pm.get_status.return_value = state
  391. await scheduler._stop_drying(1)
  392. # Should send stop to AMS 0 and 128, not AMS 1
  393. calls = mock_pm.send_drying_command.call_args_list
  394. assert len(calls) == 2
  395. assert calls[0].args == (1, 0, 0, 0)
  396. assert calls[1].args == (1, 128, 0, 0)
  397. assert 1 not in scheduler._drying_in_progress
  398. @pytest.mark.asyncio
  399. @patch("backend.app.services.print_scheduler.printer_manager")
  400. async def test_leaves_cycles_bambuddy_did_not_start(self, mock_pm, scheduler):
  401. """A hand-started dry on another unit survives (#2801).
  402. One auto-dried unit used to be enough to stop every AMS on the
  403. printer reporting dry_time > 0, which took the user's own cycle with
  404. it. The entry gate only ever knew about cycles Bambuddy began; the
  405. action now matches.
  406. """
  407. scheduler._drying_in_progress = {1: time.monotonic()}
  408. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  409. state = MagicMock()
  410. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}, {"id": 1, "dry_time": 600}]}
  411. mock_pm.get_status.return_value = state
  412. await scheduler._stop_drying(1)
  413. calls = mock_pm.send_drying_command.call_args_list
  414. assert [c.args[1] for c in calls] == [0]
  415. @pytest.mark.asyncio
  416. @patch("backend.app.services.print_scheduler.printer_manager")
  417. async def test_stops_nothing_it_cannot_prove_it_started(self, mock_pm, scheduler):
  418. """After a restart Bambuddy cannot tell its own cycle from a manual one.
  419. _sync_drying_state prunes but never adopts, for exactly this reason, so
  420. a cycle armed before the restart is left running rather than risking a
  421. stop on somebody's manual dry. Tracking is still cleared.
  422. """
  423. scheduler._drying_in_progress = {1: time.monotonic()}
  424. state = MagicMock()
  425. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}]}
  426. mock_pm.get_status.return_value = state
  427. await scheduler._stop_drying(1)
  428. assert not mock_pm.send_drying_command.called
  429. assert 1 not in scheduler._drying_in_progress
  430. @pytest.mark.asyncio
  431. @patch("backend.app.services.print_scheduler.printer_manager")
  432. async def test_clears_tracking_when_no_state(self, mock_pm, scheduler):
  433. """Clears tracking when printer has no state (disconnected)."""
  434. scheduler._drying_in_progress = {1: time.monotonic()}
  435. mock_pm.get_status.return_value = None
  436. await scheduler._stop_drying(1)
  437. assert 1 not in scheduler._drying_in_progress
  438. class TestMinimumDryingTime:
  439. """Regression #1892: a running drying cycle must never be stopped by a humidity re-check.
  440. Relative humidity reads low in heated air (the AMS sensor sees ~15-20% within
  441. minutes of the dryer starting even while the filament is still saturated), so a
  442. humidity-based auto-stop would truncate every cycle — manual or Bambuddy-started —
  443. to the old minimum-time floor. Drying is now left to run to its configured
  444. duration; the firmware stops it when the duration elapses.
  445. """
  446. @pytest.fixture
  447. def scheduler(self):
  448. return PrintScheduler()
  449. @pytest.mark.asyncio
  450. @patch("backend.app.services.print_scheduler.printer_manager")
  451. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  452. async def test_no_stop_before_minimum_time(self, mock_sd, mock_pm, scheduler):
  453. """Drying should NOT stop when humidity drops below threshold shortly after start."""
  454. # Simulate: drying started 5 minutes ago
  455. scheduler._drying_in_progress = {1: time.monotonic() - 300}
  456. state = MagicMock()
  457. state.raw_data = {
  458. "ams": [
  459. {
  460. "id": 0,
  461. "module_type": "n3f",
  462. "dry_time": 600,
  463. "humidity_raw": "18",
  464. "dry_sf_reason": [],
  465. "tray": [{"tray_type": "PLA"}],
  466. }
  467. ]
  468. }
  469. state.firmware_version = "01.09.00.00"
  470. mock_pm.get_status.return_value = state
  471. mock_pm.is_connected.return_value = True
  472. mock_pm.get_model.return_value = "X1C"
  473. # Mock _is_printer_idle and DB
  474. scheduler._is_printer_idle = MagicMock(return_value=True)
  475. db = AsyncMock()
  476. # Mock settings: enabled, threshold=21
  477. settings_returns = {
  478. "queue_drying_enabled": self._make_setting("true"),
  479. "ams_humidity_fair": self._make_setting("21"),
  480. "queue_drying_block": self._make_setting("false"),
  481. "drying_presets": None,
  482. }
  483. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns, printer_id=1))
  484. # Queue item with schedule
  485. item = MagicMock()
  486. item.printer_id = 1
  487. item.scheduled_time = MagicMock() # Has a schedule
  488. item.manual_start = False
  489. await scheduler._check_auto_drying(db, [item], set())
  490. # Should NOT have sent stop command via humidity check — minimum time not elapsed
  491. # The only calls should NOT include the humidity-based stop
  492. for call in mock_pm.send_drying_command.call_args_list:
  493. # If any stop was called, it should NOT be from the humidity path
  494. # (humidity path uses keyword args: temp=0, duration=0, mode=0)
  495. assert call != ((1, 0), {"temp": 0, "duration": 0, "mode": 0}), (
  496. "Humidity-based stop should not fire before minimum drying time"
  497. )
  498. @pytest.mark.asyncio
  499. @patch("backend.app.services.print_scheduler.printer_manager")
  500. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  501. async def test_no_stop_after_long_elapsed_time(self, mock_sd, mock_pm, scheduler):
  502. """#1892: drying must NOT stop even long after start with low humidity — let it run."""
  503. # Simulate: drying started 35 minutes ago, humidity reads low (heated air)
  504. scheduler._drying_in_progress = {1: time.monotonic() - 2100}
  505. state = MagicMock()
  506. state.raw_data = {
  507. "ams": [
  508. {
  509. "id": 0,
  510. "module_type": "n3f",
  511. "dry_time": 600,
  512. "humidity_raw": "18",
  513. "dry_sf_reason": [],
  514. "tray": [{"tray_type": "PLA"}],
  515. }
  516. ]
  517. }
  518. state.firmware_version = "01.09.00.00"
  519. mock_pm.get_status.return_value = state
  520. mock_pm.is_connected.return_value = True
  521. mock_pm.get_model.return_value = "X1C"
  522. scheduler._is_printer_idle = MagicMock(return_value=True)
  523. db = AsyncMock()
  524. settings_returns = {
  525. "queue_drying_enabled": self._make_setting("true"),
  526. "ams_humidity_fair": self._make_setting("21"),
  527. "queue_drying_block": self._make_setting("false"),
  528. "drying_presets": None,
  529. }
  530. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns, printer_id=1))
  531. item = MagicMock()
  532. item.printer_id = 1
  533. item.scheduled_time = MagicMock()
  534. item.manual_start = False
  535. await scheduler._check_auto_drying(db, [item], set())
  536. # Must NOT send a humidity-based stop — drying is left to run to its duration
  537. for call in mock_pm.send_drying_command.call_args_list:
  538. assert call != ((1, 0), {"temp": 0, "duration": 0, "mode": 0}), (
  539. "Humidity re-check must never stop a running drying cycle (#1892)"
  540. )
  541. @staticmethod
  542. def _make_setting(value):
  543. s = MagicMock()
  544. s.value = value
  545. return s
  546. @staticmethod
  547. def _make_db_side_effect(settings_map, printer_id=1):
  548. """Create a side_effect for db.execute that returns settings and printers."""
  549. async def side_effect(stmt):
  550. result = MagicMock()
  551. stmt_str = str(stmt)
  552. # Extract bind parameter values (SQLAlchemy uses :key_1 placeholders)
  553. try:
  554. compiled = stmt.compile(compile_kwargs={"literal_binds": False})
  555. param_values = list(compiled.params.values())
  556. except Exception:
  557. param_values = []
  558. # Match settings queries by checking bind parameter values
  559. matched = False
  560. for key, val in settings_map.items():
  561. if key in param_values:
  562. result.scalar_one_or_none.return_value = val
  563. matched = True
  564. break
  565. if not matched:
  566. if "printer" in stmt_str.lower() or "is_active" in stmt_str:
  567. printer = MagicMock()
  568. printer.id = printer_id
  569. printer.is_active = True
  570. scalars_mock = MagicMock()
  571. scalars_mock.__iter__ = MagicMock(return_value=iter([printer]))
  572. result.scalars.return_value = scalars_mock
  573. else:
  574. result.scalar_one_or_none.return_value = None
  575. return result
  576. return side_effect
  577. class TestAutoStopOnFeatureDisabled:
  578. """Regression: disabling auto-drying in settings should stop active drying sessions."""
  579. @pytest.fixture
  580. def scheduler(self):
  581. return PrintScheduler()
  582. @pytest.mark.asyncio
  583. @patch("backend.app.services.print_scheduler.printer_manager")
  584. async def test_stops_drying_when_disabled(self, mock_pm, scheduler):
  585. """Disabling auto-drying should send stop commands to all drying printers."""
  586. scheduler._drying_in_progress = {1: time.monotonic(), 2: time.monotonic()}
  587. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  588. scheduler._auto_dry_units[(2, 0)] = {"ended_at": None}
  589. # Printer 1: drying, Printer 2: drying
  590. def get_status(pid):
  591. state = MagicMock()
  592. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}]}
  593. return state
  594. mock_pm.get_status.side_effect = get_status
  595. db = AsyncMock()
  596. # queue_drying_enabled = false
  597. setting = MagicMock()
  598. setting.value = "false"
  599. result_mock = MagicMock()
  600. result_mock.scalar_one_or_none.return_value = setting
  601. db.execute = AsyncMock(return_value=result_mock)
  602. await scheduler._check_auto_drying(db, [], set())
  603. # Should have sent stop commands
  604. assert mock_pm.send_drying_command.call_count == 2
  605. assert not scheduler._drying_in_progress
  606. class TestAutoStopOnNoScheduledItems:
  607. """Regression: removing scheduled items should stop auto-drying."""
  608. @pytest.fixture
  609. def scheduler(self):
  610. return PrintScheduler()
  611. @staticmethod
  612. def _make_setting(value):
  613. s = MagicMock()
  614. s.value = value
  615. return s
  616. @staticmethod
  617. def _make_db_side_effect(settings_map):
  618. """Create a side_effect for db.execute that returns settings by key."""
  619. async def side_effect(stmt):
  620. result = MagicMock()
  621. try:
  622. compiled = stmt.compile(compile_kwargs={"literal_binds": False})
  623. param_values = list(compiled.params.values())
  624. except Exception:
  625. param_values = []
  626. for key, val in settings_map.items():
  627. if key in param_values:
  628. result.scalar_one_or_none.return_value = val
  629. return result
  630. result.scalar_one_or_none.return_value = None
  631. return result
  632. return side_effect
  633. @pytest.mark.asyncio
  634. @patch("backend.app.services.print_scheduler.printer_manager")
  635. async def test_stops_when_no_scheduled_items(self, mock_pm, scheduler):
  636. """Auto-drying stops when queue has no scheduled items (queue mode only)."""
  637. scheduler._drying_in_progress = {1: time.monotonic()}
  638. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  639. state = MagicMock()
  640. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}]}
  641. mock_pm.get_status.return_value = state
  642. db = AsyncMock()
  643. settings_returns = {
  644. "queue_drying_enabled": self._make_setting("true"),
  645. "ambient_drying_enabled": self._make_setting("false"),
  646. }
  647. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  648. # Manual-start items only (no scheduled_time)
  649. item = MagicMock()
  650. item.printer_id = 1
  651. item.scheduled_time = None
  652. item.manual_start = True
  653. await scheduler._check_auto_drying(db, [item], set())
  654. # Should have stopped drying
  655. assert mock_pm.send_drying_command.called
  656. assert not scheduler._drying_in_progress
  657. @pytest.mark.asyncio
  658. @patch("backend.app.services.print_scheduler.printer_manager")
  659. async def test_stops_when_empty_queue(self, mock_pm, scheduler):
  660. """Auto-drying stops when queue is completely empty (queue mode only)."""
  661. scheduler._drying_in_progress = {1: time.monotonic()}
  662. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  663. state = MagicMock()
  664. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}]}
  665. mock_pm.get_status.return_value = state
  666. db = AsyncMock()
  667. settings_returns = {
  668. "queue_drying_enabled": self._make_setting("true"),
  669. "ambient_drying_enabled": self._make_setting("false"),
  670. }
  671. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  672. await scheduler._check_auto_drying(db, [], set())
  673. assert mock_pm.send_drying_command.called
  674. assert not scheduler._drying_in_progress
  675. class TestDryingTrackingTimestamps:
  676. """Test that _drying_in_progress uses timestamps, not booleans."""
  677. def test_initial_state_empty(self):
  678. """Fresh scheduler has no drying tracked."""
  679. scheduler = PrintScheduler()
  680. assert scheduler._drying_in_progress == {}
  681. def test_timestamp_is_monotonic(self):
  682. """Tracked values should be monotonic timestamps."""
  683. scheduler = PrintScheduler()
  684. before = time.monotonic()
  685. scheduler._drying_in_progress[1] = time.monotonic()
  686. after = time.monotonic()
  687. assert before <= scheduler._drying_in_progress[1] <= after
  688. def test_timestamp_is_truthy(self):
  689. """Timestamps are truthy for .get() checks (backward compat with bool pattern)."""
  690. scheduler = PrintScheduler()
  691. scheduler._drying_in_progress[1] = time.monotonic()
  692. assert scheduler._drying_in_progress.get(1)
  693. assert not scheduler._drying_in_progress.get(999)
  694. class _DryingTestBase:
  695. """Shared helpers for auto-drying integration tests."""
  696. @staticmethod
  697. def _make_setting(value):
  698. s = MagicMock()
  699. s.value = value
  700. return s
  701. @staticmethod
  702. def _make_db_side_effect(settings_map, printer_ids=None):
  703. """Create a side_effect for db.execute that returns settings by key and printers."""
  704. if printer_ids is None:
  705. printer_ids = [1]
  706. async def side_effect(stmt):
  707. result = MagicMock()
  708. stmt_str = str(stmt)
  709. try:
  710. compiled = stmt.compile(compile_kwargs={"literal_binds": False})
  711. param_values = list(compiled.params.values())
  712. except Exception:
  713. param_values = []
  714. for key, val in settings_map.items():
  715. if key in param_values:
  716. result.scalar_one_or_none.return_value = val
  717. return result
  718. if "printer" in stmt_str.lower() or "is_active" in stmt_str:
  719. printers = []
  720. for pid in printer_ids:
  721. p = MagicMock()
  722. p.id = pid
  723. p.is_active = True
  724. printers.append(p)
  725. scalars_mock = MagicMock()
  726. scalars_mock.__iter__ = MagicMock(return_value=iter(printers))
  727. result.scalars.return_value = scalars_mock
  728. else:
  729. result.scalar_one_or_none.return_value = None
  730. return result
  731. return side_effect
  732. class TestAmbientDrying(_DryingTestBase):
  733. """Tests for ambient drying mode — drying based on humidity regardless of queue state."""
  734. @pytest.fixture
  735. def scheduler(self):
  736. return PrintScheduler()
  737. @pytest.mark.asyncio
  738. @patch("backend.app.services.print_scheduler.printer_manager")
  739. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  740. async def test_ambient_dries_idle_printer_without_queue(self, mock_sd, mock_pm, scheduler):
  741. """Ambient mode starts drying on idle printers even with no queue items."""
  742. state = MagicMock()
  743. state.raw_data = {
  744. "ams": [
  745. {
  746. "id": 0,
  747. "module_type": "n3f",
  748. "dry_time": 0,
  749. "humidity_raw": "75",
  750. "dry_sf_reason": [],
  751. "tray": [{"tray_type": "PLA"}],
  752. }
  753. ]
  754. }
  755. state.firmware_version = "01.09.00.00"
  756. mock_pm.get_status.return_value = state
  757. mock_pm.is_connected.return_value = True
  758. mock_pm.get_model.return_value = "X1C"
  759. mock_pm.send_drying_command.return_value = True
  760. scheduler._is_printer_idle = MagicMock(return_value=True)
  761. db = AsyncMock()
  762. settings_returns = {
  763. "queue_drying_enabled": self._make_setting("false"),
  764. "ambient_drying_enabled": self._make_setting("true"),
  765. "ams_humidity_fair": self._make_setting("60"),
  766. "queue_drying_block": self._make_setting("false"),
  767. "drying_presets": None,
  768. }
  769. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  770. # Empty queue — ambient mode should still dry
  771. await scheduler._check_auto_drying(db, [], set())
  772. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  773. assert 1 in scheduler._drying_in_progress
  774. @pytest.mark.asyncio
  775. @patch("backend.app.services.print_scheduler.printer_manager")
  776. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  777. async def test_ambient_does_not_dry_below_threshold(self, mock_sd, mock_pm, scheduler):
  778. """Ambient mode does NOT dry when humidity is below threshold."""
  779. state = MagicMock()
  780. state.raw_data = {
  781. "ams": [
  782. {
  783. "id": 0,
  784. "module_type": "n3f",
  785. "dry_time": 0,
  786. "humidity_raw": "40",
  787. "dry_sf_reason": [],
  788. "tray": [{"tray_type": "PLA"}],
  789. }
  790. ]
  791. }
  792. state.firmware_version = "01.09.00.00"
  793. mock_pm.get_status.return_value = state
  794. mock_pm.is_connected.return_value = True
  795. mock_pm.get_model.return_value = "X1C"
  796. scheduler._is_printer_idle = MagicMock(return_value=True)
  797. db = AsyncMock()
  798. settings_returns = {
  799. "queue_drying_enabled": self._make_setting("false"),
  800. "ambient_drying_enabled": self._make_setting("true"),
  801. "ams_humidity_fair": self._make_setting("60"),
  802. "queue_drying_block": self._make_setting("false"),
  803. "drying_presets": None,
  804. }
  805. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  806. await scheduler._check_auto_drying(db, [], set())
  807. mock_pm.send_drying_command.assert_not_called()
  808. @pytest.mark.asyncio
  809. @patch("backend.app.services.print_scheduler.printer_manager")
  810. async def test_ambient_off_stops_drying_without_queue(self, mock_pm, scheduler):
  811. """Disabling ambient drying stops drying on printers without queue items."""
  812. scheduler._drying_in_progress = {1: time.monotonic()}
  813. scheduler._auto_dry_units[(1, 0)] = {"ended_at": None}
  814. state = MagicMock()
  815. state.raw_data = {"ams": [{"id": 0, "dry_time": 120}]}
  816. mock_pm.get_status.return_value = state
  817. db = AsyncMock()
  818. settings_returns = {
  819. "queue_drying_enabled": self._make_setting("false"),
  820. "ambient_drying_enabled": self._make_setting("false"),
  821. }
  822. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  823. await scheduler._check_auto_drying(db, [], set())
  824. assert mock_pm.send_drying_command.called
  825. assert not scheduler._drying_in_progress
  826. @pytest.mark.asyncio
  827. @patch("backend.app.services.print_scheduler.printer_manager")
  828. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  829. async def test_ambient_continues_when_queue_empty(self, mock_sd, mock_pm, scheduler):
  830. """Ambient drying continues even when queue has no scheduled items (unlike queue mode)."""
  831. scheduler._drying_in_progress = {1: time.monotonic() - 100}
  832. state = MagicMock()
  833. state.raw_data = {
  834. "ams": [
  835. {
  836. "id": 0,
  837. "module_type": "n3f",
  838. "dry_time": 600,
  839. "humidity_raw": "75",
  840. "dry_sf_reason": [],
  841. "tray": [{"tray_type": "PLA"}],
  842. }
  843. ]
  844. }
  845. state.firmware_version = "01.09.00.00"
  846. mock_pm.get_status.return_value = state
  847. mock_pm.is_connected.return_value = True
  848. mock_pm.get_model.return_value = "X1C"
  849. scheduler._is_printer_idle = MagicMock(return_value=True)
  850. db = AsyncMock()
  851. settings_returns = {
  852. "queue_drying_enabled": self._make_setting("false"),
  853. "ambient_drying_enabled": self._make_setting("true"),
  854. "ams_humidity_fair": self._make_setting("60"),
  855. "queue_drying_block": self._make_setting("false"),
  856. "drying_presets": None,
  857. }
  858. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  859. await scheduler._check_auto_drying(db, [], set())
  860. # Should NOT have sent stop — humidity still high, drying continues
  861. for call in mock_pm.send_drying_command.call_args_list:
  862. assert call.kwargs.get("mode") != 0, "Should not stop drying in ambient mode with high humidity"
  863. assert 1 in scheduler._drying_in_progress
  864. @pytest.mark.asyncio
  865. @patch("backend.app.services.print_scheduler.printer_manager")
  866. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  867. async def test_queue_only_does_not_dry_without_scheduled_items(self, mock_sd, mock_pm, scheduler):
  868. """Queue mode alone does NOT dry printers that have no scheduled queue items."""
  869. state = MagicMock()
  870. state.raw_data = {
  871. "ams": [
  872. {
  873. "id": 0,
  874. "module_type": "n3f",
  875. "dry_time": 0,
  876. "humidity_raw": "75",
  877. "dry_sf_reason": [],
  878. "tray": [{"tray_type": "PLA"}],
  879. }
  880. ]
  881. }
  882. state.firmware_version = "01.09.00.00"
  883. mock_pm.get_status.return_value = state
  884. mock_pm.is_connected.return_value = True
  885. mock_pm.get_model.return_value = "X1C"
  886. scheduler._is_printer_idle = MagicMock(return_value=True)
  887. db = AsyncMock()
  888. settings_returns = {
  889. "queue_drying_enabled": self._make_setting("true"),
  890. "ambient_drying_enabled": self._make_setting("false"),
  891. "ams_humidity_fair": self._make_setting("60"),
  892. "queue_drying_block": self._make_setting("false"),
  893. "drying_presets": None,
  894. }
  895. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  896. # No queue items at all
  897. await scheduler._check_auto_drying(db, [], set())
  898. mock_pm.send_drying_command.assert_not_called()
  899. class TestBlockForDryingBugFix(_DryingTestBase):
  900. """Regression: block mode gates NEW drying starts but must leave running dries alone (#1892)."""
  901. @pytest.fixture
  902. def scheduler(self):
  903. return PrintScheduler()
  904. @pytest.mark.asyncio
  905. @patch("backend.app.services.print_scheduler.printer_manager")
  906. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  907. async def test_block_mode_leaves_active_drying_running(self, mock_sd, mock_pm, scheduler):
  908. """#1892: a printer already drying in block mode must not be stopped by a humidity re-check."""
  909. # Drying started 35 minutes ago
  910. scheduler._drying_in_progress = {1: time.monotonic() - 2100}
  911. state = MagicMock()
  912. state.raw_data = {
  913. "ams": [
  914. {
  915. "id": 0,
  916. "module_type": "n3f",
  917. "dry_time": 600,
  918. "humidity_raw": "30", # Below threshold
  919. "dry_sf_reason": [],
  920. "tray": [{"tray_type": "PLA"}],
  921. }
  922. ]
  923. }
  924. state.firmware_version = "01.09.00.00"
  925. mock_pm.get_status.return_value = state
  926. mock_pm.is_connected.return_value = True
  927. mock_pm.get_model.return_value = "X1C"
  928. scheduler._is_printer_idle = MagicMock(return_value=True)
  929. db = AsyncMock()
  930. settings_returns = {
  931. "queue_drying_enabled": self._make_setting("true"),
  932. "ambient_drying_enabled": self._make_setting("false"),
  933. "ams_humidity_fair": self._make_setting("60"),
  934. "queue_drying_block": self._make_setting("true"),
  935. "drying_presets": None,
  936. }
  937. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  938. # Queue item exists for this printer (triggers block mode gate)
  939. item = MagicMock()
  940. item.printer_id = 1
  941. item.scheduled_time = MagicMock()
  942. item.manual_start = False
  943. await scheduler._check_auto_drying(db, [item], set())
  944. # Must NOT stop the running dry — block mode gates new starts, not active cycles
  945. for call in mock_pm.send_drying_command.call_args_list:
  946. assert call != ((1, 0), {"temp": 0, "duration": 0, "mode": 0}), (
  947. "Block mode must not stop an already-running drying cycle (#1892)"
  948. )
  949. @pytest.mark.asyncio
  950. @patch("backend.app.services.print_scheduler.printer_manager")
  951. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  952. async def test_block_mode_prevents_new_drying_start(self, mock_sd, mock_pm, scheduler):
  953. """Block mode should still prevent starting NEW drying on printers with pending items."""
  954. state = MagicMock()
  955. state.raw_data = {
  956. "ams": [
  957. {
  958. "id": 0,
  959. "module_type": "n3f",
  960. "dry_time": 0,
  961. "humidity_raw": "75",
  962. "dry_sf_reason": [],
  963. "tray": [{"tray_type": "PLA"}],
  964. }
  965. ]
  966. }
  967. state.firmware_version = "01.09.00.00"
  968. mock_pm.get_status.return_value = state
  969. mock_pm.is_connected.return_value = True
  970. mock_pm.get_model.return_value = "X1C"
  971. scheduler._is_printer_idle = MagicMock(return_value=True)
  972. db = AsyncMock()
  973. settings_returns = {
  974. "queue_drying_enabled": self._make_setting("true"),
  975. "ambient_drying_enabled": self._make_setting("false"),
  976. "ams_humidity_fair": self._make_setting("60"),
  977. "queue_drying_block": self._make_setting("true"),
  978. "drying_presets": None,
  979. }
  980. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  981. item = MagicMock()
  982. item.printer_id = 1
  983. item.scheduled_time = MagicMock()
  984. item.manual_start = False
  985. await scheduler._check_auto_drying(db, [item], set())
  986. # Should NOT start drying — block mode with pending items
  987. mock_pm.send_drying_command.assert_not_called()
  988. class TestResolveHumidityThreshold:
  989. """Per-filament humidity threshold resolver (#1605).
  990. Resolves the trigger threshold for an AMS unit from the loaded tray types.
  991. Mixed loads use the lowest (most restrictive) value. Empty / unloaded trays
  992. contribute no constraint; falls back to the global ``ams_humidity_fair``
  993. when no per-type overrides are configured.
  994. """
  995. def test_no_overrides_falls_back_to_global(self):
  996. """Empty overrides map → caller's global fallback is used verbatim."""
  997. result = PrintScheduler.resolve_humidity_threshold([{"tray_type": "PLA"}], {}, 60)
  998. assert result == 60
  999. def test_single_known_type_uses_override(self):
  1000. """Single PLA tray with override = 50 returns 50."""
  1001. result = PrintScheduler.resolve_humidity_threshold(
  1002. [{"tray_type": "PLA Basic"}],
  1003. {"default": 60, "PLA": 50},
  1004. 60,
  1005. )
  1006. assert result == 50
  1007. def test_a_composite_takes_its_base_materials_threshold(self):
  1008. """Same lookup, same gap (#3067): a PA6-CF spool read as an unknown type
  1009. and took the default, so the override the user set for nylon -- the
  1010. material most worth a low threshold -- never applied to the spool they
  1011. set it for."""
  1012. result = PrintScheduler.resolve_humidity_threshold(
  1013. [{"tray_type": "PA6-CF"}],
  1014. {"default": 60, "PA": 20},
  1015. 60,
  1016. )
  1017. assert result == 20
  1018. def test_a_composite_with_its_own_threshold_row_keeps_it(self):
  1019. result = PrintScheduler.resolve_humidity_threshold(
  1020. [{"tray_type": "PETG-CF"}],
  1021. {"default": 60, "PETG": 55, "PETG-CF": 40},
  1022. 60,
  1023. )
  1024. assert result == 40
  1025. def test_mixed_load_picks_lowest(self):
  1026. """Mixed PLA (60) + Nylon (20) → most restrictive = 20."""
  1027. result = PrintScheduler.resolve_humidity_threshold(
  1028. [{"tray_type": "PLA Basic"}, {"tray_type": "PA Glass"}],
  1029. {"default": 60, "PLA": 60, "PA": 20},
  1030. 60,
  1031. )
  1032. assert result == 20
  1033. def test_unknown_type_uses_default_key(self):
  1034. """Tray type not in the map falls back to the 'default' key, not the
  1035. caller fallback. Lets the user tune unknown-filament behavior."""
  1036. result = PrintScheduler.resolve_humidity_threshold(
  1037. [{"tray_type": "EXOTIC_WOOD"}],
  1038. {"default": 40, "PLA": 60},
  1039. 999,
  1040. )
  1041. assert result == 40
  1042. def test_empty_tray_slots_skipped(self):
  1043. """Empty tray_type strings (unloaded slots) contribute no constraint."""
  1044. result = PrintScheduler.resolve_humidity_threshold(
  1045. [{"tray_type": ""}, {"tray_type": "PLA"}],
  1046. {"default": 30, "PLA": 50},
  1047. 60,
  1048. )
  1049. assert result == 50
  1050. def test_all_empty_trays_uses_default_key(self):
  1051. """No loaded trays at all → falls back to default key (or fallback if
  1052. no overrides). Matches the empty-AMS behavior of the existing alarm
  1053. site so an empty AMS still alarms at the user's default rate."""
  1054. result = PrintScheduler.resolve_humidity_threshold(
  1055. [{"tray_type": ""}, {}],
  1056. {"default": 30, "PLA": 50},
  1057. 60,
  1058. )
  1059. assert result == 30
  1060. def test_filament_name_normalized(self):
  1061. """Tray types like 'PLA Basic', 'pla basic' all normalize to 'PLA'."""
  1062. result = PrintScheduler.resolve_humidity_threshold(
  1063. [{"tray_type": "pla basic"}],
  1064. {"default": 60, "PLA": 25},
  1065. 60,
  1066. )
  1067. assert result == 25
  1068. def test_no_tray_type_field_skipped(self):
  1069. """Missing tray_type field is treated as empty (unloaded)."""
  1070. result = PrintScheduler.resolve_humidity_threshold(
  1071. [{}, {"tray_type": "ASA"}],
  1072. {"default": 60, "ASA": 30},
  1073. 60,
  1074. )
  1075. assert result == 30
  1076. class TestGetHumidityThresholds:
  1077. """The DB-loading helper for ``ams_humidity_thresholds`` (#1605)."""
  1078. @pytest.fixture
  1079. def scheduler(self):
  1080. return PrintScheduler()
  1081. @pytest.mark.asyncio
  1082. async def test_missing_setting_returns_empty(self, scheduler):
  1083. db = AsyncMock()
  1084. db.execute = AsyncMock(return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=None)))
  1085. result = await scheduler._get_humidity_thresholds(db)
  1086. assert result == {}
  1087. @pytest.mark.asyncio
  1088. async def test_empty_value_returns_empty(self, scheduler):
  1089. db = AsyncMock()
  1090. setting = MagicMock(value="")
  1091. db.execute = AsyncMock(return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=setting)))
  1092. result = await scheduler._get_humidity_thresholds(db)
  1093. assert result == {}
  1094. @pytest.mark.asyncio
  1095. async def test_invalid_json_returns_empty(self, scheduler):
  1096. db = AsyncMock()
  1097. setting = MagicMock(value="not json{")
  1098. db.execute = AsyncMock(return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=setting)))
  1099. result = await scheduler._get_humidity_thresholds(db)
  1100. assert result == {}
  1101. @pytest.mark.asyncio
  1102. async def test_valid_json_normalizes_keys(self, scheduler):
  1103. """Filament-type keys uppercase; 'default' preserved."""
  1104. db = AsyncMock()
  1105. setting = MagicMock(value='{"default": 60, "pla": 50, "ASA": 30, "garbage": "x"}')
  1106. db.execute = AsyncMock(return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=setting)))
  1107. result = await scheduler._get_humidity_thresholds(db)
  1108. assert result == {"default": 60, "PLA": 50, "ASA": 30}
  1109. class TestMidPrintDrying(_DryingTestBase):
  1110. """Tests for the print_drying_enabled path — drying that runs CONCURRENTLY
  1111. with an active print on capable hardware (H2D / H2C / H2S / P2S / X2D / X1C /
  1112. A2L / H2D Pro on recent firmware). Distinct from idle drying.
  1113. Verifies:
  1114. - With the toggle ON and capable hardware, a printer in the busy set is
  1115. still evaluated and drying fires at the capped temperature.
  1116. - The temperature cap is max(40, preset_temp - 5) — protects spools.
  1117. - With the toggle OFF, the existing busy-printer skip still applies.
  1118. - With the toggle ON but unsupported firmware, the busy-printer skip
  1119. still applies (gated by supports_drying_while_printing).
  1120. """
  1121. @pytest.fixture
  1122. def scheduler(self):
  1123. return PrintScheduler()
  1124. @staticmethod
  1125. def _ams_unit(humidity: str = "75"):
  1126. return {
  1127. "id": 0,
  1128. "module_type": "n3f",
  1129. "dry_time": 0,
  1130. "humidity_raw": humidity,
  1131. "dry_sf_reason": [],
  1132. "tray": [{"tray_type": "PLA"}],
  1133. }
  1134. def _state(self, firmware: str):
  1135. state = MagicMock()
  1136. state.raw_data = {"ams": [self._ams_unit()]}
  1137. state.firmware_version = firmware
  1138. return state
  1139. @pytest.mark.asyncio
  1140. @patch("backend.app.services.print_scheduler.printer_manager")
  1141. async def test_running_printer_dries_when_enabled_and_capable(self, mock_pm, scheduler):
  1142. """Toggle ON + capable hardware: running printer dries at capped temp."""
  1143. state = self._state("01.03.00.00")
  1144. state.state = "RUNNING"
  1145. mock_pm.get_status.return_value = state
  1146. mock_pm.is_connected.return_value = True
  1147. mock_pm.get_model.return_value = "H2D"
  1148. mock_pm.send_drying_command.return_value = True
  1149. scheduler._is_printer_idle = MagicMock(return_value=False)
  1150. db = AsyncMock()
  1151. settings_returns = {
  1152. "queue_drying_enabled": self._make_setting("true"),
  1153. "ambient_drying_enabled": self._make_setting("false"),
  1154. "print_drying_enabled": self._make_setting("true"),
  1155. "ams_humidity_fair": self._make_setting("60"),
  1156. "queue_drying_block": self._make_setting("false"),
  1157. "drying_presets": None,
  1158. }
  1159. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1160. # Actually printing (RUNNING), so the mid-print path applies
  1161. await scheduler._check_auto_drying(db, [], {1})
  1162. # PLA preset is 45 degC for n3f; mid-print cap is max(40, 45-5) = 40
  1163. mock_pm.send_drying_command.assert_called_once_with(1, 0, 40, 12, mode=1, filament="PLA")
  1164. assert 1 in scheduler._drying_in_progress
  1165. @pytest.mark.asyncio
  1166. @patch("backend.app.services.print_scheduler.printer_manager")
  1167. async def test_temp_cap_applied_above_floor(self, mock_pm, scheduler):
  1168. """Higher-temp filament (PETG n3f=65) caps to 60, not floor."""
  1169. state = MagicMock()
  1170. state.raw_data = {
  1171. "ams": [
  1172. {
  1173. "id": 0,
  1174. "module_type": "n3f",
  1175. "dry_time": 0,
  1176. "humidity_raw": "75",
  1177. "dry_sf_reason": [],
  1178. "tray": [{"tray_type": "PETG"}],
  1179. }
  1180. ]
  1181. }
  1182. state.firmware_version = "01.03.00.00"
  1183. state.state = "RUNNING"
  1184. mock_pm.get_status.return_value = state
  1185. mock_pm.is_connected.return_value = True
  1186. mock_pm.get_model.return_value = "H2D"
  1187. mock_pm.send_drying_command.return_value = True
  1188. scheduler._is_printer_idle = MagicMock(return_value=False)
  1189. db = AsyncMock()
  1190. settings_returns = {
  1191. "queue_drying_enabled": self._make_setting("true"),
  1192. "ambient_drying_enabled": self._make_setting("false"),
  1193. "print_drying_enabled": self._make_setting("true"),
  1194. "ams_humidity_fair": self._make_setting("60"),
  1195. "queue_drying_block": self._make_setting("false"),
  1196. "drying_presets": None,
  1197. }
  1198. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1199. await scheduler._check_auto_drying(db, [], {1})
  1200. # PETG preset 65 -> max(40, 65-5) = 60
  1201. mock_pm.send_drying_command.assert_called_once_with(1, 0, 60, 12, mode=1, filament="PETG")
  1202. @pytest.mark.asyncio
  1203. @patch("backend.app.services.print_scheduler.printer_manager")
  1204. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1205. async def test_running_printer_skipped_when_toggle_off(self, mock_sd, mock_pm, scheduler):
  1206. """Toggle OFF: running printer is skipped even on capable hardware."""
  1207. mock_pm.get_status.return_value = self._state("01.03.00.00")
  1208. mock_pm.is_connected.return_value = True
  1209. mock_pm.get_model.return_value = "H2D"
  1210. scheduler._is_printer_idle = MagicMock(return_value=False)
  1211. db = AsyncMock()
  1212. settings_returns = {
  1213. "queue_drying_enabled": self._make_setting("true"),
  1214. "ambient_drying_enabled": self._make_setting("false"),
  1215. "print_drying_enabled": self._make_setting("false"),
  1216. "ams_humidity_fair": self._make_setting("60"),
  1217. "queue_drying_block": self._make_setting("false"),
  1218. "drying_presets": None,
  1219. }
  1220. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1221. await scheduler._check_auto_drying(db, [], {1})
  1222. mock_pm.send_drying_command.assert_not_called()
  1223. @pytest.mark.asyncio
  1224. @patch("backend.app.services.print_scheduler.printer_manager")
  1225. async def test_running_printer_skipped_when_firmware_too_old(self, mock_pm, scheduler):
  1226. """Toggle ON but firmware below matrix threshold: skip."""
  1227. # H2D matrix minimum is 01.03.00.00; this is below
  1228. mock_pm.get_status.return_value = self._state("01.02.30.00")
  1229. mock_pm.is_connected.return_value = True
  1230. mock_pm.get_model.return_value = "H2D"
  1231. scheduler._is_printer_idle = MagicMock(return_value=False)
  1232. db = AsyncMock()
  1233. settings_returns = {
  1234. "queue_drying_enabled": self._make_setting("true"),
  1235. "ambient_drying_enabled": self._make_setting("false"),
  1236. "print_drying_enabled": self._make_setting("true"),
  1237. "ams_humidity_fair": self._make_setting("60"),
  1238. "queue_drying_block": self._make_setting("false"),
  1239. "drying_presets": None,
  1240. }
  1241. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1242. await scheduler._check_auto_drying(db, [], {1})
  1243. mock_pm.send_drying_command.assert_not_called()
  1244. @pytest.mark.asyncio
  1245. @patch("backend.app.services.print_scheduler.printer_manager")
  1246. async def test_running_printer_skipped_when_model_excluded(self, mock_pm, scheduler):
  1247. """Toggle ON, recent firmware, but excluded model (A1): skip."""
  1248. mock_pm.get_status.return_value = self._state("99.99.99.99")
  1249. mock_pm.is_connected.return_value = True
  1250. mock_pm.get_model.return_value = "A1"
  1251. scheduler._is_printer_idle = MagicMock(return_value=False)
  1252. db = AsyncMock()
  1253. settings_returns = {
  1254. "queue_drying_enabled": self._make_setting("true"),
  1255. "ambient_drying_enabled": self._make_setting("false"),
  1256. "print_drying_enabled": self._make_setting("true"),
  1257. "ams_humidity_fair": self._make_setting("60"),
  1258. "queue_drying_block": self._make_setting("false"),
  1259. "drying_presets": None,
  1260. }
  1261. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1262. await scheduler._check_auto_drying(db, [], {1})
  1263. mock_pm.send_drying_command.assert_not_called()
  1264. class TestAutoDryRearmGuards(_DryingTestBase):
  1265. """The re-arm loop from #2770.
  1266. An AMS reads higher humidity while it is warm than once it has cooled, so a
  1267. threshold set inside that band is never satisfied at the moment a cycle
  1268. ends. The firmware is separately free to end a cycle early when it decides
  1269. the filament is dry. Together those produced five 12-hour cycles armed in
  1270. four hours on the reporter's H2D, one of them six seconds after the previous
  1271. ended. These tests pin the two guards that break the loop and, just as
  1272. importantly, that neither guard ever stops a cycle that is running.
  1273. """
  1274. THRESHOLD = "14"
  1275. ABOVE = 16
  1276. BELOW = 10
  1277. @pytest.fixture
  1278. def scheduler(self):
  1279. return PrintScheduler()
  1280. @staticmethod
  1281. def _ams_state(dry_time, humidity):
  1282. state = MagicMock()
  1283. state.raw_data = {
  1284. "ams": [
  1285. {
  1286. "id": 0,
  1287. "module_type": "n3f",
  1288. "dry_time": dry_time,
  1289. "humidity_raw": str(humidity),
  1290. "dry_sf_reason": [],
  1291. "tray": [{"tray_type": "PLA"}],
  1292. }
  1293. ]
  1294. }
  1295. state.firmware_version = "01.09.00.00"
  1296. return state
  1297. def _db(self):
  1298. db = AsyncMock()
  1299. db.execute = AsyncMock(
  1300. side_effect=self._make_db_side_effect(
  1301. {
  1302. "queue_drying_enabled": self._make_setting("false"),
  1303. "ambient_drying_enabled": self._make_setting("true"),
  1304. "ams_humidity_fair": self._make_setting(self.THRESHOLD),
  1305. "queue_drying_block": self._make_setting("false"),
  1306. "drying_presets": None,
  1307. }
  1308. )
  1309. )
  1310. return db
  1311. async def _pass(self, scheduler, mock_pm, db, dry_time, humidity):
  1312. """One 30-second scheduler pass with the AMS in the given state."""
  1313. mock_pm.get_status.return_value = self._ams_state(dry_time, humidity)
  1314. await scheduler._check_auto_drying(db, [], set())
  1315. async def _unproductive_cycle(self, scheduler, mock_pm, db):
  1316. """Arm a cycle, watch it run, then see it end with humidity still high."""
  1317. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1318. await self._pass(scheduler, mock_pm, db, 720, self.ABOVE)
  1319. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1320. @pytest.mark.asyncio
  1321. @patch("backend.app.services.print_scheduler.printer_manager")
  1322. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1323. async def test_does_not_rearm_immediately_after_a_cycle_ends(self, mock_sd, mock_pm, scheduler):
  1324. """The six-second re-arm: one cycle ends, the next pass must not start another."""
  1325. mock_pm.is_connected.return_value = True
  1326. mock_pm.get_model.return_value = "H2D"
  1327. mock_pm.send_drying_command.return_value = True
  1328. scheduler._is_printer_idle = MagicMock(return_value=True)
  1329. db = self._db()
  1330. await self._unproductive_cycle(scheduler, mock_pm, db)
  1331. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1332. assert mock_pm.send_drying_command.call_count == 1
  1333. @pytest.mark.asyncio
  1334. @patch("backend.app.services.print_scheduler.notification_service")
  1335. @patch("backend.app.services.print_scheduler.printer_manager")
  1336. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1337. async def test_suspends_after_repeated_unproductive_cycles(self, mock_sd, mock_pm, mock_notify, scheduler):
  1338. """Past the cooldown the loop would resume, so the counter has to stop it."""
  1339. mock_pm.is_connected.return_value = True
  1340. mock_pm.get_model.return_value = "H2D"
  1341. mock_pm.send_drying_command.return_value = True
  1342. mock_notify.on_ams_drying_suspended = AsyncMock()
  1343. scheduler._is_printer_idle = MagicMock(return_value=True)
  1344. db = self._db()
  1345. for _ in range(AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES):
  1346. await self._unproductive_cycle(scheduler, mock_pm, db)
  1347. # Age the last cycle out of its cooldown so the next arm is allowed.
  1348. scheduler._auto_dry_units[(1, 0)]["ended_at"] -= AUTO_DRY_REARM_COOLDOWN_SECONDS + 1
  1349. assert mock_pm.send_drying_command.call_count == AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES
  1350. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1351. assert mock_pm.send_drying_command.call_count == AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES
  1352. assert scheduler._auto_dry_units[(1, 0)]["suspended"] is True
  1353. mock_notify.on_ams_drying_suspended.assert_awaited_once()
  1354. @pytest.mark.asyncio
  1355. @patch("backend.app.services.print_scheduler.notification_service")
  1356. @patch("backend.app.services.print_scheduler.printer_manager")
  1357. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1358. async def test_suspension_notifies_once_and_stays_put(self, mock_sd, mock_pm, mock_notify, scheduler):
  1359. """A suspension is a state, not a repeating alarm."""
  1360. mock_pm.is_connected.return_value = True
  1361. mock_pm.get_model.return_value = "H2D"
  1362. mock_pm.send_drying_command.return_value = True
  1363. mock_notify.on_ams_drying_suspended = AsyncMock()
  1364. scheduler._is_printer_idle = MagicMock(return_value=True)
  1365. db = self._db()
  1366. scheduler._auto_dry_units[(1, 0)] = {
  1367. "unproductive": AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES,
  1368. "suspended": False,
  1369. "ended_at": None,
  1370. }
  1371. for _ in range(4):
  1372. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1373. mock_pm.send_drying_command.assert_not_called()
  1374. assert mock_notify.on_ams_drying_suspended.await_count == 1
  1375. @pytest.mark.asyncio
  1376. @patch("backend.app.services.print_scheduler.notification_service")
  1377. @patch("backend.app.services.print_scheduler.printer_manager")
  1378. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1379. async def test_humidity_dropping_lifts_the_suspension(self, mock_sd, mock_pm, mock_notify, scheduler):
  1380. """The reading coming down is the evidence that drying works after all."""
  1381. mock_pm.is_connected.return_value = True
  1382. mock_pm.get_model.return_value = "H2D"
  1383. mock_pm.send_drying_command.return_value = True
  1384. mock_notify.on_ams_drying_suspended = AsyncMock()
  1385. scheduler._is_printer_idle = MagicMock(return_value=True)
  1386. db = self._db()
  1387. scheduler._auto_dry_units[(1, 0)] = {
  1388. "unproductive": AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES,
  1389. "suspended": True,
  1390. "ended_at": None,
  1391. }
  1392. await self._pass(scheduler, mock_pm, db, 0, self.BELOW)
  1393. # The judgement is cleared, but the re-arm clock is kept (#2801).
  1394. assert not scheduler._auto_dry_units[(1, 0)].get("suspended")
  1395. assert not scheduler._auto_dry_units[(1, 0)].get("unproductive")
  1396. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1397. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1398. @pytest.mark.asyncio
  1399. @patch("backend.app.services.print_scheduler.printer_manager")
  1400. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1401. async def test_manual_cycle_is_neither_counted_nor_interrupted(self, mock_sd, mock_pm, scheduler):
  1402. """A dry the user started by hand carries no history and is never stopped."""
  1403. mock_pm.is_connected.return_value = True
  1404. mock_pm.get_model.return_value = "H2D"
  1405. mock_pm.send_drying_command.return_value = True
  1406. scheduler._is_printer_idle = MagicMock(return_value=True)
  1407. db = self._db()
  1408. await self._pass(scheduler, mock_pm, db, 720, self.ABOVE)
  1409. await self._pass(scheduler, mock_pm, db, 600, self.ABOVE)
  1410. mock_pm.send_drying_command.assert_not_called()
  1411. assert (1, 0) not in scheduler._auto_dry_units
  1412. # It ends; Bambuddy is free to arm its own cycle, with a clean slate.
  1413. await self._pass(scheduler, mock_pm, db, 0, self.ABOVE)
  1414. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1415. assert scheduler._auto_dry_units[(1, 0)]["unproductive"] == 0
  1416. @pytest.mark.asyncio
  1417. @patch("backend.app.services.print_scheduler.printer_manager")
  1418. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1419. async def test_history_is_dropped_when_the_printer_goes_away(self, mock_sd, mock_pm, scheduler):
  1420. """A printer deleted and re-added must not inherit a suspension."""
  1421. mock_pm.get_status.return_value = None
  1422. scheduler._auto_dry_units[(1, 0)] = {"unproductive": 5, "suspended": True, "ended_at": None}
  1423. scheduler._sync_drying_state()
  1424. assert scheduler._auto_dry_units == {}
  1425. class TestAutoDryStoppedByBambuddy(_DryingTestBase):
  1426. """A cycle Bambuddy itself cut short must not count against the unit."""
  1427. THRESHOLD = "14"
  1428. ABOVE = 16
  1429. @pytest.fixture
  1430. def scheduler(self):
  1431. return PrintScheduler()
  1432. @staticmethod
  1433. def _ams_state(dry_time, humidity):
  1434. state = MagicMock()
  1435. state.raw_data = {
  1436. "ams": [
  1437. {
  1438. "id": 0,
  1439. "module_type": "n3f",
  1440. "dry_time": dry_time,
  1441. "humidity_raw": str(humidity),
  1442. "dry_sf_reason": [],
  1443. "tray": [{"tray_type": "PLA"}],
  1444. }
  1445. ]
  1446. }
  1447. state.firmware_version = "01.09.00.00"
  1448. return state
  1449. def _db(self):
  1450. db = AsyncMock()
  1451. db.execute = AsyncMock(
  1452. side_effect=self._make_db_side_effect(
  1453. {
  1454. "queue_drying_enabled": self._make_setting("false"),
  1455. "ambient_drying_enabled": self._make_setting("true"),
  1456. "ams_humidity_fair": self._make_setting(self.THRESHOLD),
  1457. "queue_drying_block": self._make_setting("false"),
  1458. "drying_presets": None,
  1459. }
  1460. )
  1461. )
  1462. return db
  1463. @pytest.mark.asyncio
  1464. @patch("backend.app.services.print_scheduler.printer_manager")
  1465. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1466. async def test_print_takes_priority_stop_is_not_an_unproductive_cycle(self, mock_sd, mock_pm, scheduler):
  1467. """The queue stopping a dry so a print can start is Bambuddy's own doing.
  1468. Counting it would suspend auto-drying on any printer that dries between
  1469. jobs often enough -- exactly the install queue-drying exists for.
  1470. """
  1471. mock_pm.is_connected.return_value = True
  1472. mock_pm.get_model.return_value = "H2D"
  1473. mock_pm.send_drying_command.return_value = True
  1474. scheduler._is_printer_idle = MagicMock(return_value=True)
  1475. db = self._db()
  1476. mock_pm.get_status.return_value = self._ams_state(0, self.ABOVE)
  1477. await scheduler._check_auto_drying(db, [], set())
  1478. mock_pm.get_status.return_value = self._ams_state(720, self.ABOVE)
  1479. await scheduler._check_auto_drying(db, [], set())
  1480. # A print is ready: check_queue stops drying on this printer.
  1481. await scheduler._stop_drying(1)
  1482. mock_pm.get_status.return_value = self._ams_state(0, self.ABOVE)
  1483. await scheduler._check_auto_drying(db, [], set())
  1484. assert scheduler._auto_dry_units[(1, 0)]["unproductive"] == 0
  1485. @pytest.mark.asyncio
  1486. @patch("backend.app.services.print_scheduler.printer_manager")
  1487. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1488. async def test_manual_stop_button_is_not_an_unproductive_cycle(self, mock_sd, mock_pm, scheduler):
  1489. """The Stop button goes straight to printer_manager, bypassing the
  1490. scheduler, so the route has to tell the scheduler to forget the cycle."""
  1491. mock_pm.is_connected.return_value = True
  1492. mock_pm.get_model.return_value = "H2D"
  1493. mock_pm.send_drying_command.return_value = True
  1494. scheduler._is_printer_idle = MagicMock(return_value=True)
  1495. db = self._db()
  1496. mock_pm.get_status.return_value = self._ams_state(0, self.ABOVE)
  1497. await scheduler._check_auto_drying(db, [], set())
  1498. mock_pm.get_status.return_value = self._ams_state(720, self.ABOVE)
  1499. await scheduler._check_auto_drying(db, [], set())
  1500. scheduler.forget_auto_dry_cycle(1, 0)
  1501. mock_pm.get_status.return_value = self._ams_state(0, self.ABOVE)
  1502. await scheduler._check_auto_drying(db, [], set())
  1503. assert scheduler._auto_dry_units[(1, 0)]["unproductive"] == 0
  1504. class TestAutoDryProgressKeepsItGoing(_DryingTestBase):
  1505. """Suspension must not punish a spool that is genuinely drying, just slowly."""
  1506. THRESHOLD = "25"
  1507. @pytest.fixture
  1508. def scheduler(self):
  1509. return PrintScheduler()
  1510. @staticmethod
  1511. def _ams_state(dry_time, humidity):
  1512. state = MagicMock()
  1513. state.raw_data = {
  1514. "ams": [
  1515. {
  1516. "id": 0,
  1517. "module_type": "n3f",
  1518. "dry_time": dry_time,
  1519. "humidity_raw": str(humidity),
  1520. "dry_sf_reason": [],
  1521. "tray": [{"tray_type": "PLA"}],
  1522. }
  1523. ]
  1524. }
  1525. state.firmware_version = "01.09.00.00"
  1526. return state
  1527. def _db(self):
  1528. db = AsyncMock()
  1529. db.execute = AsyncMock(
  1530. side_effect=self._make_db_side_effect(
  1531. {
  1532. "queue_drying_enabled": self._make_setting("false"),
  1533. "ambient_drying_enabled": self._make_setting("true"),
  1534. "ams_humidity_fair": self._make_setting(self.THRESHOLD),
  1535. "queue_drying_block": self._make_setting("false"),
  1536. "drying_presets": None,
  1537. }
  1538. )
  1539. )
  1540. return db
  1541. async def _cycle(self, scheduler, mock_pm, db, end_humidity):
  1542. """Arm a cycle, run it, and end it at the given reading."""
  1543. mock_pm.get_status.return_value = self._ams_state(0, end_humidity)
  1544. await scheduler._check_auto_drying(db, [], set())
  1545. mock_pm.get_status.return_value = self._ams_state(720, end_humidity)
  1546. await scheduler._check_auto_drying(db, [], set())
  1547. mock_pm.get_status.return_value = self._ams_state(0, end_humidity)
  1548. await scheduler._check_auto_drying(db, [], set())
  1549. entry = scheduler._auto_dry_units.get((1, 0))
  1550. if entry is not None and isinstance(entry.get("ended_at"), float):
  1551. entry["ended_at"] -= AUTO_DRY_REARM_COOLDOWN_SECONDS + 1
  1552. @pytest.mark.asyncio
  1553. @patch("backend.app.services.print_scheduler.notification_service")
  1554. @patch("backend.app.services.print_scheduler.printer_manager")
  1555. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1556. async def test_a_reading_that_keeps_falling_is_never_suspended(self, mock_sd, mock_pm, mock_notify, scheduler):
  1557. """40 -> 37 -> 35 -> 33 with a 25% threshold: nowhere near it yet, but
  1558. every cycle is working. A humid workshop must not lose auto-drying."""
  1559. mock_pm.is_connected.return_value = True
  1560. mock_pm.get_model.return_value = "H2D"
  1561. mock_pm.send_drying_command.return_value = True
  1562. mock_notify.on_ams_drying_suspended = AsyncMock()
  1563. scheduler._is_printer_idle = MagicMock(return_value=True)
  1564. db = self._db()
  1565. for reading in (40, 37, 35, 33, 31, 29):
  1566. await self._cycle(scheduler, mock_pm, db, reading)
  1567. assert scheduler._auto_dry_units[(1, 0)]["suspended"] is False
  1568. mock_notify.on_ams_drying_suspended.assert_not_awaited()
  1569. assert mock_pm.send_drying_command.call_count == 6
  1570. @pytest.mark.asyncio
  1571. @patch("backend.app.services.print_scheduler.notification_service")
  1572. @patch("backend.app.services.print_scheduler.printer_manager")
  1573. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1574. async def test_a_reading_oscillating_by_one_point_still_suspends(self, mock_sd, mock_pm, mock_notify, scheduler):
  1575. """A plateau with sensor noise — 31, 30, 31, 30 — is not progress.
  1576. Comparing against the previous cycle rather than the best-so-far would
  1577. read every other cycle as an improvement and loop indefinitely."""
  1578. mock_pm.is_connected.return_value = True
  1579. mock_pm.get_model.return_value = "H2D"
  1580. mock_pm.send_drying_command.return_value = True
  1581. mock_notify.on_ams_drying_suspended = AsyncMock()
  1582. scheduler._is_printer_idle = MagicMock(return_value=True)
  1583. db = self._db()
  1584. for reading in (31, 30, 31, 30, 31, 30):
  1585. await self._cycle(scheduler, mock_pm, db, reading)
  1586. assert scheduler._auto_dry_units[(1, 0)]["suspended"] is True
  1587. mock_notify.on_ams_drying_suspended.assert_awaited_once()
  1588. class TestAmbientDryingSustainedDelay(_DryingTestBase):
  1589. """#2518 — ambient auto-drying waits for CONTINUOUSLY-above-threshold humidity.
  1590. ``ambient_drying_sustained_minutes`` (default 0 = instant, matching the
  1591. pre-#2518 behavior) makes a pure-ambient start wait for the reading to sit
  1592. above the threshold for that many minutes straight before drying begins.
  1593. The streak lives in ``scheduler._auto_dry_above``, keyed like
  1594. ``_auto_dry_units`` by (printer_id, ams_id), but deliberately a separate
  1595. dict: arming a streak must never look like a Bambuddy-started cycle to
  1596. ``_auto_dry_units``, which is what ``_stop_drying`` and the manual-cycle
  1597. immunity in #2801 key off of.
  1598. """
  1599. UNIT_KEY = (1, 0)
  1600. @pytest.fixture
  1601. def scheduler(self):
  1602. return PrintScheduler()
  1603. @staticmethod
  1604. def _ams_unit(dry_time=0, humidity="75", include_humidity=True):
  1605. ams = {
  1606. "id": 0,
  1607. "module_type": "n3f",
  1608. "dry_time": dry_time,
  1609. "dry_sf_reason": [],
  1610. "tray": [{"tray_type": "PLA"}],
  1611. }
  1612. if include_humidity:
  1613. ams["humidity_raw"] = humidity
  1614. return ams
  1615. @classmethod
  1616. def _state(cls, dry_time=0, humidity="75", include_humidity=True):
  1617. state = MagicMock()
  1618. state.raw_data = {"ams": [cls._ams_unit(dry_time, humidity, include_humidity)]}
  1619. state.firmware_version = "01.09.00.00"
  1620. return state
  1621. def _db(self, sustained_minutes=None, queue_enabled="false", ambient_enabled="true"):
  1622. settings = {
  1623. "queue_drying_enabled": self._make_setting(queue_enabled),
  1624. "ambient_drying_enabled": self._make_setting(ambient_enabled),
  1625. "ams_humidity_fair": self._make_setting("60"),
  1626. "queue_drying_block": self._make_setting("false"),
  1627. "drying_presets": None,
  1628. }
  1629. if sustained_minutes is not None:
  1630. settings["ambient_drying_sustained_minutes"] = self._make_setting(str(sustained_minutes))
  1631. db = AsyncMock()
  1632. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings))
  1633. return db
  1634. @pytest.mark.asyncio
  1635. @patch("backend.app.services.print_scheduler.printer_manager")
  1636. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1637. async def test_setting_absent_dries_immediately(self, mock_sd, mock_pm, scheduler):
  1638. """No ``ambient_drying_sustained_minutes`` row → default 0 → instant dry,
  1639. same as ambient mode before #2518."""
  1640. mock_pm.get_status.return_value = self._state()
  1641. mock_pm.is_connected.return_value = True
  1642. mock_pm.get_model.return_value = "X1C"
  1643. mock_pm.send_drying_command.return_value = True
  1644. scheduler._is_printer_idle = MagicMock(return_value=True)
  1645. await scheduler._check_auto_drying(self._db(sustained_minutes=None), [], set())
  1646. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1647. @pytest.mark.asyncio
  1648. @patch("backend.app.services.print_scheduler.printer_manager")
  1649. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1650. async def test_first_above_threshold_pass_arms_but_does_not_dry(self, mock_sd, mock_pm, scheduler):
  1651. """First observation above threshold arms the streak instead of drying."""
  1652. mock_pm.get_status.return_value = self._state()
  1653. mock_pm.is_connected.return_value = True
  1654. mock_pm.get_model.return_value = "X1C"
  1655. scheduler._is_printer_idle = MagicMock(return_value=True)
  1656. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  1657. mock_pm.send_drying_command.assert_not_called()
  1658. assert self.UNIT_KEY in scheduler._auto_dry_above
  1659. @pytest.mark.asyncio
  1660. @patch("backend.app.services.print_scheduler.printer_manager")
  1661. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1662. async def test_matured_streak_dries_on_next_pass(self, mock_sd, mock_pm, scheduler):
  1663. """Once the streak's age clears the configured minutes, the next pass dries."""
  1664. mock_pm.get_status.return_value = self._state()
  1665. mock_pm.is_connected.return_value = True
  1666. mock_pm.get_model.return_value = "X1C"
  1667. mock_pm.send_drying_command.return_value = True
  1668. scheduler._is_printer_idle = MagicMock(return_value=True)
  1669. db = self._db(sustained_minutes=5)
  1670. await scheduler._check_auto_drying(db, [], set())
  1671. mock_pm.send_drying_command.assert_not_called()
  1672. # Age the streak past the 5-minute requirement, keeping "last" recent
  1673. # so the observation-gap guard doesn't treat it as a fresh streak.
  1674. scheduler._auto_dry_above[self.UNIT_KEY]["since"] = time.monotonic() - (5 * 60 + 5)
  1675. scheduler._auto_dry_above[self.UNIT_KEY]["last"] = time.monotonic() - 5
  1676. await scheduler._check_auto_drying(db, [], set())
  1677. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1678. @pytest.mark.asyncio
  1679. @patch("backend.app.services.print_scheduler.printer_manager")
  1680. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1681. async def test_dip_below_threshold_clears_streak(self, mock_sd, mock_pm, scheduler):
  1682. """A below-threshold reading between passes clears the streak — the wait restarts."""
  1683. mock_pm.is_connected.return_value = True
  1684. mock_pm.get_model.return_value = "X1C"
  1685. scheduler._is_printer_idle = MagicMock(return_value=True)
  1686. db = self._db(sustained_minutes=5)
  1687. mock_pm.get_status.return_value = self._state(humidity="75")
  1688. await scheduler._check_auto_drying(db, [], set())
  1689. assert self.UNIT_KEY in scheduler._auto_dry_above
  1690. mock_pm.get_status.return_value = self._state(humidity="40") # below the 60% threshold
  1691. await scheduler._check_auto_drying(db, [], set())
  1692. assert self.UNIT_KEY not in scheduler._auto_dry_above
  1693. @pytest.mark.asyncio
  1694. @patch("backend.app.services.print_scheduler.printer_manager")
  1695. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1696. async def test_missing_humidity_does_not_clear_armed_streak(self, mock_sd, mock_pm, scheduler):
  1697. """No humidity_raw/humidity in the AMS payload is no-information, not a dip below threshold."""
  1698. mock_pm.is_connected.return_value = True
  1699. mock_pm.get_model.return_value = "X1C"
  1700. scheduler._is_printer_idle = MagicMock(return_value=True)
  1701. db = self._db(sustained_minutes=5)
  1702. mock_pm.get_status.return_value = self._state(humidity="75")
  1703. await scheduler._check_auto_drying(db, [], set())
  1704. assert self.UNIT_KEY in scheduler._auto_dry_above
  1705. mock_pm.get_status.return_value = self._state(include_humidity=False)
  1706. await scheduler._check_auto_drying(db, [], set())
  1707. assert self.UNIT_KEY in scheduler._auto_dry_above
  1708. mock_pm.send_drying_command.assert_not_called()
  1709. @pytest.mark.asyncio
  1710. @patch("backend.app.services.print_scheduler.printer_manager")
  1711. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1712. async def test_manual_cycle_immunity(self, mock_sd, mock_pm, scheduler):
  1713. """Arming a streak must never create a ``_auto_dry_units`` entry — that dict is
  1714. reserved for cycles Bambuddy itself started (#2801's manual-cycle immunity). A
  1715. unit already drying by the user's own hand (dry_time > 0) with a streak still
  1716. present is left alone: no command sent, no entry created, streak untouched.
  1717. """
  1718. mock_pm.is_connected.return_value = True
  1719. mock_pm.get_model.return_value = "X1C"
  1720. scheduler._is_printer_idle = MagicMock(return_value=True)
  1721. db = self._db(sustained_minutes=5)
  1722. # First pass: nothing drying yet, arms the streak.
  1723. mock_pm.get_status.return_value = self._state(dry_time=0)
  1724. await scheduler._check_auto_drying(db, [], set())
  1725. assert self.UNIT_KEY not in scheduler._auto_dry_units
  1726. assert self.UNIT_KEY in scheduler._auto_dry_above
  1727. # A manual cycle is now running on the same unit — dry_time > 0.
  1728. mock_pm.get_status.return_value = self._state(dry_time=120)
  1729. await scheduler._check_auto_drying(db, [], set())
  1730. mock_pm.send_drying_command.assert_not_called()
  1731. assert self.UNIT_KEY not in scheduler._auto_dry_units
  1732. assert self.UNIT_KEY in scheduler._auto_dry_above
  1733. @pytest.mark.asyncio
  1734. @patch("backend.app.services.print_scheduler.printer_manager")
  1735. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1736. async def test_scheduled_queue_item_dries_immediately(self, mock_sd, mock_pm, scheduler):
  1737. """A printer with a scheduled (non-manual) queue item dries instantly —
  1738. the sustained wait applies only to pure-ambient starts."""
  1739. mock_pm.get_status.return_value = self._state()
  1740. mock_pm.is_connected.return_value = True
  1741. mock_pm.get_model.return_value = "X1C"
  1742. mock_pm.send_drying_command.return_value = True
  1743. scheduler._is_printer_idle = MagicMock(return_value=True)
  1744. db = self._db(sustained_minutes=5, queue_enabled="true", ambient_enabled="false")
  1745. item = MagicMock()
  1746. item.printer_id = 1
  1747. item.scheduled_time = MagicMock()
  1748. item.manual_start = False
  1749. await scheduler._check_auto_drying(db, [item], set())
  1750. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1751. @pytest.mark.asyncio
  1752. @patch("backend.app.services.print_scheduler.printer_manager")
  1753. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1754. async def test_observation_gap_restarts_the_streak(self, mock_sd, mock_pm, scheduler):
  1755. """A streak whose last observation is older than the gap ceiling
  1756. can no longer claim "continuously above" — it is treated as fresh and the
  1757. pass must not dry, even though 'since' alone clears the required minutes."""
  1758. mock_pm.get_status.return_value = self._state()
  1759. mock_pm.is_connected.return_value = True
  1760. mock_pm.get_model.return_value = "X1C"
  1761. scheduler._is_printer_idle = MagicMock(return_value=True)
  1762. old_since = time.monotonic() - (5 * 60 + 100)
  1763. scheduler._auto_dry_above[self.UNIT_KEY] = {
  1764. "since": old_since,
  1765. "last": time.monotonic() - (AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS + 10),
  1766. }
  1767. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  1768. mock_pm.send_drying_command.assert_not_called()
  1769. # The streak was restarted, not left at its stale (matured) age.
  1770. assert scheduler._auto_dry_above[self.UNIT_KEY]["since"] > old_since + 90
  1771. @pytest.mark.asyncio
  1772. @patch("backend.app.services.print_scheduler.printer_manager")
  1773. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1774. async def test_suspension_wins_over_a_matured_streak(self, mock_sd, mock_pm, scheduler):
  1775. """A suspended unit (#2770) stays suspended even once the sustained wait matures."""
  1776. mock_pm.get_status.return_value = self._state()
  1777. mock_pm.is_connected.return_value = True
  1778. mock_pm.get_model.return_value = "X1C"
  1779. scheduler._is_printer_idle = MagicMock(return_value=True)
  1780. scheduler._auto_dry_units[self.UNIT_KEY] = {
  1781. "unproductive": AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES,
  1782. "suspended": True,
  1783. "ended_at": None,
  1784. }
  1785. scheduler._auto_dry_above[self.UNIT_KEY] = {
  1786. "since": time.monotonic() - (5 * 60 + 5),
  1787. "last": time.monotonic() - 5,
  1788. }
  1789. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  1790. mock_pm.send_drying_command.assert_not_called()
  1791. assert scheduler._auto_dry_units[self.UNIT_KEY]["suspended"] is True
  1792. def test_forget_auto_dry_cycle_pops_the_streak(self, scheduler):
  1793. """``forget_auto_dry_cycle`` (the route-side stop path) also spends the
  1794. streak that armed the cycle (#2518). The other cycle-end path — the
  1795. in-loop branch inside ``_check_auto_drying`` that pops ``running`` when
  1796. firmware reports ``dry_time == 0`` — is covered separately by
  1797. ``test_in_loop_cycle_end_restarts_the_streak``."""
  1798. scheduler._auto_dry_units[self.UNIT_KEY] = {
  1799. "running": True,
  1800. "unproductive": 0,
  1801. "suspended": False,
  1802. "ended_at": None,
  1803. }
  1804. scheduler._auto_dry_above[self.UNIT_KEY] = {"since": time.monotonic(), "last": time.monotonic()}
  1805. scheduler.forget_auto_dry_cycle(*self.UNIT_KEY)
  1806. assert self.UNIT_KEY not in scheduler._auto_dry_above
  1807. assert "running" not in scheduler._auto_dry_units[self.UNIT_KEY]
  1808. @pytest.mark.asyncio
  1809. @patch("backend.app.services.print_scheduler.printer_manager")
  1810. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1811. async def test_in_loop_cycle_end_restarts_the_streak(self, mock_sd, mock_pm, scheduler):
  1812. """When the in-loop cycle-end branch fires (a Bambuddy-armed cycle whose
  1813. ``dry_time`` has gone to 0), the matured streak that armed it is spent —
  1814. the pass re-arms a FRESH streak rather than keeping the old ``since``.
  1815. Without the pop, a matured pre-cycle streak would survive the cycle and
  1816. reduce the sustained wait to the re-arm cooldown on every re-arm."""
  1817. mock_pm.get_status.return_value = self._state()
  1818. mock_pm.is_connected.return_value = True
  1819. mock_pm.get_model.return_value = "X1C"
  1820. scheduler._is_printer_idle = MagicMock(return_value=True)
  1821. scheduler._auto_dry_units[self.UNIT_KEY] = {"running": True}
  1822. old_since = time.monotonic() - (60 * 60)
  1823. scheduler._auto_dry_above[self.UNIT_KEY] = {"since": old_since, "last": time.monotonic() - 5}
  1824. before = time.monotonic()
  1825. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  1826. # The cycle-end pass never dries (its own ended_at starts the cooldown)...
  1827. mock_pm.send_drying_command.assert_not_called()
  1828. # ...and the streak now on file must be fresh, not the pre-cycle one.
  1829. assert scheduler._auto_dry_above[self.UNIT_KEY]["since"] >= before
  1830. @pytest.mark.asyncio
  1831. @patch("backend.app.services.print_scheduler.printer_manager")
  1832. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1833. async def test_streak_arms_during_the_rearm_cooldown(self, mock_sd, mock_pm, scheduler):
  1834. """The wait OVERLAPS the 30-minute re-arm cooldown instead of stacking
  1835. after it: a pass blocked by the cooldown still arms/advances the streak,
  1836. so a streak matured inside the cooldown dries at cooldown expiry."""
  1837. mock_pm.get_status.return_value = self._state()
  1838. mock_pm.is_connected.return_value = True
  1839. mock_pm.get_model.return_value = "X1C"
  1840. mock_pm.send_drying_command.return_value = True
  1841. scheduler._is_printer_idle = MagicMock(return_value=True)
  1842. db = self._db(sustained_minutes=5)
  1843. scheduler._auto_dry_units[self.UNIT_KEY] = {"ended_at": time.monotonic() - 60}
  1844. await scheduler._check_auto_drying(db, [], set())
  1845. mock_pm.send_drying_command.assert_not_called()
  1846. # The cooldown blocked the start, but the streak armed anyway.
  1847. assert self.UNIT_KEY in scheduler._auto_dry_above
  1848. # Cooldown over; the streak that matured inside it satisfies the wait.
  1849. scheduler._auto_dry_units[self.UNIT_KEY]["ended_at"] = time.monotonic() - (AUTO_DRY_REARM_COOLDOWN_SECONDS + 5)
  1850. scheduler._auto_dry_above[self.UNIT_KEY]["since"] = time.monotonic() - (5 * 60 + 5)
  1851. scheduler._auto_dry_above[self.UNIT_KEY]["last"] = time.monotonic() - 5
  1852. await scheduler._check_auto_drying(db, [], set())
  1853. mock_pm.send_drying_command.assert_called_once_with(1, 0, 45, 12, mode=1, filament="PLA")
  1854. @pytest.mark.asyncio
  1855. @patch("backend.app.services.print_scheduler.printer_manager")
  1856. async def test_mid_print_ambient_start_waits_like_any_ambient_start(self, mock_pm, scheduler):
  1857. """print_drying is a permission overlay, not a trigger: an ambient
  1858. start on a printer that happens to be printing is still an ambient
  1859. start and must serve the sustained wait. (The original exemption here
  1860. was disproven live — a 2-point threshold crossing mid-print bought a
  1861. parked 12h command instantly.)"""
  1862. state = self._state()
  1863. state.state = "RUNNING"
  1864. mock_pm.get_status.return_value = state
  1865. mock_pm.is_connected.return_value = True
  1866. mock_pm.get_model.return_value = "H2D"
  1867. mock_pm.send_drying_command.return_value = True
  1868. scheduler._is_printer_idle = MagicMock(return_value=False)
  1869. state.firmware_version = "01.03.00.00"
  1870. settings_returns = {
  1871. "queue_drying_enabled": self._make_setting("false"),
  1872. "ambient_drying_enabled": self._make_setting("true"),
  1873. "print_drying_enabled": self._make_setting("true"),
  1874. "ambient_drying_sustained_minutes": self._make_setting("5"),
  1875. "ams_humidity_fair": self._make_setting("60"),
  1876. "queue_drying_block": self._make_setting("false"),
  1877. "drying_presets": None,
  1878. }
  1879. db = AsyncMock()
  1880. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1881. # First pass: the streak arms; no instant start.
  1882. await scheduler._check_auto_drying(db, [], {1})
  1883. mock_pm.send_drying_command.assert_not_called()
  1884. assert self.UNIT_KEY in scheduler._auto_dry_above
  1885. # Streak matured: the start fires, at the mid-print capped
  1886. # temperature max(40, 45 - 5) = 40.
  1887. scheduler._auto_dry_above[self.UNIT_KEY]["since"] = time.monotonic() - (5 * 60 + 5)
  1888. scheduler._auto_dry_above[self.UNIT_KEY]["last"] = time.monotonic() - 5
  1889. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1890. await scheduler._check_auto_drying(db, [], {1})
  1891. mock_pm.send_drying_command.assert_called_once_with(1, 0, 40, 12, mode=1, filament="PLA")
  1892. @pytest.mark.asyncio
  1893. @patch("backend.app.services.print_scheduler.printer_manager")
  1894. async def test_mid_print_with_scheduled_item_stays_instant(self, mock_pm, scheduler):
  1895. """The instant exemption keys on the pending schedule — a printer
  1896. drying ahead of a scheduled job keeps it whether idle or printing."""
  1897. state = self._state()
  1898. state.state = "RUNNING"
  1899. mock_pm.get_status.return_value = state
  1900. mock_pm.is_connected.return_value = True
  1901. mock_pm.get_model.return_value = "H2D"
  1902. mock_pm.send_drying_command.return_value = True
  1903. scheduler._is_printer_idle = MagicMock(return_value=False)
  1904. state.firmware_version = "01.03.00.00"
  1905. settings_returns = {
  1906. "queue_drying_enabled": self._make_setting("false"),
  1907. "ambient_drying_enabled": self._make_setting("true"),
  1908. "print_drying_enabled": self._make_setting("true"),
  1909. "ambient_drying_sustained_minutes": self._make_setting("5"),
  1910. "ams_humidity_fair": self._make_setting("60"),
  1911. "queue_drying_block": self._make_setting("false"),
  1912. "drying_presets": None,
  1913. }
  1914. db = AsyncMock()
  1915. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1916. item = MagicMock()
  1917. item.printer_id = 1
  1918. item.scheduled_time = MagicMock()
  1919. item.manual_start = False
  1920. await scheduler._check_auto_drying(db, [item], {1})
  1921. mock_pm.send_drying_command.assert_called_once_with(1, 0, 40, 12, mode=1, filament="PLA")
  1922. @pytest.mark.asyncio
  1923. @patch("backend.app.services.print_scheduler.printer_manager")
  1924. async def test_stored_wait_is_inert_while_ambient_drying_is_off(self, mock_pm, scheduler):
  1925. """The settings UI hides the wait while ambient drying is off, so a value
  1926. left behind must not keep delaying a mid-print start under print_drying
  1927. (queue mode on, no scheduled item): that start stays instant, and no
  1928. streak entry is written for it."""
  1929. state = self._state()
  1930. state.state = "RUNNING"
  1931. mock_pm.get_status.return_value = state
  1932. mock_pm.is_connected.return_value = True
  1933. mock_pm.get_model.return_value = "H2D"
  1934. mock_pm.send_drying_command.return_value = True
  1935. scheduler._is_printer_idle = MagicMock(return_value=False)
  1936. state.firmware_version = "01.03.00.00"
  1937. settings_returns = {
  1938. "queue_drying_enabled": self._make_setting("true"),
  1939. "ambient_drying_enabled": self._make_setting("false"),
  1940. "print_drying_enabled": self._make_setting("true"),
  1941. "ambient_drying_sustained_minutes": self._make_setting("15"),
  1942. "ams_humidity_fair": self._make_setting("60"),
  1943. "queue_drying_block": self._make_setting("false"),
  1944. "drying_presets": None,
  1945. }
  1946. db = AsyncMock()
  1947. db.execute = AsyncMock(side_effect=self._make_db_side_effect(settings_returns))
  1948. # A streak left over from when ambient drying was on is dropped too.
  1949. scheduler._auto_dry_above[self.UNIT_KEY] = {"since": time.monotonic(), "last": time.monotonic()}
  1950. await scheduler._check_auto_drying(db, [], {1})
  1951. mock_pm.send_drying_command.assert_called_once_with(1, 0, 40, 12, mode=1, filament="PLA")
  1952. assert scheduler._auto_dry_above == {}
  1953. @patch("backend.app.services.print_scheduler.printer_manager")
  1954. def test_sync_drying_state_prunes_streaks_of_vanished_printers(self, mock_pm, scheduler):
  1955. """A printer that has gone away takes its streak with it — a deleted and
  1956. re-added printer starts a fresh wait, and entries do not leak."""
  1957. mock_pm.get_status.return_value = None
  1958. scheduler._auto_dry_above[(99, 0)] = {"since": time.monotonic(), "last": time.monotonic()}
  1959. scheduler._auto_dry_units[(99, 0)] = {"unproductive": 1}
  1960. scheduler._sync_drying_state()
  1961. assert (99, 0) not in scheduler._auto_dry_above
  1962. assert (99, 0) not in scheduler._auto_dry_units
  1963. @pytest.mark.asyncio
  1964. @patch("backend.app.services.print_scheduler.printer_manager")
  1965. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1966. async def test_dip_below_threshold_logs_the_discard_at_info(self, mock_sd, mock_pm, scheduler, caplog):
  1967. """Discarding an armed streak on a real below-threshold reading is logged
  1968. at INFO — it is the only way an operator can tell why an ambient dry
  1969. never started."""
  1970. import logging
  1971. mock_pm.get_status.return_value = self._state()
  1972. mock_pm.is_connected.return_value = True
  1973. mock_pm.get_model.return_value = "X1C"
  1974. scheduler._is_printer_idle = MagicMock(return_value=True)
  1975. db = self._db(sustained_minutes=5)
  1976. await scheduler._check_auto_drying(db, [], set())
  1977. assert self.UNIT_KEY in scheduler._auto_dry_above
  1978. mock_pm.get_status.return_value = self._state(humidity="50")
  1979. with caplog.at_level(logging.INFO, logger="backend.app.services.print_scheduler"):
  1980. await scheduler._check_auto_drying(db, [], set())
  1981. assert self.UNIT_KEY not in scheduler._auto_dry_above
  1982. assert any("fell back" in rec.getMessage() for rec in caplog.records if rec.levelno == logging.INFO)
  1983. @pytest.mark.asyncio
  1984. @patch("backend.app.services.print_scheduler.printer_manager")
  1985. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  1986. async def test_observation_gap_restart_logs_at_info(self, mock_sd, mock_pm, scheduler, caplog):
  1987. """Restarting a streak on an observation gap is logged at INFO with the
  1988. measured gap — the silent twin of the dip reset, and the only way a
  1989. user who set a long wait can see why it never matures."""
  1990. import logging
  1991. mock_pm.get_status.return_value = self._state()
  1992. mock_pm.is_connected.return_value = True
  1993. mock_pm.get_model.return_value = "X1C"
  1994. scheduler._is_printer_idle = MagicMock(return_value=True)
  1995. scheduler._auto_dry_above[self.UNIT_KEY] = {
  1996. "since": time.monotonic() - (5 * 60 + 100),
  1997. "last": time.monotonic() - (AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS + 10),
  1998. }
  1999. with caplog.at_level(logging.INFO, logger="backend.app.services.print_scheduler"):
  2000. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  2001. restarts = [
  2002. rec for rec in caplog.records if rec.levelno == logging.INFO and "streak restarted" in rec.getMessage()
  2003. ]
  2004. assert len(restarts) == 1
  2005. # The measured gap is in the message, not just the fact of a restart.
  2006. assert re.search(r"\d+s observation gap", restarts[0].getMessage())
  2007. @pytest.mark.asyncio
  2008. @patch("backend.app.services.print_scheduler.printer_manager")
  2009. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  2010. async def test_gap_ceiling_scales_with_the_check_interval(self, mock_sd, mock_pm, scheduler):
  2011. """The ceiling is max(4 * check_interval, floor): a scheduler polling
  2012. slower than the default must not void streaks it structurally cannot
  2013. observe often enough (review on #2895)."""
  2014. mock_pm.get_status.return_value = self._state()
  2015. mock_pm.is_connected.return_value = True
  2016. mock_pm.get_model.return_value = "X1C"
  2017. mock_pm.send_drying_command.return_value = True
  2018. scheduler._is_printer_idle = MagicMock(return_value=True)
  2019. scheduler._check_interval = 100 # ceiling 400s, well above the 120s floor
  2020. scheduler._auto_dry_above[self.UNIT_KEY] = {
  2021. "since": time.monotonic() - (5 * 60 + 100),
  2022. # Over the floor, under 4 * check_interval: must NOT restart.
  2023. "last": time.monotonic() - (AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS + 50),
  2024. }
  2025. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  2026. # The streak survived the slow pass and had already matured.
  2027. mock_pm.send_drying_command.assert_called_once()
  2028. @pytest.mark.asyncio
  2029. @patch("backend.app.services.print_scheduler.printer_manager")
  2030. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  2031. async def test_streak_tracking_is_inert_when_the_feature_is_off(self, mock_sd, mock_pm, scheduler):
  2032. """sustained_minutes 0 must not write streak entries — every install
  2033. would otherwise pay the bookkeeping for a feature nobody enabled
  2034. (review on #2895)."""
  2035. mock_pm.get_status.return_value = self._state()
  2036. mock_pm.is_connected.return_value = True
  2037. mock_pm.get_model.return_value = "X1C"
  2038. mock_pm.send_drying_command.return_value = True
  2039. scheduler._is_printer_idle = MagicMock(return_value=True)
  2040. await scheduler._check_auto_drying(self._db(sustained_minutes=0), [], set())
  2041. mock_pm.send_drying_command.assert_called_once()
  2042. assert scheduler._auto_dry_above == {}
  2043. @pytest.mark.asyncio
  2044. @patch("backend.app.services.print_scheduler.printer_manager")
  2045. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  2046. async def test_toggle_off_drops_a_leftover_streak_entry(self, mock_sd, mock_pm, scheduler):
  2047. """An entry armed while the feature was on is dropped once it is off,
  2048. so toggling back on later cannot inherit a stale streak."""
  2049. mock_pm.get_status.return_value = self._state()
  2050. mock_pm.is_connected.return_value = True
  2051. mock_pm.get_model.return_value = "X1C"
  2052. mock_pm.send_drying_command.return_value = True
  2053. scheduler._is_printer_idle = MagicMock(return_value=True)
  2054. scheduler._auto_dry_above[self.UNIT_KEY] = {
  2055. "since": time.monotonic() - 30,
  2056. "last": time.monotonic() - 1,
  2057. }
  2058. await scheduler._check_auto_drying(self._db(sustained_minutes=0), [], set())
  2059. assert self.UNIT_KEY not in scheduler._auto_dry_above
  2060. @pytest.mark.asyncio
  2061. @patch("backend.app.services.print_scheduler.printer_manager")
  2062. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  2063. async def test_disabling_all_auto_drying_drops_streak_before_early_return(self, mock_sd, mock_pm, scheduler):
  2064. """A quick disable/re-enable must start a fresh wait, even though the
  2065. disabled pass returns before visiting individual AMS units."""
  2066. mock_pm.get_status.return_value = self._state()
  2067. mock_pm.is_connected.return_value = True
  2068. mock_pm.get_model.return_value = "X1C"
  2069. mock_pm.send_drying_command.return_value = True
  2070. scheduler._is_printer_idle = MagicMock(return_value=True)
  2071. scheduler._auto_dry_above[self.UNIT_KEY] = {
  2072. "since": time.monotonic() - 360,
  2073. "last": time.monotonic() - 1,
  2074. }
  2075. await scheduler._check_auto_drying(self._db(sustained_minutes=5, ambient_enabled="false"), [], set())
  2076. assert self.UNIT_KEY not in scheduler._auto_dry_above
  2077. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  2078. mock_pm.send_drying_command.assert_not_called()
  2079. assert self.UNIT_KEY in scheduler._auto_dry_above
  2080. @pytest.mark.asyncio
  2081. @patch("backend.app.services.print_scheduler.printer_manager")
  2082. @patch("backend.app.services.print_scheduler.supports_drying", return_value=True)
  2083. async def test_firmware_refusal_skips_before_the_wait_logs(self, mock_sd, mock_pm, scheduler, caplog):
  2084. """A unit the firmware refuses to dry (dry_sf_reason set) hits its skip
  2085. before the sustained wait, so it never logs "waiting" for a dry it was
  2086. never going to get (review nit on #2895)."""
  2087. import logging
  2088. state = self._state()
  2089. state.raw_data["ams"][0]["dry_sf_reason"] = ["8"]
  2090. mock_pm.get_status.return_value = state
  2091. mock_pm.is_connected.return_value = True
  2092. mock_pm.get_model.return_value = "X1C"
  2093. scheduler._is_printer_idle = MagicMock(return_value=True)
  2094. with caplog.at_level(logging.DEBUG, logger="backend.app.services.print_scheduler"):
  2095. await scheduler._check_auto_drying(self._db(sustained_minutes=5), [], set())
  2096. messages = [rec.getMessage() for rec in caplog.records]
  2097. assert any("cannot dry reasons" in m for m in messages)
  2098. assert not any("waiting" in m for m in messages)