print_scheduler.py 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. from dataclasses import dataclass
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. from sqlalchemy import func, select, update
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from sqlalchemy.orm import selectinload
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import async_session, run_with_retry
  14. from backend.app.core.tasks import spawn_background_task
  15. from backend.app.core.websocket import ws_manager
  16. from backend.app.models.archive import PrintArchive
  17. from backend.app.models.library import LibraryFile
  18. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  19. from backend.app.models.printer import Printer
  20. from backend.app.models.settings import Settings
  21. from backend.app.models.smart_plug import SmartPlug
  22. from backend.app.models.spool_assignment import SpoolAssignment
  23. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  24. from backend.app.services import print_dispatch_context
  25. from backend.app.services.bambu_ftp import (
  26. UploadCancelled,
  27. cache_3mf_download,
  28. delete_file_async,
  29. get_ftp_retry_settings,
  30. upload_file_async,
  31. with_ftp_retry,
  32. )
  33. from backend.app.services.bambu_mqtt import HMS_MQTT_VERIFY_FAILED
  34. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  35. from backend.app.services.notification_service import notification_service
  36. from backend.app.services.printer_manager import (
  37. printer_manager,
  38. supports_airduct,
  39. supports_chamber_heater,
  40. supports_chamber_temp,
  41. supports_drying,
  42. supports_drying_while_printing,
  43. )
  44. from backend.app.services.smart_plug_manager import smart_plug_manager
  45. from backend.app.utils.filename import derive_remote_filename
  46. from backend.app.utils.printer_models import is_gcode_compatible, normalize_printer_model
  47. logger = logging.getLogger(__name__)
  48. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  49. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  50. # byte gate) from before the scheduler unification. Time gate keeps small
  51. # files from going silent (a single 8 KB chunk fires once and that's it);
  52. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  53. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  54. # sub-200 ms files.
  55. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  56. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  57. class _UploadProgressBridge:
  58. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  59. ``upload_file_async`` runs the FTP transfer in an executor thread and
  60. invokes its ``progress_callback`` from that thread, so the callback
  61. body cannot ``await`` directly. This bridge captures the asyncio loop
  62. at construction (on the scheduler thread) and uses
  63. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  64. matches the legacy background_dispatch.py path 1:1 so the toast feels
  65. identical to the pre-#1625 experience.
  66. Failures inside the emit are swallowed — progress is a UX nicety, the
  67. upload itself must not fail because of a WS hiccup.
  68. """
  69. def __init__(self, user_id: int | None, queue_item_id: int):
  70. self._user_id = user_id
  71. self._queue_item_id = queue_item_id
  72. try:
  73. self._loop = asyncio.get_running_loop()
  74. except RuntimeError:
  75. self._loop = None
  76. self._last_emit_bytes = 0
  77. self._last_emit_monotonic = 0.0
  78. self._has_emitted = False
  79. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  80. if self._loop is None or total_bytes <= 0:
  81. return
  82. now = time.monotonic()
  83. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  84. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  85. # the four matter most: first-call so the user sees something even
  86. # for sub-chunk-size files; uploaded >= total so the bar locks at
  87. # 100% even when the throttle would otherwise eat it.
  88. should_emit = (
  89. not self._has_emitted
  90. or bytes_transferred >= total_bytes
  91. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  92. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  93. )
  94. if not should_emit:
  95. return
  96. self._has_emitted = True
  97. self._last_emit_bytes = bytes_transferred
  98. self._last_emit_monotonic = now
  99. try:
  100. asyncio.run_coroutine_threadsafe(
  101. ws_manager.send_queue_item_upload_progress(
  102. user_id=self._user_id,
  103. queue_item_id=self._queue_item_id,
  104. bytes_transferred=bytes_transferred,
  105. total_bytes=total_bytes,
  106. ),
  107. self._loop,
  108. )
  109. except Exception:
  110. pass # progress is best-effort, never block the upload
  111. # Bambu firmware states that mean the project_file has actually been accepted
  112. # and the printer is now processing / running / paused mid-print. Used by the
  113. # dispatch watchdog (#1370): a transition into one of these states means the
  114. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  115. # a post-print prompt) is NOT a valid "command landed" signal even though the
  116. # state value did change. SLICING is included because some firmwares park
  117. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  118. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  119. # How many times the start-watchdog may revert an item to 'pending' before it
  120. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  121. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  122. # both never recovers and starves the other printers of dispatch slots. Three
  123. # is chosen to clear the transient causes the watchdog already recovers from —
  124. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  125. # force-reconnect on the very next attempt — while still bounding the loop.
  126. DISPATCH_MAX_ATTEMPTS = 3
  127. # Filament type equivalence groups — types within the same group are
  128. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  129. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  130. ["PA-CF", "PA12-CF", "PAHT-CF"],
  131. ]
  132. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  133. for _group in _FILAMENT_TYPE_GROUPS:
  134. _canonical = _group[0].upper()
  135. for _t in _group:
  136. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  137. def _canonical_filament_type(ftype: str) -> str:
  138. """Return canonical type for equivalence matching."""
  139. upper = ftype.upper()
  140. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  141. @dataclass(slots=True)
  142. class _ModelCandidate:
  143. """One (file, printer model) pair the model-based matcher may try.
  144. Model-based assignment used to have exactly one of these per item, held
  145. directly in the item's own columns. Cross-model queue items (#671) have
  146. several, held in ``print_queue_variants``. Both shapes are normalised into
  147. this so the matching, the cross-model gate and the waiting-reason handling
  148. are written once and an item without variants provably takes the same path
  149. it took before variants existed.
  150. ``variant`` is None for the item's own columns and set for a real variant
  151. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  152. item once that candidate wins.
  153. """
  154. target_model: str | None
  155. sliced_for: str | None
  156. required_filament_types: str | None
  157. filament_overrides: str | None
  158. variant: "PrintQueueVariant | None" = None
  159. def _sliced_for_model(archive, library_file) -> str | None:
  160. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  161. if archive is not None:
  162. return archive.sliced_for_model
  163. if library_file is not None and library_file.file_metadata:
  164. return library_file.file_metadata.get("sliced_for_model")
  165. return None
  166. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  167. """Candidate files for ``item``, best first.
  168. An item with no variant rows yields exactly one candidate built from its own
  169. columns — the pre-#671 behaviour, unchanged.
  170. Variants come back least-attempted first, ties broken by the user's
  171. ``position``. On the first pass every count is zero, so this is purely the
  172. user's priority order. After a start-watchdog bounce the printer that failed
  173. drops behind, so the next lap tries the other machine rather than spending the
  174. item's whole retry budget on the one that is wedged. Once every candidate has
  175. been tried equally often they cycle again, which keeps the item-level
  176. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  177. still gives up, it just does not give up without trying them.
  178. """
  179. if not item.variants:
  180. if not item.archive_id and not item.library_file_id:
  181. # Nothing to print at all. Dispatching would fail deep in the upload
  182. # on "No archive_id or library_file_id"; the caller holds the item
  183. # with an explanation instead.
  184. return []
  185. return [
  186. _ModelCandidate(
  187. target_model=item.target_model,
  188. sliced_for=_sliced_for_model(item.archive, item.library_file),
  189. required_filament_types=item.required_filament_types,
  190. filament_overrides=item.filament_overrides,
  191. )
  192. ]
  193. # Drop candidates whose file is gone or in the trash. Both are reachable and
  194. # neither is covered by the schema: library deletes are soft (the row lives
  195. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  196. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  197. # fires there and a hard delete leaves the variant row pointing at nothing.
  198. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  199. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  200. return [
  201. _ModelCandidate(
  202. target_model=v.target_model,
  203. sliced_for=_sliced_for_model(None, v.library_file),
  204. required_filament_types=v.required_filament_types,
  205. filament_overrides=v.filament_overrides,
  206. variant=v,
  207. )
  208. for v in ordered
  209. ]
  210. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  211. """Fold one waiting reason per candidate into a single line for the item.
  212. A cross-model item produces a reason per candidate, and pasting them
  213. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  214. — on which machine?). Each reason is prefixed with its model, except in the
  215. single-candidate case where the item already displays its target model and
  216. the prefix would be noise.
  217. Identical reasons collapse rather than repeat, so three idle-less models
  218. read as one clause.
  219. When *every* candidate is merely busy the parts are joined with the ``" | "``
  220. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  221. unprefixed. That case must keep testing busy-only: a fleet that is simply
  222. printing needs no user action, and labelling the clauses would turn each pass
  223. over a two-model item into a "job waiting" notification.
  224. """
  225. reasons = [(model, reason) for model, reason in per_model if reason]
  226. if not reasons:
  227. return None
  228. if len(reasons) == 1:
  229. return reasons[0][1]
  230. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  231. if len(distinct) == 1:
  232. return distinct[0]
  233. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  234. return " | ".join(distinct)
  235. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  236. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  237. """Human label for the models an item is waiting on ("H2S or H2C").
  238. Notifications take a single target model. For a cross-model item the item's
  239. own ``target_model`` is whichever variant happens to be first, which reads as
  240. a lie once it is the H2C that actually runs — so name all of them.
  241. """
  242. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  243. if not models:
  244. return None
  245. return " or ".join(models)
  246. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  247. """True if ``mapping`` is a non-empty list whose every entry is the
  248. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  249. Such a mapping is a bug artifact: a frontend status-load race can serialize
  250. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  251. recomputed from live status at dispatch rather than trusted, otherwise it
  252. reaches the print command and is silently downgraded to external-spool mode.
  253. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  254. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  255. explicit external selection (``>= 254``) is NOT unresolved either — those
  256. keep their meaning.
  257. """
  258. if not isinstance(mapping, list) or not mapping:
  259. return False
  260. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  261. def _mqtt_commands_rejected(status) -> bool:
  262. """True when the printer is currently reporting that it refused a command.
  263. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  264. a control command it could not verify. Queries still answer, so the printer
  265. looks connected and idle while project_file, gcode_line and
  266. ams_change_filament are all dropped — no amount of waiting or re-uploading
  267. changes that (#2732).
  268. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  269. ``print_error`` path builds HMSError differently), so this is safe to call on
  270. every watchdog poll.
  271. """
  272. for err in getattr(status, "hms_errors", None) or []:
  273. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  274. return True
  275. return False
  276. def _drying_ams_ids(status) -> list[int]:
  277. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  278. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  279. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  280. started (#2758) — it is a diagnostic, not a gate.
  281. Deliberately not used to block or stop drying before dispatch. This printer
  282. class supports drying concurrently with an active print
  283. (``supports_drying_while_printing``), so drying is not incompatible with
  284. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  285. while two AMS units were drying, one of them without its external PSU. Until
  286. it is known whether the blocker is drying itself or the power budget
  287. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  288. hardware is perfectly happy to continue.
  289. """
  290. ids: list[int] = []
  291. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  292. if not isinstance(unit, dict):
  293. continue
  294. try:
  295. if int(unit.get("dry_time") or 0) > 0:
  296. ids.append(int(unit.get("id", 0)))
  297. except (TypeError, ValueError):
  298. continue
  299. return ids
  300. def _installed_nozzle_diameters(status) -> list[float]:
  301. """Parse the installed nozzle diameters from a PrinterState (#1899).
  302. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  303. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  304. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  305. told us its nozzle hardware" — callers must treat that as unknown, not as a
  306. mismatch, so we never block a print on missing data.
  307. """
  308. diameters: list[float] = []
  309. for nozzle in getattr(status, "nozzles", None) or []:
  310. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  311. try:
  312. value = float(raw)
  313. except (TypeError, ValueError):
  314. continue
  315. if value > 0:
  316. diameters.append(value)
  317. return diameters
  318. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  319. """Return an actionable error message when the sliced nozzle can't be
  320. printed on any installed nozzle, else None (#1899).
  321. Fail-safe: returns None whenever we lack the data to judge — no sliced
  322. diameter, or the printer reported no nozzles — so a print is only ever
  323. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  324. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  325. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  326. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  327. """
  328. if not sliced_nozzle or not installed:
  329. return None
  330. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  331. return None
  332. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  333. return (
  334. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  335. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  336. f"install the matching nozzle before printing."
  337. )
  338. class PrintScheduler:
  339. """Background scheduler that processes the print queue."""
  340. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  341. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  342. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  343. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  344. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  345. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  346. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  347. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  348. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  349. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  350. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  351. }
  352. def __init__(self):
  353. self._running = False
  354. self._check_interval = 30 # seconds
  355. # After a pass that actually dispatched something, loop again almost
  356. # immediately instead of sleeping the full interval (#2555). A dispatch
  357. # changes printer state — a batch launch fans out over several passes as
  358. # printers free up, a wedged head-of-line job reverts to pending, an
  359. # upload slot opens — and the next batch of ready work should not have to
  360. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  361. # pending items are behind printers that are genuinely busy printing),
  362. # there is nothing to react to, so we fall back to the normal interval;
  363. # that also means this can never tight-loop, since fast ticks only
  364. # continue while dispatches keep happening and the queue is draining.
  365. self._fast_check_interval = 3 # seconds
  366. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  367. self._power_on_check_interval = 10 # seconds between connection checks
  368. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  369. self._drying_in_progress: dict[int, float] = {}
  370. # Defensive in-memory dispatch hold (#1157): a printer that just received
  371. # a project_file command must not get a second dispatch until either it
  372. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  373. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  374. # during that window the DB busy_printers seed is empirically unreliable
  375. # (multi-plate batches double-/triple-dispatched onto the same printer
  376. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  377. # or revert.
  378. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  379. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  380. # Minimum cooldown between dispatches to the same printer (covers the
  381. # H2D's project_file digestion window).
  382. self._dispatch_min_cooldown = 60.0
  383. # Hard timeout — drop the hold even if we never observed a transition,
  384. # so a lost MQTT session can't lock a printer out of the queue forever.
  385. # Matches the watchdog timeout (90 s) plus a safety margin so the
  386. # watchdog runs first on the unhappy path.
  387. self._dispatch_max_hold = 180.0
  388. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  389. # an earlier pass and is still running. `_start_print` flips the row
  390. # pending -> printing only *after* the upload completes, so until then
  391. # the row stays `pending`: each tick, check_queue excludes these
  392. # item_ids from re-selection and their printers from new dispatch /
  393. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  394. # freed slots refill on the next fast tick. check_queue is the sole,
  395. # sequential caller and the prune done-callbacks run in the same
  396. # event-loop thread, so this dict needs no lock.
  397. # item_id -> (task, printer_id)
  398. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  399. # Expected prints registered by `_start_print` that have not yet had a
  400. # print command sent. Populated at registration, dropped once
  401. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  402. # other exit. Same threading argument as `_inflight` above: one
  403. # sequential caller, callbacks on the same loop, so no lock.
  404. # item_id -> (printer_id, remote_filename, archive_id)
  405. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  406. async def run(self):
  407. """Main loop - check queue every interval."""
  408. self._running = True
  409. logger.info("Print scheduler started")
  410. await self._clear_stale_dispatch_claims(at_startup=True)
  411. while self._running:
  412. dispatched = False
  413. try:
  414. # No-op while any upload is in flight; on a quiet tick it releases
  415. # a claim whose best-effort clear failed (e.g. the database was
  416. # briefly unreachable), instead of leaving the row wedged until
  417. # the next restart.
  418. await self._clear_stale_dispatch_claims()
  419. dispatched = await self.check_queue()
  420. except Exception as e:
  421. logger.error("Scheduler error: %s", e)
  422. # Re-check quickly after a productive pass so a draining batch does
  423. # not stall behind the idle interval; otherwise sleep normally (#2555).
  424. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  425. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  426. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  427. A claim is only ever held by a live dispatch coroutine, so when this
  428. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  429. is stale. At startup that is trivially true — no coroutine survives a
  430. restart. It is equally true on any later tick where no upload is running,
  431. which is what makes this safe to repeat rather than only run once.
  432. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  433. the database is briefly unreachable at exactly the moment dispatch ends,
  434. the claim survives and the row is wedged out of the selection query. That
  435. used to last until the next restart (#2702 follow-up, seen when
  436. PostgreSQL refused a connection mid-dispatch).
  437. ``_inflight`` is populated when the task is spawned, before the coroutine
  438. claims its row, and pruned by a done-callback that cannot run before the
  439. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  440. race window and needs no age threshold. A size-derived upload deadline
  441. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  442. """
  443. if self._inflight:
  444. return
  445. try:
  446. async with async_session() as db:
  447. res = await db.execute(
  448. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  449. )
  450. await db.commit()
  451. if res.rowcount:
  452. logger.info(
  453. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  454. res.rowcount,
  455. " at startup" if at_startup else "",
  456. )
  457. except Exception as exc:
  458. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  459. def stop(self):
  460. """Stop the scheduler."""
  461. self._running = False
  462. logger.info("Print scheduler stopped")
  463. async def check_queue(self) -> bool:
  464. """Check for prints ready to start.
  465. Returns True if this pass dispatched at least one item, so the caller
  466. can loop again quickly instead of sleeping the full interval (#2555).
  467. """
  468. async with async_session() as db:
  469. # Check if shortest-job-first scheduling is enabled
  470. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  471. # Get all pending items, ordered by printer and position (or SJF order)
  472. if sjf_enabled:
  473. # SJF: group by printer (and target_model for model-based jobs),
  474. # then items already jumped get top priority (starvation guard),
  475. # then sort by print_time ascending. Items with no print time go last.
  476. result = await db.execute(
  477. select(PrintQueueItem)
  478. .where(PrintQueueItem.status == "pending")
  479. # Never re-select a row a dispatch worker has already claimed
  480. # (#2615) — belt-and-suspenders with the _inflight exclusion
  481. # below, and the guard that lets an orphaned claim be ignored
  482. # until startup reconciliation clears it.
  483. .where(PrintQueueItem.dispatching_at.is_(None))
  484. # archive/library_file are read by the cross-model gate
  485. # (#2578); eager-load once per pass instead of a lazy-load
  486. # (which would raise in async) per item.
  487. .options(
  488. selectinload(PrintQueueItem.archive),
  489. selectinload(PrintQueueItem.library_file),
  490. # Cross-model candidates (#671), plus each candidate's file
  491. # for the same cross-model gate. Lazy-loading either would
  492. # raise in async.
  493. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  494. )
  495. .order_by(
  496. PrintQueueItem.printer_id,
  497. PrintQueueItem.target_model,
  498. PrintQueueItem.been_jumped.desc(),
  499. PrintQueueItem.print_time_seconds.asc().nullslast(),
  500. PrintQueueItem.position,
  501. )
  502. )
  503. else:
  504. result = await db.execute(
  505. select(PrintQueueItem)
  506. .where(PrintQueueItem.status == "pending")
  507. # Skip rows already claimed by a dispatch worker (#2615).
  508. .where(PrintQueueItem.dispatching_at.is_(None))
  509. .options(
  510. selectinload(PrintQueueItem.archive),
  511. selectinload(PrintQueueItem.library_file),
  512. # Cross-model candidates (#671), plus each candidate's file
  513. # for the same cross-model gate. Lazy-loading either would
  514. # raise in async.
  515. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  516. )
  517. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  518. )
  519. items = list(result.scalars().all())
  520. # Drop rows whose upload is still in flight from an earlier pass
  521. # (#2602). They stay `pending` until the upload finishes, so without
  522. # this a fast tick would re-select and re-dispatch the same row.
  523. # Belt-and-suspenders with the printer exclusion below.
  524. if self._inflight:
  525. inflight_ids = set(self._inflight)
  526. items = [it for it in items if it.id not in inflight_ids]
  527. # Read plate-clear setting once per queue check. Default MUST be
  528. # False to match the schema (SettingsSchema.require_plate_clear
  529. # defaults False) and the frontend (toggle + card badge both treat a
  530. # missing value as off). When no settings row exists, a True default
  531. # here re-enabled the plate-clear gate the UI showed as disabled,
  532. # blocking dispatch to FINISH-state printers forever with no UI path
  533. # to clear it (#1865).
  534. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  535. if not items:
  536. # No dispatchable pending items — still check auto-drying on idle
  537. # printers, but keep any printer with an upload still in flight
  538. # from an earlier pass out of it (#2602): its print is imminent,
  539. # so it must not be auto-dried in the gap before the row flips to
  540. # printing. Report the pass as productive while uploads run so the
  541. # loop stays on the fast interval.
  542. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  543. await self._check_auto_drying(db, [], inflight_printers, require_plate_clear=require_plate_clear)
  544. return bool(self._inflight)
  545. logger.info(
  546. "Queue check: found %d pending items: %s",
  547. len(items),
  548. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  549. )
  550. # Seed busy_printers with printers that already have an item in 'printing'
  551. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  552. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  553. # lag several seconds behind the print command, so the next check_queue
  554. # tick still sees IDLE and would double-dispatch onto the same printer.
  555. # Without this guard, two pending items targeting the same printer
  556. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  557. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  558. busy_result = await db.execute(
  559. select(PrintQueueItem.printer_id)
  560. .where(PrintQueueItem.status == "printing")
  561. .where(PrintQueueItem.printer_id.is_not(None))
  562. )
  563. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  564. # Defense-in-depth (#1157): augment busy_printers with any printer
  565. # still in its post-dispatch hold window. Empirically, the DB seed
  566. # above can miss in-flight items in a multi-plate batch — same-file
  567. # plates were being dispatched 30 s apart while the H2D was still
  568. # digesting the first project_file. The hold is keyed in-memory and
  569. # released by the watchdog on the success path, so it adds a layer
  570. # that doesn't depend on DB row visibility or completion-callback
  571. # timing.
  572. for held_printer_id in list(self._dispatch_holds.keys()):
  573. if self._printer_in_dispatch_hold(held_printer_id):
  574. busy_printers.add(held_printer_id)
  575. # Exclude printers whose upload is still in flight from an earlier
  576. # pass (#2602). The row is `pending` until the upload finishes and
  577. # the printing-state seed / dispatch hold above only arm once the
  578. # upload completes, so this is what holds the printer (and, via
  579. # busy_printers, its auto-drying) out of the pass during the upload.
  580. for _task, inflight_pid in self._inflight.values():
  581. if inflight_pid is not None:
  582. busy_printers.add(inflight_pid)
  583. # Log skip reasons once per queue check (not per item)
  584. skip_reasons: dict[str, int] = {}
  585. # Items selected for dispatch in this pass, one per printer. The
  586. # loop below only *decides* — the uploads happen afterwards, in
  587. # parallel (#2555). See _dispatch_selected().
  588. dispatch_ids: list[int] = []
  589. # Library rows queued with `cleanup_library_after_dispatch` (the
  590. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  591. # that prints them: the row is deleted and the 3MF is unlinked from
  592. # disk. That was safe only because dispatch was serial. Run two of
  593. # them against the same row at once and the second DELETE matches no
  594. # row (StaleDataError), and the winner's unlink can pull the file out
  595. # from under the loser's in-flight upload.
  596. #
  597. # Only the cleanup flag mutates the row. An ordinary library print
  598. # just reads it, so the common fan-out — one file, many printers,
  599. # which is exactly the reporter's workload — still goes out fully in
  600. # parallel. Narrow the guard to the mutating case; do not serialise
  601. # the case the whole fix exists for.
  602. dispatch_libs: set[int] = set()
  603. consumed_libs: set[int] = set()
  604. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  605. """True if dispatching `candidate` now would race another item's cleanup."""
  606. lib_id = candidate.library_file_id
  607. if lib_id is None:
  608. return False
  609. if candidate.cleanup_library_after_dispatch:
  610. # We would delete a row someone else in this pass is reading.
  611. return lib_id in dispatch_libs
  612. # Someone else in this pass will delete the row out from under us.
  613. return lib_id in consumed_libs
  614. def _claim_library_row(candidate: PrintQueueItem) -> None:
  615. lib_id = candidate.library_file_id
  616. if lib_id is None:
  617. return
  618. dispatch_libs.add(lib_id)
  619. if candidate.cleanup_library_after_dispatch:
  620. consumed_libs.add(lib_id)
  621. for item in items:
  622. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  623. if item.scheduled_time:
  624. sched = item.scheduled_time
  625. if sched.tzinfo is None:
  626. sched = sched.replace(tzinfo=timezone.utc)
  627. if sched > datetime.now(timezone.utc):
  628. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  629. continue
  630. # Skip items that require manual start
  631. if item.manual_start:
  632. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  633. continue
  634. if item.printer_id:
  635. # Specific printer assignment (existing behavior)
  636. if item.printer_id in busy_printers:
  637. continue
  638. # Check if printer is idle
  639. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  640. printer_connected = printer_manager.is_connected(item.printer_id)
  641. # If printer not connected, try to power on via smart plug
  642. if not printer_connected:
  643. plugs = await self._get_smart_plugs(db, item.printer_id)
  644. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  645. if auto_on_plugs:
  646. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  647. # Power on using the plug that actually feeds the printer, and
  648. # wait for it to boot on that one only (#2629).
  649. primary_plug = self._pick_power_plug(auto_on_plugs)
  650. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  651. if powered_on:
  652. # Also turn on any remaining auto_on plugs (e.g., filter)
  653. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  654. try:
  655. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  656. await service.turn_on(extra_plug)
  657. logger.info(
  658. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  659. )
  660. except Exception as e:
  661. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  662. printer_connected = True
  663. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  664. else:
  665. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  666. busy_printers.add(item.printer_id)
  667. continue
  668. else:
  669. # No plug or auto_on disabled
  670. busy_printers.add(item.printer_id)
  671. continue
  672. # Check if printer is idle (busy with another print)
  673. if not printer_idle:
  674. # If printer is drying (not truly busy), handle based on queue_drying_block
  675. if self._drying_in_progress.get(item.printer_id):
  676. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  677. if block_for_drying:
  678. # Drying blocks queue — skip this printer
  679. busy_printers.add(item.printer_id)
  680. continue
  681. else:
  682. # Print takes priority — stop drying
  683. await self._stop_drying(item.printer_id)
  684. # Re-check idle after stopping drying
  685. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  686. if not printer_idle:
  687. busy_printers.add(item.printer_id)
  688. continue
  689. else:
  690. busy_printers.add(item.printer_id)
  691. continue
  692. # Check condition (previous print success)
  693. if item.require_previous_success:
  694. if not await self._check_previous_success(db, item):
  695. item.status = "skipped"
  696. item.error_message = "Previous print failed or was aborted"
  697. item.completed_at = datetime.now(timezone.utc)
  698. await db.commit()
  699. logger.info("Skipped queue item %s - previous print failed", item.id)
  700. # Send notification
  701. job_name = await self._get_job_name(db, item)
  702. printer = await self._get_printer(db, item.printer_id)
  703. await notification_service.on_queue_job_skipped(
  704. job_name=job_name,
  705. printer_id=item.printer_id,
  706. printer_name=printer.name if printer else "Unknown",
  707. reason="Previous print failed or was aborted",
  708. db=db,
  709. )
  710. continue
  711. # Resolve the AMS mapping when it's missing OR unresolved
  712. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  713. # frontend status-load race can persist [-1] (#2589) — and
  714. # must be recomputed from live trays rather than trusted.
  715. await self._ensure_ams_mapping(db, item.printer_id, item)
  716. # Filament-deficit pre-dispatch check (#1496). If the
  717. # assigned spool can't satisfy any required slot grams,
  718. # promote the item to manual_start so the user must
  719. # acknowledge via the ▶ button (which re-checks live).
  720. if await self._block_on_filament_deficit(db, item):
  721. continue
  722. # Hold this item back for the next pass rather than racing
  723. # another dispatch over the same transient library row. The
  724. # printer is still marked busy so a later item does not jump
  725. # its place in this printer's queue.
  726. if _library_row_conflict(item):
  727. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  728. busy_printers.add(item.printer_id)
  729. continue
  730. # Queue the dispatch instead of running it here — see
  731. # _dispatch_selected(). busy_printers still gets the printer
  732. # immediately, so nothing else in this pass can target it.
  733. _claim_library_row(item)
  734. dispatch_ids.append(item.id)
  735. busy_printers.add(item.printer_id)
  736. # SJF starvation guard: mark items that were jumped
  737. if sjf_enabled and item.print_time_seconds is not None:
  738. for other in items:
  739. if (
  740. other.id != item.id
  741. and other.status == "pending"
  742. and other.printer_id == item.printer_id
  743. and not other.been_jumped
  744. and other.position < item.position
  745. and (
  746. other.print_time_seconds is None
  747. or other.print_time_seconds > item.print_time_seconds
  748. )
  749. ):
  750. other.been_jumped = True
  751. await db.commit()
  752. elif item.target_model or item.variants:
  753. # Model-based assignment - find any idle printer of matching model.
  754. # A plain model-based item has exactly one candidate, built from
  755. # its own columns. A cross-model item (#671) has one per sliced
  756. # variant and takes the first that matches, walking them in the
  757. # user's priority order so the pick is reproducible when more
  758. # than one printer is free in the same pass.
  759. candidates = _candidates_for(item)
  760. printer_id = None
  761. chosen: _ModelCandidate | None = None
  762. per_model_reasons: list[tuple[str | None, str]] = []
  763. if not candidates:
  764. # Every candidate file has been deleted or trashed out from
  765. # under this item. Hold it with something the user can act
  766. # on rather than letting it look dispatchable forever.
  767. per_model_reasons.append(
  768. (
  769. item.target_model,
  770. "Every file for this job has been deleted — add a file back or remove the item",
  771. )
  772. )
  773. for candidate in candidates:
  774. # Parse required filament types if present
  775. required_types = None
  776. if candidate.required_filament_types:
  777. try:
  778. required_types = json.loads(candidate.required_filament_types)
  779. except json.JSONDecodeError:
  780. pass # Ignore malformed filament types; treat as no constraint
  781. # Parse filament overrides if present
  782. filament_overrides = None
  783. if candidate.filament_overrides:
  784. try:
  785. filament_overrides = json.loads(candidate.filament_overrides)
  786. except json.JSONDecodeError:
  787. pass
  788. # If overrides exist, use override types for validation instead
  789. effective_types = required_types
  790. if filament_overrides:
  791. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  792. if override_types:
  793. # Merge: keep original types for non-overridden slots, add override types
  794. effective_types = sorted(set(required_types or []) | set(override_types))
  795. # Cross-model safety gate (#2578): never hand a 3MF sliced
  796. # for an incompatible model to a printer, no matter how the
  797. # row got into the DB (old rows, direct API writes). Held
  798. # as pending with an actionable waiting_reason — the user
  799. # fixes it by editing the item's target model.
  800. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  801. per_model_reasons.append(
  802. (
  803. candidate.target_model,
  804. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  805. f"{candidate.target_model} — edit the item and fix its target model",
  806. )
  807. )
  808. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  809. continue
  810. match_id, match_reason = await self._find_idle_printer_for_model(
  811. db,
  812. candidate.target_model,
  813. busy_printers,
  814. effective_types,
  815. item.target_location,
  816. filament_overrides=filament_overrides,
  817. require_plate_clear=require_plate_clear,
  818. )
  819. if match_id:
  820. printer_id = match_id
  821. chosen = candidate
  822. break
  823. per_model_reasons.append((candidate.target_model, match_reason or ""))
  824. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  825. # Fold the winning variant's file and settings onto the item
  826. # before anything else looks at them — the guards below and
  827. # every step of the dispatch read the item's own columns.
  828. if chosen is not None:
  829. self._resolve_variant(item, chosen)
  830. # Update waiting_reason if changed and send notification when first waiting
  831. if item.waiting_reason != waiting_reason:
  832. was_waiting = item.waiting_reason is not None
  833. item.waiting_reason = waiting_reason
  834. await db.commit()
  835. # Send waiting notification only when transitioning to waiting state
  836. # and the reason requires user action (not just "all printers busy")
  837. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  838. job_name = await self._get_job_name(db, item)
  839. await notification_service.on_queue_job_waiting(
  840. job_name=job_name,
  841. target_model=_candidate_model_label(candidates) or item.target_model,
  842. waiting_reason=waiting_reason,
  843. db=db,
  844. )
  845. if printer_id:
  846. # Before claiming the printer: hold back rather than race
  847. # another dispatch over the same transient library row.
  848. # Checked here so a held item does not get a printer
  849. # assigned and then sit on it. See _library_row_conflict().
  850. #
  851. # No busy_printers.add() here, unlike the fixed-printer
  852. # branch above: that one protects its printer's own queue
  853. # ordering, but this item was never assigned to `printer_id`
  854. # — the matcher merely offered it. Marking it busy would
  855. # strand an idle printer for the rest of the pass.
  856. if _library_row_conflict(item):
  857. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  858. continue
  859. # Check condition (previous print success) before assigning
  860. if item.require_previous_success:
  861. if not await self._check_previous_success(db, item):
  862. item.status = "skipped"
  863. item.error_message = "Previous print failed or was aborted"
  864. item.completed_at = datetime.now(timezone.utc)
  865. await db.commit()
  866. logger.info("Skipped queue item %s - previous print failed", item.id)
  867. # Send notification
  868. job_name = await self._get_job_name(db, item)
  869. printer = await self._get_printer(db, printer_id)
  870. await notification_service.on_queue_job_skipped(
  871. job_name=job_name,
  872. printer_id=printer_id,
  873. printer_name=printer.name if printer else "Unknown",
  874. reason="Previous print failed or was aborted",
  875. db=db,
  876. )
  877. continue
  878. # Assign printer and start - clear waiting reason
  879. item.printer_id = printer_id
  880. item.waiting_reason = None
  881. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  882. # Send assignment notification
  883. job_name = await self._get_job_name(db, item)
  884. printer = await self._get_printer(db, printer_id)
  885. await notification_service.on_queue_job_assigned(
  886. job_name=job_name,
  887. printer_id=printer_id,
  888. printer_name=printer.name if printer else "Unknown",
  889. target_model=item.target_model,
  890. db=db,
  891. )
  892. # Resolve the AMS mapping for the assigned printer when it's
  893. # missing OR unresolved (all -1). Critical for model-based
  894. # jobs where mapping wasn't computed upfront, and it also
  895. # self-heals a bogus stored [-1] (#2589).
  896. await self._ensure_ams_mapping(db, printer_id, item)
  897. # Filament-deficit pre-dispatch check (#1496).
  898. if await self._block_on_filament_deficit(db, item):
  899. continue
  900. _claim_library_row(item)
  901. dispatch_ids.append(item.id)
  902. busy_printers.add(printer_id)
  903. # SJF starvation guard: mark model-based items that were jumped
  904. if sjf_enabled and item.print_time_seconds is not None:
  905. for other in items:
  906. if (
  907. other.id != item.id
  908. and other.status == "pending"
  909. and other.printer_id is None
  910. and other.target_model
  911. and other.target_model.upper() == item.target_model.upper()
  912. and not other.been_jumped
  913. and other.position < item.position
  914. and (
  915. other.print_time_seconds is None
  916. or other.print_time_seconds > item.print_time_seconds
  917. )
  918. ):
  919. other.been_jumped = True
  920. await db.commit()
  921. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  922. # as long as the slowest upload takes (minutes on a big 3MF), and a
  923. # skip summary that only lands after the transfers have finished is
  924. # useless for working out why an item did not go out.
  925. if skip_reasons:
  926. logger.info("Queue skip summary: %s", skip_reasons)
  927. if busy_printers:
  928. # Log why each printer was busy (first time it was checked)
  929. for pid in busy_printers:
  930. state = printer_manager.get_status(pid)
  931. connected = printer_manager.is_connected(pid)
  932. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  933. state_name = state.state if state else "NO_STATUS"
  934. logger.info(
  935. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  936. pid,
  937. connected,
  938. state_name,
  939. awaiting,
  940. )
  941. # Read the concurrency limit BEFORE the commit below, not inside
  942. # _dispatch_selected(). A SELECT on this session after the commit
  943. # implicitly opens a fresh transaction that nothing then closes, and
  944. # it would stay open for the whole dispatch — minutes of "idle in
  945. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  946. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  947. # checkpointed while every dispatch is writing to it.
  948. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  949. # Selection is done; every decision above is recorded on `db`
  950. # (model-based printer assignment, computed ams_mapping). Flush it
  951. # before the dispatch tasks open their own sessions, or they will
  952. # read a row that still says printer_id=None. This also releases the
  953. # connection back to the pool for the duration of the dispatch.
  954. await db.commit()
  955. if dispatch_ids:
  956. item_printers = {it.id: it.printer_id for it in items}
  957. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  958. # Auto-drying: start drying on idle printers that have no pending queue items
  959. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  960. # Keep the loop on the fast interval while any upload is in flight so
  961. # a slot freed mid-tick refills within seconds rather than after the
  962. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  963. # deferred because the pool was full) also counts as productive.
  964. return bool(dispatch_ids) or bool(self._inflight)
  965. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  966. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  967. Dispatch used to happen inline in the selection loop: ``await
  968. _start_print(db, item)`` per item in turn. Since ``_start_print``
  969. performs the FTP upload, that serialized every printer behind every
  970. other printer's transfer even though the printers are independent
  971. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  972. gather was awaited before ``check_queue`` returned, so the run loop
  973. stayed blocked until the *slowest* upload in the batch finished — a
  974. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  975. 93-printer farm even as other printers came free (#2602).
  976. Each upload now runs as an independent background task tracked in
  977. ``self._inflight``. check_queue excludes in-flight item_ids (still
  978. `pending` until their upload completes) and their printers from the
  979. next pass's selection, and this method launches at most
  980. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  981. the next fast tick instead of waiting out the whole batch. The bound
  982. exists because the printers are independent but the host is not: each
  983. in-flight upload holds a thread in the FTP pool, a TLS session and a
  984. file handle.
  985. The no-overlapping-dispatch invariant the batch-await used to provide
  986. is now carried by the in-flight exclusion in check_queue. Everything
  987. else — the pending->printing CAS, the busy-printer guard (#2598), the
  988. per-printer hold, and each item's independent failure handling — still
  989. lives in ``_start_print`` and runs per task exactly as before.
  990. Synchronous on purpose: it registers every launched task into
  991. ``self._inflight`` before returning, so the next (sequential) tick sees
  992. an accurate in-flight count with no interleaving await.
  993. """
  994. free = limit - len(self._inflight)
  995. if free <= 0:
  996. logger.info(
  997. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  998. len(self._inflight),
  999. limit,
  1000. len(item_ids),
  1001. item_ids,
  1002. )
  1003. return
  1004. to_launch = item_ids[:free]
  1005. deferred = item_ids[free:]
  1006. logger.info(
  1007. "Launching %d upload(s) (pool %d/%d in flight)%s",
  1008. len(to_launch),
  1009. len(self._inflight),
  1010. limit,
  1011. f" — deferring {deferred} to a later tick" if deferred else "",
  1012. )
  1013. for item_id in to_launch:
  1014. task = spawn_background_task(self._dispatch_one(item_id), name=f"queue-upload-{item_id}")
  1015. self._inflight[item_id] = (task, item_printers.get(item_id))
  1016. # Prune on completion so the freed slot is refillable next tick.
  1017. # spawn_background_task already logs any uncaught exception; this
  1018. # only reclaims the pool slot (fires on success, failure, or cancel).
  1019. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  1020. async def _dispatch_one(self, item_id: int) -> None:
  1021. """Upload + start one queue item in its own session (pool worker, #2602).
  1022. Its own session: pool workers run concurrently and an AsyncSession is
  1023. not safe to share across tasks; it also keeps a slow upload from pinning
  1024. the scheduler's session (and, on SQLite, its transaction) open for the
  1025. transfer's duration.
  1026. """
  1027. async with async_session() as item_db:
  1028. # Claim the row for dispatch BEFORE reading the printer snapshot or
  1029. # touching any slow I/O (#2615). The claim is an atomic CAS on
  1030. # (status='pending', dispatching_at IS NULL); while it's held the edit
  1031. # routes reject reassignment (409), so printer_id can't change out from
  1032. # under the in-flight upload and split the queue row from the
  1033. # archive/expected-print/physical command.
  1034. if not await self._claim_for_dispatch(item_db, item_id):
  1035. logger.info(
  1036. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  1037. item_id,
  1038. )
  1039. return
  1040. try:
  1041. item = await item_db.get(PrintQueueItem, item_id)
  1042. if not item:
  1043. logger.info("Queue item %s vanished after claim — skipping", item_id)
  1044. return
  1045. await self._start_print(item_db, item)
  1046. finally:
  1047. # Undo an expected-print registration whose print command never
  1048. # went out. One choke point covers every way `_start_print` can
  1049. # end without sending: a raised exception (a DB failure mid-
  1050. # dispatch is the reported case), an early return, a cancel
  1051. # winning the #1853 CAS, or `start_print()` returning False.
  1052. # A confirmed send removes the entry itself, so this is a no-op
  1053. # on the happy path.
  1054. self._rollback_unconfirmed_expected_print(item_id)
  1055. # Release the claim on every exit. Once dispatch has finished the
  1056. # row's status carries the lock (printing/failed/cancelled are all
  1057. # != pending), so the token is only needed for the duration of the
  1058. # upload. A row left pending (e.g. busy-printer deferral) becomes
  1059. # dispatchable again on the next tick.
  1060. await self._clear_dispatch_claim(item_db, item_id)
  1061. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  1062. """Drop an expectation for a print command that was never sent.
  1063. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  1064. where the interesting exception is usually the one already propagating.
  1065. """
  1066. pending = self._unconfirmed_expected_print.pop(item_id, None)
  1067. if pending is None:
  1068. return
  1069. printer_id, remote_filename, archive_id = pending
  1070. try:
  1071. from backend.app.main import unregister_expected_print
  1072. unregister_expected_print(printer_id, remote_filename, archive_id)
  1073. except Exception:
  1074. logger.warning(
  1075. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  1076. item_id,
  1077. printer_id,
  1078. remote_filename,
  1079. archive_id,
  1080. exc_info=True,
  1081. )
  1082. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  1083. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  1084. Returns True if this call won the claim, False if the row was already
  1085. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  1086. the load-bearing guard against reassign-during-dispatch (#2615)."""
  1087. res = await db.execute(
  1088. update(PrintQueueItem)
  1089. .where(PrintQueueItem.id == item_id)
  1090. .where(PrintQueueItem.status == "pending")
  1091. .where(PrintQueueItem.dispatching_at.is_(None))
  1092. .values(dispatching_at=datetime.now(timezone.utc))
  1093. )
  1094. await db.commit()
  1095. return res.rowcount > 0
  1096. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  1097. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  1098. mask the dispatch outcome.
  1099. Retried, because the failure mode in practice is transient and narrow: a
  1100. database that is momentarily unreachable — PostgreSQL out of connection
  1101. slots is the observed case — refuses this write for a second or two while
  1102. the dispatch that just ended is still holding the row out of the selection
  1103. query. One attempt was enough to wedge the item; a couple of spaced
  1104. attempts clear it. Each attempt rolls back first, since a failed write
  1105. leaves the session needing it before it can be reused.
  1106. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  1107. on the next quiet tick.
  1108. """
  1109. for attempt in range(1, 4):
  1110. try:
  1111. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  1112. await db.commit()
  1113. return
  1114. except Exception as exc:
  1115. try:
  1116. await db.rollback()
  1117. except Exception:
  1118. pass
  1119. if attempt == 3:
  1120. logger.warning(
  1121. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  1122. "— a later quiet tick will release it",
  1123. item_id,
  1124. attempt,
  1125. exc,
  1126. )
  1127. return
  1128. await asyncio.sleep(0.5 * attempt)
  1129. async def _find_idle_printer_for_model(
  1130. self,
  1131. db: AsyncSession,
  1132. model: str,
  1133. exclude_ids: set[int],
  1134. required_filament_types: list[str] | None = None,
  1135. target_location: str | None = None,
  1136. filament_overrides: list[dict] | None = None,
  1137. require_plate_clear: bool = True,
  1138. ) -> tuple[int | None, str | None]:
  1139. """Find an idle, connected printer matching the model with compatible filaments.
  1140. Args:
  1141. db: Database session
  1142. model: Printer model to match (e.g., "X1C", "P1S")
  1143. exclude_ids: Printer IDs to exclude (already busy)
  1144. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1145. If provided, only printers with all required types loaded will match.
  1146. target_location: Optional location filter. If provided, only printers in this location are considered.
  1147. filament_overrides: Optional list of override dicts. Each entry may include
  1148. ``force_color_match: true`` to require an exact type+color match
  1149. on the printer for that slot. Without the flag the existing
  1150. colour-preference logic applies.
  1151. Returns:
  1152. Tuple of (printer_id, waiting_reason):
  1153. - (printer_id, None) if a matching printer was found
  1154. - (None, reason) if no printer is available, with explanation
  1155. """
  1156. # Normalize model name and use case-insensitive matching
  1157. normalized_model = normalize_printer_model(model) or model
  1158. query = (
  1159. select(Printer)
  1160. .where(func.lower(Printer.model) == normalized_model.lower())
  1161. .where(Printer.is_active == True) # noqa: E712
  1162. )
  1163. # Add location filter if specified
  1164. if target_location:
  1165. query = query.where(Printer.location == target_location)
  1166. result = await db.execute(query)
  1167. printers = list(result.scalars().all())
  1168. location_suffix = f" in {target_location}" if target_location else ""
  1169. if not printers:
  1170. return None, f"No active {normalized_model} printers{location_suffix} configured"
  1171. # Separate force-matched overrides from preference-only overrides
  1172. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  1173. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  1174. # Track reasons for skipping printers
  1175. printers_busy = []
  1176. printers_offline = []
  1177. printers_missing_filament: list[tuple[str, list[str]]] = []
  1178. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  1179. for printer in printers:
  1180. if printer.id in exclude_ids:
  1181. # Printer is already claimed by another job in this scheduling run.
  1182. # For force-color jobs, still check if the color would match — if not,
  1183. # report it as a color mismatch rather than plain "Busy" so the user
  1184. # knows the job needs a filament change, not just to wait for availability.
  1185. if force_overrides and not pref_overrides:
  1186. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1187. if missing_colors:
  1188. printers_missing_filament.append((printer.name, missing_colors))
  1189. continue
  1190. printers_busy.append(printer.name)
  1191. continue
  1192. is_connected = printer_manager.is_connected(printer.id)
  1193. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  1194. if not is_connected:
  1195. printers_offline.append(printer.name)
  1196. continue
  1197. if not is_idle:
  1198. # Printer is currently printing. For force-color jobs, check whether the
  1199. # loaded color would satisfy the requirement — if not, surface it as a
  1200. # color-mismatch reason rather than plain "Busy" so the user understands
  1201. # that the job is waiting for a filament change, not just printer availability.
  1202. if force_overrides and not pref_overrides:
  1203. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1204. if missing_colors:
  1205. printers_missing_filament.append((printer.name, missing_colors))
  1206. logger.debug(
  1207. "Printer %s (%s) is busy but also has wrong force-color: %s",
  1208. printer.id,
  1209. printer.name,
  1210. missing_colors,
  1211. )
  1212. continue
  1213. printers_busy.append(printer.name)
  1214. continue
  1215. # Validate filament compatibility if required types are specified
  1216. if required_filament_types:
  1217. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  1218. if missing:
  1219. # When force_overrides are present, enrich missing entries with color info
  1220. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  1221. if force_overrides:
  1222. force_color_map = {
  1223. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  1224. for o in force_overrides
  1225. }
  1226. missing_enriched = [
  1227. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  1228. for t in missing
  1229. ]
  1230. printers_missing_filament.append((printer.name, missing_enriched))
  1231. else:
  1232. printers_missing_filament.append((printer.name, missing))
  1233. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  1234. continue
  1235. # Force color match: ALL flagged slots must have an exact type+color match
  1236. if force_overrides:
  1237. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1238. if missing_colors:
  1239. printers_missing_filament.append((printer.name, missing_colors))
  1240. logger.debug(
  1241. "Skipping printer %s (%s) - missing force-matched colors: %s",
  1242. printer.id,
  1243. printer.name,
  1244. missing_colors,
  1245. )
  1246. continue
  1247. # If preference-only overrides exist, rank by color matches (existing behaviour)
  1248. if pref_overrides:
  1249. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  1250. if color_matches > 0:
  1251. candidates.append((printer.id, color_matches))
  1252. else:
  1253. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  1254. printers_missing_filament.append((printer.name, override_colors))
  1255. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  1256. continue
  1257. elif force_overrides:
  1258. # Passed all force checks — immediately eligible (no preference ordering needed)
  1259. return printer.id, None
  1260. else:
  1261. # No overrides at all - take first available (existing behavior)
  1262. return printer.id, None
  1263. # If we have candidates from preference override matching, pick the one with most color matches
  1264. if candidates:
  1265. candidates.sort(key=lambda c: c[1], reverse=True)
  1266. return candidates[0][0], None
  1267. # Build waiting reason from what we found
  1268. reasons = []
  1269. if printers_missing_filament:
  1270. # Filament/color mismatch is most actionable - show first
  1271. if force_overrides and not pref_overrides:
  1272. # All mismatches are force-color failures — use descriptive message only;
  1273. # but only if there are no busy printers that DO have the matching color.
  1274. # If a printer has the right color but is busy, surface "Busy" instead so
  1275. # the user knows the job will start automatically once that printer is free.
  1276. if not printers_busy:
  1277. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  1278. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  1279. # else: fall through — printers_busy will be appended below
  1280. else:
  1281. names_and_missing = [
  1282. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  1283. ]
  1284. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  1285. if printers_busy:
  1286. reasons.append(f"Busy: {', '.join(printers_busy)}")
  1287. if printers_offline:
  1288. reasons.append(f"Offline: {', '.join(printers_offline)}")
  1289. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  1290. @staticmethod
  1291. def _is_busy_only(waiting_reason: str) -> bool:
  1292. """Check if the waiting reason only contains 'Busy' entries.
  1293. When all matching printers are simply busy printing, the queued job
  1294. will start automatically once a printer finishes — no user action
  1295. is required, so we skip the notification.
  1296. """
  1297. parts = [p.strip() for p in waiting_reason.split(" | ")]
  1298. return all(p.startswith("Busy:") for p in parts)
  1299. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  1300. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  1301. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  1302. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  1303. with an exact type+color match.
  1304. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  1305. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  1306. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  1307. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  1308. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  1309. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  1310. setups are unaffected.
  1311. Returns:
  1312. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  1313. """
  1314. status = printer_manager.get_status(printer_id)
  1315. if not status:
  1316. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  1317. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  1318. loaded: list[tuple[str, str, str]] = []
  1319. for ams_unit in status.raw_data.get("ams", []):
  1320. for tray in ams_unit.get("tray", []):
  1321. tray_type = tray.get("tray_type")
  1322. if tray_type:
  1323. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1324. loaded.append(
  1325. (_canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or "")
  1326. )
  1327. for vt in status.raw_data.get("vt_tray") or []:
  1328. vt_type = vt.get("tray_type")
  1329. if vt_type:
  1330. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1331. loaded.append((_canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  1332. missing = []
  1333. for o in force_overrides:
  1334. o_type = _canonical_filament_type(o.get("type") or "")
  1335. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1336. o_idx = o.get("tray_info_idx") or ""
  1337. satisfied = any(
  1338. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  1339. for t_type, t_color, t_idx in loaded
  1340. )
  1341. if not satisfied:
  1342. color_label = o.get("color_name") or o.get("color", "?")
  1343. missing.append(f"{o_type} ({color_label})")
  1344. return missing
  1345. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  1346. """Get the list of required filament types that are not loaded on the printer.
  1347. Args:
  1348. printer_id: The printer ID
  1349. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  1350. Returns:
  1351. List of missing filament types (empty if all are loaded)
  1352. """
  1353. status = printer_manager.get_status(printer_id)
  1354. if not status:
  1355. return required_types # Can't determine, assume all missing
  1356. # Collect all filament types loaded on this printer (AMS units + external spool)
  1357. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  1358. loaded_types: set[str] = set()
  1359. # Check AMS units (stored in raw_data["ams"])
  1360. ams_data = status.raw_data.get("ams", [])
  1361. if ams_data:
  1362. for ams_unit in ams_data:
  1363. for tray in ams_unit.get("tray", []):
  1364. tray_type = tray.get("tray_type")
  1365. if tray_type:
  1366. loaded_types.add(_canonical_filament_type(tray_type))
  1367. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  1368. for vt in status.raw_data.get("vt_tray") or []:
  1369. vt_type = vt.get("tray_type")
  1370. if vt_type:
  1371. loaded_types.add(_canonical_filament_type(vt_type))
  1372. # Find which required types are missing (using canonical type for equivalence)
  1373. missing = []
  1374. for req_type in required_types:
  1375. if _canonical_filament_type(req_type) not in loaded_types:
  1376. missing.append(req_type)
  1377. return missing
  1378. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  1379. """Count how many filament overrides have an exact color match on the printer.
  1380. Used to prefer printers that already have the desired override colors loaded.
  1381. """
  1382. status = printer_manager.get_status(printer_id)
  1383. if not status:
  1384. return 0
  1385. # Collect loaded filaments' type+color pairs
  1386. loaded: set[tuple[str, str]] = set()
  1387. for ams_unit in status.raw_data.get("ams", []):
  1388. for tray in ams_unit.get("tray", []):
  1389. tray_type = tray.get("tray_type")
  1390. tray_color = tray.get("tray_color", "")
  1391. if tray_type:
  1392. color_norm = tray_color.replace("#", "").lower()[:6]
  1393. loaded.add((tray_type.upper(), color_norm))
  1394. for vt in status.raw_data.get("vt_tray") or []:
  1395. vt_type = vt.get("tray_type")
  1396. if vt_type:
  1397. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1398. loaded.add((vt_type.upper(), color_norm))
  1399. matches = 0
  1400. for o in overrides:
  1401. o_type = (o.get("type") or "").upper()
  1402. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1403. if (o_type, o_color) in loaded:
  1404. matches += 1
  1405. return matches
  1406. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  1407. """Fold the winning candidate's file and settings onto the queue row (#671).
  1408. This is the whole trick that keeps cross-model items cheap: the many-to-many
  1409. never escapes the selection loop. By the time the pass commits, the row
  1410. looks exactly like an ordinary single-file model-based item, so the upload,
  1411. archive creation, expected-print registration, print history and reprint
  1412. paths need no knowledge that variants exist.
  1413. No-ops for a non-variant candidate, which is already the item's own columns.
  1414. Safe to run and re-run: the item's file columns are only ever *read* when it
  1415. has no variants, so an item that gets resolved and then skipped (library-row
  1416. conflict, previous-print gate) is simply resolved again on the next pass.
  1417. """
  1418. variant = candidate.variant
  1419. if variant is None:
  1420. return
  1421. item.library_file_id = variant.library_file_id
  1422. item.library_file = variant.library_file
  1423. # The dispatcher checks archive_id first and would print that instead of
  1424. # the file we just picked. Creation refuses to combine the two, so this
  1425. # only ever fires on a hand-written row — clear it rather than silently
  1426. # dispatch something the matcher never considered.
  1427. item.archive_id = None
  1428. item.archive = None
  1429. item.target_model = variant.target_model
  1430. item.plate_id = variant.plate_id
  1431. item.ams_mapping = variant.ams_mapping
  1432. item.nozzle_mapping = variant.nozzle_mapping
  1433. item.filament_overrides = variant.filament_overrides
  1434. item.required_filament_types = variant.required_filament_types
  1435. if variant.print_time_seconds is not None:
  1436. # The row carried the shortest candidate's estimate so SJF could order
  1437. # it before a printer was known; now that one is chosen, record what is
  1438. # actually going to run so history and the ETA agree with reality.
  1439. item.print_time_seconds = variant.print_time_seconds
  1440. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> None:
  1441. """Ensure the queue item carries a usable AMS mapping before dispatch.
  1442. Recomputes from live printer status when the stored mapping is missing OR
  1443. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  1444. frontend status-load race can serialize [-1] before the printer's AMS
  1445. trays are known (#2589) — and must not be trusted: downstream it would be
  1446. silently downgraded to external-spool mode and print against an empty
  1447. feed. A resolved mapping (including manual overrides, or a partially
  1448. padded one) is left untouched.
  1449. When recompute cannot resolve it either (no compatible tray loaded), the
  1450. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  1451. external selection; the print command then keeps use_ams=True and the
  1452. firmware surfaces a clear AMS-mapping error instead of silently printing
  1453. to the empty external feed.
  1454. """
  1455. stored_mapping: list | None = None
  1456. if item.ams_mapping:
  1457. try:
  1458. stored_mapping = json.loads(item.ams_mapping)
  1459. except (json.JSONDecodeError, TypeError):
  1460. stored_mapping = None
  1461. # Already resolved (present and not all-unresolved) — keep as-is so a
  1462. # user's manual mapping is never overwritten.
  1463. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  1464. return
  1465. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  1466. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  1467. item.ams_mapping = json.dumps(computed_mapping)
  1468. logger.info(
  1469. "Queue item %s: Computed AMS mapping for printer %s: %s",
  1470. item.id,
  1471. printer_id,
  1472. computed_mapping,
  1473. )
  1474. await db.commit()
  1475. elif _mapping_is_all_unresolved(stored_mapping):
  1476. logger.warning(
  1477. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  1478. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  1479. item.id,
  1480. stored_mapping,
  1481. printer_id,
  1482. )
  1483. item.ams_mapping = None
  1484. await db.commit()
  1485. async def _compute_ams_mapping_for_printer(
  1486. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  1487. ) -> list[int] | None:
  1488. """Compute AMS mapping for a printer based on filament requirements.
  1489. Called when a queue item has no ams_mapping set — either for model-based
  1490. items after printer assignment, or printer-specific items (e.g. from VP).
  1491. Args:
  1492. db: Database session
  1493. printer_id: The assigned printer ID
  1494. item: The queue item (contains archive_id or library_file_id)
  1495. Returns:
  1496. AMS mapping array or None if no mapping needed/possible
  1497. """
  1498. # Get printer status
  1499. status = printer_manager.get_status(printer_id)
  1500. if not status:
  1501. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  1502. return None
  1503. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  1504. # either extruder, so the per-nozzle hard filter below must NOT apply.
  1505. # Otherwise a print on one nozzle can't use a spool physically loaded in
  1506. # an AMS on the *other* nozzle, and the matcher falls through to a
  1507. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  1508. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  1509. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  1510. # Get filament requirements from source file
  1511. filament_reqs = await self._get_filament_requirements(db, item)
  1512. if not filament_reqs:
  1513. # When the 3MF can't be read but force-color overrides are present, build a
  1514. # direct mapping from the overrides so the printer uses the correct AMS slot.
  1515. if item.filament_overrides:
  1516. try:
  1517. overrides = json.loads(item.filament_overrides)
  1518. force_overrides = [o for o in overrides if o.get("force_color_match")]
  1519. if force_overrides:
  1520. logger.info(
  1521. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  1522. "force-color override(s)",
  1523. item.id,
  1524. len(force_overrides),
  1525. )
  1526. return self._build_override_direct_mapping(force_overrides, status)
  1527. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1528. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  1529. logger.debug("No filament requirements found for queue item %s", item.id)
  1530. return None
  1531. # Apply filament overrides if present
  1532. if item.filament_overrides:
  1533. try:
  1534. overrides = json.loads(item.filament_overrides)
  1535. override_map = {o["slot_id"]: o for o in overrides}
  1536. for req in filament_reqs:
  1537. if req["slot_id"] in override_map:
  1538. override = override_map[req["slot_id"]]
  1539. req["type"] = override["type"]
  1540. req["color"] = override["color"]
  1541. # A manual/preference override SWAPS the slot's filament, so the
  1542. # 3MF's original tray_info_idx now points at the old spool and must
  1543. # be cleared — matching then falls back to type+colour. A
  1544. # force_color_match override is not a swap: it carries the 3MF's
  1545. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  1546. # it here too, letting the matcher pin the correct variant slot on a
  1547. # printer holding two same-colour spools of different variants (#2650).
  1548. # If that variant isn't loaded the matcher falls back to type+colour,
  1549. # so an eligible printer never fails to map.
  1550. req["tray_info_idx"] = (
  1551. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  1552. )
  1553. logger.debug(
  1554. "Queue item %s: Override slot %d -> %s %s",
  1555. item.id,
  1556. req["slot_id"],
  1557. override["type"],
  1558. override["color"],
  1559. )
  1560. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1561. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  1562. # Build loaded filaments from printer status
  1563. loaded_filaments = self._build_loaded_filaments(status)
  1564. if not loaded_filaments:
  1565. logger.debug("No filaments loaded on printer %s", printer_id)
  1566. return None
  1567. # Check if user prefers lowest remaining filament when multiple spools match
  1568. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  1569. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  1570. # Without backup, the printer will not switch to a second spool when the
  1571. # picked one runs out — so sorting toward the lowest leaves the print
  1572. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  1573. # today's behaviour intentionally.
  1574. if prefer_lowest and status.ams_filament_backup is False:
  1575. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  1576. prefer_lowest = False
  1577. # When the preference is on, surface Bambuddy's inventory-side
  1578. # remaining for each slot that's bound to a tracked spool, so the
  1579. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  1580. # entirely when the preference is off — no behaviour change for
  1581. # users who haven't opted in.
  1582. inventory_remain_overrides: dict[int, float] | None = None
  1583. if prefer_lowest:
  1584. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  1585. # Compute mapping: match required filaments to available slots
  1586. return self._match_filaments_to_slots(
  1587. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  1588. )
  1589. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  1590. """Build an AMS mapping directly from force-color overrides without a 3MF.
  1591. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  1592. slice_info is missing or unreadable) but ``force_color_match`` overrides
  1593. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  1594. treated as the filament requirement for that slot and matched against the
  1595. current AMS state of the printer.
  1596. Returns the same format as ``_match_filaments_to_slots``, or None when
  1597. the AMS has no loaded filaments.
  1598. """
  1599. loaded = self._build_loaded_filaments(status)
  1600. if not loaded:
  1601. return None
  1602. reqs = [
  1603. {
  1604. "slot_id": o["slot_id"],
  1605. "type": o.get("type", ""),
  1606. "color": o.get("color", ""),
  1607. # These are all force_color_match overrides, so the idx (when the
  1608. # 3MF carried one) is the intended variant, not a stale swap —
  1609. # keep it so the matcher pins the right variant slot, falling back
  1610. # to type+colour when it isn't loaded (#2650).
  1611. "tray_info_idx": o.get("tray_info_idx", ""),
  1612. }
  1613. for o in force_overrides
  1614. ]
  1615. return self._match_filaments_to_slots(reqs, loaded)
  1616. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  1617. """Resolve the queue item's source 3MF and parse the per-slot
  1618. filament requirements out of it. Thin DB-resolver wrapper around
  1619. ``filament_requirements.extract_filament_requirements`` so the VP
  1620. queue-mode write path (#1188) can reuse the same parser at upload
  1621. time.
  1622. """
  1623. from backend.app.services.filament_requirements import extract_filament_requirements
  1624. file_path: Path | None = None
  1625. if item.archive_id:
  1626. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1627. archive = result.scalar_one_or_none()
  1628. if archive:
  1629. file_path = settings.base_dir / archive.file_path
  1630. elif item.library_file_id:
  1631. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1632. library_file = result.scalar_one_or_none()
  1633. if library_file:
  1634. lib_path = Path(library_file.file_path)
  1635. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1636. if not file_path or not file_path.exists():
  1637. return None
  1638. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  1639. return filaments if filaments else None
  1640. def _build_loaded_filaments(self, status) -> list[dict]:
  1641. """Build list of loaded filaments from printer status.
  1642. Args:
  1643. status: PrinterState from printer_manager
  1644. Returns:
  1645. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  1646. """
  1647. filaments = []
  1648. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  1649. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  1650. # Parse AMS units from raw_data
  1651. ams_data = status.raw_data.get("ams", [])
  1652. for ams_unit in ams_data:
  1653. ams_id = int(ams_unit.get("id", 0))
  1654. trays = ams_unit.get("tray", [])
  1655. is_ht = len(trays) == 1 # AMS-HT has single tray
  1656. for tray in trays:
  1657. tray_type = tray.get("tray_type")
  1658. if tray_type:
  1659. tray_id = int(tray.get("id", 0))
  1660. tray_color = tray.get("tray_color", "")
  1661. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  1662. tray_info_idx = tray.get("tray_info_idx", "")
  1663. # Normalize color: remove alpha, add hash
  1664. color = self._normalize_color(tray_color)
  1665. # Calculate global tray ID
  1666. # AMS-HT units have IDs starting at 128 with a single tray
  1667. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  1668. filaments.append(
  1669. {
  1670. "type": tray_type,
  1671. "color": color,
  1672. "tray_info_idx": tray_info_idx,
  1673. "ams_id": ams_id,
  1674. "tray_id": tray_id,
  1675. "is_ht": is_ht,
  1676. "is_external": False,
  1677. "global_tray_id": global_tray_id,
  1678. "extruder_id": ams_extruder_map.get(str(ams_id)),
  1679. "remain": tray.get("remain", -1),
  1680. }
  1681. )
  1682. # Check external spool(s) (vt_tray is a list)
  1683. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  1684. if vt.get("tray_type"):
  1685. color = self._normalize_color(vt.get("tray_color", ""))
  1686. tray_id = int(vt.get("id", 254))
  1687. filaments.append(
  1688. {
  1689. "type": vt["tray_type"],
  1690. "color": color,
  1691. "tray_info_idx": vt.get("tray_info_idx", ""),
  1692. "ams_id": -1,
  1693. "tray_id": idx,
  1694. "is_ht": False,
  1695. "is_external": True,
  1696. "global_tray_id": tray_id,
  1697. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  1698. "remain": vt.get("remain", -1),
  1699. }
  1700. )
  1701. return filaments
  1702. def _normalize_color(self, color: str | None) -> str:
  1703. """Normalize color to #RRGGBB format."""
  1704. if not color:
  1705. return "#808080"
  1706. hex_color = color.replace("#", "")[:6]
  1707. return f"#{hex_color}"
  1708. def _normalize_color_for_compare(self, color: str | None) -> str:
  1709. """Normalize color for comparison (lowercase, no hash)."""
  1710. if not color:
  1711. return ""
  1712. return color.replace("#", "").lower()[:6]
  1713. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  1714. """Check if two colors are visually similar within a threshold."""
  1715. hex1 = self._normalize_color_for_compare(color1)
  1716. hex2 = self._normalize_color_for_compare(color2)
  1717. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  1718. return False
  1719. try:
  1720. r1 = int(hex1[0:2], 16)
  1721. g1 = int(hex1[2:4], 16)
  1722. b1 = int(hex1[4:6], 16)
  1723. r2 = int(hex2[0:2], 16)
  1724. g2 = int(hex2[2:4], 16)
  1725. b2 = int(hex2[4:6], 16)
  1726. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  1727. except ValueError:
  1728. return False
  1729. async def _build_inventory_remain_overrides(
  1730. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  1731. ) -> dict[int, float]:
  1732. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  1733. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  1734. The MQTT ``remain`` field on a tray is the printer firmware's
  1735. RFID-decremented value, which has two limitations the "Prefer Lowest
  1736. Remaining Filament" feature has been ignoring (#1508):
  1737. - it's only meaningful for Bambu RFID spools; everything else reports
  1738. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  1739. compare equal and the sort collapses to AMS-slot order — the user
  1740. who's curating inventory weights gets the lower-slot pick instead
  1741. of the lower-remaining pick;
  1742. - even when set, it's the *printer's* counter, not Bambuddy's
  1743. ``label_weight - weight_used`` (internal mode) or Spoolman's
  1744. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  1745. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  1746. When the user has bound a spool to a slot, their own inventory
  1747. tracking is authoritative; this helper surfaces that value so the
  1748. sort can prefer it. Slots without a binding are absent from the
  1749. returned map — the caller then falls back to MQTT ``remain`` for
  1750. those, preserving the pre-#1508 behaviour for un-tracked spools.
  1751. Returns an empty map on any failure (no inventory bindings, DB
  1752. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  1753. is a preference, not a guarantee.
  1754. """
  1755. if not loaded:
  1756. return {}
  1757. # External / virtual-tray slots are tracked separately from AMS — skip
  1758. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  1759. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  1760. # match is fiddly and out of scope for this fix).
  1761. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  1762. if not tracked_slots:
  1763. return {}
  1764. is_spoolman = await self._is_spoolman_mode(db)
  1765. overrides: dict[int, float] = {}
  1766. if is_spoolman:
  1767. result = await db.execute(
  1768. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1769. )
  1770. assignments = list(result.scalars().all())
  1771. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  1772. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  1773. for ams_id, tray_id, gtid in tracked_slots:
  1774. spoolman_id = by_slot.get((ams_id, tray_id))
  1775. if spoolman_id is None:
  1776. continue
  1777. grams = await _spoolman_remaining_grams(spoolman_id)
  1778. if grams is not None:
  1779. overrides[gtid] = grams
  1780. return overrides
  1781. # Internal inventory mode (default). selectinload matches the pattern
  1782. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  1783. # plus an eager-loaded relationship rather than an explicit join, so
  1784. # the row-attribute shape is exactly what those routes already rely on.
  1785. result = await db.execute(
  1786. select(SpoolAssignment)
  1787. .options(selectinload(SpoolAssignment.spool))
  1788. .where(SpoolAssignment.printer_id == printer_id)
  1789. )
  1790. assignments = list(result.scalars().all())
  1791. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  1792. for ams_id, tray_id, gtid in tracked_slots:
  1793. spool = by_slot.get((ams_id, tray_id))
  1794. if spool is None:
  1795. continue
  1796. label = float(spool.label_weight or 0)
  1797. used = float(spool.weight_used or 0)
  1798. overrides[gtid] = max(0.0, label - used)
  1799. return overrides
  1800. @staticmethod
  1801. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  1802. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  1803. here to avoid making this module import-dependent on that private
  1804. helper's signature."""
  1805. try:
  1806. from backend.app.api.routes.settings import get_setting
  1807. v = await get_setting(db, "spoolman_enabled")
  1808. return bool(v) and v.lower() == "true"
  1809. except Exception:
  1810. return False
  1811. @staticmethod
  1812. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  1813. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  1814. Three bands, matched to the emission order in ``_build_loaded_filaments``
  1815. so a tied sort produces the same physical-position order the pre-#1508
  1816. stable sort did (preserves the regression-free baseline):
  1817. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  1818. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  1819. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  1820. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  1821. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  1822. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  1823. """
  1824. if ams_id is None or ams_id < 0:
  1825. return 10_000
  1826. if ams_id >= 128:
  1827. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  1828. return ams_id * 4 + (tray_id or 0)
  1829. @staticmethod
  1830. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  1831. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  1832. Two-tier ordering: inventory-tracked spools always sort BEFORE
  1833. non-tracked spools (the user has told us they care about these
  1834. specifically), then ascending by remaining within each tier, then
  1835. ascending by AMS slot position as the deterministic tie-breaker.
  1836. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  1837. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  1838. because the tier flag dominates — which is what lets us mix grams
  1839. (inventory) and percent (MQTT) without a unit conversion.
  1840. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  1841. spools the printer DOES know something about sort ahead of those
  1842. it knows nothing about — preserves pre-#1508 behaviour for the
  1843. no-inventory-binding case.
  1844. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  1845. external on ties, matching the legacy emission-order stable sort.
  1846. """
  1847. gtid = f.get("global_tray_id")
  1848. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  1849. if overrides and gtid in overrides:
  1850. return (0, overrides[gtid], slot_order)
  1851. remain = f.get("remain", -1)
  1852. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  1853. def _match_filaments_to_slots(
  1854. self,
  1855. required: list[dict],
  1856. loaded: list[dict],
  1857. prefer_lowest: bool = False,
  1858. inventory_remain_overrides: dict[int, float] | None = None,
  1859. fts_installed: bool = False,
  1860. ) -> list[int] | None:
  1861. """Match required filaments to loaded filaments and build AMS mapping.
  1862. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  1863. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  1864. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  1865. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  1866. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  1867. matching among those trays.
  1868. Args:
  1869. required: List of required filaments with slot_id, type, color, tray_info_idx
  1870. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  1871. Returns:
  1872. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  1873. """
  1874. if not required:
  1875. return None
  1876. # Track used trays to avoid duplicate assignment
  1877. used_tray_ids: set[int] = set()
  1878. comparisons = []
  1879. for req in required:
  1880. req_type = (req.get("type") or "").upper()
  1881. req_color = req.get("color", "")
  1882. req_tray_info_idx = req.get("tray_info_idx", "")
  1883. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  1884. idx_match = None
  1885. exact_match = None
  1886. similar_match = None
  1887. type_only_match = None
  1888. # Get available trays (not already used)
  1889. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  1890. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  1891. # Hard filter — cross-nozzle assignment causes print failures
  1892. # ("position of left hotend is abnormal"), so never fall back.
  1893. # Skipped when an FTS is installed: it routes any AMS slot to either
  1894. # extruder, so restricting to one nozzle would wrongly exclude the
  1895. # correct spool sitting in the other nozzle's AMS (#2186).
  1896. req_nozzle_id = req.get("nozzle_id")
  1897. if req_nozzle_id is not None and not fts_installed:
  1898. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  1899. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  1900. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  1901. # _prefer_lowest_sort_key for the full rationale.
  1902. if prefer_lowest:
  1903. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1904. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  1905. # One line per filament req so a bug report can be diagnosed
  1906. # without enabling debug logging: shows what the matcher saw
  1907. # (req shape + sorted candidate trays with their remain values
  1908. # and any inventory override that was applied). Mirrored by
  1909. # the picked-match log at the bottom of the loop.
  1910. logger.info(
  1911. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  1912. req.get("slot_id"),
  1913. req_type,
  1914. req_color,
  1915. req_tray_info_idx,
  1916. req_nozzle_id,
  1917. [
  1918. {
  1919. "gtid": f.get("global_tray_id"),
  1920. "type": f.get("type"),
  1921. "color": f.get("color"),
  1922. "tii": f.get("tray_info_idx"),
  1923. "remain": f.get("remain"),
  1924. "inv_g": (
  1925. inventory_remain_overrides.get(f.get("global_tray_id"))
  1926. if inventory_remain_overrides
  1927. else None
  1928. ),
  1929. }
  1930. for f in available
  1931. ],
  1932. )
  1933. # Check if tray_info_idx is unique among available trays
  1934. if req_tray_info_idx:
  1935. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  1936. if len(idx_matches) == 1:
  1937. # Unique tray_info_idx - use it as definitive match
  1938. idx_match = idx_matches[0]
  1939. logger.debug(
  1940. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  1941. f"-> tray {idx_match['global_tray_id']}"
  1942. )
  1943. elif len(idx_matches) > 1:
  1944. # Multiple trays with same tray_info_idx - use color matching among them
  1945. logger.debug(
  1946. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  1947. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  1948. )
  1949. if prefer_lowest:
  1950. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1951. # Use color matching within this subset
  1952. for f in idx_matches:
  1953. f_color = f.get("color", "")
  1954. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1955. if not exact_match:
  1956. exact_match = f
  1957. elif self._colors_are_similar(f_color, req_color):
  1958. if not similar_match:
  1959. similar_match = f
  1960. elif not type_only_match:
  1961. type_only_match = f
  1962. # If no idx_match yet, do standard type/color matching on all available trays
  1963. if not idx_match and not exact_match and not similar_match and not type_only_match:
  1964. for f in available:
  1965. f_type = (f.get("type") or "").upper()
  1966. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  1967. continue
  1968. # Type matches - check color
  1969. f_color = f.get("color", "")
  1970. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1971. if not exact_match:
  1972. exact_match = f
  1973. elif self._colors_are_similar(f_color, req_color):
  1974. if not similar_match:
  1975. similar_match = f
  1976. elif not type_only_match:
  1977. type_only_match = f
  1978. match = idx_match or exact_match or similar_match or type_only_match
  1979. if match:
  1980. used_tray_ids.add(match["global_tray_id"])
  1981. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  1982. else:
  1983. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1984. if prefer_lowest:
  1985. # Pair with the "available (sorted)" log above so the reporter
  1986. # bundle shows BOTH what the matcher saw AND which match bucket
  1987. # won — fast triage when "Prefer Lowest Filament" picks the
  1988. # wrong slot (#1766).
  1989. if match:
  1990. bucket = (
  1991. "idx"
  1992. if idx_match is not None
  1993. else "exact_color"
  1994. if exact_match is not None
  1995. else "similar_color"
  1996. if similar_match is not None
  1997. else "type_only"
  1998. )
  1999. logger.info(
  2000. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  2001. match["global_tray_id"],
  2002. bucket,
  2003. req.get("slot_id"),
  2004. )
  2005. else:
  2006. logger.info(
  2007. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  2008. req.get("slot_id"),
  2009. req_type,
  2010. req_color,
  2011. req_tray_info_idx,
  2012. )
  2013. # Build mapping array
  2014. if not comparisons:
  2015. return None
  2016. max_slot_id = max(c["slot_id"] for c in comparisons)
  2017. if max_slot_id <= 0:
  2018. return None
  2019. mapping = [-1] * max_slot_id
  2020. for c in comparisons:
  2021. slot_id = c["slot_id"]
  2022. if slot_id and slot_id > 0:
  2023. mapping[slot_id - 1] = c["global_tray_id"]
  2024. return mapping
  2025. def _mark_printer_dispatched(
  2026. self,
  2027. printer_id: int,
  2028. pre_state: str | None,
  2029. pre_subtask_id: str | None,
  2030. ) -> None:
  2031. """Record that a print command was just sent to ``printer_id``.
  2032. Held until either the watchdog observes a state/subtask transition
  2033. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  2034. """
  2035. if not pre_state:
  2036. # No pre_state means we can't detect a transition — fall back to a
  2037. # pure time-based hold using empty string as a sentinel that won't
  2038. # match any real printer state.
  2039. pre_state = ""
  2040. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  2041. def _release_dispatch_hold(self, printer_id: int) -> None:
  2042. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  2043. self._dispatch_holds.pop(printer_id, None)
  2044. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  2045. """True if ``printer_id`` is still inside its post-dispatch hold window.
  2046. Returns False (and clears the hold) once any of these are true:
  2047. - hard timeout (``_dispatch_max_hold``) has elapsed
  2048. - the printer has transitioned out of pre_state and we're past the
  2049. minimum cooldown
  2050. - the printer's subtask_id has advanced past pre_subtask_id and we're
  2051. past the minimum cooldown
  2052. Otherwise the printer is held — caller should treat it as busy.
  2053. """
  2054. entry = self._dispatch_holds.get(printer_id)
  2055. if not entry:
  2056. return False
  2057. started_at, pre_state, pre_subtask_id = entry
  2058. elapsed = time.monotonic() - started_at
  2059. if elapsed >= self._dispatch_max_hold:
  2060. self._dispatch_holds.pop(printer_id, None)
  2061. return False
  2062. # Without a pre_state we can't detect a transition — fall back to the
  2063. # min cooldown alone, then drop the hold.
  2064. if not pre_state:
  2065. if elapsed >= self._dispatch_min_cooldown:
  2066. self._dispatch_holds.pop(printer_id, None)
  2067. return False
  2068. return True
  2069. status = printer_manager.get_status(printer_id)
  2070. current_state = getattr(status, "state", None) if status else None
  2071. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  2072. transitioned = (current_state is not None and current_state != pre_state) or (
  2073. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  2074. )
  2075. if transitioned and elapsed >= self._dispatch_min_cooldown:
  2076. self._dispatch_holds.pop(printer_id, None)
  2077. return False
  2078. return True
  2079. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  2080. """Check if a printer is connected and idle."""
  2081. if not printer_manager.is_connected(printer_id):
  2082. logger.debug("Printer %d: not connected", printer_id)
  2083. return False
  2084. state = printer_manager.get_status(printer_id)
  2085. if not state:
  2086. logger.debug("Printer %d: no status available", printer_id)
  2087. return False
  2088. # Plate-clear gate: if the printer finished/failed a previous print and the user
  2089. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  2090. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  2091. # printer, it boots back into IDLE with no memory of the previous finish; without
  2092. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  2093. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  2094. logger.debug(
  2095. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  2096. printer_id,
  2097. state.state,
  2098. )
  2099. return False
  2100. idle = state.state in ("IDLE", "FINISH", "FAILED")
  2101. if not idle:
  2102. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  2103. return idle
  2104. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  2105. """Read a setting value from the database."""
  2106. result = await db.execute(select(Settings).where(Settings.key == key))
  2107. setting = result.scalar_one_or_none()
  2108. return setting.value if setting else None
  2109. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  2110. """Read a boolean setting from the database."""
  2111. result = await db.execute(select(Settings).where(Settings.key == key))
  2112. setting = result.scalar_one_or_none()
  2113. if setting:
  2114. return setting.value.lower() == "true"
  2115. return default
  2116. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  2117. """Read an int setting; falls back to default on missing/unparseable rows."""
  2118. result = await db.execute(select(Settings).where(Settings.key == key))
  2119. setting = result.scalar_one_or_none()
  2120. if setting and setting.value:
  2121. try:
  2122. return int(setting.value)
  2123. except ValueError:
  2124. pass
  2125. return default
  2126. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  2127. """Get drying presets (user-configured or built-in defaults)."""
  2128. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  2129. setting = result.scalar_one_or_none()
  2130. if setting and setting.value:
  2131. try:
  2132. presets = json.loads(setting.value)
  2133. if isinstance(presets, dict) and presets:
  2134. return presets
  2135. except json.JSONDecodeError:
  2136. pass
  2137. return self.DEFAULT_DRYING_PRESETS
  2138. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  2139. """Per-filament humidity thresholds (#1605).
  2140. Returns the user-configured overrides map keyed by normalized filament
  2141. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  2142. unknown / unmapped types. Empty / unset → empty dict, in which case
  2143. callers fall back to ``ams_humidity_fair``.
  2144. """
  2145. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  2146. setting = result.scalar_one_or_none()
  2147. if not setting or not setting.value:
  2148. return {}
  2149. try:
  2150. data = json.loads(setting.value)
  2151. except json.JSONDecodeError:
  2152. return {}
  2153. if not isinstance(data, dict):
  2154. return {}
  2155. out: dict[str, int] = {}
  2156. for key, value in data.items():
  2157. try:
  2158. out[str(key).upper() if key != "default" else "default"] = int(value)
  2159. except (TypeError, ValueError):
  2160. continue
  2161. return out
  2162. @staticmethod
  2163. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  2164. """Resolve the effective humidity threshold for an AMS unit (#1605).
  2165. For mixed filament types loaded into one AMS, returns the most
  2166. restrictive (lowest) threshold across all loaded tray types — matches
  2167. the conservative-params strategy already used for drying temp/hours.
  2168. Empty / unloaded trays contribute no constraint. Unknown types use the
  2169. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  2170. when no per-type map is configured at all.
  2171. """
  2172. default = thresholds.get("default", fallback)
  2173. if not thresholds:
  2174. return fallback
  2175. candidates: list[int] = []
  2176. for tray in trays:
  2177. tray_type = str(tray.get("tray_type") or "").strip()
  2178. if not tray_type:
  2179. continue
  2180. base_type = tray_type.split()[0].upper()
  2181. candidates.append(thresholds.get(base_type, default))
  2182. if not candidates:
  2183. return default
  2184. return min(candidates)
  2185. def _get_conservative_drying_params(
  2186. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  2187. ) -> tuple[int, int, str] | None:
  2188. """Get the most conservative drying params for mixed filament types in an AMS unit.
  2189. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  2190. """
  2191. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  2192. hours_key = f"{temp_key}_hours"
  2193. min_temp = None
  2194. max_hours = None
  2195. filament_type = ""
  2196. for tray in trays:
  2197. tray_type = tray.get("tray_type", "")
  2198. if not tray_type:
  2199. continue
  2200. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  2201. base_type = tray_type.split()[0].upper()
  2202. preset = presets.get(base_type)
  2203. if not preset:
  2204. continue
  2205. temp = preset.get(temp_key, 55)
  2206. hours = preset.get(hours_key, 12)
  2207. # Conservative: lowest temp, longest duration
  2208. if min_temp is None or temp < min_temp:
  2209. min_temp = temp
  2210. if max_hours is None or hours > max_hours:
  2211. max_hours = hours
  2212. if not filament_type:
  2213. filament_type = base_type
  2214. if min_temp is None:
  2215. return None
  2216. return (min_temp, max_hours or 12, filament_type)
  2217. async def _check_auto_drying(
  2218. self,
  2219. db: AsyncSession,
  2220. queue_items: list[PrintQueueItem],
  2221. busy_printers: set[int],
  2222. *,
  2223. require_plate_clear: bool = True,
  2224. ):
  2225. """Start drying on idle printers based on humidity.
  2226. Three modes (can all be enabled independently):
  2227. - queue_drying_enabled: Dry between scheduled queue prints
  2228. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  2229. - print_drying_enabled: Also evaluate printers that are currently printing,
  2230. when model+firmware supports "Print While Drying" (gated by
  2231. supports_drying_while_printing). Drying temperature is capped at
  2232. max(40, preset_temp - 5) to protect spools mid-print.
  2233. """
  2234. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  2235. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  2236. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  2237. if not queue_drying_enabled and not ambient_drying_enabled:
  2238. # Stop active drying on all printers if both features disabled
  2239. if self._drying_in_progress:
  2240. for pid in list(self._drying_in_progress):
  2241. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  2242. await self._stop_drying(pid)
  2243. return
  2244. # Update drying state from printer status (handles backend restart)
  2245. self._sync_drying_state()
  2246. # Find printers with scheduled items (for queue drying mode)
  2247. printers_with_scheduled: set[int] = set()
  2248. printers_with_items: set[int] = set()
  2249. for item in queue_items:
  2250. if item.printer_id:
  2251. printers_with_items.add(item.printer_id)
  2252. if item.scheduled_time and not item.manual_start:
  2253. printers_with_scheduled.add(item.printer_id)
  2254. # If only queue mode is on and no printers have scheduled items, stop drying
  2255. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  2256. # may still be eligible for mid-print drying regardless of queue state).
  2257. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  2258. for pid in list(self._drying_in_progress):
  2259. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  2260. await self._stop_drying(pid)
  2261. return
  2262. # Get humidity threshold (global fallback)
  2263. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2264. setting = result.scalar_one_or_none()
  2265. global_humidity_threshold = int(setting.value) if setting else 60
  2266. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  2267. # to the global threshold for every AMS unit.
  2268. per_type_thresholds = await self._get_humidity_thresholds(db)
  2269. # Get drying presets
  2270. presets = await self._get_drying_presets(db)
  2271. # Determine if drying should be skipped for printers with pending items
  2272. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  2273. # Get all active printers
  2274. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2275. for printer in all_printers.scalars():
  2276. pid = printer.id
  2277. # Resolve model+firmware up front — needed to decide whether this printer
  2278. # qualifies for mid-print drying (busy printer on capable hardware).
  2279. state = printer_manager.get_status(pid)
  2280. if not state:
  2281. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  2282. continue
  2283. model = printer_manager.get_model(pid)
  2284. firmware = state.firmware_version
  2285. mid_print = (
  2286. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  2287. )
  2288. if pid in busy_printers and not mid_print:
  2289. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  2290. continue
  2291. if not mid_print:
  2292. # In queue-only mode, only dry printers that have scheduled prints
  2293. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  2294. if self._drying_in_progress.get(pid):
  2295. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  2296. await self._stop_drying(pid)
  2297. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  2298. continue
  2299. # When block mode is on, don't START new drying on printers with pending items.
  2300. # But allow already-drying printers through so humidity auto-stop logic still runs.
  2301. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  2302. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  2303. continue
  2304. if not printer_manager.is_connected(pid):
  2305. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  2306. continue
  2307. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  2308. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  2309. continue
  2310. # Check drying capability. For mid-print path, supports_drying_while_printing
  2311. # was already verified when computing mid_print above.
  2312. if not mid_print and not supports_drying(model, firmware):
  2313. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  2314. continue
  2315. # Check each AMS unit from raw_data
  2316. ams_list = state.raw_data.get("ams", [])
  2317. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  2318. for ams_data in ams_list:
  2319. module_type = str(ams_data.get("module_type") or "")
  2320. ams_id = int(ams_data.get("id", 0))
  2321. # Only n3f/n3s support drying
  2322. if module_type not in ("n3f", "n3s"):
  2323. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  2324. continue
  2325. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  2326. # Most-restrictive of all loaded tray types; falls back to the
  2327. # global threshold when no overrides are configured.
  2328. trays = ams_data.get("tray", []) or []
  2329. humidity_threshold = self.resolve_humidity_threshold(
  2330. trays, per_type_thresholds, global_humidity_threshold
  2331. )
  2332. dry_time = int(ams_data.get("dry_time") or 0)
  2333. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  2334. humidity = None
  2335. h_raw = ams_data.get("humidity_raw")
  2336. if h_raw is not None:
  2337. try:
  2338. humidity = int(h_raw)
  2339. except (ValueError, TypeError):
  2340. pass
  2341. if humidity is None:
  2342. h_idx = ams_data.get("humidity")
  2343. if h_idx is not None:
  2344. try:
  2345. humidity = int(h_idx)
  2346. except (ValueError, TypeError):
  2347. pass
  2348. # Already drying — let it run to its configured duration (#1892).
  2349. #
  2350. # We deliberately do NOT stop drying from a humidity re-check here.
  2351. # Relative humidity drops steeply in heated air, so the AMS sensor
  2352. # reads ~15-20% within minutes of the dryer starting even while the
  2353. # filament is still saturated. A humidity-based early-stop therefore
  2354. # always fires at the minimum-time floor, truncating both user-started
  2355. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  2356. # The firmware stops when the configured duration elapses; scheduling
  2357. # stops (print takes priority, queue no longer needs drying) are
  2358. # handled separately via _stop_drying().
  2359. if dry_time > 0:
  2360. if pid not in self._drying_in_progress:
  2361. # Drying we didn't start (manual or from before restart) —
  2362. # track it so scheduling stops still apply; never auto-stop it.
  2363. self._drying_in_progress[pid] = time.monotonic()
  2364. logger.debug(
  2365. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  2366. pid,
  2367. ams_id,
  2368. dry_time,
  2369. humidity,
  2370. )
  2371. continue
  2372. # Humidity below threshold — no need to start drying
  2373. if humidity is None or humidity <= humidity_threshold:
  2374. logger.debug(
  2375. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  2376. pid,
  2377. ams_id,
  2378. humidity,
  2379. humidity_threshold,
  2380. )
  2381. continue
  2382. # Check cannot-dry reasons (power constraints etc.)
  2383. sf_reasons = ams_data.get("dry_sf_reason", [])
  2384. if sf_reasons:
  2385. logger.debug(
  2386. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  2387. pid,
  2388. ams_id,
  2389. sf_reasons,
  2390. )
  2391. continue
  2392. # Get conservative drying params for mixed filaments
  2393. params = self._get_conservative_drying_params(trays, module_type, presets)
  2394. if not params:
  2395. logger.debug(
  2396. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  2397. )
  2398. continue
  2399. temp, duration_hours, filament_type = params
  2400. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  2401. # "drying temperature must not exceed the filament's softening temperature"
  2402. # for Print While Drying). Floor at 40 degC — below that the dryer is
  2403. # ineffective and firmware will reject anyway.
  2404. if mid_print:
  2405. temp = max(40, temp - 5)
  2406. # Start drying
  2407. logger.info(
  2408. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  2409. "starting %s drying at %d°C for %dh%s",
  2410. pid,
  2411. ams_id,
  2412. humidity,
  2413. humidity_threshold,
  2414. filament_type,
  2415. temp,
  2416. duration_hours,
  2417. " (mid-print)" if mid_print else "",
  2418. )
  2419. success = printer_manager.send_drying_command(
  2420. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  2421. )
  2422. if success:
  2423. self._drying_in_progress[pid] = time.monotonic()
  2424. def _sync_drying_state(self):
  2425. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  2426. One direction only: it prunes, it never adds. A printer drying without an
  2427. entry here — because the user started the cycle from Studio, the printer's
  2428. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  2429. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  2430. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  2431. That is deliberate for now rather than an oversight: populating this from
  2432. telemetry would hand the scheduler authority to stop drying a user started
  2433. by hand. It also means the backend-restart case this used to claim to
  2434. handle is not handled.
  2435. """
  2436. to_remove = []
  2437. for pid in self._drying_in_progress:
  2438. state = printer_manager.get_status(pid)
  2439. if not state:
  2440. to_remove.append(pid)
  2441. continue
  2442. # Check if any AMS unit is still drying
  2443. ams_list = state.raw_data.get("ams", [])
  2444. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  2445. if not any_drying:
  2446. to_remove.append(pid)
  2447. for pid in to_remove:
  2448. self._drying_in_progress.pop(pid, None)
  2449. async def _stop_drying(self, printer_id: int):
  2450. """Stop all active drying on a printer (print takes priority)."""
  2451. state = printer_manager.get_status(printer_id)
  2452. if not state:
  2453. self._drying_in_progress.pop(printer_id, None)
  2454. return
  2455. ams_list = state.raw_data.get("ams", [])
  2456. for ams_data in ams_list:
  2457. dry_time = int(ams_data.get("dry_time") or 0)
  2458. if dry_time > 0:
  2459. ams_id = int(ams_data.get("id", 0))
  2460. logger.info(
  2461. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  2462. printer_id,
  2463. ams_id,
  2464. )
  2465. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  2466. self._drying_in_progress.pop(printer_id, None)
  2467. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  2468. """Get all smart plugs associated with a printer."""
  2469. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2470. return list(result.scalars().all())
  2471. @staticmethod
  2472. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  2473. """Pick the plug to power-cycle a printer back online with (#2629).
  2474. Only a plug flagged ``controls_printer_power`` can actually bring the
  2475. printer back; waiting for a boot on an accessory (filter fan, lights)
  2476. just burns the power-on timeout and fails the dispatch. Falls back to
  2477. the first plug when none is flagged, which is the pre-#2629 behaviour.
  2478. Callers must pass a non-empty list.
  2479. """
  2480. for plug in auto_on_plugs:
  2481. if plug.controls_printer_power:
  2482. return plug
  2483. return auto_on_plugs[0]
  2484. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  2485. # chamber-temperature recommendations BambuStudio ships for the matching
  2486. # filament profile; users can override via Settings → Workflow → Preheat
  2487. # card. "default" applies when a loaded tray's normalised type isn't in
  2488. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  2489. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  2490. "PLA": 0,
  2491. "PETG": 0,
  2492. "PETG-CF": 40,
  2493. "ABS": 45,
  2494. "ASA": 45,
  2495. "PA": 50,
  2496. "PA-CF": 55,
  2497. "PC": 50,
  2498. "PC-FR": 50,
  2499. "TPU": 0,
  2500. "PVA": 0,
  2501. "default": 0,
  2502. }
  2503. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  2504. """Parse the user-configured filament→chamber-target map, falling back
  2505. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  2506. are uppercased and the 'default' fallback is always present in the
  2507. returned dict so the resolution loop can index it unconditionally."""
  2508. raw = await self._get_setting(db, "preheat_filament_targets")
  2509. if not raw:
  2510. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2511. try:
  2512. parsed = json.loads(raw)
  2513. if not isinstance(parsed, dict):
  2514. raise ValueError("not an object")
  2515. except (json.JSONDecodeError, ValueError) as exc:
  2516. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  2517. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2518. # Coerce values to int; drop unparseable rows so a stray string
  2519. # doesn't crash the loop.
  2520. out: dict[str, int] = {}
  2521. for key, value in parsed.items():
  2522. try:
  2523. out[str(key).upper()] = int(value)
  2524. except (TypeError, ValueError):
  2525. continue
  2526. if "DEFAULT" not in out:
  2527. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  2528. return out
  2529. @staticmethod
  2530. def _normalize_filament_type(tray_type: str) -> str:
  2531. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  2532. existing drying-preset normalisation (split-at-space, upper-case) so
  2533. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  2534. "PA-CF" (no space to split on)."""
  2535. return tray_type.split()[0].upper() if tray_type else ""
  2536. def _derive_chamber_target(
  2537. self,
  2538. printer: Printer,
  2539. targets: dict[str, int],
  2540. ) -> int:
  2541. """Look up the chamber target for each loaded AMS tray and return the
  2542. max. Returns 0 when no AMS data is available (e.g. external-spool
  2543. prints) or when every loaded slot maps to 0 — the chamber phase then
  2544. short-circuits in the main loop.
  2545. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  2546. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  2547. less slots have empty `tray_type` and contribute nothing."""
  2548. state = printer_manager.get_status(printer.id)
  2549. if state is None:
  2550. return 0
  2551. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  2552. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  2553. if isinstance(ams_list, dict):
  2554. ams_list = ams_list.get("ams") or []
  2555. if not isinstance(ams_list, list):
  2556. return 0
  2557. best = 0
  2558. for ams in ams_list:
  2559. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  2560. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  2561. if not normalised:
  2562. continue
  2563. target = targets.get(normalised, targets.get("DEFAULT", 0))
  2564. if target > best:
  2565. best = target
  2566. return best
  2567. async def _preheat_and_soak(
  2568. self,
  2569. db: AsyncSession,
  2570. item: PrintQueueItem,
  2571. printer: Printer,
  2572. archive: PrintArchive | None,
  2573. ) -> None:
  2574. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  2575. Resolution order:
  2576. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  2577. to the global `preheat_enabled` setting; 'on' forces the stage on
  2578. even if the global is off.
  2579. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  2580. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  2581. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  2582. phase + soak timer).
  2583. 3. Three hardware tiers branch the wait loop:
  2584. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  2585. send M141 to the resolved target, then wait for the chamber sensor
  2586. to reach it (or the max-wait timeout to elapse).
  2587. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  2588. no M141; the bed is the only heat source, so we wait for the chamber
  2589. sensor to rise via bed radiation OR fall through on timeout.
  2590. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  2591. temperature; the function just heats the bed and holds for the
  2592. configured soak duration.
  2593. The bed target comes from the archive's parsed metadata
  2594. (`bed_temperature`); if missing the preheat stage logs and returns
  2595. without dispatching anything, rather than guessing at a default that
  2596. might wreck filament setup.
  2597. Failures are logged but never re-raised — preheat is best-effort. A
  2598. printer that goes offline mid-soak, a refused gcode command, or a
  2599. missing temperature reading must not turn into a failed queue item; the
  2600. normal upload + start path runs immediately after this method returns.
  2601. """
  2602. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  2603. if override == "off":
  2604. return
  2605. if override == "inherit":
  2606. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  2607. if not enabled:
  2608. return
  2609. # override == "on" forces the stage on regardless of the global setting.
  2610. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  2611. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  2612. # Chamber target resolution:
  2613. # 1. Explicit per-item override beats everything (user knows best).
  2614. # 2. Otherwise derive from loaded AMS filament types via the per-
  2615. # filament target map. PLA-only print derives 0 → chamber phase
  2616. # auto-skips without the user touching anything.
  2617. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  2618. if explicit_target is not None and explicit_target > 0:
  2619. chamber_target = int(explicit_target)
  2620. chamber_source = "item-override"
  2621. elif explicit_target == 0:
  2622. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  2623. chamber_source = "item-override-zero"
  2624. else:
  2625. targets = await self._get_preheat_filament_targets(db)
  2626. chamber_target = self._derive_chamber_target(printer, targets)
  2627. chamber_source = "filament-map"
  2628. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  2629. if bed_target <= 0:
  2630. logger.info(
  2631. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  2632. item.id,
  2633. )
  2634. return
  2635. client = printer_manager.get_client(printer.id)
  2636. if client is None:
  2637. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  2638. return
  2639. model = printer.model or ""
  2640. has_heater = supports_chamber_heater(model)
  2641. has_sensor = supports_chamber_temp(model)
  2642. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  2643. logger.info(
  2644. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  2645. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  2646. item.id,
  2647. bed_target,
  2648. chamber_target if do_chamber else 0,
  2649. chamber_source,
  2650. override,
  2651. model,
  2652. has_heater,
  2653. has_sensor,
  2654. max_wait,
  2655. soak_seconds,
  2656. )
  2657. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  2658. # cache the target locally so the polling reads below see consistent
  2659. # state (firmware MQTT echoes lag by ~1s).
  2660. try:
  2661. client.set_bed_temperature(bed_target)
  2662. except Exception as exc:
  2663. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  2664. return
  2665. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  2666. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  2667. # left it on, regardless of M141. Default cooling actively vents the
  2668. # chamber, so a `chamber_target > 0` print with the flap stuck in
  2669. # cooling never converges — the heater fights the open exhaust. We
  2670. # flip the flap BEFORE M141 to "heating" when the preheat wants
  2671. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  2672. # on an H2D that was previously running ABS would otherwise stay in
  2673. # heating mode and overheat PLA). The current-state read keeps the
  2674. # command idempotent — no MQTT chatter when the flap is already where
  2675. # we want it.
  2676. if supports_airduct(model):
  2677. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  2678. desired_id = 1 if desired_airduct == "heating" else 0
  2679. current_state = printer_manager.get_status(printer.id)
  2680. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  2681. if current_airduct != desired_id:
  2682. try:
  2683. client.set_airduct_mode(desired_airduct)
  2684. except Exception as exc:
  2685. logger.warning(
  2686. "Queue item %s: preheat airduct %s mode failed: %s",
  2687. item.id,
  2688. desired_airduct,
  2689. exc,
  2690. )
  2691. if do_chamber and has_heater:
  2692. try:
  2693. client.set_chamber_temperature(chamber_target)
  2694. except Exception as exc:
  2695. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  2696. # Release the pooled DB connection before the (potentially many-minute)
  2697. # heat-soak wait below (#2572). Every setting this method needs is read
  2698. # above; the wait/soak loop only polls printer_manager state and sleeps —
  2699. # it never touches the DB. Without this the caller's transaction sat
  2700. # "idle in transaction" for the whole soak, pinning one pooled connection
  2701. # per preheating printer. expire_on_commit=False keeps item/printer
  2702. # readable afterwards; there are no pending writes to lose here.
  2703. await db.commit()
  2704. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  2705. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  2706. # Poll every 3s — frequent enough for responsive logging without
  2707. # spamming the MQTT state stream. The "converged" predicate is:
  2708. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  2709. # AND
  2710. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  2711. BED_TOLERANCE = 2.0
  2712. CHAMBER_TOLERANCE = 2.0
  2713. POLL_INTERVAL = 3.0
  2714. deadline = asyncio.get_event_loop().time() + max_wait
  2715. while True:
  2716. state = printer_manager.get_status(printer.id)
  2717. if state is None:
  2718. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  2719. break
  2720. temps = state.temperatures or {}
  2721. bed_now = float(temps.get("bed", 0) or 0)
  2722. chamber_now = float(temps.get("chamber", 0) or 0)
  2723. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  2724. if not do_chamber:
  2725. chamber_ok = True # phase disabled or model has neither sensor nor heater
  2726. elif not has_sensor:
  2727. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  2728. else:
  2729. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  2730. if bed_ok and chamber_ok:
  2731. logger.info(
  2732. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  2733. item.id,
  2734. bed_now,
  2735. chamber_now,
  2736. )
  2737. break
  2738. if asyncio.get_event_loop().time() >= deadline:
  2739. logger.info(
  2740. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  2741. item.id,
  2742. bed_now,
  2743. bed_target,
  2744. chamber_now,
  2745. chamber_target if do_chamber else 0,
  2746. )
  2747. break
  2748. await asyncio.sleep(POLL_INTERVAL)
  2749. if soak_seconds > 0:
  2750. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  2751. await asyncio.sleep(soak_seconds)
  2752. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  2753. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  2754. """Turn on smart plug and wait for printer to connect.
  2755. Returns True if printer connected successfully within timeout.
  2756. """
  2757. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  2758. service = await smart_plug_manager.get_service_for_plug(plug, db)
  2759. # Check current plug state
  2760. status = await service.get_status(plug)
  2761. if not status.get("reachable"):
  2762. logger.warning("Smart plug '%s' is not reachable", plug.name)
  2763. return False
  2764. # Turn on if not already on
  2765. if status.get("state") != "ON":
  2766. success = await service.turn_on(plug)
  2767. if not success:
  2768. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  2769. return False
  2770. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  2771. # Get printer from database for connection
  2772. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2773. printer = result.scalar_one_or_none()
  2774. if not printer:
  2775. logger.error("Printer %s not found in database", printer_id)
  2776. return False
  2777. # Wait for printer to boot (give it some time before trying to connect)
  2778. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  2779. await asyncio.sleep(30)
  2780. # Try to connect to the printer periodically
  2781. elapsed = 30 # Already waited 30s
  2782. while elapsed < self._power_on_wait_time:
  2783. # Try to connect
  2784. logger.info("Attempting to connect to printer %s...", printer_id)
  2785. try:
  2786. connected = await printer_manager.connect_printer(printer)
  2787. if connected:
  2788. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  2789. # Give it a moment to stabilize and get status
  2790. await asyncio.sleep(5)
  2791. return True
  2792. except Exception as e:
  2793. logger.debug("Connection attempt failed: %s", e)
  2794. await asyncio.sleep(self._power_on_check_interval)
  2795. elapsed += self._power_on_check_interval
  2796. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  2797. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  2798. return False
  2799. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  2800. """Check if the previous print on this printer succeeded.
  2801. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  2802. deliberate action, not a failure, so subsequent items should still
  2803. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  2804. a skip isn't an actual print attempt, so it must not gate downstream
  2805. items — counting it as a failed predecessor was the cascade bug that
  2806. let a single cancellation block 18 items over 3 days for the reporter.
  2807. Only `failed` and `aborted` — real print-attempt failures — block.
  2808. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  2809. action — #1818) are also excluded from the lookback so the user can
  2810. clear the gate after fixing the physical issue without having to
  2811. re-queue every downstream job.
  2812. """
  2813. result = await db.execute(
  2814. select(PrintQueueItem)
  2815. .where(PrintQueueItem.printer_id == item.printer_id)
  2816. .where(PrintQueueItem.id != item.id)
  2817. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  2818. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  2819. .order_by(PrintQueueItem.completed_at.desc())
  2820. .limit(1)
  2821. )
  2822. prev_item = result.scalar_one_or_none()
  2823. # If no previous item, assume success (first in queue)
  2824. if not prev_item:
  2825. return True
  2826. return prev_item.status in ("completed", "cancelled")
  2827. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  2828. """Schedule power-off if the queue item enabled auto_off_after.
  2829. Delegates to the smart-plug manager so the off honours each plug's
  2830. configured strategy (time delay or temperature threshold), is cancelled
  2831. if the printer starts printing again, and never cuts power on a loaded
  2832. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  2833. powered off on the timeout regardless of print state.
  2834. """
  2835. if not item.auto_off_after:
  2836. return
  2837. try:
  2838. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  2839. except Exception as e:
  2840. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  2841. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  2842. """Get a human-readable name for a queue item."""
  2843. if item.archive_id:
  2844. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2845. archive = result.scalar_one_or_none()
  2846. if archive:
  2847. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2848. if item.library_file_id:
  2849. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2850. library_file = result.scalar_one_or_none()
  2851. if library_file:
  2852. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2853. # A cross-model item (#671) holds no file of its own until a printer is
  2854. # picked, so name it after its first candidate — otherwise every waiting
  2855. # notification for one reads "Job #12". Queried rather than read off
  2856. # item.variants because callers outside the selection loop have not
  2857. # eager-loaded them, and a lazy load raises in async.
  2858. first_variant_name = (
  2859. await db.execute(
  2860. select(LibraryFile.filename)
  2861. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  2862. .where(PrintQueueVariant.queue_item_id == item.id)
  2863. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  2864. .limit(1)
  2865. )
  2866. ).scalar_one_or_none()
  2867. if first_variant_name:
  2868. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  2869. return f"Job #{item.id}"
  2870. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  2871. """Get printer by ID."""
  2872. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2873. return result.scalar_one_or_none()
  2874. async def _notify_dispatch_gave_up(
  2875. self,
  2876. queue_item_id: int,
  2877. printer_id: int,
  2878. created_by_id: int | None,
  2879. reason: str = "Printer accepted the file but never started printing",
  2880. ) -> None:
  2881. """Tell the user the queue item was failed after exhausting its dispatch retries.
  2882. Called from the watchdog, which is a background task with no session of
  2883. its own — hence the fresh one here. Best-effort throughout: the row is
  2884. already marked failed and that is the load-bearing part; a notification
  2885. provider being down must not resurrect the retry loop we just stopped.
  2886. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  2887. path passes its own, because "accepted the file but never started" is the
  2888. opposite of what happened there — the printer refused it outright (#2732).
  2889. """
  2890. try:
  2891. async with async_session() as db:
  2892. item = await db.get(PrintQueueItem, queue_item_id)
  2893. if not item:
  2894. return
  2895. job_name = await self._get_job_name(db, item)
  2896. printer = await self._get_printer(db, printer_id)
  2897. await notification_service.on_queue_job_failed(
  2898. job_name=job_name,
  2899. printer_id=printer_id,
  2900. printer_name=printer.name if printer else "Unknown",
  2901. reason=reason,
  2902. db=db,
  2903. )
  2904. except Exception as e:
  2905. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  2906. try:
  2907. await ws_manager.send_queue_item_failed(
  2908. user_id=created_by_id,
  2909. queue_item_id=queue_item_id,
  2910. printer_id=printer_id,
  2911. reason="never_started",
  2912. )
  2913. except Exception:
  2914. pass # toast is best-effort
  2915. async def _block_on_filament_deficit(
  2916. self,
  2917. db: AsyncSession,
  2918. item: PrintQueueItem,
  2919. ) -> bool:
  2920. """Promote the item to manual_start when the assigned spool is short (#1496).
  2921. Returns True when this dispatch attempt was blocked, False when the
  2922. item is clear to start. A previously-flagged item whose spool has
  2923. since been swapped to one with enough material clears the flag here
  2924. so the next scheduler tick dispatches it.
  2925. """
  2926. # User has explicitly acknowledged the deficit ("Print Anyway") —
  2927. # don't re-flag, don't even compute. Without this short-circuit the
  2928. # scheduler bounces between "user said anyway" (route clears
  2929. # manual_start) and "scheduler re-blocked" (this method re-flags it
  2930. # on identical spool state) (#1698-followup).
  2931. if item.skip_filament_check:
  2932. # #1762 diagnostic: surface the short-circuit at INFO so a
  2933. # future "Print Anyway didn't work" report (e.g. issue #1762
  2934. # comment 3) has actionable evidence in the support bundle
  2935. # without needing DEBUG enabled.
  2936. logger.info(
  2937. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  2938. item.id,
  2939. )
  2940. return False
  2941. try:
  2942. deficit = await compute_deficit_for_queue_item(db, item)
  2943. except Exception as e:
  2944. # Never let a flaky deficit check wedge the queue — log and let
  2945. # dispatch proceed. The PrintModal-side check still runs on the
  2946. # manual paths.
  2947. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  2948. return False
  2949. if deficit:
  2950. item.filament_short = True
  2951. item.manual_start = True
  2952. await db.commit()
  2953. job_name = await self._get_job_name(db, item)
  2954. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  2955. logger.info(
  2956. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  2957. item.id,
  2958. len(deficit),
  2959. )
  2960. try:
  2961. await notification_service.on_queue_job_waiting(
  2962. job_name=job_name,
  2963. target_model=(printer.model if printer else "") or "",
  2964. waiting_reason="filament_short",
  2965. db=db,
  2966. )
  2967. except Exception as e:
  2968. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  2969. return True
  2970. # No deficit — clear any stale flag from a previous tick.
  2971. if item.filament_short:
  2972. item.filament_short = False
  2973. await db.commit()
  2974. return False
  2975. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  2976. """Hand the queue item's owner to printer_manager so the
  2977. print-complete callback can credit the user in PrintLogEntry (#1670).
  2978. No-ops when the item has no `created_by_id` or the referenced user
  2979. row is missing (e.g. user deleted between queue-add and dispatch —
  2980. in that case the print log row falls back to the existing un-credited
  2981. behaviour rather than crashing the dispatch).
  2982. """
  2983. if not item.created_by_id:
  2984. return
  2985. from backend.app.models.user import User
  2986. owner = await db.get(User, item.created_by_id)
  2987. if owner:
  2988. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  2989. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  2990. """Upload file and start print for a queue item.
  2991. Supports two sources:
  2992. - archive_id: Print from an existing archive
  2993. - library_file_id: Print from a library file (file manager)
  2994. """
  2995. logger.info("Starting queue item %s", item.id)
  2996. # Get printer first (needed for both paths)
  2997. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  2998. printer = result.scalar_one_or_none()
  2999. if not printer:
  3000. item.status = "failed"
  3001. item.error_message = "Printer not found"
  3002. item.completed_at = datetime.now(timezone.utc)
  3003. await db.commit()
  3004. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  3005. await self._power_off_if_needed(db, item)
  3006. return
  3007. # Check printer is connected
  3008. if not printer_manager.is_connected(item.printer_id):
  3009. item.status = "failed"
  3010. item.error_message = "Printer not connected"
  3011. item.completed_at = datetime.now(timezone.utc)
  3012. await db.commit()
  3013. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  3014. await self._power_off_if_needed(db, item)
  3015. return
  3016. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  3017. # `items` was taken at the top of check_queue, but the user can /cancel
  3018. # any pending row in the gap before we reach this point. Re-read the
  3019. # row and bail out cleanly instead of starting an FTP upload for a row
  3020. # that's already cancelled. The atomic CAS at the pending→printing
  3021. # transition (below, before start_print) is the load-bearing guard;
  3022. # this is the early-exit optimisation that avoids wasted FTP I/O.
  3023. await db.refresh(item)
  3024. if item.status != "pending":
  3025. logger.info(
  3026. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  3027. item.id,
  3028. item.status,
  3029. )
  3030. return
  3031. # Busy-printer guard (#2598). check_queue gates dispatch on
  3032. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  3033. # keep reporting FINISH for tens of seconds *after* it accepted a
  3034. # project_file (see the watchdog's phase-B note). A watchdog revert
  3035. # (#2555) also releases the dispatch hold, so a re-selected item can
  3036. # reach here while its printer has actually started printing. Uploading
  3037. # and dispatching then collides with the live job — the firmware answers
  3038. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  3039. # live state right before the expensive FTP upload: if the printer is
  3040. # busy, leave the item pending and let a later tick dispatch it once the
  3041. # printer is genuinely idle. No wasted upload, no collision.
  3042. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3043. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  3044. logger.info(
  3045. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  3046. "leaving item pending for a later tick (#2598)",
  3047. item.id,
  3048. item.printer_id,
  3049. pre_dispatch_state,
  3050. )
  3051. return
  3052. # Determine source: archive or library file
  3053. archive = None
  3054. library_file = None
  3055. file_path = None
  3056. filename = None
  3057. cleanup_disk_paths: list[Path] = []
  3058. if item.archive_id:
  3059. # Print from archive
  3060. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3061. archive = result.scalar_one_or_none()
  3062. if not archive:
  3063. item.status = "failed"
  3064. item.error_message = "Archive not found"
  3065. item.completed_at = datetime.now(timezone.utc)
  3066. await db.commit()
  3067. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  3068. await self._power_off_if_needed(db, item)
  3069. return
  3070. # Persist the queue item's selected plate onto the archive so Print
  3071. # History can show the actual plate after cancel/fail/complete (#2603).
  3072. # Only when the archive doesn't already carry one, so a reprint of a
  3073. # plate-specific archive isn't relabelled by a differently-plated
  3074. # queue row.
  3075. if archive.plate_id is None and item.plate_id is not None:
  3076. archive.plate_id = item.plate_id
  3077. file_path = settings.base_dir / archive.file_path
  3078. filename = archive.filename
  3079. elif item.library_file_id:
  3080. # Print from library file (file manager)
  3081. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3082. library_file = result.scalar_one_or_none()
  3083. if not library_file:
  3084. item.status = "failed"
  3085. item.error_message = "Library file not found"
  3086. item.completed_at = datetime.now(timezone.utc)
  3087. await db.commit()
  3088. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  3089. await self._power_off_if_needed(db, item)
  3090. return
  3091. # Library files store absolute paths
  3092. lib_path = Path(library_file.file_path)
  3093. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3094. filename = library_file.filename
  3095. # Create archive from library file so usage tracking has access to the 3MF
  3096. queue_item_id = item.id
  3097. try:
  3098. from backend.app.services.archive import ArchiveService
  3099. archive_service = ArchiveService(db)
  3100. archive = await archive_service.archive_print(
  3101. printer_id=item.printer_id,
  3102. source_file=file_path,
  3103. original_filename=filename,
  3104. created_by_id=item.created_by_id,
  3105. project_id=item.project_id,
  3106. library_file_id=item.library_file_id, # per-file project progress (#1897)
  3107. plate_id=item.plate_id, # selected plate → Print History (#2603)
  3108. )
  3109. if archive:
  3110. item.archive_id = archive.id
  3111. if item.cleanup_library_after_dispatch and not library_file.is_external:
  3112. item.library_file_id = None
  3113. cleanup_disk_paths.append(file_path)
  3114. if library_file.thumbnail_path:
  3115. thumb_path = Path(library_file.thumbnail_path)
  3116. if not thumb_path.is_absolute():
  3117. thumb_path = settings.base_dir / library_file.thumbnail_path
  3118. cleanup_disk_paths.append(thumb_path)
  3119. await db.delete(library_file)
  3120. file_path = settings.base_dir / archive.file_path
  3121. filename = archive.filename
  3122. # Commit, not flush — flush opens the SQLite write
  3123. # transaction (item.archive_id update + library_file
  3124. # delete) and would hold the WAL writer lock through the
  3125. # FTP upload below, causing "database is locked" cascades
  3126. # for sensor history + concurrent cancels (#1853).
  3127. await db.commit()
  3128. logger.info(
  3129. "Queue item %s: Created archive %s from library file %s",
  3130. item.id,
  3131. archive.id,
  3132. item.library_file_id,
  3133. )
  3134. except Exception as e:
  3135. logger.warning(
  3136. "Queue item %s: Failed to create archive from library file: %s",
  3137. queue_item_id,
  3138. e,
  3139. exc_info=True,
  3140. )
  3141. await db.rollback()
  3142. item = await db.get(PrintQueueItem, queue_item_id)
  3143. if item:
  3144. item.status = "failed"
  3145. item.error_message = "Failed to create archive from library file"
  3146. item.completed_at = datetime.now(timezone.utc)
  3147. await db.commit()
  3148. await self._power_off_if_needed(db, item)
  3149. return
  3150. if not archive:
  3151. item.status = "failed"
  3152. item.error_message = "Failed to create archive from library file"
  3153. item.completed_at = datetime.now(timezone.utc)
  3154. await db.commit()
  3155. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  3156. await self._power_off_if_needed(db, item)
  3157. return
  3158. else:
  3159. # Neither archive nor library file specified
  3160. item.status = "failed"
  3161. item.error_message = "No source file specified"
  3162. item.completed_at = datetime.now(timezone.utc)
  3163. await db.commit()
  3164. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  3165. await self._power_off_if_needed(db, item)
  3166. return
  3167. # Check file exists on disk
  3168. if not file_path.exists():
  3169. item.status = "failed"
  3170. item.error_message = "Source file not found on disk"
  3171. item.completed_at = datetime.now(timezone.utc)
  3172. await db.commit()
  3173. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  3174. await self._power_off_if_needed(db, item)
  3175. return
  3176. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  3177. # size dispatched to a printer with a different nozzle installed is
  3178. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  3179. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  3180. # gives the user no idea what went wrong. Catch it here, before we spend
  3181. # time preheating and uploading, and fail with an actionable message.
  3182. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  3183. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  3184. # the printer hasn't reported its nozzles yet, we fall through and let the
  3185. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  3186. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  3187. # as one of the two hotends is a 0.6.
  3188. sliced_nozzle = archive.nozzle_diameter if archive else None
  3189. if sliced_nozzle:
  3190. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  3191. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  3192. if mismatch_msg:
  3193. item.status = "failed"
  3194. item.error_message = mismatch_msg
  3195. item.completed_at = datetime.now(timezone.utc)
  3196. await db.commit()
  3197. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  3198. await notification_service.on_queue_job_failed(
  3199. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3200. printer_id=printer.id,
  3201. printer_name=printer.name,
  3202. reason=mismatch_msg,
  3203. db=db,
  3204. )
  3205. try:
  3206. await ws_manager.send_queue_item_failed(
  3207. user_id=item.created_by_id,
  3208. queue_item_id=item.id,
  3209. printer_id=item.printer_id,
  3210. reason="nozzle_mismatch",
  3211. )
  3212. except Exception:
  3213. pass
  3214. await self._power_off_if_needed(db, item)
  3215. return
  3216. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  3217. # bed (and chamber, if applicable) is at temperature when the firmware
  3218. # starts the actual print routine. Best-effort: any failure logs and
  3219. # falls through to the normal upload+start path rather than turning a
  3220. # configuration issue into a failed queue item.
  3221. await self._preheat_and_soak(db, item, printer, archive)
  3222. # G-code injection for auto-print systems (#422)
  3223. injected_path = None
  3224. # #2547: tracked separately from `injected_path`, which is also set when
  3225. # only a START snippet was injected. Only an END snippet changes what the
  3226. # camera sees at print completion.
  3227. end_gcode_injected = False
  3228. if item.gcode_injection:
  3229. try:
  3230. snippets_raw = await self._get_setting(db, "gcode_snippets")
  3231. if snippets_raw:
  3232. snippets = json.loads(snippets_raw)
  3233. model_snippets = snippets.get(printer.model, {})
  3234. start_gc = (model_snippets.get("start_gcode") or "").strip()
  3235. end_gc = (model_snippets.get("end_gcode") or "").strip()
  3236. if start_gc or end_gc:
  3237. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  3238. injected_path = inject_gcode_into_3mf(
  3239. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  3240. )
  3241. if injected_path:
  3242. file_path = injected_path
  3243. end_gcode_injected = bool(end_gc)
  3244. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  3245. else:
  3246. logger.warning(
  3247. "Queue item %s: G-code injection returned no result, using original", item.id
  3248. )
  3249. except Exception as e:
  3250. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  3251. # #2547: the finish-photo path can't learn from telemetry that this print
  3252. # ends with user End G-code — which means the plate may be gone by the
  3253. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  3254. # the print once the printer confirms it running.
  3255. if end_gcode_injected:
  3256. print_dispatch_context.mark_pending(printer.id)
  3257. # Upload to root directory (not /cache/) - the start_print command references
  3258. # files by name only (ftp://{filename}), so they must be in the root
  3259. remote_filename = derive_remote_filename(filename)
  3260. remote_path = f"/{remote_filename}"
  3261. # Get FTP retry settings
  3262. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3263. logger.info(
  3264. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  3265. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  3266. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  3267. )
  3268. # Release the pooled DB connection before the FTP delete/upload (#2572).
  3269. # Every read this method needs (printer, archive/library, preheat) is
  3270. # done, and the library-file branch already committed its archive
  3271. # creation. Without this the transaction opened by the first SELECT above
  3272. # stays "idle in transaction" for the entire upload — multiple seconds
  3273. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  3274. # a farm dispatching many jobs at once then exhausts the pool. This was
  3275. # correlated to an exact idle-in-transaction session on a 93-printer farm
  3276. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  3277. # readable; the status writes below (upload-failure path and the
  3278. # pending->printing CAS) transparently open a fresh transaction.
  3279. await db.commit()
  3280. # Delete existing file if present (avoids 553 error on overwrite)
  3281. try:
  3282. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  3283. delete_result = await delete_file_async(
  3284. printer.ip_address,
  3285. printer.access_code,
  3286. remote_path,
  3287. socket_timeout=ftp_timeout,
  3288. printer_model=printer.model,
  3289. )
  3290. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  3291. except Exception as e:
  3292. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  3293. # Dispatch toast — announce the upload start with the total byte
  3294. # count so the frontend can render an honest progress bar.
  3295. toast_uid = item.created_by_id
  3296. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3297. try:
  3298. total_bytes = file_path.stat().st_size
  3299. except OSError:
  3300. total_bytes = 0
  3301. try:
  3302. await ws_manager.send_queue_item_uploading(
  3303. user_id=toast_uid,
  3304. queue_item_id=item.id,
  3305. printer_id=item.printer_id,
  3306. printer_name=printer.name,
  3307. file_name=toast_file_name,
  3308. total_bytes=total_bytes,
  3309. )
  3310. except Exception:
  3311. pass # toast is best-effort
  3312. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  3313. # A deadline expiry gets its own message: "check your SD card" is the
  3314. # wrong advice for a link that was simply too slow to finish (#2529).
  3315. upload_error: str | None = None
  3316. try:
  3317. if ftp_retry_enabled:
  3318. uploaded = await with_ftp_retry(
  3319. upload_file_async,
  3320. printer.ip_address,
  3321. printer.access_code,
  3322. file_path,
  3323. remote_path,
  3324. socket_timeout=ftp_timeout,
  3325. printer_model=printer.model,
  3326. progress_callback=progress_bridge,
  3327. max_retries=ftp_retry_count,
  3328. retry_delay=ftp_retry_delay,
  3329. operation_name=f"Upload print to {printer.name}",
  3330. )
  3331. else:
  3332. uploaded = await upload_file_async(
  3333. printer.ip_address,
  3334. printer.access_code,
  3335. file_path,
  3336. remote_path,
  3337. socket_timeout=ftp_timeout,
  3338. printer_model=printer.model,
  3339. progress_callback=progress_bridge,
  3340. )
  3341. except UploadCancelled as e:
  3342. uploaded = False
  3343. upload_error = (
  3344. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  3345. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  3346. )
  3347. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  3348. except Exception as e:
  3349. uploaded = False
  3350. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  3351. # Clean up injected temp file after upload attempt
  3352. if injected_path and injected_path.exists():
  3353. injected_path.unlink(missing_ok=True)
  3354. if not uploaded:
  3355. error_msg = upload_error or (
  3356. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  3357. "See server logs for detailed diagnostics."
  3358. )
  3359. item.status = "failed"
  3360. item.error_message = error_msg
  3361. item.completed_at = datetime.now(timezone.utc)
  3362. await db.commit()
  3363. logger.error(
  3364. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  3365. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  3366. )
  3367. # Send failure notification
  3368. await notification_service.on_queue_job_failed(
  3369. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3370. printer_id=printer.id,
  3371. printer_name=printer.name,
  3372. reason="Failed to upload file to printer",
  3373. db=db,
  3374. )
  3375. try:
  3376. await ws_manager.send_queue_item_failed(
  3377. user_id=toast_uid,
  3378. queue_item_id=item.id,
  3379. printer_id=item.printer_id,
  3380. reason="upload_failed",
  3381. )
  3382. except Exception:
  3383. pass
  3384. await self._power_off_if_needed(db, item)
  3385. return
  3386. # Parse AMS mapping if stored
  3387. ams_mapping = None
  3388. if item.ams_mapping:
  3389. try:
  3390. ams_mapping = json.loads(item.ams_mapping)
  3391. except json.JSONDecodeError:
  3392. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  3393. # Register as expected print so we don't create a duplicate archive
  3394. # Only applicable for archive-based prints
  3395. if archive:
  3396. from backend.app.main import register_expected_print
  3397. register_expected_print(
  3398. item.printer_id,
  3399. remote_filename,
  3400. archive.id,
  3401. ams_mapping=ams_mapping,
  3402. created_by_id=item.created_by_id,
  3403. plate_id=item.plate_id,
  3404. )
  3405. # Registration happens before the print command by necessity (the
  3406. # printer can report the print before the send returns), so record
  3407. # what to undo if we never get as far as sending. `_dispatch_one`
  3408. # rolls back anything still pending here on every exit — exception,
  3409. # early return, or cancel winning the CAS below.
  3410. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  3411. # Propagate the queue item's owner into printer_manager so the
  3412. # print-complete callback can credit the user in the PrintLogEntry
  3413. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  3414. # items) or when the user clicks the manual-start button.
  3415. await self._propagate_owner_to_printer_manager(db, item)
  3416. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  3417. # This prevents phantom reprints if the backend crashes/restarts after the
  3418. # print command is sent but before the status update is committed.
  3419. # If we crash after this commit but before start_print(), the item will be
  3420. # in "printing" status without actually printing - but that's safer than
  3421. # accidentally reprinting the same file hours later.
  3422. #
  3423. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  3424. # initial pending read at the top of check_queue and this point) flips
  3425. # the row to "cancelled" in a separate session. Without the WHERE
  3426. # status='pending' clause, the unconditional update here would silently
  3427. # overwrite that cancellation and we'd ship the MQTT start_print below
  3428. # — printer obeys, user sees "I pressed cancel and the print started".
  3429. # rowcount==0 means the user won the race; bail out, best-effort delete
  3430. # the file we just uploaded, do NOT send start_print.
  3431. now_utc = datetime.now(timezone.utc)
  3432. cas = await db.execute(
  3433. update(PrintQueueItem)
  3434. .where(PrintQueueItem.id == item.id)
  3435. .where(PrintQueueItem.status == "pending")
  3436. .values(status="printing", started_at=now_utc)
  3437. )
  3438. await db.commit()
  3439. if cas.rowcount == 0:
  3440. logger.info(
  3441. "Queue item %s no longer pending at print-command time "
  3442. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  3443. item.id,
  3444. )
  3445. try:
  3446. await delete_file_async(
  3447. printer.ip_address,
  3448. printer.access_code,
  3449. remote_path,
  3450. socket_timeout=ftp_timeout,
  3451. printer_model=printer.model,
  3452. )
  3453. except Exception as cleanup_err:
  3454. logger.debug(
  3455. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  3456. item.id,
  3457. cleanup_err,
  3458. )
  3459. try:
  3460. await ws_manager.send_queue_item_failed(
  3461. user_id=toast_uid,
  3462. queue_item_id=item.id,
  3463. printer_id=item.printer_id,
  3464. reason="cancelled_mid_dispatch",
  3465. )
  3466. except Exception:
  3467. pass
  3468. return
  3469. # Sync the in-memory item so subsequent code that reads item.status /
  3470. # item.started_at sees the values we just persisted.
  3471. item.status = "printing"
  3472. item.started_at = now_utc
  3473. for cleanup_path in cleanup_disk_paths:
  3474. try:
  3475. if cleanup_path.exists():
  3476. cleanup_path.unlink()
  3477. except OSError as cleanup_err:
  3478. logger.warning(
  3479. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  3480. json.dumps(
  3481. {
  3482. "queue_item_id": item.id,
  3483. "path": str(cleanup_path),
  3484. "error": str(cleanup_err),
  3485. },
  3486. sort_keys=True,
  3487. ),
  3488. )
  3489. # Clear the awaiting-plate-clear flag now that we're starting a new print
  3490. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  3491. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  3492. # Capture state before dispatch so the watchdog can detect whether the
  3493. # printer actually transitioned (#967). Also capture subtask_id so the
  3494. # watchdog can recognise "command landed but state hasn't flipped yet"
  3495. # on slow H2D transitions (#1078).
  3496. pre_status = printer_manager.get_status(item.printer_id)
  3497. pre_state = getattr(pre_status, "state", None) if pre_status else None
  3498. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  3499. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  3500. # #1721: respect the user's explicit timelapse choice. The #1397
  3501. # force-on at dispatch was removed because it caused per-layer nozzle
  3502. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  3503. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  3504. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  3505. # FINISH-state fallback — no need to force a video.
  3506. effective_timelapse = bool(item.timelapse)
  3507. # Start the print with AMS mapping, plate_id and print options.
  3508. # nozzle_mapping rides through verbatim — JSON string captured from
  3509. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  3510. # parses + injects it only for dual-nozzle models so a null on every
  3511. # other model is a transparent pass-through.
  3512. started = printer_manager.start_print(
  3513. item.printer_id,
  3514. remote_filename,
  3515. plate_id=item.plate_id or 1,
  3516. ams_mapping=ams_mapping,
  3517. bed_levelling=item.bed_levelling,
  3518. flow_cali=item.flow_cali,
  3519. vibration_cali=item.vibration_cali,
  3520. layer_inspect=item.layer_inspect,
  3521. timelapse=effective_timelapse,
  3522. use_ams=item.use_ams,
  3523. nozzle_offset_cali=item.nozzle_offset_cali,
  3524. nozzle_mapping=item.nozzle_mapping,
  3525. )
  3526. if started:
  3527. # The command is away, so the expectation is now legitimate and must
  3528. # survive. Anything still in this dict when _dispatch_one exits gets
  3529. # rolled back.
  3530. self._unconfirmed_expected_print.pop(item.id, None)
  3531. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  3532. # No dispatch-toast event here: the legacy bg-dispatch path kept
  3533. # status='processing' from upload start until the printer acked
  3534. # (or timed out). The frontend derives "Awaiting printer…" purely
  3535. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  3536. # event would push the status chip out of 'PROCESSING' prematurely
  3537. # — which is exactly what the screenshot at #1625-followup
  3538. # complained about.
  3539. # Register the local 3MF in the cover-cache so /cover skips FTP
  3540. # (#1166 follow-up). file_path was resolved earlier from either the
  3541. # archive or the library file row.
  3542. if file_path is not None:
  3543. cache_3mf_download(item.printer_id, remote_filename, file_path)
  3544. # Hold the printer against further dispatches until the watchdog
  3545. # confirms the printer transitioned (or until the hard timeout).
  3546. # Prevents multi-plate batches from triple-dispatching onto the
  3547. # same H2D Pro while it digests the first project_file (#1157).
  3548. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  3549. # Watchdog: if the printer never transitions out of pre_state AND
  3550. # never advances subtask_id, the MQTT publish was accepted locally but
  3551. # didn't reach the printer (half-broken session — same shape as
  3552. # #887/#936). Revert the queue item so the next dispatch can pick it
  3553. # up instead of leaving it stuck in "printing" (#967). subtask_id
  3554. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  3555. # that would otherwise cause the item to re-dispatch as a reprint
  3556. # of the just-finished job (#1078).
  3557. if pre_state:
  3558. spawn_background_task(
  3559. self._watchdog_print_start(
  3560. item.id,
  3561. item.printer_id,
  3562. pre_state,
  3563. pre_subtask_id,
  3564. pre_gcode_file,
  3565. created_by_id=toast_uid,
  3566. ),
  3567. name=f"watchdog-print-start-{item.id}",
  3568. )
  3569. # Get estimated time for notification.
  3570. #
  3571. # This used to fall back to `library_file.print_time_seconds`, a column
  3572. # LibraryFile does not have — the print time it knows about lives in
  3573. # `file_metadata`. So a library print whose archive carried no parseable
  3574. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  3575. # AttributeError right here, *after* the printer had already been sent
  3576. # the job: the started-notification never fired, and the exception
  3577. # unwound the whole queue pass, so every other printer still waiting to
  3578. # be dispatched on that tick silently missed its turn.
  3579. #
  3580. # The queue item caches the print time at creation ("Cached from
  3581. # archive/library"), which is the value this was reaching for.
  3582. estimated_time = None
  3583. if archive and archive.print_time_seconds:
  3584. estimated_time = archive.print_time_seconds
  3585. elif item.print_time_seconds:
  3586. estimated_time = item.print_time_seconds
  3587. # Send job started notification
  3588. await notification_service.on_queue_job_started(
  3589. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3590. printer_id=printer.id,
  3591. printer_name=printer.name,
  3592. db=db,
  3593. estimated_time=estimated_time,
  3594. )
  3595. # MQTT relay - publish queue job started
  3596. try:
  3597. from backend.app.services.mqtt_relay import mqtt_relay
  3598. await mqtt_relay.on_queue_job_started(
  3599. job_id=item.id,
  3600. filename=filename,
  3601. printer_id=printer.id,
  3602. printer_name=printer.name,
  3603. printer_serial=printer.serial_number,
  3604. )
  3605. except Exception:
  3606. pass # Don't fail if MQTT fails
  3607. else:
  3608. # Clean up uploaded file from SD card to prevent phantom prints
  3609. try:
  3610. await delete_file_async(
  3611. printer.ip_address,
  3612. printer.access_code,
  3613. remote_path,
  3614. printer_model=printer.model,
  3615. )
  3616. except Exception:
  3617. pass # Best-effort — don't fail the error handler
  3618. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  3619. # state can flip from idle to active in the window between the
  3620. # pre-dispatch check above and this publish (the FTP upload takes
  3621. # seconds); start_print() then refuses to send project_file to the
  3622. # now-busy printer and returns False. Failing the item here would be
  3623. # wrong — the printer is fine, it is simply busy — so revert to
  3624. # pending and let a later tick dispatch it once the printer is idle,
  3625. # exactly like the pre-dispatch guard. Only a start_print() False on
  3626. # an idle/unknown printer is a genuine command failure.
  3627. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3628. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  3629. logger.info(
  3630. "Queue item %s: printer %s became busy (state=%s) before the start "
  3631. "command was sent — deferring, reverting item to pending (#2598)",
  3632. item.id,
  3633. item.printer_id,
  3634. post_dispatch_state,
  3635. )
  3636. item.status = "pending"
  3637. item.started_at = None
  3638. await db.commit()
  3639. return
  3640. # Print command failed - revert status
  3641. item.status = "failed"
  3642. item.error_message = "Failed to send print command to printer"
  3643. item.completed_at = datetime.now(timezone.utc)
  3644. await db.commit()
  3645. logger.error(
  3646. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  3647. f"printer_manager.start_print() returned False. "
  3648. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  3649. f"Check printer status and backend logs for details."
  3650. )
  3651. # Send failure notification
  3652. await notification_service.on_queue_job_failed(
  3653. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3654. printer_id=printer.id,
  3655. printer_name=printer.name,
  3656. reason="Failed to send print command to printer - check printer connection and status",
  3657. db=db,
  3658. )
  3659. try:
  3660. await ws_manager.send_queue_item_failed(
  3661. user_id=toast_uid,
  3662. queue_item_id=item.id,
  3663. printer_id=item.printer_id,
  3664. reason="start_command_failed",
  3665. )
  3666. except Exception:
  3667. pass
  3668. await self._power_off_if_needed(db, item)
  3669. @staticmethod
  3670. async def _watchdog_print_start(
  3671. queue_item_id: int,
  3672. printer_id: int,
  3673. pre_state: str,
  3674. pre_subtask_id: str | None = None,
  3675. pre_gcode_file: str | None = None,
  3676. timeout: float = 90.0,
  3677. phase_b_timeout: float = 180.0,
  3678. poll_interval: float = 3.0,
  3679. created_by_id: int | None = None,
  3680. ) -> None:
  3681. """Revert a queue item if the printer never acknowledges the start command.
  3682. Bambuddy optimistically marks the queue item as "printing" right after the
  3683. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  3684. Phase A (up to ``timeout``): wait for either an active-state transition
  3685. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  3686. primary signal; subtask_id advance handles the H2D case where state can
  3687. sit at FINISH for ~50 s after the printer accepted ``project_file``
  3688. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  3689. was lost on a half-broken session (#887/#936) — revert and force
  3690. reconnect (the #967 recovery path).
  3691. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  3692. alone): keep watching for the active-state transition. subtask_id alone
  3693. proves the file landed but not that the printer started — and a printer
  3694. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  3695. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  3696. used to leave the queue item stuck in 'printing' forever because the
  3697. old watchdog returned success as soon as subtask_id advanced. If Phase
  3698. B times out, revert the queue item so the user can retry without
  3699. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  3700. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3701. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  3702. transitions that also don't emit an early subtask_id tick.
  3703. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  3704. refuses to verify our commands will never start this job or any other,
  3705. so waiting out the full 270 s and re-uploading the 3MF twice more only
  3706. burns an upload slot the rest of the farm is queued behind — that path
  3707. is for a printer that might still come good, which this one cannot
  3708. (#2732). It fails the item on the spot with the actual reason instead.
  3709. """
  3710. last_status = None
  3711. landed_on_subtask = False
  3712. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  3713. # every push carrying an `hms` key, so the fault can come and go between
  3714. # 3-second polls. Seeing it once inside the dispatch window is enough.
  3715. command_rejected = False
  3716. # Latched for the same reason as command_rejected: drying can finish, or
  3717. # be stopped by the user, part-way through the dispatch window. Seeing it
  3718. # once is what matters — it is the state the printer was in when it
  3719. # declined to start (#2758).
  3720. drying_ams_ids: list[int] = []
  3721. deadline = time.monotonic() + timeout
  3722. while time.monotonic() < deadline:
  3723. await asyncio.sleep(poll_interval)
  3724. status = printer_manager.get_status(printer_id)
  3725. if not status:
  3726. # Printer disconnected — don't mess with the DB. Drop the
  3727. # in-memory dispatch hold too so a fresh dispatch can retry
  3728. # once the printer comes back; the hard timeout would
  3729. # otherwise hold the printer unnecessarily.
  3730. scheduler._release_dispatch_hold(printer_id)
  3731. return
  3732. last_status = status
  3733. if status.state in _ACTIVE_PRINT_STATES:
  3734. # Printer is actively processing the job — release the
  3735. # post-dispatch hold so the next pending item for this printer
  3736. # can be evaluated normally. We do NOT accept arbitrary state
  3737. # transitions: a printer going FINISH -> IDLE (user dismissed
  3738. # the post-print prompt without accepting our project_file)
  3739. # would otherwise look like "command landed" and leave the
  3740. # queue item stuck in 'printing' forever (#1370).
  3741. scheduler._release_dispatch_hold(printer_id)
  3742. try:
  3743. await ws_manager.send_queue_item_acked(
  3744. user_id=created_by_id,
  3745. queue_item_id=queue_item_id,
  3746. printer_id=printer_id,
  3747. )
  3748. except Exception:
  3749. pass
  3750. return
  3751. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  3752. # Checked only after the active-state exit above: a stale HMS left
  3753. # over from an earlier job must never abort a print that is visibly
  3754. # running. An actually-refused command leaves the printer idle, so
  3755. # this ordering costs the detection nothing.
  3756. if _mqtt_commands_rejected(status):
  3757. command_rejected = True
  3758. break
  3759. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  3760. # Phase A exit — printer accepted the file (subtask_id flipped
  3761. # to our submission id). Don't return yet: the printer may
  3762. # have accepted the command but never actually start (e.g.
  3763. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  3764. # B watches for the active-state transition.
  3765. landed_on_subtask = True
  3766. break
  3767. if landed_on_subtask and not command_rejected:
  3768. phase_b_deadline = time.monotonic() + phase_b_timeout
  3769. while time.monotonic() < phase_b_deadline:
  3770. await asyncio.sleep(poll_interval)
  3771. status = printer_manager.get_status(printer_id)
  3772. if not status:
  3773. scheduler._release_dispatch_hold(printer_id)
  3774. return
  3775. last_status = status
  3776. if status.state in _ACTIVE_PRINT_STATES:
  3777. scheduler._release_dispatch_hold(printer_id)
  3778. try:
  3779. await ws_manager.send_queue_item_acked(
  3780. user_id=created_by_id,
  3781. queue_item_id=queue_item_id,
  3782. printer_id=printer_id,
  3783. )
  3784. except Exception:
  3785. pass
  3786. return
  3787. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  3788. # Same ordering rule as Phase A: a running print wins over a
  3789. # lingering HMS.
  3790. if _mqtt_commands_rejected(status):
  3791. command_rejected = True
  3792. break
  3793. # No active-state transition. Revert the item so the scheduler can retry.
  3794. # Drop the in-memory hold so the retry isn't blocked by it.
  3795. scheduler._release_dispatch_hold(printer_id)
  3796. # Logged on every failed dispatch window, not just the last one, so a
  3797. # support bundle shows the correlation from the first attempt rather than
  3798. # only after the retry budget is spent (#2758).
  3799. if drying_ams_ids:
  3800. logger.info(
  3801. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  3802. queue_item_id,
  3803. printer_id,
  3804. ", ".join(str(i) for i in drying_ams_ids),
  3805. )
  3806. # Four outcomes from the revert attempt, each routed differently:
  3807. # "reverted": row flipped from printing -> pending, run recovery
  3808. # "gave_up": same, but the retry budget is spent — row failed
  3809. # rather than pending, so it stops going round again
  3810. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  3811. # on_print_complete or user). Skip recovery entirely
  3812. # — the print clearly landed somewhere even if the
  3813. # watchdog didn't see the active-state transition.
  3814. # "revert_failed": SQLite contention exhausted retries. Still run
  3815. # recovery so the MQTT session gets a fresh client_id
  3816. # on the half-broken-session path.
  3817. #
  3818. # The retry budget (#2555): reverting to 'pending' hands the item straight
  3819. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  3820. # the watchdog again. For a printer that is genuinely wedged that loop never
  3821. # ends — the reporter had one printer "since this morning still not launch"
  3822. # — and each lap also consumes an upload slot that the other printers in the
  3823. # farm are waiting on. Retrying is right; retrying forever is not.
  3824. async def _do_revert(db):
  3825. item = await db.get(PrintQueueItem, queue_item_id)
  3826. if not item or item.status != "printing":
  3827. return "already_moved_on"
  3828. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  3829. item.started_at = None
  3830. # Charge the attempt to the candidate that was actually dispatched, so
  3831. # a cross-model item (#671) reaches for its other file next lap instead
  3832. # of retrying the printer that just failed to start. Matched by file
  3833. # because that is what the resolver copied onto the row.
  3834. if item.library_file_id is not None:
  3835. await db.execute(
  3836. update(PrintQueueVariant)
  3837. .where(PrintQueueVariant.queue_item_id == item.id)
  3838. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  3839. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  3840. )
  3841. if command_rejected:
  3842. # No retry budget for this one: the printer refused to verify the
  3843. # command, and re-uploading the same 3MF to the same printer will
  3844. # be refused the same way. Fail now with the fix rather than after
  3845. # three laps of a message about SD cards (#2732).
  3846. item.status = "failed"
  3847. item.error_message = (
  3848. "The printer rejected the print command: MQTT command verification failed "
  3849. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  3850. "then start the job again."
  3851. )
  3852. item.completed_at = datetime.now(timezone.utc)
  3853. await db.commit()
  3854. return "command_rejected"
  3855. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  3856. item.status = "failed"
  3857. if drying_ams_ids:
  3858. # #2758: the generic message below sent the reporter looking
  3859. # at the SD card while the actual obstacle — AMS units in a
  3860. # drying cycle — was on screen the whole time. Name what we
  3861. # observed and let the user judge it; Bambuddy does not stop
  3862. # the cycle itself, because on this hardware drying can run
  3863. # alongside a print and stopping it may not be the fix.
  3864. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  3865. item.error_message = (
  3866. f"The printer accepted the file but never started printing, after "
  3867. f"{item.dispatch_attempts} attempts. {units} "
  3868. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  3869. f"some printers refuse to begin a print while an AMS is in a drying "
  3870. f"cycle, and an AMS drying without its external power supply can also "
  3871. f"leave too little power for the start-of-print calibration. Stop the "
  3872. f"drying, or connect the AMS power supply, and start the job again."
  3873. )
  3874. else:
  3875. item.error_message = (
  3876. f"The printer accepted the file but never started printing, after "
  3877. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  3878. f"prompt or error, confirm its SD card is readable, and start the job again."
  3879. )
  3880. item.completed_at = datetime.now(timezone.utc)
  3881. await db.commit()
  3882. return "gave_up"
  3883. item.status = "pending"
  3884. await db.commit()
  3885. return "reverted"
  3886. try:
  3887. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  3888. except Exception as e:
  3889. logger.warning(
  3890. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  3891. "scheduler may keep treating this item as in-flight",
  3892. queue_item_id,
  3893. printer_id,
  3894. e,
  3895. )
  3896. revert_outcome = "revert_failed"
  3897. if revert_outcome == "already_moved_on":
  3898. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  3899. # other path) already moved the item past 'printing', don't run the
  3900. # MQTT session-recovery logic below — a forced reconnect on a healthy
  3901. # session breaks ongoing prints on the same printer.
  3902. return
  3903. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  3904. if revert_outcome == "command_rejected":
  3905. logger.error(
  3906. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  3907. "failed) — the print command was rejected, not lost. Failing the item "
  3908. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  3909. queue_item_id,
  3910. printer_id,
  3911. HMS_MQTT_VERIFY_FAILED,
  3912. )
  3913. await scheduler._notify_dispatch_gave_up(
  3914. queue_item_id,
  3915. printer_id,
  3916. created_by_id,
  3917. reason="Printer rejected the print command (MQTT command verification failed)",
  3918. )
  3919. # Same reasoning as the landed_on_subtask path below: the file is on
  3920. # the printer and a forced reconnect would only add 0500_4003 to a
  3921. # problem that has nothing to do with the MQTT session (#1150).
  3922. return
  3923. if revert_outcome == "gave_up":
  3924. logger.error(
  3925. "Queue item %s: printer %d never started the print after %d dispatch "
  3926. "attempts (last one waited %.0fs) — marking the item failed instead of "
  3927. "re-uploading it again (#2555)",
  3928. queue_item_id,
  3929. printer_id,
  3930. DISPATCH_MAX_ATTEMPTS,
  3931. total_timeout,
  3932. )
  3933. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  3934. elif revert_outcome == "reverted":
  3935. if landed_on_subtask:
  3936. logger.warning(
  3937. "Queue item %s: printer %d accepted project_file (subtask_id "
  3938. "advanced) but never transitioned to an active state within "
  3939. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  3940. "for retry (#1678)",
  3941. queue_item_id,
  3942. printer_id,
  3943. total_timeout,
  3944. )
  3945. else:
  3946. logger.warning(
  3947. "Queue item %s: printer %d did not respond to print command within "
  3948. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  3949. "for retry (#967)",
  3950. queue_item_id,
  3951. printer_id,
  3952. timeout,
  3953. pre_state,
  3954. pre_subtask_id,
  3955. )
  3956. # Phase B was entered iff subtask_id advanced, which means the
  3957. # project_file landed on the printer. A forced reconnect at this point
  3958. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  3959. # skip the recovery entirely.
  3960. if landed_on_subtask:
  3961. return
  3962. # Phase A timeout path: if the printer's gcode_file changed since
  3963. # pre-dispatch, the project_file command landed and the printer is
  3964. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3965. # If gcode_file is unchanged, the publish was silently swallowed
  3966. # (#887/#936) and force_reconnect recovery is what we want.
  3967. client = printer_manager.get_client(printer_id)
  3968. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  3969. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  3970. if publish_landed:
  3971. logger.warning(
  3972. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  3973. "received the command and is parsing slowly. Skipping forced "
  3974. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  3975. queue_item_id,
  3976. current_gcode_file,
  3977. pre_gcode_file,
  3978. )
  3979. elif client and hasattr(client, "force_reconnect_stale_session"):
  3980. client.force_reconnect_stale_session(
  3981. f"queue print command unacknowledged after {timeout:.0f}s "
  3982. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  3983. )
  3984. # Global scheduler instance
  3985. scheduler = PrintScheduler()