print_scheduler.py 485 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from fastapi import HTTPException
  14. from sqlalchemy import delete, false, func, or_, select, true, update
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy.orm import selectinload
  17. from backend.app.core.config import settings
  18. from backend.app.core.database import async_session, run_with_retry
  19. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  20. from backend.app.core.tasks import spawn_background_task
  21. from backend.app.core.websocket import ws_manager
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.library import LibraryFile
  24. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  25. from backend.app.models.printer import Printer
  26. from backend.app.models.scheduled_drying import ScheduledDrying
  27. from backend.app.models.settings import Settings
  28. from backend.app.models.smart_plug import SmartPlug
  29. from backend.app.models.spool_assignment import SpoolAssignment
  30. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  31. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  32. from backend.app.services.bambu_ftp import (
  33. FtpFailureKind,
  34. FtpFailureReport,
  35. UploadCancelled,
  36. cache_3mf_download,
  37. delete_file_async,
  38. describe_upload_failure,
  39. get_ftp_retry_settings,
  40. upload_file_async,
  41. with_ftp_retry,
  42. )
  43. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  44. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  45. from backend.app.services.finance_budget import (
  46. create_budget_reservation,
  47. release_budget_reservation,
  48. validate_print_budget,
  49. )
  50. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  51. from backend.app.services.mqtt_relay import mqtt_relay
  52. from backend.app.services.notification_service import notification_service
  53. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  54. from backend.app.services.printer_manager import (
  55. printer_manager,
  56. supports_airduct,
  57. supports_chamber_heater,
  58. supports_chamber_temp,
  59. supports_drying,
  60. supports_drying_while_printing,
  61. )
  62. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  63. from backend.app.services.spool_assignment_notifications import (
  64. _global_tray_from_assignment,
  65. _slot_label_from_global_tray,
  66. )
  67. from backend.app.utils.ams_drying import is_countdown_parked
  68. from backend.app.utils.ams_humidity import ams_humidity_percent
  69. from backend.app.utils.archive_paths import archive_photos_dir
  70. from backend.app.utils.color_utils import perceptual_color_distance
  71. from backend.app.utils.filament_types import canonical_filament_type
  72. from backend.app.utils.filename import derive_remote_filename
  73. from backend.app.utils.library_paths import move_library_photos
  74. from backend.app.utils.local_time import utcnow_naive
  75. from backend.app.utils.printer_models import (
  76. is_dual_nozzle_model,
  77. is_gcode_compatible,
  78. is_nozzle_rack_model,
  79. normalize_printer_model,
  80. )
  81. from backend.app.utils.threemf_tools import (
  82. default_plate_number,
  83. extract_rack_plan_from_3mf,
  84. extract_slot_extruders_from_3mf,
  85. select_plate_gcode_name,
  86. )
  87. logger = logging.getLogger(__name__)
  88. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  89. """Human slot name for an assignment tuple, in the spelling already in use.
  90. Composed from the notification side's own pair rather than spelled out again
  91. here. The hand-rolled version this replaces got three real slot kinds wrong:
  92. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  93. ``chr(191)``; both externals collapsed to one label, because an external
  94. assignment stores ams_id 255 with tray_id picking left or right
  95. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  96. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  97. Naming the same slot two ways is its own defect once an alert and the
  98. Inventory page are meant to be talking about the same tray, so this defers
  99. rather than adding a fifth spelling.
  100. """
  101. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  102. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  103. # interval: the fast path runs every 3 s while an upload is in flight, and a
  104. # low spool does not need answering at that resolution (#2913).
  105. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  106. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  107. # days, so a finer check would only repeat the same answer.
  108. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  109. # The settings row that holds which stock alerts have already been sent (#2955).
  110. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  111. # The Inventory page asks for this many usage records and the forecast panel
  112. # builds its rates from them; the alert reads the same window so the two agree.
  113. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  114. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  115. """Remaining filament as a percentage of the label weight.
  116. The same arithmetic the Inventory page's Low Stock count uses, and it works
  117. unchanged in both inventory modes: internal spools store ``weight_used``
  118. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  119. ``remaining_weight`` so the shape matches. Returns None when there is no
  120. label weight to be a percentage of -- a spool that cannot say how full it
  121. started cannot say how empty it is.
  122. """
  123. if not label_weight or label_weight <= 0:
  124. return None
  125. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  126. return remaining / float(label_weight) * 100.0
  127. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  128. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  129. # byte gate) from before the scheduler unification. Time gate keeps small
  130. # files from going silent (a single 8 KB chunk fires once and that's it);
  131. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  132. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  133. # sub-200 ms files.
  134. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  135. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  136. # How far back chamber temperature samples are retained. 2h comfortably spans
  137. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  138. # before the next print.
  139. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  140. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  141. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  142. # who clear plates promptly will want far less than this; it is deliberately
  143. # the cautious end, since the cost of it being too short is only a re-soak.
  144. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  145. # Max acceptable gap between two consecutive chamber samples before we treat
  146. # the older one as belonging to a separate observation run (printer went
  147. # offline and came back). Above ~30s cadence with a safety margin.
  148. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  149. # How long the chamber must read below target before we accept that it really
  150. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  151. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  152. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  153. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  154. # sub-target readings are therefore a door opening or noise, not lost soak,
  155. # and a plate swap (exactly when keep-warm is running) produces one. Six
  156. # minutes clears the longest such artifact observed (~5 min once bracketed by
  157. # its neighbouring samples) and still sits far below the 23-minute floor for
  158. # real cooling.
  159. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  160. # How often the preheat stage re-checks that the item it is heating for still
  161. # wants to be printed. Cancelling only writes `status` to the database — it
  162. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  163. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  164. # and the printer stays in `busy_printers`, blocking every other queued item
  165. # behind a print that is not happening.
  166. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  167. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  168. _AIRDUCT_MODE_COOLING = 0
  169. _AIRDUCT_MODE_HEATING = 1
  170. # How long a queue row may stay 'printing' while its printer sits in a terminal
  171. # state before the scheduler closes it itself (#2829).
  172. #
  173. # A real completion arrives within seconds of the printer going terminal, so
  174. # five minutes is far outside the normal path — this only ever sees a row whose
  175. # completion was refused or never delivered. It is the whole cost of the
  176. # failure to the user, though: a stranded row blocks every later job for that
  177. # printer, so it should not be raised without reason.
  178. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  179. # gcode_state values that mean the print is over, mapped to the queue status
  180. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  181. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  182. # which the queue calls cancelled) so a recovered row cannot disagree with one
  183. # closed by the normal path.
  184. _TERMINAL_STATE_QUEUE_STATUS = {
  185. "FINISH": "completed",
  186. "FAILED": "failed",
  187. "IDLE": "cancelled",
  188. }
  189. def _terminal_queue_status(state) -> str | None:
  190. """Queue status implied by *state*, or None if the print is not over.
  191. None for a disconnected printer as well as a busy one: a printer we are not
  192. talking to has a stale ``state`` field that proves nothing about what it is
  193. doing now.
  194. """
  195. if state is None or not getattr(state, "connected", False):
  196. return None
  197. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  198. @dataclass
  199. class _KeepWarmEntry:
  200. """Per-printer keep-warm state.
  201. - ``started``: monotonic time when keep-warm first fired for this printer.
  202. Used by the max-duration timeout.
  203. - ``held_target``: last bed target we successfully published. On release
  204. we only send bed-off when firmware still reports this value, so a user
  205. or subsequent print that changed the target isn't clobbered.
  206. - ``expired``: latched True when the max-duration timeout fires. Prevents
  207. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  208. release sweep drops the entry entirely once the printer leaves the
  209. candidate set.
  210. """
  211. started: float
  212. held_target: int
  213. expired: bool = False
  214. # Auto-drying re-arm guards (#2770).
  215. #
  216. # An AMS reports HIGHER relative humidity while it is warm than once it has
  217. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  218. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  219. # threshold set inside that band therefore cannot be satisfied while the box is
  220. # hot, and the firmware is free to end a cycle whenever it decides the filament
  221. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  222. # the threshold and arms another cycle. The reporter's log has five 12-hour
  223. # cycles armed inside four hours, one of them six seconds after the previous
  224. # ended.
  225. #
  226. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  227. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  228. # manual or firmware-run dry is untouched.
  229. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  230. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  231. # Sustained-humidity wait (#2518): an above-threshold streak is only
  232. # "continuous" if some pass observed it within the gap ceiling. A unit that
  233. # goes unobserved longer (print running, printer disconnected, sensor silent)
  234. # restarts its streak rather than inheriting a stale one. The ceiling is
  235. # derived from the scheduler cadence — four missed passes — with this floor so
  236. # a fast-polling configuration does not void streaks on a single hiccup.
  237. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  238. # How long a finished scheduled drying row is kept before it is pruned.
  239. SCHEDULED_DRYING_RETENTION_DAYS = 7
  240. # How often that prune actually runs. The check itself is called on every queue
  241. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  242. # write transaction, which SQLite serialises against every other writer. Rows
  243. # only become prunable a week after they finish, so anything short of hourly is
  244. # paying that cost for nothing.
  245. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  246. class _UploadProgressBridge:
  247. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  248. ``upload_file_async`` runs the FTP transfer in an executor thread and
  249. invokes its ``progress_callback`` from that thread, so the callback
  250. body cannot ``await`` directly. This bridge captures the asyncio loop
  251. at construction (on the scheduler thread) and uses
  252. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  253. matches the legacy background_dispatch.py path 1:1 so the toast feels
  254. identical to the pre-#1625 experience.
  255. Failures inside the emit are swallowed — progress is a UX nicety, the
  256. upload itself must not fail because of a WS hiccup.
  257. """
  258. def __init__(self, user_id: int | None, queue_item_id: int):
  259. self._user_id = user_id
  260. self._queue_item_id = queue_item_id
  261. try:
  262. self._loop = asyncio.get_running_loop()
  263. except RuntimeError:
  264. self._loop = None
  265. self._last_emit_bytes = 0
  266. self._last_emit_monotonic = 0.0
  267. self._has_emitted = False
  268. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  269. if self._loop is None or total_bytes <= 0:
  270. return
  271. now = time.monotonic()
  272. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  273. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  274. # the four matter most: first-call so the user sees something even
  275. # for sub-chunk-size files; uploaded >= total so the bar locks at
  276. # 100% even when the throttle would otherwise eat it.
  277. should_emit = (
  278. not self._has_emitted
  279. or bytes_transferred >= total_bytes
  280. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  281. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  282. )
  283. if not should_emit:
  284. return
  285. self._has_emitted = True
  286. self._last_emit_bytes = bytes_transferred
  287. self._last_emit_monotonic = now
  288. try:
  289. asyncio.run_coroutine_threadsafe(
  290. ws_manager.send_queue_item_upload_progress(
  291. user_id=self._user_id,
  292. queue_item_id=self._queue_item_id,
  293. bytes_transferred=bytes_transferred,
  294. total_bytes=total_bytes,
  295. ),
  296. self._loop,
  297. )
  298. except Exception:
  299. pass # progress is best-effort, never block the upload
  300. # Bambu firmware states that mean the project_file has actually been accepted
  301. # and the printer is now processing / running / paused mid-print. Used by the
  302. # dispatch watchdog (#1370): a transition into one of these states means the
  303. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  304. # a post-print prompt) is NOT a valid "command landed" signal even though the
  305. # state value did change. SLICING is included because some firmwares park
  306. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  307. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  308. # How many times the start-watchdog may revert an item to 'pending' before it
  309. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  310. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  311. # both never recovers and starves the other printers of dispatch slots. Three
  312. # is chosen to clear the transient causes the watchdog already recovers from —
  313. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  314. # force-reconnect on the very next attempt — while still bounding the loop.
  315. DISPATCH_MAX_ATTEMPTS = 3
  316. # Upload failures that mean the file never reached the printer's storage: the
  317. # file service refused or never answered (#3210). These put the item back in
  318. # the queue instead of failing it, because nothing about the job is wrong --
  319. # and failing it left the printer idle, so the next pass handed it the next
  320. # item, which failed the same way. One P2S whose file service was out of
  321. # connection slots ate 43 queued jobs in ten minutes that way.
  322. #
  323. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  324. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  325. # and an upload that overran its deadline -- each of those would fail the same
  326. # way on every retry.
  327. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  328. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  329. )
  330. # How long a printer whose upload was put back stays out of dispatch (#3210).
  331. # The first window matches the FTP client's own handshake cool-off, so the
  332. # retry lands after the client would talk to the printer again anyway. Each
  333. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  334. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  335. # five connection attempts and a page of log. A successful upload resets it.
  336. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  337. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  338. def _upload_backoff_seconds(refusals: int) -> int:
  339. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  340. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  341. @dataclass(slots=True)
  342. class _ModelCandidate:
  343. """One (file, printer model) pair the model-based matcher may try.
  344. Model-based assignment used to have exactly one of these per item, held
  345. directly in the item's own columns. Cross-model queue items (#671) have
  346. several, held in ``print_queue_variants``. Both shapes are normalised into
  347. this so the matching, the cross-model gate and the waiting-reason handling
  348. are written once and an item without variants provably takes the same path
  349. it took before variants existed.
  350. ``variant`` is None for the item's own columns and set for a real variant
  351. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  352. item once that candidate wins.
  353. """
  354. target_model: str | None
  355. sliced_for: str | None
  356. required_filament_types: str | None
  357. filament_overrides: str | None
  358. variant: "PrintQueueVariant | None" = None
  359. def _sliced_for_model(archive, library_file) -> str | None:
  360. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  361. if archive is not None:
  362. return archive.sliced_for_model
  363. if library_file is not None and library_file.file_metadata:
  364. return library_file.file_metadata.get("sliced_for_model")
  365. return None
  366. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  367. """The filament a candidate needs, as ``(types, overrides)``.
  368. Both columns are JSON text written by the slicer step. Malformed content is
  369. treated as no constraint rather than as an error: a job whose overrides
  370. cannot be parsed still prints, it just gets no filament-based narrowing.
  371. Overrides carry their own types, so the returned type list is the union of
  372. the two — an override on one slot must not drop the requirements of the
  373. slots it says nothing about.
  374. Shared by the matcher and by the smart-plug wake step so both ask a printer
  375. for the same filament (#2876). Waking a printer the matcher would then
  376. reject on colour is the bug this exists to prevent.
  377. """
  378. required_types = None
  379. if candidate.required_filament_types:
  380. try:
  381. required_types = json.loads(candidate.required_filament_types)
  382. except json.JSONDecodeError:
  383. pass
  384. filament_overrides = None
  385. if candidate.filament_overrides:
  386. try:
  387. filament_overrides = json.loads(candidate.filament_overrides)
  388. except json.JSONDecodeError:
  389. pass
  390. effective_types = required_types
  391. if filament_overrides:
  392. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  393. if override_types:
  394. effective_types = sorted(set(required_types or []) | set(override_types))
  395. return effective_types, filament_overrides
  396. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  397. """Whether ``item`` was competing for the printer another item just took.
  398. The SJF starvation guard marks a job as jumped when a shorter one lower in
  399. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  400. compete for the same printer, so the guard has to look across both lanes
  401. (#3200); looking only inside the dispatched item's own lane let a stream of
  402. short model-based jobs hold a longer pinned job back indefinitely.
  403. Location filters are not checked: over-marking only lifts an item that was
  404. going to wait anyway, while under-marking is the starvation this prevents.
  405. """
  406. if item.printer_id is not None:
  407. return item.printer_id == printer_id
  408. if not printer_model:
  409. return False
  410. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  411. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  412. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  413. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  414. """Candidate files for ``item``, best first.
  415. An item with no variant rows yields exactly one candidate built from its own
  416. columns — the pre-#671 behaviour, unchanged.
  417. Variants come back least-attempted first, ties broken by the user's
  418. ``position``. On the first pass every count is zero, so this is purely the
  419. user's priority order. After a start-watchdog bounce the printer that failed
  420. drops behind, so the next lap tries the other machine rather than spending the
  421. item's whole retry budget on the one that is wedged. Once every candidate has
  422. been tried equally often they cycle again, which keeps the item-level
  423. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  424. still gives up, it just does not give up without trying them.
  425. """
  426. if not item.variants:
  427. if not item.archive_id and not item.library_file_id:
  428. # Nothing to print at all. Dispatching would fail deep in the upload
  429. # on "No archive_id or library_file_id"; the caller holds the item
  430. # with an explanation instead.
  431. return []
  432. return [
  433. _ModelCandidate(
  434. target_model=item.target_model,
  435. sliced_for=_sliced_for_model(item.archive, item.library_file),
  436. required_filament_types=item.required_filament_types,
  437. filament_overrides=item.filament_overrides,
  438. )
  439. ]
  440. # Drop candidates whose file is gone or in the trash. Both are reachable and
  441. # neither is covered by the schema: library deletes are soft (the row lives
  442. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  443. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  444. # fires there and a hard delete leaves the variant row pointing at nothing.
  445. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  446. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  447. return [
  448. _ModelCandidate(
  449. target_model=v.target_model,
  450. sliced_for=_sliced_for_model(None, v.library_file),
  451. required_filament_types=v.required_filament_types,
  452. filament_overrides=v.filament_overrides,
  453. variant=v,
  454. )
  455. for v in ordered
  456. ]
  457. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  458. """Fold one waiting reason per candidate into a single line for the item.
  459. A cross-model item produces a reason per candidate, and pasting them
  460. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  461. — on which machine?). Each reason is prefixed with its model, except in the
  462. single-candidate case where the item already displays its target model and
  463. the prefix would be noise.
  464. Identical reasons collapse rather than repeat, so three idle-less models
  465. read as one clause.
  466. When *every* candidate is merely busy the parts are joined with the ``" | "``
  467. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  468. unprefixed. That case must keep testing busy-only: a fleet that is simply
  469. printing needs no user action, and labelling the clauses would turn each pass
  470. over a two-model item into a "job waiting" notification.
  471. """
  472. reasons = [(model, reason) for model, reason in per_model if reason]
  473. if not reasons:
  474. return None
  475. if len(reasons) == 1:
  476. return reasons[0][1]
  477. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  478. if len(distinct) == 1:
  479. return distinct[0]
  480. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  481. return " | ".join(distinct)
  482. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  483. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  484. """Human label for the models an item is waiting on ("H2S or H2C").
  485. Notifications take a single target model. For a cross-model item the item's
  486. own ``target_model`` is whichever variant happens to be first, which reads as
  487. a lie once it is the H2C that actually runs — so name all of them.
  488. """
  489. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  490. if not models:
  491. return None
  492. return " or ".join(models)
  493. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  494. """True if ``mapping`` is a non-empty list whose every entry is the
  495. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  496. Such a mapping is a bug artifact: a frontend status-load race can serialize
  497. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  498. recomputed from live status at dispatch rather than trusted, otherwise it
  499. reaches the print command and is silently downgraded to external-spool mode.
  500. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  501. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  502. explicit external selection (``>= 254``) is NOT unresolved either — those
  503. keep their meaning.
  504. """
  505. if not isinstance(mapping, list) or not mapping:
  506. return False
  507. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  508. def _is_tray_id(value: object) -> bool:
  509. """True when ``value`` can be read as a global tray ID.
  510. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  511. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  512. against whatever happens to be loaded there.
  513. """
  514. return isinstance(value, int) and not isinstance(value, bool)
  515. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  516. # stages an item (#2799). The manual_start branch clears every other reason on
  517. # a staged item (#3074); this one is the reason it was staged, so it stays.
  518. _UNMATCHED_HOLD_PREFIX = "Needs "
  519. # How often an "any model" job held for low filament looks for another printer
  520. # of its model that has enough (#3137). Each look matches its filament on every
  521. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  522. _SHORT_HOLD_RECHECK_SECONDS = 120
  523. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  524. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  525. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  526. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  527. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  528. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  529. for a filament this plate does not use. A slot past the end of the mapping
  530. is unresolved too.
  531. """
  532. unresolved = []
  533. for req in required:
  534. slot_id = req.get("slot_id") or 0
  535. if slot_id <= 0:
  536. continue
  537. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  538. if not _is_tray_id(tray) or tray < 0:
  539. unresolved.append(req)
  540. return unresolved
  541. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  542. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  543. # on `_mapping_is_all_unresolved`.
  544. _EXTERNAL_TRAY_ID_MIN = 254
  545. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  546. """The ``mapping`` entries for the slots this plate actually prints.
  547. ``required`` comes from ``extract_filament_requirements``, which drops any
  548. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  549. consumes, and one absent from it is padding. That distinction is why this
  550. decision lives here and not in the MQTT command builder: a ``-1`` in the
  551. mapping means either "this plate does not print filament N" or "we never
  552. worked out which tray", and only the plate's own filament list separates
  553. them. The builder sees both as the same byte, which is how a plate whose one
  554. printed filament sat on the external spool went out as `use_ams=true` with a
  555. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  556. with 07FF_8012 (#3087).
  557. Returns None whenever the two cannot be lined up — no mapping, no parsed
  558. requirements, or a requirement the mapping is too short to cover — so every
  559. caller falls back to existing behaviour rather than acting on a guess.
  560. """
  561. if not isinstance(mapping, list) or not mapping or not required:
  562. return None
  563. entries = []
  564. for filament in required:
  565. slot_id = filament.get("slot_id")
  566. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  567. # The mapping and the requirements disagree about how many filaments
  568. # the file has. They came from different reads, so judge nothing.
  569. return None
  570. entries.append(mapping[slot_id - 1])
  571. return entries or None
  572. def _is_external_tray(tray_id) -> bool:
  573. """True for an explicit external-spool selection (254/255), not for an
  574. unresolved slot and not for an AMS tray."""
  575. if tray_id is None:
  576. return False
  577. try:
  578. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  579. except (TypeError, ValueError):
  580. return False
  581. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  582. """Whether this printer could have two extruders, judged generously.
  583. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  584. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  585. why the MQTT command builder skips its own use_ams reconcile there. Anything
  586. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  587. with, external spools or not.
  588. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  589. behaviour it has always had, while a wrong "no" would rewrite a field that
  590. steers which nozzle prints. The model name is the first answer (it is what
  591. the command builder falls back to as well), then the same live evidence the
  592. dispatcher's extruder annotation uses — a second nozzle reporting a
  593. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  594. since a single-nozzle printer has exactly one.
  595. """
  596. if is_dual_nozzle_model(printer_model):
  597. return True
  598. nozzles = getattr(status, "nozzles", None) or []
  599. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  600. return True
  601. raw = getattr(status, "raw_data", None) or {}
  602. if raw.get("ams_extruder_map"):
  603. return True
  604. vt_trays = raw.get("vt_tray") or []
  605. return isinstance(vt_trays, list) and len(vt_trays) > 1
  606. def _int_or(value, default: int) -> int:
  607. """``int(value)``, or ``default`` when the field is missing or junk.
  608. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  609. the next — and a tray id that fails to parse must not take the whole
  610. derivation down with it.
  611. """
  612. try:
  613. return int(value)
  614. except (TypeError, ValueError):
  615. return default
  616. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  617. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  618. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  619. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  620. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  621. agree or a mapping cannot be read back against live tray telemetry.
  622. """
  623. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  624. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  625. """The global tray ids ``item`` actually prints from, or None if unknown.
  626. ``ams_mapping`` is the array the print command carries: position = filament
  627. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  628. not use. None means "no usable statement" — no mapping, unparseable JSON,
  629. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  630. documents), or one that resolves to no tray at all. Callers must treat None
  631. as "consider every loaded tray" rather than "consider none": narrowing on
  632. an absent mapping would silently drop requirements the print really has.
  633. """
  634. raw = getattr(item, "ams_mapping", None)
  635. if not raw:
  636. return None
  637. if isinstance(raw, str):
  638. try:
  639. mapping = json.loads(raw)
  640. except (json.JSONDecodeError, TypeError):
  641. return None
  642. else:
  643. mapping = raw
  644. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  645. return None
  646. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  647. return used or None
  648. def _mqtt_commands_rejected(status) -> bool:
  649. """True when the printer is currently reporting that it refused a command.
  650. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  651. a control command it could not verify. Queries still answer, so the printer
  652. looks connected and idle while project_file, gcode_line and
  653. ams_change_filament are all dropped — no amount of waiting or re-uploading
  654. changes that (#2732).
  655. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  656. ``print_error`` path builds HMSError differently), so this is safe to call on
  657. every watchdog poll.
  658. """
  659. for err in getattr(status, "hms_errors", None) or []:
  660. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  661. return True
  662. return False
  663. def _drying_ams_ids(status) -> list[int]:
  664. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  665. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  666. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  667. started (#2758) — it is a diagnostic, not a gate.
  668. Deliberately not used to block or stop drying before dispatch. This printer
  669. class supports drying concurrently with an active print
  670. (``supports_drying_while_printing``), so drying is not incompatible with
  671. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  672. while two AMS units were drying, one of them without its external PSU. Until
  673. it is known whether the blocker is drying itself or the power budget
  674. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  675. hardware is perfectly happy to continue.
  676. """
  677. ids: list[int] = []
  678. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  679. if not isinstance(unit, dict):
  680. continue
  681. try:
  682. if int(unit.get("dry_time") or 0) > 0:
  683. ids.append(int(unit.get("id", 0)))
  684. except (TypeError, ValueError):
  685. continue
  686. return ids
  687. def _parse_diameter(raw) -> float | None:
  688. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  689. try:
  690. value = float(raw)
  691. except (TypeError, ValueError):
  692. return None
  693. return value if value > 0 else None
  694. def _nozzle_info_by_id(status) -> dict[int, dict]:
  695. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  696. The field name is historical: on the H2 series ``nozzle_info`` carries an
  697. entry for *every* nozzle the printer knows about — the L/R hotends under
  698. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  699. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  700. :func:`_installed_nozzle_diameters` each take the half they need.
  701. """
  702. by_id: dict[int, dict] = {}
  703. for entry in getattr(status, "nozzle_rack", None) or []:
  704. if not isinstance(entry, dict):
  705. continue
  706. try:
  707. by_id[int(entry.get("id"))] = entry
  708. except (TypeError, ValueError):
  709. continue
  710. return by_id
  711. # What the firmware puts in a nozzle's serial number when the carriage or dock
  712. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  713. # its nozzle back in the rack (#2885).
  714. _EMPTY_NOZZLE_SERIAL = "N/A"
  715. def _nozzle_is_mounted(entry: dict | None) -> bool:
  716. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  717. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  718. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  719. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  720. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  721. the dock. So the diameter is not a presence signal (#2885).
  722. Emptiness has to be stated, not merely unstated. The serial must be the
  723. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  724. absent — an empty serial only means the printer didn't say, and a firmware
  725. that reports neither field normalises to exactly that. Treating "didn't
  726. say" as "empty" would silently switch the #1899 guard off on any such
  727. machine, so everything we cannot positively call empty counts as mounted.
  728. """
  729. if entry is None:
  730. return True
  731. serial = str(entry.get("serial_number") or "").strip().upper()
  732. if serial != _EMPTY_NOZZLE_SERIAL:
  733. return True
  734. try:
  735. max_temp = float(entry.get("max_temp") or 0)
  736. except (TypeError, ValueError):
  737. return True
  738. return max_temp > 0
  739. def _installed_nozzle_diameters(status) -> list[float]:
  740. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  741. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  742. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  743. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  744. told us its nozzle hardware" — callers must treat that as unknown, not as a
  745. mismatch, so we never block a print on missing data.
  746. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  747. though ``nozzles`` still carries a diameter for it: that value is stale, and
  748. counting it would let a slice match a nozzle the machine does not have
  749. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  750. """
  751. info = _nozzle_info_by_id(status)
  752. diameters: list[float] = []
  753. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  754. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  755. try:
  756. value = float(raw)
  757. except (TypeError, ValueError):
  758. continue
  759. if value > 0 and _nozzle_is_mounted(info.get(index)):
  760. diameters.append(value)
  761. return diameters
  762. def _rack_nozzle_diameters(status) -> list[float]:
  763. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  764. Keyed off the nozzle ids themselves rather than the printer model: only a
  765. rack machine ever reports ids 16-21, so there is no model registry to keep
  766. in sync. An empty dock is simply absent from the payload — measured on an
  767. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  768. present — so appearing here already means "a nozzle is in that dock".
  769. ``stat`` is deliberately not interpreted: its values aren't known, and
  770. reading it wrongly could hide a nozzle the printer would happily fetch.
  771. """
  772. diameters: list[float] = []
  773. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  774. if nozzle_id not in _RACK_NOZZLE_IDS:
  775. continue
  776. # PrinterState spells it "diameter"; the REST schema renames it to
  777. # "nozzle_diameter". Accept either so a caller holding the serialised
  778. # shape gets the same answer.
  779. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  780. if value is not None:
  781. diameters.append(value)
  782. return diameters
  783. def _format_diameters(diameters: list[float]) -> str:
  784. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  785. Deduplicated because a loaded rack holds several nozzles of the same size,
  786. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  787. short form doesn't. Matching still runs over the full list.
  788. """
  789. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  790. def _nozzle_mismatch_message(
  791. sliced_nozzle: float | None,
  792. installed: list[float],
  793. rack: list[float] | None = None,
  794. ) -> str | None:
  795. """Return an actionable error message when the sliced nozzle can't be
  796. printed on any nozzle the machine can reach, else None (#1899).
  797. Fail-safe: returns None whenever we lack the data to judge — no sliced
  798. diameter, or the printer reported no nozzles — so a print is only ever
  799. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  800. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  801. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  802. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  803. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  804. as reachable: the printer fetches one as part of starting the print, so a
  805. slice that matches a docked nozzle is not a mismatch. Without this the
  806. guard blocked every job whose nozzle happened not to be on a hotend at
  807. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  808. diameter already mounted could ever print, and the user had to fetch the
  809. nozzle by hand on the printer's own UI first (#2885).
  810. """
  811. reachable = [*installed, *(rack or [])]
  812. if not sliced_nozzle or not reachable:
  813. return None
  814. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  815. return None
  816. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  817. if rack:
  818. where += f" and {_format_diameters(rack)} in the nozzle rack"
  819. return (
  820. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  821. f"{where}. Re-slice for an available nozzle, or fit the matching "
  822. f"nozzle before printing."
  823. )
  824. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  825. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  826. Shared by the required and loaded sides, which name their extruder
  827. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  828. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  829. 1 the left/deputy — and both are absent on single-nozzle printers, where
  830. naming a nozzle would be noise.
  831. """
  832. parts = [(entry.get("type") or "filament").upper()]
  833. if entry.get("color"):
  834. parts.append(str(entry["color"]))
  835. nozzle = entry.get(nozzle_key)
  836. if nozzle == 0:
  837. parts.append("(right nozzle)")
  838. elif nozzle == 1:
  839. parts.append("(left nozzle)")
  840. return " ".join(parts)
  841. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  842. """Explain that nothing loaded matches what the file needs (#2771).
  843. Only ever built for a printer with no AMS, where the loaded list is short
  844. enough to quote in full and there is no "load another spool and hit Resume"
  845. recovery — the external spool holder is all there is, so the user needs to
  846. be told which filament to put on it.
  847. """
  848. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  849. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  850. return (
  851. f"No filament loaded on this printer matches the file. It needs {want}; "
  852. f"the printer has {have} and no AMS. Load the required filament on the "
  853. f"external spool holder, or send this job to a printer that has it."
  854. )
  855. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  856. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  857. every call site below it: G-code injection, usage registration, rack-plan
  858. lookup, slot-extruder lookup, the external-spool check, and the actual
  859. print command.
  860. A positive explicit ``plate_id`` on the queue item always wins. A
  861. non-positive one is treated as "not set" and resolved from the archive,
  862. the way the rest of the queue code already reads it (``if item.plate_id:``
  863. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  864. field, and passing a 0 straight through would build a print command for
  865. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  866. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  867. Falling back to a bare ``1`` instead of reading the archive assumes a
  868. single-plate file's one G-code is numbered 1, which only holds for a
  869. plate exported on its own: one cut out of a larger project keeps its
  870. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  871. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  872. the file, throws an HMS error, and sits wedged in IDLE until
  873. power-cycled (#2947).
  874. The call sites agreed on a fallback only by accident before this:
  875. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  876. the archive's own default plate internally whenever the plate id it's
  877. handed isn't in the file, so it could silently inject into a different
  878. plate than the one the print command itself asked for.
  879. Falls back to 1 when the archive can't be read, holds no G-code member at
  880. all, or its default member doesn't follow the ``plate_N`` naming
  881. convention (a slicer that doesn't use it has no number to dispatch).
  882. An explicit plate the archive doesn't hold is logged and then sent
  883. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  884. to a plate that is in the file would print a model nobody asked for,
  885. which is the worse of the two.
  886. """
  887. try:
  888. with zipfile.ZipFile(file_path, "r") as zf:
  889. names = zf.namelist()
  890. except (OSError, zipfile.BadZipFile) as exc:
  891. logger.warning(
  892. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  893. "is unavailable; dispatching plate %s",
  894. file_path,
  895. exc,
  896. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  897. )
  898. names = None
  899. if explicit_plate_id is not None and explicit_plate_id > 0:
  900. if (
  901. names is not None
  902. and default_plate_number(names) is not None
  903. and select_plate_gcode_name(names, explicit_plate_id) is None
  904. ):
  905. logger.warning(
  906. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  907. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  908. "file, since printing a different plate would print the wrong model (#2947)",
  909. file_path,
  910. explicit_plate_id,
  911. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  912. explicit_plate_id,
  913. )
  914. return explicit_plate_id
  915. resolved = default_plate_number(names) if names is not None else None
  916. return resolved if resolved is not None else 1
  917. class PrintScheduler:
  918. """Background scheduler that processes the print queue."""
  919. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  920. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  921. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  922. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  923. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  924. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  925. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  926. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  927. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  928. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  929. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  930. }
  931. def __init__(self):
  932. self._running = False
  933. self._check_interval = 30 # seconds
  934. # After a pass that actually dispatched something, loop again almost
  935. # immediately instead of sleeping the full interval (#2555). A dispatch
  936. # changes printer state — a batch launch fans out over several passes as
  937. # printers free up, a wedged head-of-line job reverts to pending, an
  938. # upload slot opens — and the next batch of ready work should not have to
  939. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  940. # pending items are behind printers that are genuinely busy printing),
  941. # there is nothing to react to, so we fall back to the normal interval;
  942. # that also means this can never tight-loop, since fast ticks only
  943. # continue while dispatches keep happening and the queue is draining.
  944. self._fast_check_interval = 3 # seconds
  945. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  946. self._power_on_check_interval = 10 # seconds between connection checks
  947. # Printers whose class-target power-on failed, mapped to the monotonic
  948. # time their cool-off expires (#2786).
  949. #
  950. # Without this, one printer with an unreachable plug starves every
  951. # sibling of its model forever: the wake step walks candidates in id
  952. # order, spends the pass's single attempt on the same broken printer
  953. # every time, and the healthy one two slots down is never reached. It
  954. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  955. # which delays the whole queue, not just this job.
  956. #
  957. # Entries expire on read rather than being cleared on success: a printer
  958. # inside its cool-off is skipped before the power-on is reached, so a
  959. # live entry can never be overwritten by a success anyway. A printer
  960. # that comes back by any other route stops being a wake candidate the
  961. # moment it connects.
  962. self._wake_failures: dict[int, float] = {}
  963. self._wake_failure_cooloff = 600 # seconds
  964. # Printers whose last upload never reached them, mapped to the monotonic
  965. # time they may be dispatched to again (#3210). Same expire-on-read shape
  966. # as `_wake_failures`. Without it, a printer that cannot take files is
  967. # idle on every pass, so it is picked on every pass.
  968. self._upload_backoff: dict[int, float] = {}
  969. # Refused uploads in a row per printer, which sets the next backoff
  970. # window. Cleared by a successful upload to that printer.
  971. self._upload_refusals: dict[int, int] = {}
  972. # Printers whose current run of refusals has already sent its one
  973. # "job waiting" notification. Each retry clears the item's waiting
  974. # reason and the next refusal sets it again, which `hold_item` reads as
  975. # a new reason; without this, every retry would notify. Cleared with
  976. # `_upload_refusals`.
  977. self._upload_refusal_notified: set[int] = set()
  978. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  979. self._drying_in_progress: dict[int, float] = {}
  980. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  981. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  982. # cycle and the humidity finally coming down, so the normal steady
  983. # state is an empty dict. Fields:
  984. # running — a cycle we armed is (or should be) on the firmware
  985. # ended_at — monotonic when we observed that cycle end
  986. # unproductive — consecutive armed cycles that ended with the reading
  987. # still above the threshold
  988. # suspended — we have stopped arming this unit and said so
  989. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  990. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  991. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  992. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  993. # print-takes-priority stop, the manual-cycle adoption guard, and the
  994. # arming setdefault all act on that meaning -- a unit that is merely
  995. # waiting out its streak must not become stoppable or judgeable.
  996. # since -- monotonic stamp when the current continuous above-threshold
  997. # streak began
  998. # last -- monotonic stamp of the last pass that observed the streak
  999. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1000. # Slots already notified as low on filament:
  1001. # {(printer_id, ams_id, tray_id, spool_id)}.
  1002. # Cleared when the slot goes back above its threshold rather than on a
  1003. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1004. # boundary must not produce an alert on every pass, and a slot that has
  1005. # been refilled has to be able to alert again. See #2913.
  1006. #
  1007. # The spool id is part of the key because the slot alone cannot clear
  1008. # itself. Pull a low spool and put a different part-used one in the same
  1009. # slot: the key survives the pass where the slot resolves to nothing --
  1010. # deliberately, so a brief Spoolman outage does not re-alert everything
  1011. # when it returns -- and the replacement never goes above the threshold,
  1012. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1013. # different key and the stale one is inert.
  1014. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1015. # The same, for the MQTT relay's filament/low event: its own record, so
  1016. # one channel having been told never silences the other.
  1017. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1018. # Earliest monotonic time the next low-filament check may run (#2913).
  1019. self._filament_low_next_check: float = 0.0
  1020. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1021. # condition is "reorder" or "break", the events are those that had a
  1022. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1023. # condition clears, so it can alert again, and when nobody wants either
  1024. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1025. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1026. # re-send one message per SKU that is still low.
  1027. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1028. # The JSON last read from or written to that row; None until it has been read.
  1029. self._stock_alerts_persisted: str | None = None
  1030. # Earliest monotonic time the next stock forecast check may run (#2955).
  1031. self._stock_forecast_next_check: float = 0.0
  1032. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1033. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1034. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1035. # both features share _drying_in_progress.
  1036. self._scheduled_drying_printer_ids: set[int] = set()
  1037. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1038. # the first pass after a restart reaps anything left behind.
  1039. self._last_scheduled_drying_prune: float | None = None
  1040. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1041. # a project_file command must not get a second dispatch until either it
  1042. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1043. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1044. # during that window the DB busy_printers seed is empirically unreliable
  1045. # (multi-plate batches double-/triple-dispatched onto the same printer
  1046. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1047. # or revert.
  1048. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1049. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1050. # Minimum cooldown between dispatches to the same printer (covers the
  1051. # H2D's project_file digestion window).
  1052. self._dispatch_min_cooldown = 60.0
  1053. # Hard timeout — drop the hold even if we never observed a transition,
  1054. # so a lost MQTT session can't lock a printer out of the queue forever.
  1055. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1056. # watchdog runs first on the unhappy path.
  1057. self._dispatch_max_hold = 180.0
  1058. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1059. # an earlier pass and is still running. `_start_print` flips the row
  1060. # pending -> printing only *after* the upload completes, so until then
  1061. # the row stays `pending`: each tick, check_queue excludes these
  1062. # item_ids from re-selection and their printers from new dispatch /
  1063. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1064. # freed slots refill on the next fast tick. check_queue is the sole,
  1065. # sequential caller and the prune done-callbacks run in the same
  1066. # event-loop thread, so this dict needs no lock.
  1067. # item_id -> (task, printer_id)
  1068. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1069. # Expected prints registered by `_start_print` that have not yet had a
  1070. # print command sent. Populated at registration, dropped once
  1071. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1072. # other exit. Same threading argument as `_inflight` above: one
  1073. # sequential caller, callbacks on the same loop, so no lock.
  1074. # item_id -> (printer_id, remote_filename, archive_id)
  1075. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1076. # Budget reservations created for a dispatch whose print command has
  1077. # not been confirmed yet. `_dispatch_one` releases these on every
  1078. # unsuccessful exit; a successful start removes the item id and leaves
  1079. # the reservation for finance_billing to consume with the archive.
  1080. self._unconfirmed_budget_reservations: set[int] = set()
  1081. # Chamber temperature history for smart soak-time reduction.
  1082. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1083. # Entries older than _chamber_history_ttl are pruned on write.
  1084. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1085. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1086. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1087. # Populated on engagement in `_apply_keep_warm`, cleared by
  1088. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1089. # when a gate setting toggles off mid-hold — the release publishes
  1090. # bed → 0 first).
  1091. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1092. # Preheat rollback registry: printer_id -> subset of
  1093. # {"bed", "chamber", "airduct"} listing which preheat commands
  1094. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1095. # every entry still present at exit unless the print successfully
  1096. # started, so a failed upload / cancel / exception never leaves the
  1097. # printer heating for a job that isn't happening.
  1098. self._preheat_pin: dict[int, set[str]] = {}
  1099. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1100. # rollback can tell its own target from one someone else has since
  1101. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1102. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1103. self._preheat_pin_bed: dict[int, int] = {}
  1104. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1105. # its preheat was still holding at temperature. Set by
  1106. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1107. # `_preheat_sleep`, and cleared when the dispatch exits.
  1108. self._cancelled_dispatches: set[int] = set()
  1109. # printer_id -> monotonic time it was first seen terminal while one of
  1110. # its queue rows was still 'printing'. Reset by any non-terminal
  1111. # observation, so it measures an unbroken run rather than a total.
  1112. # In-memory on purpose: a restart re-arms the grace period, which only
  1113. # delays a recovery that is already the exceptional path (#2829).
  1114. self._terminal_since: dict[int, float] = {}
  1115. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1116. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1117. # across idle printers repeats that for every one of them in a single
  1118. # pass. Cleared at the top of each pass so a re-sliced file is never
  1119. # served from a previous tick.
  1120. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1121. # When each "any model" job held for low filament last looked for
  1122. # another printer (#3137), by queue item id.
  1123. self._short_hold_checked_at: dict[int, float] = {}
  1124. async def run(self):
  1125. """Main loop - check queue every interval."""
  1126. self._running = True
  1127. logger.info("Print scheduler started")
  1128. await self._clear_stale_dispatch_claims(at_startup=True)
  1129. while self._running:
  1130. dispatched = False
  1131. try:
  1132. self._sample_chamber_temps()
  1133. # No-op while any upload is in flight; on a quiet tick it releases
  1134. # a claim whose best-effort clear failed (e.g. the database was
  1135. # briefly unreachable), instead of leaving the row wedged until
  1136. # the next restart.
  1137. await self._clear_stale_dispatch_claims()
  1138. await self._close_stranded_printing_items()
  1139. dispatched = await self.check_queue()
  1140. except Exception as e:
  1141. logger.error("Scheduler error: %s", e)
  1142. # Re-check quickly after a productive pass so a draining batch does
  1143. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1144. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1145. async def _close_stranded_printing_items(self) -> None:
  1146. """Close a ``printing`` row the completion event never closed (#2829).
  1147. ``on_print_complete`` refuses to close a row when the completion's
  1148. subtask name disagrees with the file the row was dispatched with, so a
  1149. completion meant for something else (the printer's own
  1150. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1151. The refusal has no way back, though: nothing else ever closes the row,
  1152. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1153. one bad comparison wedges that printer's queue until a human presses
  1154. cancel. That is what #2829's reporters hit, and the guard's own
  1155. docstring already called stranding the worse of the two failures.
  1156. This is the way back. When a row has been ``printing`` while its
  1157. printer sat in a terminal state for the whole grace period, the print
  1158. is over however the event was read, and the row is closed with the
  1159. status the printer's own state implies.
  1160. Deliberately conservative:
  1161. * Only a connected printer counts. A disconnected one has a stale
  1162. ``state`` and proves nothing.
  1163. * The clock is reset by any non-terminal observation, so this cannot
  1164. fire on a printer that is merely between stages.
  1165. * The grace period is far longer than the gap between a printer
  1166. finishing and its completion arriving, so the normal path always
  1167. wins the race and this only ever sees genuine strandings.
  1168. What it does *not* do is replay the completion's side effects --
  1169. notifications, billing, auto-off. It restores the queue, which is the
  1170. harm being undone; the archive was updated by the normal path
  1171. regardless, since only the queue block refuses. A recovery that
  1172. silently re-fired notifications minutes late would be its own bug.
  1173. """
  1174. try:
  1175. async with async_session() as db:
  1176. result = await db.execute(
  1177. select(PrintQueueItem)
  1178. .where(PrintQueueItem.status == "printing")
  1179. .where(PrintQueueItem.printer_id.is_not(None))
  1180. )
  1181. items = list(result.scalars().all())
  1182. if not items:
  1183. self._terminal_since.clear()
  1184. return
  1185. now = time.monotonic()
  1186. seen_printers: set[int] = set()
  1187. closed = False
  1188. for item in items:
  1189. printer_id = item.printer_id
  1190. seen_printers.add(printer_id)
  1191. state = printer_manager.get_status(printer_id)
  1192. status = _terminal_queue_status(state)
  1193. if status is None:
  1194. self._terminal_since.pop(printer_id, None)
  1195. continue
  1196. since = self._terminal_since.setdefault(printer_id, now)
  1197. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1198. continue
  1199. item.status = status
  1200. item.completed_at = datetime.now(timezone.utc)
  1201. closed = True
  1202. logger.warning(
  1203. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1204. "closing it as %s. Its completion event was never matched to it, which blocks "
  1205. "every later job for this printer (#2829).",
  1206. item.id,
  1207. printer_id,
  1208. getattr(state, "state", None),
  1209. now - since,
  1210. status,
  1211. )
  1212. if closed:
  1213. await db.commit()
  1214. for printer_id in list(self._terminal_since):
  1215. if printer_id not in seen_printers:
  1216. del self._terminal_since[printer_id]
  1217. except Exception as e:
  1218. # Best-effort, same as the claim sweep beside it: a recovery path
  1219. # that can itself break the scheduler loop is worse than the strand.
  1220. logger.error("Stranded-item sweep failed: %s", e)
  1221. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1222. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1223. A claim is only ever held by a live dispatch coroutine, so when this
  1224. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1225. is stale. At startup that is trivially true — no coroutine survives a
  1226. restart. It is equally true on any later tick where no upload is running,
  1227. which is what makes this safe to repeat rather than only run once.
  1228. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1229. the database is briefly unreachable at exactly the moment dispatch ends,
  1230. the claim survives and the row is wedged out of the selection query. That
  1231. used to last until the next restart (#2702 follow-up, seen when
  1232. PostgreSQL refused a connection mid-dispatch).
  1233. ``_inflight`` is populated when the task is spawned, before the coroutine
  1234. claims its row, and pruned by a done-callback that cannot run before the
  1235. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1236. race window and needs no age threshold. A size-derived upload deadline
  1237. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1238. """
  1239. if self._inflight:
  1240. return
  1241. try:
  1242. async with async_session() as db:
  1243. res = await db.execute(
  1244. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1245. )
  1246. await db.commit()
  1247. if res.rowcount:
  1248. logger.info(
  1249. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1250. res.rowcount,
  1251. " at startup" if at_startup else "",
  1252. )
  1253. except Exception as exc:
  1254. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1255. def stop(self):
  1256. """Stop the scheduler."""
  1257. self._running = False
  1258. logger.info("Print scheduler stopped")
  1259. async def check_queue(self) -> bool:
  1260. """Check for prints ready to start.
  1261. Returns True if this pass dispatched at least one item, so the caller
  1262. can loop again quickly instead of sleeping the full interval (#2555).
  1263. """
  1264. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1265. self._filament_req_memo.clear()
  1266. async with async_session() as db:
  1267. # Check if shortest-job-first scheduling is enabled
  1268. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1269. # Get all pending items in the one order the queue page shows them
  1270. # in (#3200). The first eligible item takes a printer, so this order
  1271. # decides who wins a printer that a pinned job and an "Any <model>"
  1272. # job both want. It used to start with ``printer_id``, which made the
  1273. # lane outrank the position: SQLite sorts NULL first, so model-based
  1274. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1275. # Neither is what the user dragged into place.
  1276. if sjf_enabled:
  1277. # SJF: items already jumped get top priority (starvation guard),
  1278. # then sort by print_time ascending. Items with no print time go
  1279. # last, and position breaks ties.
  1280. result = await db.execute(
  1281. select(PrintQueueItem)
  1282. .where(PrintQueueItem.status == "pending")
  1283. # Never re-select a row a dispatch worker has already claimed
  1284. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1285. # below, and the guard that lets an orphaned claim be ignored
  1286. # until startup reconciliation clears it.
  1287. .where(PrintQueueItem.dispatching_at.is_(None))
  1288. # archive/library_file are read by the cross-model gate
  1289. # (#2578); eager-load once per pass instead of a lazy-load
  1290. # (which would raise in async) per item.
  1291. .options(
  1292. selectinload(PrintQueueItem.archive),
  1293. selectinload(PrintQueueItem.library_file),
  1294. # Cross-model candidates (#671), plus each candidate's file
  1295. # for the same cross-model gate. Lazy-loading either would
  1296. # raise in async.
  1297. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1298. )
  1299. .order_by(
  1300. PrintQueueItem.been_jumped.desc(),
  1301. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1302. PrintQueueItem.position,
  1303. PrintQueueItem.id,
  1304. )
  1305. )
  1306. else:
  1307. result = await db.execute(
  1308. select(PrintQueueItem)
  1309. .where(PrintQueueItem.status == "pending")
  1310. # Skip rows already claimed by a dispatch worker (#2615).
  1311. .where(PrintQueueItem.dispatching_at.is_(None))
  1312. .options(
  1313. selectinload(PrintQueueItem.archive),
  1314. selectinload(PrintQueueItem.library_file),
  1315. # Cross-model candidates (#671), plus each candidate's file
  1316. # for the same cross-model gate. Lazy-loading either would
  1317. # raise in async.
  1318. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1319. )
  1320. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1321. )
  1322. items = list(result.scalars().all())
  1323. # Drop rows whose upload is still in flight from an earlier pass
  1324. # (#2602). They stay `pending` until the upload finishes, so without
  1325. # this a fast tick would re-select and re-dispatch the same row.
  1326. # Belt-and-suspenders with the printer exclusion below.
  1327. if self._inflight:
  1328. inflight_ids = set(self._inflight)
  1329. items = [it for it in items if it.id not in inflight_ids]
  1330. # Read plate-clear setting once per queue check. Default MUST be
  1331. # False to match the schema (SettingsSchema.require_plate_clear
  1332. # defaults False) and the frontend (toggle + card badge both treat a
  1333. # missing value as off). When no settings row exists, a True default
  1334. # here re-enabled the plate-clear gate the UI showed as disabled,
  1335. # blocking dispatch to FINISH-state printers forever with no UI path
  1336. # to clear it (#1865).
  1337. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1338. # Dispatch and track scheduled drying runs (#2638)
  1339. await self._check_scheduled_dryings(db)
  1340. if not items:
  1341. # No dispatchable pending items — still check auto-drying on idle
  1342. # printers, but keep any printer with an upload still in flight
  1343. # from an earlier pass out of it (#2602): its print is imminent,
  1344. # so it must not be auto-dried in the gap before the row flips to
  1345. # printing. Report the pass as productive while uploads run so the
  1346. # loop stays on the fast interval.
  1347. #
  1348. # Also release any keep-warm holds that got orphaned by the queue
  1349. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1350. # this early return, so call it directly with an empty candidate
  1351. # set. Without this, a printer whose queued item was cancelled or
  1352. # deleted would keep its bed at target until the max-duration
  1353. # timeout expired.
  1354. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1355. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1356. await self._check_auto_drying(db, [], inflight_printers)
  1357. await self._check_filament_low(db)
  1358. await self._check_stock_forecast(db)
  1359. return bool(self._inflight)
  1360. logger.info(
  1361. "Queue check: found %d pending items: %s",
  1362. len(items),
  1363. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1364. )
  1365. # Forget jobs that left the queue since they were last checked.
  1366. pending_ids = {i.id for i in items}
  1367. self._short_hold_checked_at = {
  1368. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1369. }
  1370. # Seed busy_printers with printers that already have an item in 'printing'
  1371. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1372. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1373. # lag several seconds behind the print command, so the next check_queue
  1374. # tick still sees IDLE and would double-dispatch onto the same printer.
  1375. # Without this guard, two pending items targeting the same printer
  1376. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1377. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1378. busy_result = await db.execute(
  1379. select(PrintQueueItem.printer_id)
  1380. .where(PrintQueueItem.status == "printing")
  1381. .where(PrintQueueItem.printer_id.is_not(None))
  1382. )
  1383. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1384. # Why each printer left this pass, recorded where the decision is
  1385. # made rather than re-derived when the summary is logged. #3018's
  1386. # bundle shows what the old summary produced: "printer 1 not
  1387. # available -- connected=True, state=IDLE" immediately followed by a
  1388. # dispatch to printer 1. Two things went wrong at once. The line read
  1389. # live state at log time, which by then no longer matched the state
  1390. # the decision was made on; and `busy_printers` holds both printers
  1391. # that cannot take work and printers this pass has claimed for it,
  1392. # which are opposite facts. It is the first line anyone greps for
  1393. # "why did my item not go out", so it has to say which.
  1394. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1395. # Printers this pass is dispatching to. They are in busy_printers so
  1396. # nothing else in the pass targets them -- that is a reservation, not
  1397. # an obstruction, and the summary says so.
  1398. claimed_printers: set[int] = set()
  1399. def mark_busy(printer_id: int, reason: str) -> None:
  1400. """Take ``printer_id`` out of this pass, recording why.
  1401. First reason wins: a printer already excluded by a stronger fact
  1402. -- a print running on it -- must not be relabelled by a weaker
  1403. check that ran later and would have excluded it anyway.
  1404. """
  1405. busy_printers.add(printer_id)
  1406. busy_reasons.setdefault(printer_id, reason)
  1407. def claim_printer(printer_id: int) -> None:
  1408. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1409. claimed_printers.add(printer_id)
  1410. mark_busy(printer_id, "selected for dispatch in this pass")
  1411. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1412. # worded for a different audience: the log wants "still inside its
  1413. # post-dispatch hold window", the queue row wants to know the printer
  1414. # is taken and nothing is broken. Only the cases that would read wrong
  1415. # as a plain "Busy" are recorded here; the rest fall back to it.
  1416. item_hold_reasons: dict[int, str] = {}
  1417. # Names and models for the printers this pass may have to write a
  1418. # waiting reason about, read once rather than per skip per tick. The
  1419. # model-based branch already has its names from `_printers_for_model`.
  1420. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1421. pinned_printers: dict[int, tuple[str, str]] = {}
  1422. if pinned_printer_ids:
  1423. pinned_rows = await db.execute(
  1424. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1425. )
  1426. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1427. def printer_label(printer_id: int) -> str:
  1428. """What to call this printer in a queue row."""
  1429. entry = pinned_printers.get(printer_id)
  1430. return (entry[0] if entry else "") or f"printer {printer_id}"
  1431. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1432. """Record why *item* is not going out, in the words the queue row shows.
  1433. The fixed-printer branch's single writer for ``waiting_reason``
  1434. (#3074). Before this, the sensor interlock was the only thing that
  1435. wrote the field there, so an item pinned to a printer that was
  1436. merely printing sat at `pending` with nothing to show for it —
  1437. indistinguishable from a queue that had stopped working — while
  1438. the same job queued as "Any <model>" explained itself.
  1439. Every exit from that branch now calls this, which is also what
  1440. replaced the interlock's old habit of clearing the field up front:
  1441. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1442. because whichever exit runs next overwrites it and the dispatch
  1443. path clears it.
  1444. A notification goes out when this item starts asking for
  1445. something, and only then: the new reason needs the user, and what
  1446. it replaced did not. "What it replaced did not" has to include a
  1447. busy-only reason, not just an empty one. The sequence this branch
  1448. actually produces is a print running (``Busy: X1C-01``) and then
  1449. the plate it left behind (``Waiting for plate confirmation``), and
  1450. testing "was the field empty" would call that no transition at all
  1451. and stay quiet through the one case worth saying out loud.
  1452. The cost is that a printer dropping offline, coming back busy and
  1453. dropping again asks twice rather than once. That is the honest
  1454. reading — it went wrong twice — and the alternative was a rule
  1455. that never fired for the case this was built for.
  1456. *notify* is how a caller opts out. The sensor interlock does: it
  1457. has never sent this notification, and a change about what the
  1458. queue *displays* is not the place to start (#1148).
  1459. """
  1460. if item.waiting_reason == reason:
  1461. return
  1462. # Busy-only and empty are the same thing here: neither is the
  1463. # queue asking the user for anything.
  1464. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1465. item.waiting_reason = reason
  1466. await db.commit()
  1467. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1468. return
  1469. try:
  1470. job_name = await self._get_job_name(db, item)
  1471. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1472. await notification_service.on_queue_job_waiting(
  1473. job_name=job_name,
  1474. target_model=(entry[1] if entry else "") or "",
  1475. waiting_reason=reason,
  1476. db=db,
  1477. )
  1478. except Exception as e:
  1479. # A queue that cannot say why it is waiting is the bug being
  1480. # fixed here; a queue that stops dispatching because a
  1481. # notification provider is down would be a worse one.
  1482. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1483. async def hold_for_printer(
  1484. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1485. ) -> None:
  1486. """Take *printer_id* out of this pass and tell the item's owner why."""
  1487. mark_busy(printer_id, log_reason)
  1488. item_hold_reasons.setdefault(printer_id, item_reason)
  1489. await hold_item(item, item_reason)
  1490. # Defense-in-depth (#1157): augment busy_printers with any printer
  1491. # still in its post-dispatch hold window. Empirically, the DB seed
  1492. # above can miss in-flight items in a multi-plate batch — same-file
  1493. # plates were being dispatched 30 s apart while the H2D was still
  1494. # digesting the first project_file. The hold is keyed in-memory and
  1495. # released by the watchdog on the success path, so it adds a layer
  1496. # that doesn't depend on DB row visibility or completion-callback
  1497. # timing.
  1498. for held_printer_id in list(self._dispatch_holds.keys()):
  1499. if self._printer_in_dispatch_hold(held_printer_id):
  1500. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1501. # Exclude printers whose upload is still in flight from an earlier
  1502. # pass (#2602). The row is `pending` until the upload finishes and
  1503. # the printing-state seed / dispatch hold above only arm once the
  1504. # upload completes, so this is what holds the printer (and, via
  1505. # busy_printers, its auto-drying) out of the pass during the upload.
  1506. for _task, inflight_pid in self._inflight.values():
  1507. if inflight_pid is not None:
  1508. mark_busy(inflight_pid, "an upload to it is still in flight")
  1509. # Snapshot taken here, before the item loop adds anything (#2801).
  1510. #
  1511. # The three sources above all mean the same thing: a print on this
  1512. # printer is running or imminent. Everything the loop adds below
  1513. # means only "the queue could not dispatch to it this pass", which
  1514. # is a different statement -- a printer waiting on a plate-clear
  1515. # acknowledgment, an offline printer, one with no matching file.
  1516. #
  1517. # Auto-drying must only see the first kind. Reading the whole set
  1518. # as "is currently printing" is what put a plate-held printer down
  1519. # the mid-print path: it capped the drying temperature, logged the
  1520. # cycle as (mid-print), and skipped the very gate that was supposed
  1521. # to hold it. The interlock block below already documents the same
  1522. # hazard and works around it by staying out of busy_printers; this
  1523. # generalises that workaround instead of repeating it per case.
  1524. dispatching_printers: set[int] = set(busy_printers)
  1525. # Printers whose last upload never reached them (#3210). After the
  1526. # snapshot above on purpose: such a printer is idle, not about to
  1527. # print, and auto-drying must keep treating it as idle.
  1528. now_mono = time.monotonic()
  1529. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1530. # can leave them out: there is no print to keep a bed warm for.
  1531. backoff_printers: set[int] = set()
  1532. # In backoff, and the "job waiting" notification for this run of
  1533. # refusals has gone out already. Their holds are written silently.
  1534. silent_hold_printers: set[int] = set()
  1535. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1536. if now_mono >= retry_at:
  1537. del self._upload_backoff[backoff_pid]
  1538. continue
  1539. backoff_printers.add(backoff_pid)
  1540. if backoff_pid in self._upload_refusal_notified:
  1541. silent_hold_printers.add(backoff_pid)
  1542. else:
  1543. self._upload_refusal_notified.add(backoff_pid)
  1544. mark_busy(
  1545. backoff_pid,
  1546. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1547. )
  1548. item_hold_reasons.setdefault(
  1549. backoff_pid,
  1550. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1551. )
  1552. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1553. # enclosure door left open, say. The fixed-printer branch turns
  1554. # this into a waiting_reason the user can act on; the model-based
  1555. # branch hides these printers from the matcher so an "Any <model>"
  1556. # job runs on a sibling instead of queueing behind the held one.
  1557. #
  1558. # Deliberately NOT merged into busy_printers, even though that set
  1559. # already means "unavailable this pass". _check_auto_drying reads
  1560. # it as "is currently printing" and would put an idle-but-held
  1561. # printer down the mid-print drying path, which caps the drying
  1562. # temperature and skips the queue-only gating. A held printer is
  1563. # idle; it should dry exactly as it did before.
  1564. #
  1565. # Only sensors we actually read and found alerting appear here; see
  1566. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1567. # holds nothing.
  1568. interlocked: dict[int, str] = {}
  1569. try:
  1570. interlocked = await ha_sensor_manager.blocked_printers(db)
  1571. except Exception as e:
  1572. # Never let the interlock stop the queue running. A broken
  1573. # lookup means no holds, not no dispatches.
  1574. logger.warning("Home Assistant interlock check failed: %s", e)
  1575. interlocked = {}
  1576. # Printers a smart plug can bring back, read once for the whole pass
  1577. # (#2786). Used by the model-based branch both to word "Offline" in
  1578. # the waiting reason and to decide what the wake step may switch on.
  1579. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1580. # At most one power-on per queue check. Each one blocks this loop
  1581. # for the boot wait, so a queue of ten class-targeted jobs must not
  1582. # switch on ten printers inside a single pass — the next pass wakes
  1583. # the next one (#2786).
  1584. power_on_attempted = False
  1585. # Log skip reasons once per queue check (not per item)
  1586. skip_reasons: dict[str, int] = {}
  1587. # Items selected for dispatch in this pass, one per printer. The
  1588. # loop below only *decides* — the uploads happen afterwards, in
  1589. # parallel (#2555). See _dispatch_selected().
  1590. dispatch_ids: list[int] = []
  1591. # Library rows queued with `cleanup_library_after_dispatch` (the
  1592. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1593. # that prints them: the row is deleted and the 3MF is unlinked from
  1594. # disk. That was safe only because dispatch was serial. Run two of
  1595. # them against the same row at once and the second DELETE matches no
  1596. # row (StaleDataError), and the winner's unlink can pull the file out
  1597. # from under the loser's in-flight upload.
  1598. #
  1599. # Only the cleanup flag mutates the row. An ordinary library print
  1600. # just reads it, so the common fan-out — one file, many printers,
  1601. # which is exactly the reporter's workload — still goes out fully in
  1602. # parallel. Narrow the guard to the mutating case; do not serialise
  1603. # the case the whole fix exists for.
  1604. dispatch_libs: set[int] = set()
  1605. consumed_libs: set[int] = set()
  1606. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1607. """True if dispatching `candidate` now would race another item's cleanup."""
  1608. lib_id = candidate.library_file_id
  1609. if lib_id is None:
  1610. return False
  1611. if candidate.cleanup_library_after_dispatch:
  1612. # We would delete a row someone else in this pass is reading.
  1613. return lib_id in dispatch_libs
  1614. # Someone else in this pass will delete the row out from under us.
  1615. return lib_id in consumed_libs
  1616. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1617. lib_id = candidate.library_file_id
  1618. if lib_id is None:
  1619. return
  1620. dispatch_libs.add(lib_id)
  1621. if candidate.cleanup_library_after_dispatch:
  1622. consumed_libs.add(lib_id)
  1623. # Printer scope of each job's creator (#1727), so an "any <model>"
  1624. # job only lands on a printer its creator may use. Loaded lazily,
  1625. # once per creator per pass.
  1626. from backend.app.core.auth import is_auth_enabled
  1627. scope_auth_enabled = await is_auth_enabled(db)
  1628. creator_scopes: dict[int, PrinterScope] = {}
  1629. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1630. if not scope_auth_enabled or user_id is None:
  1631. return ALL_PRINTERS
  1632. if user_id not in creator_scopes:
  1633. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1634. return creator_scopes[user_id]
  1635. for item in items:
  1636. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1637. if item.scheduled_time:
  1638. sched = item.scheduled_time
  1639. if sched.tzinfo is None:
  1640. sched = sched.replace(tzinfo=timezone.utc)
  1641. if sched > datetime.now(timezone.utc):
  1642. # Waiting on the clock, not on a printer.
  1643. await hold_item(item, None)
  1644. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1645. continue
  1646. # Skip items that require manual start, except an "any model"
  1647. # job held for low filament that another idle printer can now
  1648. # run: that one is moved there and carries on below (#3137).
  1649. if item.manual_start and not (
  1650. item.filament_short
  1651. and await self._release_short_model_hold(
  1652. db,
  1653. item,
  1654. busy_printers | interlocked.keys(),
  1655. require_plate_clear,
  1656. await _creator_scope(item.created_by_id),
  1657. )
  1658. ):
  1659. # Waiting on the user, not on a printer. Cleared here because
  1660. # this is the last pass that will look at the row: a staged
  1661. # item never reaches the branches below again, so a reason
  1662. # left from before it was staged would stand forever (#3074).
  1663. # The one exception is the unmatched-filament hold, whose
  1664. # reason was written at staging and is why the item waits:
  1665. # it names the filament to load (#2799). Pressing start
  1666. # clears manual_start, and the branches below overwrite it.
  1667. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1668. await hold_item(item, keep)
  1669. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1670. continue
  1671. if item.printer_id and item.printer_id not in pinned_printers:
  1672. # Moved by the release above to a printer no row named when
  1673. # the labels were read.
  1674. moved_to = await self._get_printer(db, item.printer_id)
  1675. if moved_to is not None:
  1676. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1677. if item.printer_id:
  1678. # Its creator may no longer use this printer (#1727): an
  1679. # admin took it away from their group after the job was
  1680. # queued, say to keep it free for a training session. Held,
  1681. # not failed, so it starts if access comes back or the user
  1682. # moves it to a printer they still have.
  1683. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1684. await hold_item(
  1685. item,
  1686. "Its owner no longer has access to this printer — move it to another printer",
  1687. notify=False,
  1688. )
  1689. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1690. continue
  1691. # Held by a sensor interlock (#1148). Checked before the
  1692. # busy_printers test that would otherwise swallow it
  1693. # silently — "waiting for a printer" and "waiting for you
  1694. # to shut the enclosure" need to read differently, and only
  1695. # one of them is something the user can fix.
  1696. #
  1697. # It used to be the only thing that wrote a waiting_reason on
  1698. # this branch, and it cleared the field up front so a lifted
  1699. # hold could not leave a shut door reading "Waiting on
  1700. # Enclosure Door". `hold_item` carries that guarantee now —
  1701. # every exit below writes — so the clear is gone and the
  1702. # interlock is an ordinary hold like the rest (#3074).
  1703. interlock_reason = interlocked.get(item.printer_id)
  1704. if interlock_reason:
  1705. # Silent, exactly as it has always been. #1148 built this
  1706. # as a hold that shows on the row, never as an alert, and
  1707. # routing it through the shared writer must not quietly
  1708. # turn every open door into a notification.
  1709. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1710. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1711. continue
  1712. # Specific printer assignment (existing behavior)
  1713. if item.printer_id in busy_printers:
  1714. # Whatever took the printer out of this pass — a print
  1715. # already running on it, a post-dispatch hold, an upload
  1716. # still in flight, an item ahead of this one in the same
  1717. # pass — reads the same way from the queue: the printer is
  1718. # taken and this item is in line for it. The exceptions
  1719. # that do not (an offline printer, say) recorded their own
  1720. # wording in `item_hold_reasons` when they held it.
  1721. await hold_item(
  1722. item,
  1723. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1724. notify=item.printer_id not in silent_hold_printers,
  1725. )
  1726. continue
  1727. # Check if printer is idle
  1728. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1729. printer_connected = printer_manager.is_connected(item.printer_id)
  1730. # If printer not connected, try to power on via smart plug
  1731. if not printer_connected:
  1732. plugs = await self._get_smart_plugs(db, item.printer_id)
  1733. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1734. if auto_on_plugs:
  1735. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1736. # Power on using the plug that actually feeds the printer, and
  1737. # wait for it to boot on that one only (#2629).
  1738. primary_plug = self._pick_power_plug(auto_on_plugs)
  1739. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1740. if powered_on:
  1741. # Also turn on any remaining auto_on plugs (e.g., filter)
  1742. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1743. try:
  1744. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1745. if await service.turn_on(extra_plug):
  1746. await publish_plug_state(
  1747. extra_plug.id,
  1748. extra_plug.name,
  1749. extra_plug.printer_id,
  1750. on=True,
  1751. ha_entity_id=extra_plug.ha_entity_id,
  1752. )
  1753. logger.info(
  1754. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1755. )
  1756. except Exception as e:
  1757. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1758. printer_connected = True
  1759. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1760. else:
  1761. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1762. await hold_for_printer(
  1763. item,
  1764. item.printer_id,
  1765. "smart-plug power-on failed",
  1766. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1767. )
  1768. continue
  1769. else:
  1770. # No plug or auto_on disabled. Worded exactly as the
  1771. # model-based branch words it (#2786): this is the one
  1772. # entry on that list the user has to act on, because
  1773. # Bambuddy will never switch this printer on itself.
  1774. await hold_for_printer(
  1775. item,
  1776. item.printer_id,
  1777. "offline, with no smart plug to power it on",
  1778. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1779. )
  1780. continue
  1781. # Check if printer is idle (busy with another print)
  1782. if not printer_idle:
  1783. await hold_for_printer(
  1784. item,
  1785. item.printer_id,
  1786. "not idle",
  1787. self._pinned_hold_reason(
  1788. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1789. ),
  1790. )
  1791. continue
  1792. # Drying blocks the queue, if the user asked it to. A hold
  1793. # is a skip like any other, so it belongs here with the
  1794. # rest of the availability checks.
  1795. # A parked timer (#2896) never ends, so it must not hold the
  1796. # queue; it stays tracked so the stop paths still reach it.
  1797. if (
  1798. self._drying_in_progress.get(item.printer_id)
  1799. and not self._drying_is_only_parked(item.printer_id)
  1800. and await self._get_bool_setting(db, "queue_drying_block")
  1801. ):
  1802. # Busy-shaped on purpose: the cycle ends on its own and
  1803. # the job goes out, so there is nothing to alert about.
  1804. await hold_for_printer(
  1805. item,
  1806. item.printer_id,
  1807. "drying, and drying is set to block the queue",
  1808. f"Busy: {printer_label(item.printer_id)} (drying)",
  1809. )
  1810. continue
  1811. # Check condition (previous print success)
  1812. if item.require_previous_success:
  1813. if not await self._check_previous_success(db, item):
  1814. item.status = "skipped"
  1815. item.error_message = "Previous print failed or was aborted"
  1816. item.completed_at = datetime.now(timezone.utc)
  1817. # Not pending any more, so not waiting for anything.
  1818. item.waiting_reason = None
  1819. await db.commit()
  1820. logger.info("Skipped queue item %s - previous print failed", item.id)
  1821. # Send notification
  1822. job_name = await self._get_job_name(db, item)
  1823. printer = await self._get_printer(db, item.printer_id)
  1824. await notification_service.on_queue_job_skipped(
  1825. job_name=job_name,
  1826. printer_id=item.printer_id,
  1827. printer_name=printer.name if printer else "Unknown",
  1828. reason="Previous print failed or was aborted",
  1829. db=db,
  1830. )
  1831. continue
  1832. # Resolve the AMS mapping when it's missing OR unresolved
  1833. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1834. # frontend status-load race can persist [-1] (#2589) — and
  1835. # must be recomputed from live trays rather than trusted.
  1836. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1837. if unmappable:
  1838. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1839. continue
  1840. # Filament-deficit pre-dispatch check (#1496). If the
  1841. # assigned spool can't satisfy any required slot grams,
  1842. # promote the item to manual_start so the user must
  1843. # acknowledge via the ▶ button (which re-checks live).
  1844. if await self._block_on_filament_deficit(db, item):
  1845. # Now staged for the user to start by hand, and the row
  1846. # shows the filament-short badge instead. Cleared because
  1847. # a staged item never reaches this branch again.
  1848. await hold_item(item, None)
  1849. continue
  1850. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1851. # than let the printer pick a substitute for a slot the
  1852. # matcher could not resolve on this printer.
  1853. if await self._block_on_unmatched_filament(db, item):
  1854. continue
  1855. # Hold this item back for the next pass rather than racing
  1856. # another dispatch over the same transient library row. The
  1857. # printer is still marked busy so a later item does not jump
  1858. # its place in this printer's queue.
  1859. if _library_row_conflict(item):
  1860. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1861. await hold_for_printer(
  1862. item,
  1863. item.printer_id,
  1864. "holding its place while another item releases a library row",
  1865. f"Busy: {printer_label(item.printer_id)}",
  1866. )
  1867. continue
  1868. # Print takes priority: stop a cycle Bambuddy armed, now
  1869. # that this item is definitely going out.
  1870. #
  1871. # Placement is the whole point (#2801). This used to sit up
  1872. # with the availability checks, inside the not-idle branch
  1873. # -- so it fired only on the passes where the print was NOT
  1874. # going to start, and never on the ones where it was.
  1875. # Drying is not one of the things `_is_printer_idle` looks
  1876. # at, so a stop could never have unblocked that printer
  1877. # anyway; the cycle was spent for nothing, auto-drying
  1878. # re-armed on the next tick, and a plate left
  1879. # unacknowledged turned that into a loop on the scheduler
  1880. # interval. Every skip between there and here -- a failed
  1881. # previous print, an unmappable item, a filament deficit, a
  1882. # contested library row -- is another way to lose a cycle
  1883. # for a print that never happens, which is why this waits
  1884. # until the decision is actually made.
  1885. if self._drying_in_progress.get(
  1886. item.printer_id
  1887. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1888. await self._stop_drying(item.printer_id)
  1889. # Queue the dispatch instead of running it here — see
  1890. # _dispatch_selected(). busy_printers still gets the printer
  1891. # immediately, so nothing else in this pass can target it.
  1892. #
  1893. # The reason goes first: this item is not waiting for anything
  1894. # any more, and the model-based branch clears its own at the
  1895. # equivalent moment (#3074).
  1896. await hold_item(item, None)
  1897. _claim_library_row(item)
  1898. dispatch_ids.append(item.id)
  1899. claim_printer(item.printer_id)
  1900. # SJF starvation guard: mark items that were jumped
  1901. if sjf_enabled and item.print_time_seconds is not None:
  1902. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1903. for other in items:
  1904. if (
  1905. other.id != item.id
  1906. and other.id not in dispatch_ids
  1907. and other.status == "pending"
  1908. and _could_take_printer(other, item.printer_id, pinned_model)
  1909. and not other.been_jumped
  1910. and other.position < item.position
  1911. and (
  1912. other.print_time_seconds is None
  1913. or other.print_time_seconds > item.print_time_seconds
  1914. )
  1915. ):
  1916. other.been_jumped = True
  1917. await db.commit()
  1918. elif item.target_model or item.variants:
  1919. # Model-based assignment - find any idle printer of matching model.
  1920. # A plain model-based item has exactly one candidate, built from
  1921. # its own columns. A cross-model item (#671) has one per sliced
  1922. # variant and takes the first that matches, walking them in the
  1923. # user's priority order so the pick is reproducible when more
  1924. # than one printer is free in the same pass.
  1925. candidates = _candidates_for(item)
  1926. item_scope = await _creator_scope(item.created_by_id)
  1927. printer_id = None
  1928. chosen: _ModelCandidate | None = None
  1929. per_model_reasons: list[tuple[str | None, str]] = []
  1930. # Candidates that cleared the cross-model gate below. The
  1931. # smart-plug wake step may only consider these — waking a
  1932. # printer for a file that can never legally run on it is
  1933. # worse than not waking at all (#2786).
  1934. wakeable_candidates: list[_ModelCandidate] = []
  1935. if not candidates:
  1936. # Every candidate file has been deleted or trashed out from
  1937. # under this item. Hold it with something the user can act
  1938. # on rather than letting it look dispatchable forever.
  1939. per_model_reasons.append(
  1940. (
  1941. item.target_model,
  1942. "Every file for this job has been deleted — add a file back or remove the item",
  1943. )
  1944. )
  1945. for candidate in candidates:
  1946. effective_types, filament_overrides = _filament_constraints(candidate)
  1947. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1948. # for an incompatible model to a printer, no matter how the
  1949. # row got into the DB (old rows, direct API writes). Held
  1950. # as pending with an actionable waiting_reason — the user
  1951. # fixes it by editing the item's target model.
  1952. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1953. per_model_reasons.append(
  1954. (
  1955. candidate.target_model,
  1956. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  1957. f"{candidate.target_model} — edit the item and fix its target model",
  1958. )
  1959. )
  1960. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  1961. continue
  1962. wakeable_candidates.append(candidate)
  1963. async def is_short(
  1964. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  1965. ) -> bool:
  1966. # The check reads the file and plate off the item,
  1967. # so it must hold this candidate's. Resolving is
  1968. # safe to repeat, and the winner is resolved again
  1969. # below.
  1970. self._resolve_variant(item, candidate)
  1971. return await self._filament_short_on(db, item, pid)
  1972. match_id, match_reason = await self._find_idle_printer_for_model(
  1973. db,
  1974. candidate.target_model,
  1975. # Sensor-held printers are unavailable to the
  1976. # matcher but stay out of busy_printers itself
  1977. # (#1148) — see where `interlocked` is built.
  1978. busy_printers | interlocked.keys(),
  1979. effective_types,
  1980. item.target_location,
  1981. filament_overrides=filament_overrides,
  1982. require_plate_clear=require_plate_clear,
  1983. wakeable_ids=wakeable_printer_ids,
  1984. printer_scope=item_scope,
  1985. is_short=is_short,
  1986. )
  1987. if match_id:
  1988. printer_id = match_id
  1989. chosen = candidate
  1990. break
  1991. per_model_reasons.append((candidate.target_model, match_reason or ""))
  1992. # Nothing is available and nothing has been woken this pass:
  1993. # switch one matching printer on. Assignment is left to the
  1994. # next pass, which sees the booted printer's live state
  1995. # instead of guessing at it seconds after connect (#2786).
  1996. if printer_id is None and not power_on_attempted and wakeable_candidates:
  1997. woken_id, attempted_id = await self._wake_printer_for_model(
  1998. db,
  1999. wakeable_candidates,
  2000. item.target_location,
  2001. busy_printers | interlocked.keys(),
  2002. wakeable_printer_ids,
  2003. require_plate_clear,
  2004. printer_scope=item_scope,
  2005. )
  2006. # An attempt spends the pass's one wake whether or not
  2007. # it worked: it has already blocked the queue loop for
  2008. # the boot wait. A failed printer is held out of later
  2009. # passes by its own cool-off, deliberately NOT by
  2010. # busy_printers — it is off, not busy, and labelling it
  2011. # busy would both misdescribe it in every later item's
  2012. # waiting reason and suppress the notification, since
  2013. # an all-busy reason is treated as needing no action.
  2014. power_on_attempted = attempted_id is not None
  2015. if woken_id is not None:
  2016. # Hold this item back rather than dispatching onto a
  2017. # printer whose AMS has not reported yet.
  2018. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2019. continue
  2020. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2021. # Fold the winning variant's file and settings onto the item
  2022. # before anything else looks at them — the guards below and
  2023. # every step of the dispatch read the item's own columns.
  2024. if chosen is not None:
  2025. self._resolve_variant(item, chosen)
  2026. # Update waiting_reason if changed and send notification when first waiting
  2027. if item.waiting_reason != waiting_reason:
  2028. was_waiting = item.waiting_reason is not None
  2029. item.waiting_reason = waiting_reason
  2030. await db.commit()
  2031. # Send waiting notification only when transitioning to waiting state
  2032. # and the reason requires user action (not just "all printers busy")
  2033. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  2034. job_name = await self._get_job_name(db, item)
  2035. await notification_service.on_queue_job_waiting(
  2036. job_name=job_name,
  2037. target_model=_candidate_model_label(candidates) or item.target_model,
  2038. waiting_reason=waiting_reason,
  2039. db=db,
  2040. )
  2041. if printer_id:
  2042. # Before claiming the printer: hold back rather than race
  2043. # another dispatch over the same transient library row.
  2044. # Checked here so a held item does not get a printer
  2045. # assigned and then sit on it. See _library_row_conflict().
  2046. #
  2047. # No busy_printers.add() here, unlike the fixed-printer
  2048. # branch above: that one protects its printer's own queue
  2049. # ordering, but this item was never assigned to `printer_id`
  2050. # — the matcher merely offered it. Marking it busy would
  2051. # strand an idle printer for the rest of the pass.
  2052. if _library_row_conflict(item):
  2053. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2054. continue
  2055. # Check condition (previous print success) before assigning
  2056. if item.require_previous_success:
  2057. if not await self._check_previous_success(db, item):
  2058. item.status = "skipped"
  2059. item.error_message = "Previous print failed or was aborted"
  2060. item.completed_at = datetime.now(timezone.utc)
  2061. await db.commit()
  2062. logger.info("Skipped queue item %s - previous print failed", item.id)
  2063. # Send notification
  2064. job_name = await self._get_job_name(db, item)
  2065. printer = await self._get_printer(db, printer_id)
  2066. await notification_service.on_queue_job_skipped(
  2067. job_name=job_name,
  2068. printer_id=printer_id,
  2069. printer_name=printer.name if printer else "Unknown",
  2070. reason="Previous print failed or was aborted",
  2071. db=db,
  2072. )
  2073. continue
  2074. # Assign printer and start - clear waiting reason
  2075. item.printer_id = printer_id
  2076. item.waiting_reason = None
  2077. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2078. # Send assignment notification
  2079. job_name = await self._get_job_name(db, item)
  2080. printer = await self._get_printer(db, printer_id)
  2081. await notification_service.on_queue_job_assigned(
  2082. job_name=job_name,
  2083. printer_id=printer_id,
  2084. printer_name=printer.name if printer else "Unknown",
  2085. target_model=item.target_model,
  2086. db=db,
  2087. )
  2088. # A mapping on this item was not made for the printer just
  2089. # picked: it came with a job moved here from a fixed
  2090. # printer, or from a variant. Its tray IDs can name a
  2091. # tray of the right type in another colour here, which
  2092. # the fit check lets through (#3239). Match afresh, by
  2093. # type and colour.
  2094. if item.ams_mapping:
  2095. logger.info(
  2096. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2097. item.id,
  2098. item.ams_mapping,
  2099. printer_id,
  2100. )
  2101. item.ams_mapping = None
  2102. # Resolve the AMS mapping for the assigned printer. It is
  2103. # always missing here, so this computes it, and it also
  2104. # self-heals a bogus stored [-1] (#2589).
  2105. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2106. if unmappable:
  2107. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2108. continue
  2109. # Filament-deficit pre-dispatch check (#1496).
  2110. if await self._block_on_filament_deficit(db, item):
  2111. continue
  2112. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2113. # selection already filters on filament type, so this is a
  2114. # backstop for an AMS that changed between assignment and
  2115. # dispatch, and for a type loaded on the wrong nozzle.
  2116. # The assignment made above is released with the hold —
  2117. # this item asked for a model, not this printer.
  2118. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2119. continue
  2120. _claim_library_row(item)
  2121. dispatch_ids.append(item.id)
  2122. claim_printer(printer_id)
  2123. # SJF starvation guard: mark items that were jumped
  2124. if sjf_enabled and item.print_time_seconds is not None:
  2125. for other in items:
  2126. if (
  2127. other.id != item.id
  2128. and other.id not in dispatch_ids
  2129. and other.status == "pending"
  2130. and _could_take_printer(other, printer_id, item.target_model)
  2131. and not other.been_jumped
  2132. and other.position < item.position
  2133. and (
  2134. other.print_time_seconds is None
  2135. or other.print_time_seconds > item.print_time_seconds
  2136. )
  2137. ):
  2138. other.been_jumped = True
  2139. await db.commit()
  2140. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2141. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2142. # skip summary that only lands after the transfers have finished is
  2143. # useless for working out why an item did not go out.
  2144. if skip_reasons:
  2145. logger.info("Queue skip summary: %s", skip_reasons)
  2146. for pid in sorted(busy_printers):
  2147. reason = busy_reasons.get(pid, "no reason recorded")
  2148. if pid in claimed_printers:
  2149. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2150. continue
  2151. # The three live fields stay, because they are what someone
  2152. # reading a bundle wants next -- but they are labelled as read
  2153. # now, not as the state the decision was made on, which is what
  2154. # made the old line contradict itself.
  2155. state = printer_manager.get_status(pid)
  2156. logger.info(
  2157. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2158. pid,
  2159. reason,
  2160. printer_manager.is_connected(pid),
  2161. state.state if state else "NO_STATUS",
  2162. printer_manager.is_awaiting_plate_clear(pid),
  2163. )
  2164. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2165. # selection and `_launch_uploads`, so anything raising here would
  2166. # discard this tick's selections — computed AMS mappings and all —
  2167. # and, on a persistent fault, stop the queue dispatching entirely.
  2168. # Same reasoning as the deficit check's guard below: never let an
  2169. # auxiliary check wedge the queue. The bed simply stays wherever it
  2170. # was, and the next tick tries again.
  2171. try:
  2172. await self._apply_keep_warm(
  2173. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2174. )
  2175. except Exception as e:
  2176. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2177. # Read the concurrency limit BEFORE the commit below, not inside
  2178. # _dispatch_selected(). A SELECT on this session after the commit
  2179. # implicitly opens a fresh transaction that nothing then closes, and
  2180. # it would stay open for the whole dispatch — minutes of "idle in
  2181. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2182. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2183. # checkpointed while every dispatch is writing to it.
  2184. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2185. # Selection is done; every decision above is recorded on `db`
  2186. # (model-based printer assignment, computed ams_mapping). Flush it
  2187. # before the dispatch tasks open their own sessions, or they will
  2188. # read a row that still says printer_id=None. This also releases the
  2189. # connection back to the pool for the duration of the dispatch.
  2190. await db.commit()
  2191. if dispatch_ids:
  2192. item_printers = {it.id: it.printer_id for it in items}
  2193. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2194. # Auto-drying: start drying on idle printers that have no pending queue items
  2195. await self._check_auto_drying(db, items, dispatching_printers)
  2196. # Low filament: alert on assigned spools that have crossed their
  2197. # low-stock threshold (#2913). Runs on both paths out of this method
  2198. # for the same reason auto-drying does — an empty queue does not mean
  2199. # the spools in the printers stopped mattering.
  2200. await self._check_filament_low(db)
  2201. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2202. # is about to run out before a replenishment could arrive (#2955).
  2203. await self._check_stock_forecast(db)
  2204. # Keep the loop on the fast interval while any upload is in flight so
  2205. # a slot freed mid-tick refills within seconds rather than after the
  2206. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2207. # deferred because the pool was full) also counts as productive.
  2208. return bool(dispatch_ids) or bool(self._inflight)
  2209. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2210. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2211. Dispatch used to happen inline in the selection loop: ``await
  2212. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2213. performs the FTP upload, that serialized every printer behind every
  2214. other printer's transfer even though the printers are independent
  2215. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2216. gather was awaited before ``check_queue`` returned, so the run loop
  2217. stayed blocked until the *slowest* upload in the batch finished — a
  2218. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2219. 93-printer farm even as other printers came free (#2602).
  2220. Each upload now runs as an independent background task tracked in
  2221. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2222. `pending` until their upload completes) and their printers from the
  2223. next pass's selection, and this method launches at most
  2224. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2225. the next fast tick instead of waiting out the whole batch. The bound
  2226. exists because the printers are independent but the host is not: each
  2227. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2228. file handle.
  2229. The no-overlapping-dispatch invariant the batch-await used to provide
  2230. is now carried by the in-flight exclusion in check_queue. Everything
  2231. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2232. per-printer hold, and each item's independent failure handling — still
  2233. lives in ``_start_print`` and runs per task exactly as before.
  2234. Synchronous on purpose: it registers every launched task into
  2235. ``self._inflight`` before returning, so the next (sequential) tick sees
  2236. an accurate in-flight count with no interleaving await.
  2237. """
  2238. free = limit - len(self._inflight)
  2239. if free <= 0:
  2240. logger.info(
  2241. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2242. len(self._inflight),
  2243. limit,
  2244. len(item_ids),
  2245. item_ids,
  2246. )
  2247. return
  2248. to_launch = item_ids[:free]
  2249. deferred = item_ids[free:]
  2250. logger.info(
  2251. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2252. len(to_launch),
  2253. len(self._inflight),
  2254. limit,
  2255. f" — deferring {deferred} to a later tick" if deferred else "",
  2256. )
  2257. for item_id in to_launch:
  2258. task = spawn_background_task(
  2259. self._dispatch_one(item_id, item_printers.get(item_id)),
  2260. name=f"queue-upload-{item_id}",
  2261. )
  2262. self._inflight[item_id] = (task, item_printers.get(item_id))
  2263. # Prune on completion so the freed slot is refillable next tick.
  2264. # spawn_background_task already logs any uncaught exception; this
  2265. # only reclaims the pool slot (fires on success, failure, or cancel).
  2266. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2267. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2268. """Upload + start one queue item in its own session (pool worker, #2602).
  2269. Its own session: pool workers run concurrently and an AsyncSession is
  2270. not safe to share across tasks; it also keeps a slow upload from pinning
  2271. the scheduler's session (and, on SQLite, its transaction) open for the
  2272. transfer's duration.
  2273. ``selected_printer_id`` is the printer this item was selected for, taken
  2274. from the same snapshot the caller used. It exists so the preheat pin can
  2275. be unwound on the paths that never reach the ``finally`` below — see the
  2276. claim failure a few lines down. Optional so the direct-call tests keep
  2277. working; when it is absent those paths simply behave as they did before.
  2278. """
  2279. async with async_session() as item_db:
  2280. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2281. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2282. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2283. # routes reject reassignment (409), so printer_id can't change out from
  2284. # under the in-flight upload and split the queue row from the
  2285. # archive/expected-print/physical command.
  2286. if not await self._claim_for_dispatch(item_db, item_id):
  2287. logger.info(
  2288. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2289. item_id,
  2290. )
  2291. # This return is outside the try/finally below, so the rollback
  2292. # has to happen here. Selecting this item already handed any
  2293. # keep-warm hold on its printer over to the preheat pin
  2294. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2295. # unwind it. Bailing without doing so leaves the bed hot with
  2296. # nothing tracking it: the keep-warm entry is gone, so the
  2297. # max-duration cap no longer applies, and if this was the
  2298. # printer's last pending item nothing else will ever turn it
  2299. # off. Reachable whenever a cancel or delete lands between
  2300. # selection and the claim.
  2301. if selected_printer_id is not None:
  2302. self._rollback_preheat_pin(item_id, selected_printer_id)
  2303. return
  2304. # Seeded from the caller's snapshot so the `item vanished` return
  2305. # below still unwinds the pin; overwritten with the row's own
  2306. # printer_id as soon as we have it.
  2307. item_printer_id: int | None = selected_printer_id
  2308. try:
  2309. item = await item_db.get(PrintQueueItem, item_id)
  2310. if not item:
  2311. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2312. return
  2313. item_printer_id = item.printer_id
  2314. await self._start_print(item_db, item)
  2315. finally:
  2316. # Undo an expected-print registration whose print command never
  2317. # went out. One choke point covers every way `_start_print` can
  2318. # end without sending: a raised exception (a DB failure mid-
  2319. # dispatch is the reported case), an early return, a cancel
  2320. # winning the #1853 CAS, or `start_print()` returning False.
  2321. # A confirmed send removes the entry itself, so this is a no-op
  2322. # on the happy path.
  2323. self._rollback_unconfirmed_expected_print(item_id)
  2324. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2325. # reservation survives only after start_print() accepted the
  2326. # command. Failure, cancellation, deferral, and exceptions all
  2327. # release it here.
  2328. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2329. # Unwind preheat state (bed/chamber/airduct) if the
  2330. # dispatch aborted before the print's own gcode took over.
  2331. # `_start_print` clears the pin on successful `start_print()`;
  2332. # anything still present here is by definition an aborted
  2333. # dispatch and gets rolled back so the printer isn't left
  2334. # heating for a job that isn't happening.
  2335. if item_printer_id is not None:
  2336. self._rollback_preheat_pin(item_id, item_printer_id)
  2337. # The cancellation flag only has meaning while this dispatch is
  2338. # running; drop it so the set cannot grow without bound and a
  2339. # re-queued item never inherits a stale cancellation.
  2340. self._cancelled_dispatches.discard(item_id)
  2341. # Release the claim on every exit. Once dispatch has finished the
  2342. # row's status carries the lock (printing/failed/cancelled are all
  2343. # != pending), so the token is only needed for the duration of the
  2344. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2345. # dispatchable again on the next tick.
  2346. await self._clear_dispatch_claim(item_db, item_id)
  2347. async def _requeue_after_upload_refused(
  2348. self,
  2349. db: AsyncSession,
  2350. item: PrintQueueItem,
  2351. printer: Printer,
  2352. error_msg: str,
  2353. toast_uid: int | None,
  2354. ) -> None:
  2355. """Put an item back in the queue after its file never reached the printer (#3210).
  2356. The item keeps its printer. Its AMS mapping was computed against that
  2357. printer's trays, and nothing on the row says whether a mapping was
  2358. computed or set by the user, so moving it to a sibling could print from
  2359. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2360. keeps every other item away from it; this one waits there and is the
  2361. only thing that knocks again, once per backoff window. The window
  2362. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2363. `dispatch_attempts` is not charged: that budget bounds a printer that
  2364. takes the file and then never starts, which this is not.
  2365. """
  2366. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2367. self._upload_refusals[printer.id] = refusals
  2368. backoff = _upload_backoff_seconds(refusals)
  2369. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2370. # The row is still `pending` -- it only moves to `printing` after a
  2371. # successful upload -- so there is no status to write back. Writing one
  2372. # anyway would undo a cancel that landed during the upload.
  2373. if item.error_message:
  2374. item.error_message = None
  2375. await db.commit()
  2376. logger.warning(
  2377. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2378. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2379. item.id,
  2380. printer.id,
  2381. printer.name,
  2382. error_msg,
  2383. refusals,
  2384. backoff,
  2385. )
  2386. try:
  2387. # Closes the dispatch toast for this attempt. Without it the toast
  2388. # keeps spinning on an upload that has ended.
  2389. await ws_manager.send_queue_item_failed(
  2390. user_id=toast_uid,
  2391. queue_item_id=item.id,
  2392. printer_id=item.printer_id,
  2393. reason="upload_failed",
  2394. )
  2395. except Exception:
  2396. pass # toast is best-effort
  2397. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2398. """Drop an expectation for a print command that was never sent.
  2399. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2400. where the interesting exception is usually the one already propagating.
  2401. """
  2402. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2403. if pending is None:
  2404. return
  2405. printer_id, remote_filename, archive_id = pending
  2406. try:
  2407. from backend.app.main import unregister_expected_print
  2408. unregister_expected_print(printer_id, remote_filename, archive_id)
  2409. except Exception:
  2410. logger.warning(
  2411. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2412. item_id,
  2413. printer_id,
  2414. remote_filename,
  2415. archive_id,
  2416. exc_info=True,
  2417. )
  2418. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2419. """Release a queue reservation without touching the dispatch session."""
  2420. if item_id not in self._unconfirmed_budget_reservations:
  2421. return
  2422. for attempt in range(1, 4):
  2423. async with async_session() as cleanup_db:
  2424. try:
  2425. await release_budget_reservation(
  2426. cleanup_db,
  2427. source_type="print_queue",
  2428. source_id=item_id,
  2429. status="released",
  2430. )
  2431. await cleanup_db.commit()
  2432. self._unconfirmed_budget_reservations.discard(item_id)
  2433. return
  2434. except Exception as exc:
  2435. try:
  2436. await cleanup_db.rollback()
  2437. except Exception:
  2438. pass
  2439. if attempt == 3:
  2440. logger.error(
  2441. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2442. item_id,
  2443. attempt,
  2444. exc,
  2445. )
  2446. return
  2447. await asyncio.sleep(0.5 * attempt)
  2448. @staticmethod
  2449. def _reported_bed_target(printer_id: int) -> int | None:
  2450. """The bed target firmware currently reports, or None if it can't be read.
  2451. None means "no evidence", not "zero" — callers must not treat it as a
  2452. temperature. Deliberately total: this feeds cleanup paths that run in a
  2453. ``finally``, where a malformed status must not become the exception the
  2454. caller sees.
  2455. """
  2456. try:
  2457. state = printer_manager.get_status(printer_id)
  2458. if state is None:
  2459. return None
  2460. temps = state.temperatures
  2461. if not isinstance(temps, dict):
  2462. return None
  2463. return int(float(temps.get("bed_target", 0) or 0))
  2464. except (TypeError, ValueError, AttributeError):
  2465. return None
  2466. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2467. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2468. Turns the bed heater off, the chamber heater off, and opens the
  2469. airduct flap back to cooling — for whichever of those preheat
  2470. actually applied. `_start_print` clears the pin on successful
  2471. `start_print()`; anything still present when `_dispatch_one` exits
  2472. is by definition an aborted dispatch and gets rolled back here.
  2473. The bed is the one action that can be declined: if firmware has since
  2474. been given a target other than the one we pinned, it belongs to someone
  2475. else and is left alone. See the comment at that branch.
  2476. Also called directly from `_dispatch_one`'s claim-failure return, which
  2477. never reaches the ``finally``.
  2478. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2479. """
  2480. pin = self._preheat_pin.pop(printer_id, set())
  2481. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2482. if not pin:
  2483. return
  2484. client = printer_manager.get_client(printer_id)
  2485. if client is None:
  2486. logger.info(
  2487. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2488. item_id,
  2489. printer_id,
  2490. )
  2491. return
  2492. if "bed" in pin:
  2493. # Only undo our own target. If firmware reports something else, the
  2494. # user or another writer owns the bed now and zeroing it would
  2495. # clobber their choice -- the same guard `_release_keep_warm`
  2496. # applies to a keep-warm hold.
  2497. #
  2498. # Every uncertain case switches the bed off rather than leaving it:
  2499. # no recorded target (a pin written before this bookkeeping, or a
  2500. # setter that raised after pinning) and an unreadable status both
  2501. # fall through. A bed left hot with no owner is the worse failure,
  2502. # and this runs in a `finally` where raising would mask the real
  2503. # exception.
  2504. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2505. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2506. logger.info(
  2507. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2508. item_id,
  2509. printer_id,
  2510. cur_bed_target,
  2511. pinned_bed,
  2512. )
  2513. else:
  2514. try:
  2515. client.set_bed_temperature(0)
  2516. except Exception as exc:
  2517. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2518. if "chamber" in pin:
  2519. try:
  2520. client.set_chamber_temperature(0)
  2521. except Exception as exc:
  2522. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2523. if "airduct" in pin:
  2524. try:
  2525. client.set_airduct_mode("cooling")
  2526. except Exception as exc:
  2527. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2528. logger.info(
  2529. "Dispatch item %s (printer %d): preheat rollback → %s",
  2530. item_id,
  2531. printer_id,
  2532. sorted(pin),
  2533. )
  2534. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  2535. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2536. Returns True if this call won the claim, False if the row was already
  2537. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2538. the load-bearing guard against reassign-during-dispatch (#2615)."""
  2539. res = await db.execute(
  2540. update(PrintQueueItem)
  2541. .where(PrintQueueItem.id == item_id)
  2542. .where(PrintQueueItem.status == "pending")
  2543. .where(PrintQueueItem.dispatching_at.is_(None))
  2544. .values(dispatching_at=datetime.now(timezone.utc))
  2545. )
  2546. await db.commit()
  2547. return res.rowcount > 0
  2548. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2549. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2550. mask the dispatch outcome.
  2551. Retried, because the failure mode in practice is transient and narrow: a
  2552. database that is momentarily unreachable — PostgreSQL out of connection
  2553. slots is the observed case — refuses this write for a second or two while
  2554. the dispatch that just ended is still holding the row out of the selection
  2555. query. One attempt was enough to wedge the item; a couple of spaced
  2556. attempts clear it. Each attempt rolls back first, since a failed write
  2557. leaves the session needing it before it can be reused.
  2558. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2559. on the next quiet tick.
  2560. """
  2561. for attempt in range(1, 4):
  2562. try:
  2563. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2564. await db.commit()
  2565. return
  2566. except Exception as exc:
  2567. try:
  2568. await db.rollback()
  2569. except Exception:
  2570. pass
  2571. if attempt == 3:
  2572. logger.warning(
  2573. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2574. "— a later quiet tick will release it",
  2575. item_id,
  2576. attempt,
  2577. exc,
  2578. )
  2579. return
  2580. await asyncio.sleep(0.5 * attempt)
  2581. async def _printers_for_model(
  2582. self,
  2583. db: AsyncSession,
  2584. model: str,
  2585. target_location: str | None = None,
  2586. printer_scope: PrinterScope = ALL_PRINTERS,
  2587. ) -> list[Printer]:
  2588. """Active printers of *model*, optionally narrowed to one location.
  2589. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2590. answer "which printers can this job run on" from one query — a job can
  2591. only be woken onto a printer the matcher would also have considered.
  2592. ``printer_scope`` is the job creator's (#1727).
  2593. """
  2594. normalized_model = normalize_printer_model(model) or model
  2595. query = (
  2596. select(Printer)
  2597. .where(func.lower(Printer.model) == normalized_model.lower())
  2598. .where(Printer.is_active == True) # noqa: E712
  2599. )
  2600. if target_location:
  2601. query = query.where(Printer.location == target_location)
  2602. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2603. query = query.where(clause)
  2604. result = await db.execute(query)
  2605. return list(result.scalars().all())
  2606. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2607. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2608. Read once per queue check rather than per printer: it decides both
  2609. whether the wake step has anything to do and how an offline printer is
  2610. worded in the waiting reason — "Offline" and "offline with no Auto On
  2611. plug" are different problems, and the second is the one the user has to
  2612. fix themselves (#2786).
  2613. """
  2614. result = await db.execute(
  2615. select(SmartPlug.printer_id)
  2616. .where(SmartPlug.printer_id.is_not(None))
  2617. .where(SmartPlug.enabled == True) # noqa: E712
  2618. .where(SmartPlug.auto_on == True) # noqa: E712
  2619. )
  2620. return {pid for (pid,) in result.all() if pid is not None}
  2621. def _wake_recently_failed(self, printer_id: int) -> bool:
  2622. """True while this printer's failed power-on is still cooling off (#2786)."""
  2623. deadline = self._wake_failures.get(printer_id)
  2624. if deadline is None:
  2625. return False
  2626. if time.monotonic() >= deadline:
  2627. del self._wake_failures[printer_id]
  2628. return False
  2629. return True
  2630. async def _wake_printer_for_model(
  2631. self,
  2632. db: AsyncSession,
  2633. candidates: list[_ModelCandidate],
  2634. target_location: str | None,
  2635. exclude_ids: set[int],
  2636. wakeable_ids: set[int],
  2637. require_plate_clear: bool,
  2638. printer_scope: PrinterScope = ALL_PRINTERS,
  2639. ) -> tuple[int | None, int | None]:
  2640. """Power on one offline printer a model-based item could run on (#2786).
  2641. The fixed-printer branch has powered a printer on since smart plugs
  2642. existed. The model-based branch never could: its matcher drops an
  2643. offline printer into the "Offline:" waiting reason and nothing looks at
  2644. its plugs, so a class-targeted job with every matching printer switched
  2645. off sat pending forever. The reporter's log is the controlled
  2646. experiment — the same item, same plug, same Auto On setting, dispatched
  2647. the moment they edited it onto a specific printer.
  2648. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2649. power-on was actually tried, so the caller can tell "nothing here was
  2650. wakeable" (both None — cheap, other items may still find something)
  2651. from "we tried and it did not come up" (only ``attempted_id`` — the
  2652. boot timeout has already been spent).
  2653. A printer whose last known trays cannot satisfy the job is passed over
  2654. rather than woken (#2876): the colours are readable while it is off, so
  2655. switching a farm on one machine at a time to discover them wakes
  2656. printers that could never have taken the job.
  2657. Deliberately does NOT go on to match the job once a printer is up: AMS
  2658. trays arrive with the first status push after connect, so a filament
  2659. check against a printer that booted seconds ago can reject the printer
  2660. we just woke. The next queue pass matches it with live state.
  2661. At most one printer per pass. Each wake blocks the queue loop for the
  2662. boot wait, and a queue of ten class-targeted jobs must not switch on
  2663. ten printers inside one check.
  2664. """
  2665. for candidate in candidates:
  2666. if not candidate.target_model:
  2667. continue
  2668. required_types, filament_overrides = _filament_constraints(candidate)
  2669. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2670. for printer in sorted(printers, key=lambda p: p.id):
  2671. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2672. continue
  2673. if printer_manager.is_connected(printer.id):
  2674. continue
  2675. if self._wake_recently_failed(printer.id):
  2676. # Its plug did not bring it back a moment ago. Move on to a
  2677. # sibling instead of spending this pass — and every pass —
  2678. # on the same printer.
  2679. continue
  2680. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2681. # Waking this one buys nothing: it would boot into IDLE and
  2682. # then be held by the plate-clear gate, which is exactly
  2683. # what the reporter's log shows happening for 80 minutes
  2684. # after a fixed-printer wake. The flag is Bambuddy-side and
  2685. # persisted, so it is readable while the printer is off.
  2686. logger.info(
  2687. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2688. printer.id,
  2689. candidate.target_model,
  2690. )
  2691. continue
  2692. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2693. if shortfall:
  2694. logger.info(
  2695. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2696. printer.id,
  2697. candidate.target_model,
  2698. ", ".join(shortfall),
  2699. )
  2700. continue
  2701. plugs = await self._get_smart_plugs(db, printer.id)
  2702. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2703. if not auto_on_plugs:
  2704. # wakeable_ids said otherwise — the plug changed under us
  2705. # mid-pass. Nothing to do but move on.
  2706. continue
  2707. logger.info(
  2708. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2709. candidate.target_model,
  2710. printer.id,
  2711. )
  2712. primary_plug = self._pick_power_plug(auto_on_plugs)
  2713. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2714. logger.warning(
  2715. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2716. printer.id,
  2717. self._wake_failure_cooloff,
  2718. )
  2719. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2720. return None, printer.id
  2721. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2722. try:
  2723. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2724. if await service.turn_on(extra_plug):
  2725. await publish_plug_state(
  2726. extra_plug.id,
  2727. extra_plug.name,
  2728. extra_plug.printer_id,
  2729. on=True,
  2730. ha_entity_id=extra_plug.ha_entity_id,
  2731. )
  2732. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2733. except Exception as e:
  2734. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2735. return printer.id, printer.id
  2736. return None, None
  2737. async def _find_idle_printer_for_model(
  2738. self,
  2739. db: AsyncSession,
  2740. model: str,
  2741. exclude_ids: set[int],
  2742. required_filament_types: list[str] | None = None,
  2743. target_location: str | None = None,
  2744. filament_overrides: list[dict] | None = None,
  2745. require_plate_clear: bool = True,
  2746. wakeable_ids: set[int] | None = None,
  2747. printer_scope: PrinterScope = ALL_PRINTERS,
  2748. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2749. ) -> tuple[int | None, str | None]:
  2750. """Find an idle, connected printer matching the model with compatible filaments.
  2751. Args:
  2752. db: Database session
  2753. model: Printer model to match (e.g., "X1C", "P1S")
  2754. exclude_ids: Printer IDs to exclude (already busy)
  2755. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2756. If provided, only printers with all required types loaded will match.
  2757. target_location: Optional location filter. If provided, only printers in this location are considered.
  2758. filament_overrides: Optional list of override dicts. Each entry may include
  2759. ``force_color_match: true`` to require an exact type+color match
  2760. on the printer for that slot. Without the flag the existing
  2761. colour-preference logic applies.
  2762. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2763. offline printer is worded: one Bambuddy will switch on reads
  2764. differently from one the user has to go and switch on themselves.
  2765. is_short: Says whether a printer's spools are too light for the job (#3137).
  2766. A printer it flags is passed over while another eligible one
  2767. is not. When every eligible printer is short, the first is
  2768. returned all the same, so the deficit gate holds the job there
  2769. and "Print Anyway" still has a printer to print on.
  2770. Returns:
  2771. Tuple of (printer_id, waiting_reason):
  2772. - (printer_id, None) if a matching printer was found
  2773. - (None, reason) if no printer is available, with explanation
  2774. """
  2775. normalized_model = normalize_printer_model(model) or model
  2776. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2777. location_suffix = f" in {target_location}" if target_location else ""
  2778. if not printers:
  2779. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2780. # Separate force-matched overrides from preference-only overrides
  2781. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2782. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2783. # Track reasons for skipping printers
  2784. printers_busy = []
  2785. printers_offline = []
  2786. printers_offline_no_plug = []
  2787. printers_missing_filament: list[tuple[str, list[str]]] = []
  2788. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2789. # The first eligible printer that is short on filament, kept in case
  2790. # every eligible printer is (#3137).
  2791. short_fallback: int | None = None
  2792. for printer in printers:
  2793. if printer.id in exclude_ids:
  2794. # Printer is already claimed by another job in this scheduling run.
  2795. # For force-color jobs, still check if the color would match — if not,
  2796. # report it as a color mismatch rather than plain "Busy" so the user
  2797. # knows the job needs a filament change, not just to wait for availability.
  2798. if force_overrides and not pref_overrides:
  2799. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2800. if missing_colors:
  2801. printers_missing_filament.append((printer.name, missing_colors))
  2802. continue
  2803. printers_busy.append(printer.name)
  2804. continue
  2805. is_connected = printer_manager.is_connected(printer.id)
  2806. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2807. if not is_connected:
  2808. # An offline printer whose last known filament cannot run this
  2809. # job is reported as needing filament rather than as offline
  2810. # (#2876). It is also the printer the smart-plug step will now
  2811. # decline to switch on, and "Offline:" on its own would leave
  2812. # that decision looking like nothing happening at all.
  2813. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2814. if shortfall:
  2815. printers_missing_filament.append((printer.name, shortfall))
  2816. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2817. printers_offline_no_plug.append(printer.name)
  2818. else:
  2819. printers_offline.append(printer.name)
  2820. continue
  2821. if not is_idle:
  2822. # Printer is currently printing. For force-color jobs, check whether the
  2823. # loaded color would satisfy the requirement — if not, surface it as a
  2824. # color-mismatch reason rather than plain "Busy" so the user understands
  2825. # that the job is waiting for a filament change, not just printer availability.
  2826. if force_overrides and not pref_overrides:
  2827. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2828. if missing_colors:
  2829. printers_missing_filament.append((printer.name, missing_colors))
  2830. logger.debug(
  2831. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2832. printer.id,
  2833. printer.name,
  2834. missing_colors,
  2835. )
  2836. continue
  2837. printers_busy.append(printer.name)
  2838. continue
  2839. # Validate filament compatibility if required types are specified
  2840. if required_filament_types:
  2841. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2842. if missing:
  2843. # When force_overrides are present, enrich missing entries with color info
  2844. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2845. if force_overrides:
  2846. force_color_map = {
  2847. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2848. for o in force_overrides
  2849. }
  2850. missing_enriched = [
  2851. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2852. for t in missing
  2853. ]
  2854. printers_missing_filament.append((printer.name, missing_enriched))
  2855. else:
  2856. printers_missing_filament.append((printer.name, missing))
  2857. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2858. continue
  2859. # Force color match: ALL flagged slots must have an exact type+color match
  2860. if force_overrides:
  2861. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2862. if missing_colors:
  2863. printers_missing_filament.append((printer.name, missing_colors))
  2864. logger.debug(
  2865. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2866. printer.id,
  2867. printer.name,
  2868. missing_colors,
  2869. )
  2870. continue
  2871. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2872. if pref_overrides:
  2873. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2874. if color_matches > 0:
  2875. candidates.append((printer.id, color_matches))
  2876. else:
  2877. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2878. printers_missing_filament.append((printer.name, override_colors))
  2879. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2880. continue
  2881. else:
  2882. # No preference ordering needed: the first eligible printer
  2883. # wins, unless its spools are too light for the job (#3137).
  2884. if is_short is not None and await is_short(printer.id):
  2885. if short_fallback is None:
  2886. short_fallback = printer.id
  2887. logger.info(
  2888. "Model-based assignment: passing over printer %s (%s), not enough filament",
  2889. printer.id,
  2890. printer.name,
  2891. )
  2892. continue
  2893. return printer.id, None
  2894. # If we have candidates from preference override matching, pick the one with most color matches
  2895. if candidates:
  2896. candidates.sort(key=lambda c: c[1], reverse=True)
  2897. if is_short is not None:
  2898. for candidate_id, _ in candidates:
  2899. if not await is_short(candidate_id):
  2900. return candidate_id, None
  2901. logger.info(
  2902. "Model-based assignment: passing over printer %s, not enough filament",
  2903. candidate_id,
  2904. )
  2905. return candidates[0][0], None
  2906. if short_fallback is not None:
  2907. return short_fallback, None
  2908. # Build waiting reason from what we found
  2909. reasons = []
  2910. if printers_missing_filament:
  2911. # Filament/color mismatch is most actionable - show first
  2912. if force_overrides and not pref_overrides:
  2913. # All mismatches are force-color failures — use descriptive message only;
  2914. # but only if there are no busy printers that DO have the matching color.
  2915. # If a printer has the right color but is busy, surface "Busy" instead so
  2916. # the user knows the job will start automatically once that printer is free.
  2917. # Same for a printer that is merely offline: Bambuddy switches that one on
  2918. # by itself, so the job is not actually waiting on anybody to change a
  2919. # spool (#2876 — offline printers reach this list now that a switched-off
  2920. # printer's own filament is read).
  2921. if not printers_busy and not printers_offline:
  2922. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  2923. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  2924. # else: fall through — the self-resolving entries are appended below
  2925. else:
  2926. names_and_missing = [
  2927. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  2928. ]
  2929. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  2930. if printers_busy:
  2931. reasons.append(f"Busy: {', '.join(printers_busy)}")
  2932. if printers_offline:
  2933. reasons.append(f"Offline: {', '.join(printers_offline)}")
  2934. if printers_offline_no_plug:
  2935. # Named separately because it is the one entry on this list the
  2936. # user has to act on: no enabled Auto On plug means Bambuddy will
  2937. # never power this printer on for the queue (#2786).
  2938. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  2939. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  2940. @staticmethod
  2941. def _is_busy_only(waiting_reason: str) -> bool:
  2942. """Check if the waiting reason only contains 'Busy' entries.
  2943. When all matching printers are simply busy printing, the queued job
  2944. will start automatically once a printer finishes — no user action
  2945. is required, so we skip the notification.
  2946. """
  2947. parts = [p.strip() for p in waiting_reason.split(" | ")]
  2948. return all(p.startswith("Busy:") for p in parts)
  2949. def _get_missing_force_color_slots(
  2950. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  2951. ) -> list[str]:
  2952. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  2953. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  2954. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  2955. with an exact type+color match.
  2956. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  2957. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  2958. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  2959. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  2960. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  2961. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  2962. setups are unaffected.
  2963. Returns:
  2964. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  2965. """
  2966. if raw_data is None:
  2967. status = printer_manager.get_status(printer_id)
  2968. if not status:
  2969. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  2970. raw_data = status.raw_data
  2971. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  2972. loaded: list[tuple[str, str, str]] = []
  2973. for ams_unit in raw_data.get("ams", []):
  2974. for tray in ams_unit.get("tray", []):
  2975. tray_type = tray.get("tray_type")
  2976. if tray_type:
  2977. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2978. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  2979. for vt in raw_data.get("vt_tray") or []:
  2980. vt_type = vt.get("tray_type")
  2981. if vt_type:
  2982. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2983. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  2984. missing = []
  2985. for o in force_overrides:
  2986. o_type = canonical_filament_type(o.get("type") or "")
  2987. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2988. o_idx = o.get("tray_info_idx") or ""
  2989. satisfied = any(
  2990. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  2991. for t_type, t_color, t_idx in loaded
  2992. )
  2993. if not satisfied:
  2994. color_label = o.get("color_name") or o.get("color", "?")
  2995. missing.append(f"{o_type} ({color_label})")
  2996. return missing
  2997. def _get_missing_filament_types(
  2998. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  2999. ) -> list[str]:
  3000. """Get the list of required filament types that are not loaded on the printer.
  3001. Args:
  3002. printer_id: The printer ID
  3003. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3004. Returns:
  3005. List of missing filament types (empty if all are loaded)
  3006. """
  3007. if raw_data is None:
  3008. status = printer_manager.get_status(printer_id)
  3009. if not status:
  3010. return required_types # Can't determine, assume all missing
  3011. raw_data = status.raw_data
  3012. # Collect all filament types loaded on this printer (AMS units + external spool)
  3013. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3014. loaded_types: set[str] = set()
  3015. # Check AMS units (stored in raw_data["ams"])
  3016. ams_data = raw_data.get("ams", [])
  3017. if ams_data:
  3018. for ams_unit in ams_data:
  3019. for tray in ams_unit.get("tray", []):
  3020. tray_type = tray.get("tray_type")
  3021. if tray_type:
  3022. loaded_types.add(canonical_filament_type(tray_type))
  3023. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3024. for vt in raw_data.get("vt_tray") or []:
  3025. vt_type = vt.get("tray_type")
  3026. if vt_type:
  3027. loaded_types.add(canonical_filament_type(vt_type))
  3028. # Find which required types are missing (using canonical type for equivalence)
  3029. missing = []
  3030. for req_type in required_types:
  3031. if canonical_filament_type(req_type) not in loaded_types:
  3032. missing.append(req_type)
  3033. return missing
  3034. def _count_override_color_matches(
  3035. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3036. ) -> int:
  3037. """Count how many filament overrides have an exact color match on the printer.
  3038. Used to prefer printers that already have the desired override colors loaded.
  3039. """
  3040. if raw_data is None:
  3041. status = printer_manager.get_status(printer_id)
  3042. if not status:
  3043. return 0
  3044. raw_data = status.raw_data
  3045. # Collect loaded filaments' type+color pairs
  3046. loaded: set[tuple[str, str]] = set()
  3047. for ams_unit in raw_data.get("ams", []):
  3048. for tray in ams_unit.get("tray", []):
  3049. tray_type = tray.get("tray_type")
  3050. # `or ""`, not a dict default: a slot can carry the key with a
  3051. # null value, and this now runs against switched-off printers
  3052. # too, where nobody is watching for the AttributeError.
  3053. tray_color = tray.get("tray_color") or ""
  3054. if tray_type:
  3055. color_norm = tray_color.replace("#", "").lower()[:6]
  3056. loaded.add((tray_type.upper(), color_norm))
  3057. for vt in raw_data.get("vt_tray") or []:
  3058. vt_type = vt.get("tray_type")
  3059. if vt_type:
  3060. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3061. loaded.add((vt_type.upper(), color_norm))
  3062. matches = 0
  3063. for o in overrides:
  3064. o_type = (o.get("type") or "").upper()
  3065. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3066. if (o_type, o_color) in loaded:
  3067. matches += 1
  3068. return matches
  3069. @staticmethod
  3070. def _tray_reading(printer_id: int) -> dict:
  3071. """The best tray reading available for a printer that is not printing.
  3072. Live status first: a printer keeps its last status after the power
  3073. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3074. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3075. for when the client itself has been dropped and taken its status with
  3076. it — which is what every power-on attempt does.
  3077. An empty result means "we have never heard", not "nothing is loaded":
  3078. the two are indistinguishable from here, and only the second would be
  3079. safe to act on.
  3080. """
  3081. status = printer_manager.get_status(printer_id)
  3082. raw = (status.raw_data if status else None) or {}
  3083. for ams_unit in raw.get("ams") or []:
  3084. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3085. return raw
  3086. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3087. return raw
  3088. return printer_manager.last_known_trays(printer_id)
  3089. def _cached_filament_shortfall(
  3090. self,
  3091. printer_id: int,
  3092. required_types: list[str] | None,
  3093. filament_overrides: list[dict] | None,
  3094. ) -> list[str]:
  3095. """What a switched-off printer's last known filament cannot provide (#2876).
  3096. The smart-plug wake step used to consider only the model, so a job for a
  3097. colour loaded on the last printer in ID order switched on every earlier
  3098. one in turn, evaluated it, rejected it on colour and left it running.
  3099. Bambuddy knew those colours the whole time. This asks the same three
  3100. questions the matcher asks a live printer — required types, forced
  3101. colours, preferred colours — of the trays it last reported, and returns
  3102. the answers in the same shape the "Waiting for filament" reason uses.
  3103. Empty means the printer may still be able to take the job.
  3104. Fails open, and deliberately: with no tray reading (never connected
  3105. since Bambuddy started, or the cache dropped by a reconnect) this
  3106. returns nothing to report and the printer is treated as it was before.
  3107. A farm restarted while its printers were off must not conclude that
  3108. none of them can print.
  3109. """
  3110. if not required_types and not filament_overrides:
  3111. return []
  3112. raw_data = self._tray_reading(printer_id)
  3113. if not raw_data:
  3114. return []
  3115. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3116. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3117. if required_types:
  3118. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3119. if missing:
  3120. # Same enrichment the live path applies: a bare "PLA" is not
  3121. # much help when what is missing is a particular PLA.
  3122. force_color_map = {
  3123. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3124. }
  3125. return [
  3126. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3127. for t in missing
  3128. ]
  3129. if force_overrides:
  3130. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3131. if missing_colors:
  3132. return missing_colors
  3133. # Preference overrides read as a preference but the matcher treats zero
  3134. # matches as a skip, so a printer with none of the wanted colours is
  3135. # rejected there too. Waking it would only produce that same rejection.
  3136. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3137. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3138. return []
  3139. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3140. """Fold the winning candidate's file and settings onto the queue row (#671).
  3141. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3142. never escapes the selection loop. By the time the pass commits, the row
  3143. looks exactly like an ordinary single-file model-based item, so the upload,
  3144. archive creation, expected-print registration, print history and reprint
  3145. paths need no knowledge that variants exist.
  3146. No-ops for a non-variant candidate, which is already the item's own columns.
  3147. Safe to run and re-run: the item's file columns are only ever *read* when it
  3148. has no variants, so an item that gets resolved and then skipped (library-row
  3149. conflict, previous-print gate) is simply resolved again on the next pass.
  3150. """
  3151. variant = candidate.variant
  3152. if variant is None:
  3153. return
  3154. item.library_file_id = variant.library_file_id
  3155. item.library_file = variant.library_file
  3156. # The dispatcher checks archive_id first and would print that instead of
  3157. # the file we just picked. Creation refuses to combine the two, so this
  3158. # only ever fires on a hand-written row — clear it rather than silently
  3159. # dispatch something the matcher never considered.
  3160. item.archive_id = None
  3161. item.archive = None
  3162. item.target_model = variant.target_model
  3163. item.plate_id = variant.plate_id
  3164. item.ams_mapping = variant.ams_mapping
  3165. item.nozzle_mapping = variant.nozzle_mapping
  3166. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3167. item.filament_overrides = variant.filament_overrides
  3168. item.required_filament_types = variant.required_filament_types
  3169. if variant.print_time_seconds is not None:
  3170. # The row carried the shortest candidate's estimate so SJF could order
  3171. # it before a printer was known; now that one is chosen, record what is
  3172. # actually going to run so history and the ETA agree with reality.
  3173. item.print_time_seconds = variant.print_time_seconds
  3174. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3175. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3176. Recomputes from live printer status when the stored mapping is missing OR
  3177. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3178. frontend status-load race can serialize [-1] before the printer's AMS
  3179. trays are known (#2589) — and must not be trusted: downstream it would be
  3180. silently downgraded to external-spool mode and print against an empty
  3181. feed. A resolved mapping is re-checked against the target printer's
  3182. live trays before it is trusted (#2799) and recomputed when it does not
  3183. fit. When it does fit, its resolved slots are kept as they are and only
  3184. the slots the plate prints that are still unresolved are matched again;
  3185. all of it is left alone when the user has acknowledged it with "Print
  3186. Anyway".
  3187. When recompute cannot resolve it either (no compatible tray loaded), the
  3188. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3189. external selection. On a printer that reported loaded trays,
  3190. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3191. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3192. and the firmware surfaces a clear AMS-mapping error instead of silently
  3193. printing to the empty external feed.
  3194. Returns an actionable message when that firmware error is the only
  3195. possible outcome — the matcher ran, matched nothing, and the printer has
  3196. no AMS to load a different spool into (#2771). The caller fails the item
  3197. on it instead of spending an upload on a print that cannot start.
  3198. Returns None everywhere else, including every case where we simply lack
  3199. the data to judge, so dispatch is only ever blocked on a positive
  3200. finding.
  3201. """
  3202. stored_mapping: list | None = None
  3203. if item.ams_mapping:
  3204. try:
  3205. stored_mapping = json.loads(item.ams_mapping)
  3206. except (json.JSONDecodeError, TypeError):
  3207. stored_mapping = None
  3208. # Present and resolved. Global tray IDs only mean something relative to
  3209. # the printer they were resolved against, so "resolved" is not the same
  3210. # as "resolved *here*" — check the mapping still fits the printer that
  3211. # is about to run this item before trusting it (#2799). "Print anyway"
  3212. # is the user overriding exactly this judgement, so it short-circuits.
  3213. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3214. if item.skip_filament_check:
  3215. return None
  3216. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3217. if conflict is None:
  3218. # It fits, but a slot the plate prints may still be empty: the
  3219. # spool was missing when it was mapped, and has perhaps been
  3220. # loaded since. Nothing else would ever look at that slot again,
  3221. # so a job held for it would be held again on every Start.
  3222. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3223. if filled is not None:
  3224. item.ams_mapping = json.dumps(filled)
  3225. logger.info(
  3226. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3227. item.id,
  3228. stored_mapping,
  3229. printer_id,
  3230. filled,
  3231. )
  3232. await db.commit()
  3233. return None
  3234. logger.warning(
  3235. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3236. item.id,
  3237. stored_mapping,
  3238. printer_id,
  3239. conflict,
  3240. )
  3241. # Drop it before recomputing so a failed recompute cannot fall back
  3242. # to the mapping we just rejected.
  3243. item.ams_mapping = None
  3244. stored_mapping = None
  3245. await db.commit()
  3246. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3247. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3248. item.ams_mapping = json.dumps(computed_mapping)
  3249. logger.info(
  3250. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3251. item.id,
  3252. printer_id,
  3253. computed_mapping,
  3254. )
  3255. await db.commit()
  3256. return None
  3257. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3258. if external_only is not None:
  3259. item.ams_mapping = json.dumps(external_only)
  3260. logger.info(
  3261. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3262. "mapping every filament to it: %s",
  3263. item.id,
  3264. printer_id,
  3265. external_only,
  3266. )
  3267. await db.commit()
  3268. return None
  3269. if _mapping_is_all_unresolved(stored_mapping):
  3270. logger.warning(
  3271. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3272. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3273. item.id,
  3274. stored_mapping,
  3275. printer_id,
  3276. )
  3277. item.ams_mapping = None
  3278. await db.commit()
  3279. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3280. async def _external_spool_only_mapping(
  3281. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3282. ) -> list[int] | None:
  3283. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3284. A printer without an AMS prints from its external spool, and an external
  3285. spool whose filament was never set reports no type, so the matcher has
  3286. nothing to match. Sent without a mapping, the print goes out with the AMS
  3287. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3288. to carry such a job through; a job placed by model or location no longer
  3289. keeps one, and one queued that way never had one.
  3290. Only on a positive report: the printer has said it has no AMS, it has a
  3291. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3292. is not ours to pick), and no feed has a filament set — with one set, the
  3293. matcher has already given its answer. Not for a job that asked for its
  3294. colours to be matched strictly: a spool without a filament set has no
  3295. colour to check. Returns None otherwise.
  3296. """
  3297. if item.filament_overrides:
  3298. try:
  3299. overrides = json.loads(item.filament_overrides)
  3300. except (json.JSONDecodeError, TypeError):
  3301. return None
  3302. if not isinstance(overrides, list) or any(
  3303. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3304. ):
  3305. return None
  3306. status = printer_manager.get_status(printer_id)
  3307. if status is None or not isinstance(status.raw_data, dict):
  3308. return None
  3309. ams_units = status.raw_data.get("ams")
  3310. if not isinstance(ams_units, list) or ams_units:
  3311. return None
  3312. vt_trays = status.raw_data.get("vt_tray")
  3313. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3314. return None
  3315. if self._build_loaded_filaments(status):
  3316. return None
  3317. printer = await self._get_printer(db, printer_id)
  3318. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3319. return None
  3320. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3321. if external < _EXTERNAL_TRAY_ID_MIN:
  3322. return None
  3323. required = await self._get_filament_requirements(db, item)
  3324. slot_ids = [r.get("slot_id") for r in required or []]
  3325. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3326. if not slot_ids:
  3327. return None
  3328. mapping = [-1] * max(slot_ids)
  3329. for slot_id in slot_ids:
  3330. mapping[slot_id - 1] = external
  3331. return mapping
  3332. async def _fill_unresolved_slots(
  3333. self,
  3334. db: AsyncSession,
  3335. printer_id: int,
  3336. item: PrintQueueItem,
  3337. stored_mapping: list | None,
  3338. ) -> list | None:
  3339. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3340. Every resolved entry is kept, so a tray the user picked by hand stays
  3341. picked. Only the plate's unresolved slots are matched, and only against
  3342. trays the mapping does not already use: the matcher never gives two
  3343. slots one tray, and filling a gap with a tray the user assigned to
  3344. another slot would print that slot's filament twice.
  3345. Returns None when there is nothing to fill or nothing could be filled.
  3346. """
  3347. if not isinstance(stored_mapping, list) or not stored_mapping:
  3348. return None
  3349. required = await self._get_filament_requirements(db, item)
  3350. if not required:
  3351. return None
  3352. self._apply_filament_overrides(item, required)
  3353. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3354. if not gaps:
  3355. return None
  3356. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3357. computed = await self._compute_ams_mapping_for_printer(
  3358. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3359. )
  3360. if not computed:
  3361. return None
  3362. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3363. filled = False
  3364. for slot_id in gaps:
  3365. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3366. if _is_tray_id(tray) and tray >= 0:
  3367. merged[slot_id - 1] = tray
  3368. filled = True
  3369. return merged if filled else None
  3370. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3371. """What a staged item would be held for if it were started now (#2799).
  3372. The Start button asks this before releasing an item, so that a job whose
  3373. filament is still not loaded offers "Print Anyway" instead of being
  3374. released, held again by the scheduler and leaving no way past the hold.
  3375. It reaches the same answer the dispatch path would: a stored mapping
  3376. that fits is kept and only its gaps are matched again, and one that
  3377. does not fit (or is missing) is replaced by a fresh match.
  3378. Returns the missing filaments, described the way the queue row
  3379. describes them, or None when nothing is missing or there is not enough
  3380. evidence to say: no printer yet (a model-based item picks one at
  3381. dispatch), no status, no trays reported, or no readable 3MF.
  3382. """
  3383. if item.skip_filament_check or not item.printer_id:
  3384. return None
  3385. status = printer_manager.get_status(item.printer_id)
  3386. if status is None or not self._build_loaded_filaments(status):
  3387. return None
  3388. # Called from a request, not from a pass: drop whatever the last pass
  3389. # memoised so this reads the file as it is now. A pass running at the
  3390. # same time only loses its cache.
  3391. self._filament_req_memo.clear()
  3392. mapping: list | None = None
  3393. if item.ams_mapping:
  3394. try:
  3395. mapping = json.loads(item.ams_mapping)
  3396. except (json.JSONDecodeError, TypeError):
  3397. mapping = None
  3398. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3399. mapping = None
  3400. if mapping is not None:
  3401. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3402. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3403. else:
  3404. mapping = None
  3405. if mapping is None:
  3406. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3407. required = await self._get_filament_requirements(db, item)
  3408. if not required:
  3409. return None
  3410. self._apply_filament_overrides(item, required)
  3411. missing = _unresolved_required(required, mapping)
  3412. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3413. async def _stored_mapping_conflict(
  3414. self,
  3415. db: AsyncSession,
  3416. printer_id: int,
  3417. item: PrintQueueItem,
  3418. stored_mapping: list | None,
  3419. ) -> str | None:
  3420. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3421. A mapping is a list of global tray IDs, and those are only meaningful
  3422. relative to the printer they were resolved against — the same rule
  3423. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3424. arrives at a printer it was not resolved for:
  3425. * the print dialog stamps one mapping onto every selected printer, so a
  3426. mapping computed against the first printer is dispatched verbatim to
  3427. the rest, whose AMS slot order differs;
  3428. * a spool is moved between queueing and dispatch.
  3429. Both end the same way: the slot index still resolves, so nothing looks
  3430. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3431. the firmware's own type check, so a PETG slot happily prints in ASA.
  3432. Returns a short reason when the mapping names a tray this printer does
  3433. not have loaded, points a slot at a tray holding a different filament
  3434. type, or points it at an external spool this printer reports empty while
  3435. its AMS holds that slot's filament (#3239). Returns None when the
  3436. mapping fits, and — deliberately — whenever we lack the evidence to
  3437. judge, so a recompute only ever follows a positive finding.
  3438. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3439. matcher had nothing, not that the mapping belongs to another printer,
  3440. and destroying a partially hand-resolved mapping over it would lose the
  3441. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3442. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3443. item when that finds nothing.
  3444. """
  3445. if not isinstance(stored_mapping, list) or not stored_mapping:
  3446. return None
  3447. status = printer_manager.get_status(printer_id)
  3448. if status is None:
  3449. return None
  3450. loaded = self._build_loaded_filaments(status)
  3451. if not loaded:
  3452. # Nothing reported yet (reconnect, first push pending). Saying
  3453. # "tray not loaded" here would recompute against an AMS we cannot
  3454. # see, which is how #2589 produced a bogus all-[-1] in the first
  3455. # place.
  3456. return None
  3457. by_tray = {f["global_tray_id"]: f for f in loaded}
  3458. # Cheap pass first, on live status alone: every tray the mapping names
  3459. # has to exist here. This catches a foreign mapping without opening the
  3460. # 3MF, which is worth doing because the parse below is neither cached
  3461. # nor free.
  3462. for index, tray in enumerate(stored_mapping):
  3463. if not _is_tray_id(tray) or tray < 0:
  3464. continue
  3465. if tray in by_tray:
  3466. continue
  3467. if tray >= 254:
  3468. # An external feed we have not heard about is absence of
  3469. # evidence about *that slot* — the rest of the mapping is still
  3470. # worth judging, so skip it rather than abandoning the pass.
  3471. continue
  3472. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3473. # Only now is the 3MF worth opening: the type check needs to know what
  3474. # each slot actually asked for. The external spool is checked the same
  3475. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3476. # two printers with different filament in the external feed is the same
  3477. # failure this method exists to catch.
  3478. required = await self._get_filament_requirements(db, item)
  3479. if not required:
  3480. return None
  3481. self._apply_filament_overrides(item, required)
  3482. # External feeds the printer reports and reports as empty. That is
  3483. # evidence, unlike an external feed it says nothing about (#3239).
  3484. empty_external: set[int] = set()
  3485. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3486. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3487. if isinstance(vt, dict) and not vt.get("tray_type"):
  3488. try:
  3489. empty_external.add(int(vt.get("id", 254)))
  3490. except (TypeError, ValueError):
  3491. continue
  3492. for req in required:
  3493. slot_id = req.get("slot_id") or 0
  3494. if slot_id <= 0:
  3495. continue
  3496. if slot_id > len(stored_mapping):
  3497. return f"slot {slot_id} is not covered by the mapping"
  3498. tray = stored_mapping[slot_id - 1]
  3499. if not _is_tray_id(tray) or tray < 0:
  3500. continue
  3501. loaded_tray = by_tray.get(tray)
  3502. if loaded_tray is None:
  3503. # A mapping made for a printer that feeds this slot from its
  3504. # external spool, sent to one whose external spool is empty and
  3505. # whose AMS holds the filament (#3239). Only then: an external
  3506. # spool can be loaded without its filament set, and on a printer
  3507. # with nothing else to offer that job printed before. The colour
  3508. # has to match too: with only another colour in the AMS, the
  3509. # printer asking for the spool beats printing in that colour.
  3510. want = canonical_filament_type(req.get("type"))
  3511. if tray >= 254 and tray in empty_external and want:
  3512. ams_tray = next(
  3513. (
  3514. f
  3515. for f in loaded
  3516. if not f.get("is_external")
  3517. and canonical_filament_type(f.get("type")) == want
  3518. and self._colors_are_similar(f.get("color"), req.get("color"))
  3519. ),
  3520. None,
  3521. )
  3522. if ams_tray is not None:
  3523. return (
  3524. f"slot {slot_id} points at the external spool, which is empty, "
  3525. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3526. )
  3527. continue
  3528. want = canonical_filament_type(req.get("type"))
  3529. have = canonical_filament_type(loaded_tray.get("type"))
  3530. if want and have and want != have:
  3531. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3532. return None
  3533. async def _unmappable_without_ams_message(
  3534. self,
  3535. db: AsyncSession,
  3536. printer_id: int,
  3537. item: PrintQueueItem,
  3538. computed_mapping: list[int] | None,
  3539. ) -> str | None:
  3540. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3541. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3542. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3543. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3544. uploaded several megabytes and burned its dispatch retries. This method
  3545. speaks only for the AMS-less case: there is nothing to resume into — the
  3546. external spool holder is the whole inventory — so the useful answer is to
  3547. say which filament is missing and stop. With an AMS attached it returns
  3548. None: where live status reported loaded trays,
  3549. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3550. reported none the print goes out and the firmware error is the answer —
  3551. the user can load the right spool and press Resume.
  3552. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3553. every branch that lacks the evidence to be sure returns None.
  3554. """
  3555. # None means the matcher never ran (no requirements parsed from the 3MF,
  3556. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3557. # dispatch as they always have.
  3558. if not _mapping_is_all_unresolved(computed_mapping):
  3559. return None
  3560. status = printer_manager.get_status(printer_id)
  3561. if status is None:
  3562. return None
  3563. # "No AMS" has to be a fact the printer stated, not the absence of a
  3564. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3565. # handled and is preserved across partial pushes thereafter, so a missing
  3566. # key means we have not heard yet — most likely a reconnect, where the
  3567. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3568. # empty list is the positive report of a printer with no AMS.
  3569. ams_units = status.raw_data.get("ams")
  3570. if not isinstance(ams_units, list) or ams_units:
  3571. return None
  3572. required = await self._get_filament_requirements(db, item)
  3573. loaded = self._build_loaded_filaments(status)
  3574. if not required or not loaded:
  3575. # Both were non-empty moments ago or the matcher could not have run.
  3576. # If the picture changed under us, say nothing rather than fail an
  3577. # item on stale evidence.
  3578. return None
  3579. self._apply_filament_overrides(item, required)
  3580. return _unmatched_filament_message(required, loaded)
  3581. async def _fail_unmappable_item(
  3582. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3583. ) -> None:
  3584. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3585. This replaces a failure, not a success: without it the item is uploaded,
  3586. rejected by the firmware with 0700_8012, retried twice more and failed
  3587. anyway with "never started the print after N dispatch attempts". So this
  3588. applies on the model-based path too, even though it means an "Any <model>"
  3589. job stops at the first printer offered rather than trying its siblings —
  3590. deferring instead would need the check to move inside
  3591. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3592. re-assigns the same printer on the next tick.
  3593. """
  3594. item.status = "failed"
  3595. item.error_message = message
  3596. item.completed_at = datetime.now(timezone.utc)
  3597. item.waiting_reason = None
  3598. await db.commit()
  3599. logger.warning(
  3600. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3601. item.id,
  3602. printer_id,
  3603. message,
  3604. )
  3605. job_name = await self._get_job_name(db, item)
  3606. printer = await self._get_printer(db, printer_id)
  3607. await notification_service.on_queue_job_failed(
  3608. job_name=job_name,
  3609. printer_id=printer_id,
  3610. printer_name=printer.name if printer else "Unknown",
  3611. reason=message,
  3612. db=db,
  3613. )
  3614. try:
  3615. await ws_manager.send_queue_item_failed(
  3616. user_id=item.created_by_id,
  3617. queue_item_id=item.id,
  3618. printer_id=printer_id,
  3619. reason="filament_unmappable",
  3620. )
  3621. except Exception:
  3622. pass
  3623. async def _compute_ams_mapping_for_printer(
  3624. self,
  3625. db: AsyncSession,
  3626. printer_id: int,
  3627. item: PrintQueueItem,
  3628. *,
  3629. only_slots: set[int] | None = None,
  3630. reserved_trays: set[int] | None = None,
  3631. ) -> list[int] | None:
  3632. """Compute AMS mapping for a printer based on filament requirements.
  3633. Called when a queue item has no ams_mapping set — either for model-based
  3634. items after printer assignment, or printer-specific items (e.g. from VP).
  3635. Args:
  3636. db: Database session
  3637. printer_id: The assigned printer ID
  3638. item: The queue item (contains archive_id or library_file_id)
  3639. only_slots: Match only these filament slots; every other slot comes
  3640. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3641. reserved_trays: Global tray IDs to leave out of the match, because
  3642. the stored mapping already gives them to another slot.
  3643. Returns:
  3644. AMS mapping array or None if no mapping needed/possible
  3645. """
  3646. # Get printer status
  3647. status = printer_manager.get_status(printer_id)
  3648. if not status:
  3649. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3650. return None
  3651. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3652. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3653. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3654. # an AMS on the *other* nozzle, and the matcher falls through to a
  3655. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3656. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3657. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3658. # Get filament requirements from source file
  3659. filament_reqs = await self._get_filament_requirements(db, item)
  3660. if not filament_reqs:
  3661. # When the 3MF can't be read but force-color overrides are present, build a
  3662. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3663. if item.filament_overrides:
  3664. try:
  3665. overrides = json.loads(item.filament_overrides)
  3666. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3667. if force_overrides:
  3668. logger.info(
  3669. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3670. "force-color override(s)",
  3671. item.id,
  3672. len(force_overrides),
  3673. )
  3674. return self._build_override_direct_mapping(force_overrides, status)
  3675. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3676. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3677. logger.debug("No filament requirements found for queue item %s", item.id)
  3678. return None
  3679. self._apply_filament_overrides(item, filament_reqs)
  3680. if only_slots is not None:
  3681. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3682. if not filament_reqs:
  3683. return None
  3684. # Build loaded filaments from printer status
  3685. loaded_filaments = self._build_loaded_filaments(status)
  3686. if reserved_trays:
  3687. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3688. if not loaded_filaments:
  3689. logger.debug("No filaments loaded on printer %s", printer_id)
  3690. return None
  3691. # Check if user prefers lowest remaining filament when multiple spools match
  3692. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3693. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3694. # Without backup, the printer will not switch to a second spool when the
  3695. # picked one runs out — so sorting toward the lowest leaves the print
  3696. # at risk of running dry mid-job. None (unknown: no status report with
  3697. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3698. if prefer_lowest and status.ams_filament_backup is False:
  3699. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3700. prefer_lowest = False
  3701. # When the preference is on, surface Bambuddy's inventory-side
  3702. # remaining for each slot that's bound to a tracked spool, so the
  3703. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3704. # entirely when the preference is off — no behaviour change for
  3705. # users who haven't opted in.
  3706. inventory_remain_overrides: dict[int, float] | None = None
  3707. if prefer_lowest:
  3708. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3709. # Compute mapping: match required filaments to available slots
  3710. return self._match_filaments_to_slots(
  3711. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3712. )
  3713. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3714. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3715. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3716. diagnosis (#2771) describes the filament the matcher actually looked
  3717. for, not the one the 3MF was sliced with — naming the pre-override
  3718. filament in a user-facing error would send the user to load the wrong
  3719. spool.
  3720. """
  3721. if not item.filament_overrides:
  3722. return
  3723. try:
  3724. overrides = json.loads(item.filament_overrides)
  3725. override_map = {o["slot_id"]: o for o in overrides}
  3726. for req in filament_reqs:
  3727. if req["slot_id"] in override_map:
  3728. override = override_map[req["slot_id"]]
  3729. req["type"] = override["type"]
  3730. req["color"] = override["color"]
  3731. # A manual/preference override SWAPS the slot's filament, so the
  3732. # 3MF's original tray_info_idx now points at the old spool and must
  3733. # be cleared — matching then falls back to type+colour. A
  3734. # force_color_match override is not a swap: it carries the 3MF's
  3735. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3736. # it here too, letting the matcher pin the correct variant slot on a
  3737. # printer holding two same-colour spools of different variants (#2650).
  3738. # If that variant isn't loaded the matcher falls back to type+colour,
  3739. # so an eligible printer never fails to map.
  3740. req["tray_info_idx"] = (
  3741. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3742. )
  3743. logger.debug(
  3744. "Queue item %s: Override slot %d -> %s %s",
  3745. item.id,
  3746. req["slot_id"],
  3747. override["type"],
  3748. override["color"],
  3749. )
  3750. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3751. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3752. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3753. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3754. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3755. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3756. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3757. treated as the filament requirement for that slot and matched against the
  3758. current AMS state of the printer.
  3759. Returns the same format as ``_match_filaments_to_slots``, or None when
  3760. the AMS has no loaded filaments.
  3761. """
  3762. loaded = self._build_loaded_filaments(status)
  3763. if not loaded:
  3764. return None
  3765. reqs = [
  3766. {
  3767. "slot_id": o["slot_id"],
  3768. "type": o.get("type", ""),
  3769. "color": o.get("color", ""),
  3770. # These are all force_color_match overrides, so the idx (when the
  3771. # 3MF carried one) is the intended variant, not a stale swap —
  3772. # keep it so the matcher pins the right variant slot, falling back
  3773. # to type+colour when it isn't loaded (#2650).
  3774. "tray_info_idx": o.get("tray_info_idx", ""),
  3775. }
  3776. for o in force_overrides
  3777. ]
  3778. return self._match_filaments_to_slots(reqs, loaded)
  3779. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3780. """Resolve the queue item's source 3MF and parse the per-slot
  3781. filament requirements out of it. Thin DB-resolver wrapper around
  3782. ``filament_requirements.extract_filament_requirements`` so the VP
  3783. queue-mode write path (#1188) can reuse the same parser at upload
  3784. time.
  3785. """
  3786. from backend.app.services.filament_requirements import extract_filament_requirements
  3787. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3788. # so every caller gets its own copy — a shared list would leak one
  3789. # item's overrides into the next item that happens to print the same
  3790. # plate.
  3791. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3792. if memo_key in self._filament_req_memo:
  3793. cached = self._filament_req_memo[memo_key]
  3794. return [dict(r) for r in cached] if cached else None
  3795. file_path: Path | None = None
  3796. if item.archive_id:
  3797. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3798. archive = result.scalar_one_or_none()
  3799. if archive:
  3800. file_path = settings.base_dir / archive.file_path
  3801. elif item.library_file_id:
  3802. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3803. library_file = result.scalar_one_or_none()
  3804. if library_file:
  3805. lib_path = Path(library_file.file_path)
  3806. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3807. if not file_path or not file_path.exists():
  3808. self._filament_req_memo[memo_key] = None
  3809. return None
  3810. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3811. self._filament_req_memo[memo_key] = filaments or None
  3812. return [dict(r) for r in filaments] if filaments else None
  3813. def _build_loaded_filaments(self, status) -> list[dict]:
  3814. """Build list of loaded filaments from printer status.
  3815. Args:
  3816. status: PrinterState from printer_manager
  3817. Returns:
  3818. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3819. """
  3820. filaments = []
  3821. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3822. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3823. # Dual-nozzle detection, used below to route external spools to an
  3824. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  3825. # which was corrected for #1257 while this copy kept the old signal.
  3826. #
  3827. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  3828. # printer with zero AMS units reports an empty map — and every external
  3829. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  3830. # `_match_filaments_to_slots` rejects outright because `None` equals
  3831. # neither 0 nor 1. On an X2D feeding from external spools only that left
  3832. # nothing to match, the mapping came back all -1, and the print went out
  3833. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  3834. # "Failed to get AMS mapping table".
  3835. #
  3836. # `nozzles` is always a two-entry list (the state seeds it with two empty
  3837. # NozzleInfo stubs), so its length proves nothing; only a populated
  3838. # diameter on the second entry means real hardware. The other two signals
  3839. # are fallbacks for firmware revisions that surface one but not the
  3840. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  3841. # and so is more than one `vt_tray` entry, since single-nozzle printers
  3842. # expose exactly one external feed.
  3843. nozzles = getattr(status, "nozzles", None) or []
  3844. vt_trays = status.raw_data.get("vt_tray") or []
  3845. is_dual_nozzle = bool(
  3846. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  3847. or ams_extruder_map
  3848. # isinstance, because a dict here would count its ~30 keys as trays.
  3849. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  3850. # so this is unreachable — but the loop below would raise on a dict
  3851. # and that is the pre-existing behaviour to keep, not to paper over.
  3852. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  3853. )
  3854. # Parse AMS units from raw_data
  3855. ams_data = status.raw_data.get("ams", [])
  3856. for ams_unit in ams_data:
  3857. ams_id = int(ams_unit.get("id", 0))
  3858. trays = ams_unit.get("tray", [])
  3859. is_ht = len(trays) == 1 # AMS-HT has single tray
  3860. for tray in trays:
  3861. tray_type = tray.get("tray_type")
  3862. if tray_type:
  3863. tray_id = int(tray.get("id", 0))
  3864. tray_color = tray.get("tray_color", "")
  3865. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  3866. tray_info_idx = tray.get("tray_info_idx", "")
  3867. # Normalize color: remove alpha, add hash
  3868. color = self._normalize_color(tray_color)
  3869. # Calculate global tray ID
  3870. # AMS-HT units have IDs starting at 128 with a single tray
  3871. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  3872. filaments.append(
  3873. {
  3874. "type": tray_type,
  3875. "color": color,
  3876. "tray_info_idx": tray_info_idx,
  3877. "ams_id": ams_id,
  3878. "tray_id": tray_id,
  3879. "is_ht": is_ht,
  3880. "is_external": False,
  3881. "global_tray_id": global_tray_id,
  3882. "extruder_id": ams_extruder_map.get(str(ams_id)),
  3883. "remain": tray.get("remain", -1),
  3884. }
  3885. )
  3886. # Check external spool(s) (vt_tray is a list)
  3887. for idx, vt in enumerate(vt_trays):
  3888. if vt.get("tray_type"):
  3889. color = self._normalize_color(vt.get("tray_color", ""))
  3890. tray_id = int(vt.get("id", 254))
  3891. filaments.append(
  3892. {
  3893. "type": vt["tray_type"],
  3894. "color": color,
  3895. "tray_info_idx": vt.get("tray_info_idx", ""),
  3896. "ams_id": -1,
  3897. "tray_id": idx,
  3898. "is_ht": False,
  3899. "is_external": True,
  3900. "global_tray_id": tray_id,
  3901. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  3902. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  3903. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  3904. "remain": vt.get("remain", -1),
  3905. }
  3906. )
  3907. return filaments
  3908. def _normalize_color(self, color: str | None) -> str:
  3909. """Normalize color to #RRGGBB format."""
  3910. if not color:
  3911. return "#808080"
  3912. hex_color = color.replace("#", "")[:6]
  3913. return f"#{hex_color}"
  3914. def _normalize_color_for_compare(self, color: str | None) -> str:
  3915. """Normalize color for comparison (lowercase, no hash)."""
  3916. if not color:
  3917. return ""
  3918. return color.replace("#", "").lower()[:6]
  3919. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  3920. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  3921. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  3922. stays the per-channel box that shipped — this only decides which of
  3923. several eligible spools is closest, so nothing becomes usable or
  3924. unusable because of it.
  3925. It ranks by how far apart the colours *look*, not how far apart their
  3926. numbers are. RGB distance overweights blue badly enough to invert the
  3927. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  3928. the nearer of two eligible spools by RGB and the further by a factor of
  3929. four once measured perceptually.
  3930. Alpha is ignored, deliberately: the alpha a slicer writes for a
  3931. transparent filament is not a colour the user chose, and counting it
  3932. would stop a transparent filament matching itself.
  3933. """
  3934. return perceptual_color_distance(color1, color2)
  3935. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  3936. """Check if two colors are visually similar within a threshold."""
  3937. hex1 = self._normalize_color_for_compare(color1)
  3938. hex2 = self._normalize_color_for_compare(color2)
  3939. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  3940. return False
  3941. try:
  3942. r1 = int(hex1[0:2], 16)
  3943. g1 = int(hex1[2:4], 16)
  3944. b1 = int(hex1[4:6], 16)
  3945. r2 = int(hex2[0:2], 16)
  3946. g2 = int(hex2[2:4], 16)
  3947. b2 = int(hex2[4:6], 16)
  3948. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  3949. except ValueError:
  3950. return False
  3951. async def _build_inventory_remain_overrides(
  3952. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  3953. ) -> dict[int, float]:
  3954. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  3955. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  3956. The MQTT ``remain`` field on a tray is the printer firmware's
  3957. RFID-decremented value, which has two limitations the "Prefer Lowest
  3958. Remaining Filament" feature has been ignoring (#1508):
  3959. - it's only meaningful for Bambu RFID spools; everything else reports
  3960. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  3961. compare equal and the sort collapses to AMS-slot order — the user
  3962. who's curating inventory weights gets the lower-slot pick instead
  3963. of the lower-remaining pick;
  3964. - even when set, it's the *printer's* counter, not Bambuddy's
  3965. ``label_weight - weight_used`` (internal mode) or Spoolman's
  3966. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  3967. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  3968. When the user has bound a spool to a slot, their own inventory
  3969. tracking is authoritative; this helper surfaces that value so the
  3970. sort can prefer it. Slots without a binding are absent from the
  3971. returned map — the caller then falls back to MQTT ``remain`` for
  3972. those, preserving the pre-#1508 behaviour for un-tracked spools.
  3973. Returns an empty map on any failure (no inventory bindings, DB
  3974. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  3975. is a preference, not a guarantee.
  3976. """
  3977. if not loaded:
  3978. return {}
  3979. # External / virtual-tray slots are tracked separately from AMS — skip
  3980. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  3981. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  3982. # match is fiddly and out of scope for this fix).
  3983. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  3984. if not tracked_slots:
  3985. return {}
  3986. is_spoolman = await self._is_spoolman_mode(db)
  3987. overrides: dict[int, float] = {}
  3988. if is_spoolman:
  3989. result = await db.execute(
  3990. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3991. )
  3992. assignments = list(result.scalars().all())
  3993. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  3994. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  3995. for ams_id, tray_id, gtid in tracked_slots:
  3996. spoolman_id = by_slot.get((ams_id, tray_id))
  3997. if spoolman_id is None:
  3998. continue
  3999. grams = await _spoolman_remaining_grams(spoolman_id)
  4000. if grams is not None:
  4001. overrides[gtid] = grams
  4002. return overrides
  4003. # Internal inventory mode (default). selectinload matches the pattern
  4004. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4005. # plus an eager-loaded relationship rather than an explicit join, so
  4006. # the row-attribute shape is exactly what those routes already rely on.
  4007. result = await db.execute(
  4008. select(SpoolAssignment)
  4009. .options(selectinload(SpoolAssignment.spool))
  4010. .where(SpoolAssignment.printer_id == printer_id)
  4011. )
  4012. assignments = list(result.scalars().all())
  4013. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4014. for ams_id, tray_id, gtid in tracked_slots:
  4015. spool = by_slot.get((ams_id, tray_id))
  4016. if spool is None:
  4017. continue
  4018. label = float(spool.label_weight or 0)
  4019. used = float(spool.weight_used or 0)
  4020. overrides[gtid] = max(0.0, label - used)
  4021. return overrides
  4022. @staticmethod
  4023. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4024. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4025. here to avoid making this module import-dependent on that private
  4026. helper's signature."""
  4027. try:
  4028. from backend.app.api.routes.settings import get_setting
  4029. v = await get_setting(db, "spoolman_enabled")
  4030. return bool(v) and v.lower() == "true"
  4031. except Exception:
  4032. return False
  4033. @staticmethod
  4034. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4035. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4036. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4037. so a tied sort produces the same physical-position order the pre-#1508
  4038. stable sort did (preserves the regression-free baseline):
  4039. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4040. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4041. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4042. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4043. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4044. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4045. """
  4046. if ams_id is None or ams_id < 0:
  4047. return 10_000
  4048. if ams_id >= 128:
  4049. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4050. return ams_id * 4 + (tray_id or 0)
  4051. @staticmethod
  4052. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4053. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4054. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4055. non-tracked spools (the user has told us they care about these
  4056. specifically), then ascending by remaining within each tier, then
  4057. ascending by AMS slot position as the deterministic tie-breaker.
  4058. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4059. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4060. because the tier flag dominates — which is what lets us mix grams
  4061. (inventory) and percent (MQTT) without a unit conversion.
  4062. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4063. spools the printer DOES know something about sort ahead of those
  4064. it knows nothing about — preserves pre-#1508 behaviour for the
  4065. no-inventory-binding case.
  4066. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4067. external on ties, matching the legacy emission-order stable sort.
  4068. """
  4069. gtid = f.get("global_tray_id")
  4070. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4071. if overrides and gtid in overrides:
  4072. return (0, overrides[gtid], slot_order)
  4073. remain = f.get("remain", -1)
  4074. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4075. def _match_filaments_to_slots(
  4076. self,
  4077. required: list[dict],
  4078. loaded: list[dict],
  4079. prefer_lowest: bool = False,
  4080. inventory_remain_overrides: dict[int, float] | None = None,
  4081. fts_installed: bool = False,
  4082. ) -> list[int] | None:
  4083. """Match required filaments to loaded filaments and build AMS mapping.
  4084. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4085. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4086. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4087. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4088. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4089. matching among those trays.
  4090. Args:
  4091. required: List of required filaments with slot_id, type, color, tray_info_idx
  4092. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4093. Returns:
  4094. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4095. """
  4096. if not required:
  4097. return None
  4098. # Track used trays to avoid duplicate assignment
  4099. used_tray_ids: set[int] = set()
  4100. comparisons = []
  4101. for req in required:
  4102. req_type = (req.get("type") or "").upper()
  4103. req_color = req.get("color", "")
  4104. req_tray_info_idx = req.get("tray_info_idx", "")
  4105. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4106. idx_match = None
  4107. exact_match = None
  4108. similar_match = None
  4109. similar_distance = float("inf")
  4110. type_only_match = None
  4111. # Get available trays (not already used)
  4112. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4113. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4114. # Hard filter — cross-nozzle assignment causes print failures
  4115. # ("position of left hotend is abnormal"), so never fall back.
  4116. # Skipped when an FTS is installed: it routes any AMS slot to either
  4117. # extruder, so restricting to one nozzle would wrongly exclude the
  4118. # correct spool sitting in the other nozzle's AMS (#2186).
  4119. req_nozzle_id = req.get("nozzle_id")
  4120. if req_nozzle_id is not None and not fts_installed:
  4121. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4122. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4123. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4124. # _prefer_lowest_sort_key for the full rationale.
  4125. if prefer_lowest:
  4126. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4127. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4128. # One line per filament req so a bug report can be diagnosed
  4129. # without enabling debug logging: shows what the matcher saw
  4130. # (req shape + sorted candidate trays with their remain values
  4131. # and any inventory override that was applied). Mirrored by
  4132. # the picked-match log at the bottom of the loop.
  4133. logger.info(
  4134. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4135. req.get("slot_id"),
  4136. req_type,
  4137. req_color,
  4138. req_tray_info_idx,
  4139. req_nozzle_id,
  4140. [
  4141. {
  4142. "gtid": f.get("global_tray_id"),
  4143. "type": f.get("type"),
  4144. "color": f.get("color"),
  4145. "tii": f.get("tray_info_idx"),
  4146. "remain": f.get("remain"),
  4147. "inv_g": (
  4148. inventory_remain_overrides.get(f.get("global_tray_id"))
  4149. if inventory_remain_overrides
  4150. else None
  4151. ),
  4152. }
  4153. for f in available
  4154. ],
  4155. )
  4156. # Check if tray_info_idx is unique among available trays
  4157. if req_tray_info_idx:
  4158. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4159. if len(idx_matches) == 1:
  4160. # Unique tray_info_idx - use it as definitive match
  4161. idx_match = idx_matches[0]
  4162. logger.debug(
  4163. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4164. f"-> tray {idx_match['global_tray_id']}"
  4165. )
  4166. elif len(idx_matches) > 1:
  4167. # Multiple trays with same tray_info_idx - use color matching among them
  4168. logger.debug(
  4169. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4170. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4171. )
  4172. if prefer_lowest:
  4173. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4174. # Use color matching within this subset
  4175. for f in idx_matches:
  4176. f_color = f.get("color", "")
  4177. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4178. if not exact_match:
  4179. exact_match = f
  4180. elif self._colors_are_similar(f_color, req_color):
  4181. distance = self._color_distance(f_color, req_color)
  4182. if distance is not None and distance < similar_distance:
  4183. similar_match = f
  4184. similar_distance = distance
  4185. elif not type_only_match:
  4186. type_only_match = f
  4187. # If no idx_match yet, do standard type/color matching on all available trays
  4188. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4189. for f in available:
  4190. f_type = (f.get("type") or "").upper()
  4191. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4192. continue
  4193. # Type matches - check color
  4194. f_color = f.get("color", "")
  4195. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4196. if not exact_match:
  4197. exact_match = f
  4198. elif self._colors_are_similar(f_color, req_color):
  4199. # Nearest wins, not first-in-tray-order. `available` is
  4200. # already in the caller's order (slot order, or the
  4201. # prefer-lowest sort), and `<` keeps the earliest of
  4202. # equally close spools — so that order survives as the
  4203. # tie-break (#2804).
  4204. distance = self._color_distance(f_color, req_color)
  4205. if distance is not None and distance < similar_distance:
  4206. similar_match = f
  4207. similar_distance = distance
  4208. elif not type_only_match:
  4209. type_only_match = f
  4210. match = idx_match or exact_match or similar_match or type_only_match
  4211. if match:
  4212. used_tray_ids.add(match["global_tray_id"])
  4213. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4214. else:
  4215. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4216. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4217. # "Why did it pick that spool" is the question every wrong-filament
  4218. # report starts with, and a `similar_color` win is now a ranked
  4219. # choice among several eligible spools rather than whichever tray
  4220. # came first, so it is worth being able to see after the fact.
  4221. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4222. # is on (#1766).
  4223. if match:
  4224. bucket = (
  4225. "idx"
  4226. if idx_match is not None
  4227. else "exact_color"
  4228. if exact_match is not None
  4229. else "similar_color"
  4230. if similar_match is not None
  4231. else "type_only"
  4232. )
  4233. logger.info(
  4234. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4235. match["global_tray_id"],
  4236. bucket,
  4237. req.get("slot_id"),
  4238. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4239. )
  4240. else:
  4241. logger.info(
  4242. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4243. req.get("slot_id"),
  4244. req_type,
  4245. req_color,
  4246. req_tray_info_idx,
  4247. )
  4248. # Build mapping array
  4249. if not comparisons:
  4250. return None
  4251. max_slot_id = max(c["slot_id"] for c in comparisons)
  4252. if max_slot_id <= 0:
  4253. return None
  4254. mapping = [-1] * max_slot_id
  4255. for c in comparisons:
  4256. slot_id = c["slot_id"]
  4257. if slot_id and slot_id > 0:
  4258. mapping[slot_id - 1] = c["global_tray_id"]
  4259. return mapping
  4260. def _mark_printer_dispatched(
  4261. self,
  4262. printer_id: int,
  4263. pre_state: str | None,
  4264. pre_subtask_id: str | None,
  4265. ) -> None:
  4266. """Record that a print command was just sent to ``printer_id``.
  4267. Held until either the watchdog observes a state/subtask transition
  4268. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4269. """
  4270. if not pre_state:
  4271. # No pre_state means we can't detect a transition — fall back to a
  4272. # pure time-based hold using empty string as a sentinel that won't
  4273. # match any real printer state.
  4274. pre_state = ""
  4275. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4276. def _release_dispatch_hold(self, printer_id: int) -> None:
  4277. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4278. self._dispatch_holds.pop(printer_id, None)
  4279. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4280. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4281. Returns False (and clears the hold) once any of these are true:
  4282. - hard timeout (``_dispatch_max_hold``) has elapsed
  4283. - the printer has transitioned out of pre_state and we're past the
  4284. minimum cooldown
  4285. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4286. past the minimum cooldown
  4287. Otherwise the printer is held — caller should treat it as busy.
  4288. """
  4289. entry = self._dispatch_holds.get(printer_id)
  4290. if not entry:
  4291. return False
  4292. started_at, pre_state, pre_subtask_id = entry
  4293. elapsed = time.monotonic() - started_at
  4294. if elapsed >= self._dispatch_max_hold:
  4295. self._dispatch_holds.pop(printer_id, None)
  4296. return False
  4297. # Without a pre_state we can't detect a transition — fall back to the
  4298. # min cooldown alone, then drop the hold.
  4299. if not pre_state:
  4300. if elapsed >= self._dispatch_min_cooldown:
  4301. self._dispatch_holds.pop(printer_id, None)
  4302. return False
  4303. return True
  4304. status = printer_manager.get_status(printer_id)
  4305. current_state = getattr(status, "state", None) if status else None
  4306. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4307. transitioned = (current_state is not None and current_state != pre_state) or (
  4308. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4309. )
  4310. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4311. self._dispatch_holds.pop(printer_id, None)
  4312. return False
  4313. return True
  4314. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4315. """Check if a printer is connected and idle."""
  4316. if not printer_manager.is_connected(printer_id):
  4317. logger.debug("Printer %d: not connected", printer_id)
  4318. return False
  4319. state = printer_manager.get_status(printer_id)
  4320. if not state:
  4321. logger.debug("Printer %d: no status available", printer_id)
  4322. return False
  4323. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4324. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4325. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4326. # printer, it boots back into IDLE with no memory of the previous finish; without
  4327. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4328. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4329. logger.debug(
  4330. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4331. printer_id,
  4332. state.state,
  4333. )
  4334. return False
  4335. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4336. if not idle:
  4337. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4338. return idle
  4339. @staticmethod
  4340. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4341. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4342. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4343. and that the fixed-printer branch has already found connected, so the two
  4344. offline cases answer at their own exits and never arrive here.
  4345. The default is the model-based branch's ``Busy:`` wording, which
  4346. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4347. the right answer for the connected-but-no-telemetry second or two after a
  4348. reconnect: the model-based branch has always reported it that way, and it
  4349. is not something to wake anybody up for.
  4350. A plate nobody has confirmed is the one case here that does not resolve
  4351. itself — somebody has to walk over to the printer — so it is worded as
  4352. itself and allowed to notify.
  4353. """
  4354. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4355. return f"Waiting for plate confirmation: {printer_name}"
  4356. return f"Busy: {printer_name}"
  4357. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4358. """Read a setting value from the database."""
  4359. result = await db.execute(select(Settings).where(Settings.key == key))
  4360. setting = result.scalar_one_or_none()
  4361. return setting.value if setting else None
  4362. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4363. """Read a boolean setting from the database."""
  4364. result = await db.execute(select(Settings).where(Settings.key == key))
  4365. setting = result.scalar_one_or_none()
  4366. if setting:
  4367. return setting.value.lower() == "true"
  4368. return default
  4369. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4370. """Read an int setting; falls back to default on missing/unparseable rows."""
  4371. result = await db.execute(select(Settings).where(Settings.key == key))
  4372. setting = result.scalar_one_or_none()
  4373. if setting and setting.value:
  4374. try:
  4375. return int(setting.value)
  4376. except ValueError:
  4377. pass
  4378. return default
  4379. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4380. """Get drying presets (user-configured or built-in defaults)."""
  4381. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4382. setting = result.scalar_one_or_none()
  4383. if setting and setting.value:
  4384. try:
  4385. presets = json.loads(setting.value)
  4386. if isinstance(presets, dict) and presets:
  4387. return presets
  4388. except json.JSONDecodeError:
  4389. pass
  4390. return self.DEFAULT_DRYING_PRESETS
  4391. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4392. """Per-filament humidity thresholds (#1605).
  4393. Returns the user-configured overrides map keyed by normalized filament
  4394. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4395. unknown / unmapped types. Empty / unset → empty dict, in which case
  4396. callers fall back to ``ams_humidity_fair``.
  4397. """
  4398. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4399. setting = result.scalar_one_or_none()
  4400. if not setting or not setting.value:
  4401. return {}
  4402. try:
  4403. data = json.loads(setting.value)
  4404. except json.JSONDecodeError:
  4405. return {}
  4406. if not isinstance(data, dict):
  4407. return {}
  4408. out: dict[str, int] = {}
  4409. for key, value in data.items():
  4410. try:
  4411. out[str(key).upper() if key != "default" else "default"] = int(value)
  4412. except (TypeError, ValueError):
  4413. continue
  4414. return out
  4415. # Materials whose AMS spelling differs from the key the tables above use.
  4416. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4417. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4418. # good PA row (#3067).
  4419. #
  4420. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4421. # The drying popover has resolved these correctly since #2774 and the
  4422. # scheduler never did, which is exactly why #3067's reporter could dry a
  4423. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4424. #
  4425. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4426. # of nylon, so it is the one entry that is a judgement rather than a
  4427. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4428. # way, and PA's row is the hottest the table has. Drying it there is closer
  4429. # to right than not drying it at all, which is what it got before.
  4430. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4431. "NYLON": "PA",
  4432. "PA6": "PA",
  4433. "PA11": "PA",
  4434. "PA12": "PA",
  4435. "PAHT": "PA",
  4436. "PPA": "PA",
  4437. }
  4438. @classmethod
  4439. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4440. """The key in *table* that answers for this tray's material, or None.
  4441. The printer reports the material in ``tray_type``, and it spells filled
  4442. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4443. tables here are keyed by base material, so matching the raw string alone
  4444. found a row for 8 of the 41 types a printer can report and skipped the
  4445. rest -- silently, because every caller reads "no row" as "nothing to do
  4446. for this tray". Auto-drying therefore ignored every composite spool on
  4447. the install (#3067).
  4448. Exact match first, so a table the user has extended with a row of its
  4449. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4450. base material's. Then the suffix is dropped, then the alias map above
  4451. answers for the polyamide spellings.
  4452. Returns None rather than a default: what to do with an unrecognised
  4453. material differs per caller, and only the caller knows whether "no row"
  4454. means skip the tray or fall back to a catch-all. Nothing here invents a
  4455. temperature for a material the table does not list.
  4456. """
  4457. raw = cls._normalize_filament_type(tray_type or "")
  4458. if not raw:
  4459. return None
  4460. for candidate in (raw, raw.split("-")[0]):
  4461. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4462. if key in table:
  4463. return key
  4464. return None
  4465. @staticmethod
  4466. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4467. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4468. For mixed filament types loaded into one AMS, returns the most
  4469. restrictive (lowest) threshold across all loaded tray types — matches
  4470. the conservative-params strategy already used for drying temp/hours.
  4471. Empty / unloaded trays contribute no constraint. Unknown types use the
  4472. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4473. when no per-type map is configured at all.
  4474. """
  4475. default = thresholds.get("default", fallback)
  4476. if not thresholds:
  4477. return fallback
  4478. candidates: list[int] = []
  4479. for tray in trays:
  4480. tray_type = str(tray.get("tray_type") or "").strip()
  4481. if not tray_type:
  4482. continue
  4483. # A composite carries its base material's threshold when it has no
  4484. # row of its own, the same way it takes its drying preset (#3067).
  4485. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4486. candidates.append(thresholds[key] if key is not None else default)
  4487. if not candidates:
  4488. return default
  4489. return min(candidates)
  4490. def _get_conservative_drying_params(
  4491. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4492. ) -> tuple[int, int, str] | None:
  4493. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4494. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4495. """
  4496. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4497. hours_key = f"{temp_key}_hours"
  4498. min_temp = None
  4499. max_hours = None
  4500. filament_type = ""
  4501. for tray in trays:
  4502. tray_type = tray.get("tray_type", "")
  4503. if not tray_type:
  4504. continue
  4505. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4506. # which is what stopped auto-drying on every composite spool (#3067).
  4507. base_type = self._resolve_filament_key(tray_type, presets)
  4508. if base_type is None:
  4509. continue
  4510. # The table is user-editable JSON with no per-row validation, so a
  4511. # row can be present and empty. That has always meant "skip this
  4512. # material", and it has to keep meaning it: the reads below fall
  4513. # back to 55C/12h per missing field, which is a temperature nobody
  4514. # chose and would deform a PLA spool.
  4515. preset = presets[base_type]
  4516. if not preset:
  4517. continue
  4518. temp = preset.get(temp_key, 55)
  4519. hours = preset.get(hours_key, 12)
  4520. # Conservative: lowest temp, longest duration
  4521. if min_temp is None or temp < min_temp:
  4522. min_temp = temp
  4523. if max_hours is None or hours > max_hours:
  4524. max_hours = hours
  4525. if not filament_type:
  4526. filament_type = base_type
  4527. if min_temp is None:
  4528. return None
  4529. return (min_temp, max_hours or 12, filament_type)
  4530. async def _check_filament_low(self, db: AsyncSession) -> None:
  4531. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4532. ``on_filament_low`` has had a column, a schema field, a route, a template
  4533. and a UI toggle since the notification system was built, and no caller --
  4534. so the toggle could be switched on and could never fire. This is the
  4535. producer.
  4536. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4537. ``low_stock_threshold_pct`` override is already exactly this decision:
  4538. already configurable, already surfaced, already driving the Inventory
  4539. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4540. consulted -- it has been measured up to 56 points out against a scale,
  4541. which is not a number to page someone on.
  4542. Only slots with an assigned spool produce an event. A slot Bambuddy
  4543. cannot resolve to a spool has no remaining weight it can stand behind,
  4544. and guessing one is how the remain percentage would have got in.
  4545. """
  4546. from backend.app.models.spool import Spool
  4547. # Time-gated rather than run on every pass. run() sleeps
  4548. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4549. # early-return path counts as productive while an upload is in flight
  4550. # (#2602), so an unthrottled check would re-read the whole spool
  4551. # collection every 3 seconds for the length of a batch drain. In
  4552. # Spoolman mode that is a request storm against a third-party service,
  4553. # which is the thing this producer's design note argues against; and
  4554. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4555. # check_queue holding the scheduler's session, so the outage would
  4556. # throttle the print queue itself. A low spool is not a 3-second
  4557. # concern -- the idle interval is the natural resolution.
  4558. now = time.monotonic()
  4559. if now < self._filament_low_next_check:
  4560. return
  4561. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4562. try:
  4563. # on_filament_low defaults to off on every provider, so on most
  4564. # installs nobody wants this alert. Without this the check would
  4565. # still read every assigned spool each interval -- the whole
  4566. # collection over HTTP in Spoolman mode -- for an event that is
  4567. # switched off. One query against the provider table settles it
  4568. # before any spool work, the same guard the bed-cooled waiter uses.
  4569. # No printer_id: this asks whether any provider wants the event at
  4570. # all; per-printer scoping is applied when the event is sent.
  4571. #
  4572. # While nobody wants it, no pass sees a slot go back above its
  4573. # threshold, so nothing can re-arm; a spool refilled under the same
  4574. # id in that time would stay silenced until a restart. Forgetting
  4575. # what was sent is right anyway: whoever switches the event back on
  4576. # is told about the spools that are low now.
  4577. #
  4578. # The MQTT relay publishes the same event, so a connected relay is
  4579. # reason enough to run the check. Its record is forgotten when the
  4580. # relay is switched off, not when the broker drops: a reconnect must
  4581. # not re-send every low slot.
  4582. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low"))
  4583. relay = mqtt_relay.enabled and mqtt_relay.connected
  4584. if not notify:
  4585. self._notified_filament_low.clear()
  4586. if not mqtt_relay.enabled:
  4587. self._relayed_filament_low.clear()
  4588. if not notify and not relay:
  4589. return
  4590. global_threshold = await self._get_low_stock_threshold(db)
  4591. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4592. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4593. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4594. if spoolman_on:
  4595. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4596. else:
  4597. rows = (
  4598. await db.execute(
  4599. select(SpoolAssignment, Spool)
  4600. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4601. # An archived spool is not stock. The Inventory page's
  4602. # Low Stock count skips them (InventoryPage.tsx:1089)
  4603. # and get_all_spools without allow_archived already
  4604. # excludes them in Spoolman mode, so without this the
  4605. # internal path is the only one that alerts on them.
  4606. .where(Spool.archived_at.is_(None))
  4607. )
  4608. ).all()
  4609. for assignment, spool in rows:
  4610. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4611. if pct is None:
  4612. continue
  4613. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4614. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4615. pct,
  4616. threshold,
  4617. spool.color_name,
  4618. )
  4619. if not slots:
  4620. # Nothing resolvable this pass. Deliberately not clearing the
  4621. # notified set: a Spoolman that is briefly unreachable would
  4622. # otherwise re-alert on every spool as soon as it came back.
  4623. return
  4624. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4625. except Exception as e:
  4626. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4627. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4628. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4629. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4630. if raw is None or raw.value is None:
  4631. return 20.0
  4632. try:
  4633. value = float(raw.value)
  4634. except (TypeError, ValueError):
  4635. return 20.0
  4636. return value if 0 < value <= 100 else 20.0
  4637. async def _filament_low_slots_spoolman(
  4638. self, db: AsyncSession, global_threshold: float
  4639. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4640. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4641. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4642. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4643. so the global threshold is the only one that applies here. That matches
  4644. what the Inventory page already does in this mode.
  4645. One ``get_all_spools`` call covers every slot rather than a request per
  4646. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4647. without ``allow_archived`` -- which is the behaviour the internal path
  4648. has to ask for explicitly.
  4649. An unreachable Spoolman returns no slots rather than raising. It is an
  4650. ordinary state for a third-party service, not an error in this pass: the
  4651. caller's "nothing resolvable" branch already leaves the notified set
  4652. alone, which is exactly right here, whereas letting it reach the broad
  4653. ``except`` would write a full traceback every time the check runs.
  4654. """
  4655. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4656. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4657. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4658. if not assignments:
  4659. return {}
  4660. client = await get_spoolman_client()
  4661. if client is None:
  4662. return {}
  4663. try:
  4664. all_spools = await client.get_all_spools()
  4665. except SpoolmanUnavailableError as e:
  4666. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4667. return {}
  4668. by_id: dict[int, dict] = {}
  4669. for raw in all_spools:
  4670. raw_id = raw.get("id")
  4671. if isinstance(raw_id, int):
  4672. by_id[raw_id] = raw
  4673. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4674. for assignment in assignments:
  4675. raw = by_id.get(assignment.spoolman_spool_id)
  4676. if raw is None:
  4677. continue
  4678. try:
  4679. mapped = _map_spoolman_spool(raw)
  4680. except ValueError:
  4681. continue
  4682. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4683. if pct is None:
  4684. continue
  4685. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4686. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4687. return slots
  4688. async def _emit_filament_low(
  4689. self,
  4690. db: AsyncSession,
  4691. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4692. *,
  4693. notify: bool = True,
  4694. relay: bool = False,
  4695. ) -> None:
  4696. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4697. printers: dict[int, Printer] = {}
  4698. for key, (pct, threshold, color) in slots.items():
  4699. printer_id, ams_id, tray_id, spool_id = key
  4700. if pct >= threshold:
  4701. # Back above the line: re-arm rather than expire on a timer, so a
  4702. # refilled slot can alert again and a spool sitting just under the
  4703. # threshold stays quiet.
  4704. self._notified_filament_low.discard(key)
  4705. self._relayed_filament_low.discard(key)
  4706. continue
  4707. send_notification = notify and key not in self._notified_filament_low
  4708. # Only while connected, so a crossing the relay missed reaches it
  4709. # after the reconnect.
  4710. send_relay = relay and key not in self._relayed_filament_low
  4711. if not send_notification and not send_relay:
  4712. continue
  4713. # Marked before sending, which is a choice rather than the only
  4714. # option, and it is the opposite failure mode from the one the
  4715. # debounce argues against: one transient provider failure loses this
  4716. # alert until the spool goes back above the threshold and crosses it
  4717. # again. Marking after a successful send would trade that for
  4718. # re-alerting on every pass while a provider is down -- which is the
  4719. # repetition the whole debounce exists to prevent, and the louder of
  4720. # the two failures. A spool that is low stays low, so the next real
  4721. # signal is not far away; a provider stuck retrying is a signal that
  4722. # never stops.
  4723. if send_notification:
  4724. self._notified_filament_low.add(key)
  4725. if send_relay:
  4726. self._relayed_filament_low.add(key)
  4727. if printer_id not in printers:
  4728. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4729. if printer is None:
  4730. continue
  4731. printers[printer_id] = printer
  4732. printer = printers[printer_id]
  4733. slot = _ams_slot_label(ams_id, tray_id)
  4734. if send_notification:
  4735. try:
  4736. await notification_service.on_filament_low(
  4737. printer_id,
  4738. printer.name,
  4739. slot,
  4740. int(pct),
  4741. db,
  4742. color=color,
  4743. )
  4744. except Exception as e:
  4745. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4746. if send_relay:
  4747. try:
  4748. await mqtt_relay.on_filament_low(
  4749. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  4750. )
  4751. except Exception as e:
  4752. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  4753. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4754. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4755. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4756. a schema field, a template and a UI toggle, and nothing that computes the
  4757. condition -- the Forecast panel does it in the browser, so with no page
  4758. open nothing could ever alert. This runs the same arithmetic
  4759. (``stock_forecast``) from the scheduler loop.
  4760. An alert is sent when a SKU *moves into* a condition, once, and again
  4761. after the condition has cleared. A SKU that worsens from reorder to break
  4762. alerts again as a break, because the panel treats the two as exclusive; one
  4763. that eases from break back to reorder does not alert again.
  4764. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4765. while it is still low tells you.
  4766. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4767. loop runs every 3 s while an upload is in flight, and the whole spool
  4768. collection is read over HTTP in Spoolman mode. Both events default to off
  4769. on every provider, so nothing is read unless a provider wants one.
  4770. """
  4771. now = time.monotonic()
  4772. if now < self._stock_forecast_next_check:
  4773. return
  4774. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4775. try:
  4776. if self._stock_alerts_persisted is None:
  4777. await self._load_stock_alerts(db)
  4778. wanted = {
  4779. "reorder": bool(await notification_service._get_providers_for_event(db, "on_stock_reorder_alert")),
  4780. "break": bool(await notification_service._get_providers_for_event(db, "on_stock_break_alert")),
  4781. }
  4782. if not any(wanted.values()):
  4783. # Nobody wants either event. Forget what was sent, so whoever
  4784. # switches one on is told about the SKUs that are low now.
  4785. self._notified_stock_alerts.clear()
  4786. await self._save_stock_alerts(db)
  4787. return
  4788. forecasts = await self._stock_forecasts(db)
  4789. if forecasts is None:
  4790. # Spoolman unreachable. Deliberately not clearing the notified
  4791. # set: a brief outage would otherwise re-alert every SKU when it
  4792. # came back.
  4793. return
  4794. await self._emit_stock_alerts(db, forecasts, wanted)
  4795. await self._save_stock_alerts(db)
  4796. except Exception as e:
  4797. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4798. def _serialize_stock_alerts(self) -> str:
  4799. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4800. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4801. return json.dumps(rows)
  4802. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4803. """Read the notified set saved by the last run, once per process.
  4804. A missing or unreadable row is an empty set: the worst that does is one
  4805. repeat of what a restart used to cause every time.
  4806. """
  4807. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4808. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4809. if raw and raw.value:
  4810. try:
  4811. for key, kind, events in json.loads(raw.value):
  4812. if len(key) == 4 and kind in ("reorder", "break"):
  4813. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4814. except (ValueError, TypeError):
  4815. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4816. loaded = {}
  4817. self._notified_stock_alerts = loaded
  4818. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4819. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4820. """Write the notified set to its settings row if it changed since it was last read or written."""
  4821. serialized = self._serialize_stock_alerts()
  4822. if serialized == self._stock_alerts_persisted:
  4823. return
  4824. from backend.app.core.db_dialect import upsert_setting
  4825. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4826. await db.commit()
  4827. self._stock_alerts_persisted = serialized
  4828. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4829. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4830. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4831. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4832. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4833. sku_settings = {
  4834. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4835. lead_time_days=row.lead_time_days,
  4836. safety_margin_value=row.safety_margin_value,
  4837. safety_margin_unit=row.safety_margin_unit,
  4838. alerts_snoozed=bool(row.alerts_snoozed),
  4839. )
  4840. for row in sku_rows
  4841. }
  4842. if await self._get_bool_setting(db, "spoolman_enabled"):
  4843. spools = await self._stock_spools_spoolman()
  4844. if spools is None:
  4845. return None
  4846. # Spoolman owns the usage in this mode and Bambuddy's own history
  4847. # table holds nothing for those spools, so the rate is always the
  4848. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4849. # are local spool ids, and a Spoolman id that happens to match one
  4850. # (left over from before Spoolman was switched on) would borrow an
  4851. # unrelated spool's history.
  4852. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4853. else:
  4854. spools = await self._stock_spools_internal(db)
  4855. history = await self._stock_usage_history(db)
  4856. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4857. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4858. from backend.app.models.spool import Spool
  4859. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4860. return [
  4861. stock_forecast.StockSpool(
  4862. id=spool.id,
  4863. material=spool.material,
  4864. subtype=spool.subtype,
  4865. brand=spool.brand,
  4866. color_name=spool.color_name,
  4867. label_weight=float(spool.label_weight or 0),
  4868. weight_used=float(spool.weight_used or 0),
  4869. weight_used_baseline=float(spool.weight_used_baseline or 0),
  4870. created_at=spool.created_at,
  4871. )
  4872. for spool in rows
  4873. ]
  4874. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  4875. from backend.app.models.spool_usage_history import SpoolUsageHistory
  4876. rows = (
  4877. await db.execute(
  4878. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  4879. .order_by(SpoolUsageHistory.created_at.desc())
  4880. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  4881. )
  4882. ).all()
  4883. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4884. for spool_id, created_at, weight_used in rows:
  4885. if created_at is None:
  4886. continue
  4887. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  4888. return history
  4889. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  4890. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  4891. ``get_all_spools`` leaves archived spools out unless asked, which is the
  4892. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  4893. is the same mapping the Inventory page (and so the panel) reads.
  4894. """
  4895. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4896. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4897. client = await get_spoolman_client()
  4898. if client is None:
  4899. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  4900. return None
  4901. try:
  4902. raw_spools = await client.get_all_spools()
  4903. except SpoolmanUnavailableError as e:
  4904. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  4905. return None
  4906. spools: list[stock_forecast.StockSpool] = []
  4907. for raw in raw_spools:
  4908. try:
  4909. mapped = _map_spoolman_spool(raw)
  4910. except ValueError:
  4911. continue
  4912. created_at = None
  4913. if mapped.get("created_at"):
  4914. try:
  4915. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  4916. except ValueError:
  4917. created_at = None
  4918. spools.append(
  4919. stock_forecast.StockSpool(
  4920. id=mapped["id"],
  4921. material=mapped["material"],
  4922. subtype=mapped.get("subtype"),
  4923. brand=mapped.get("brand"),
  4924. color_name=mapped.get("color_name"),
  4925. label_weight=float(mapped.get("label_weight") or 0),
  4926. weight_used=float(mapped.get("weight_used") or 0),
  4927. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  4928. created_at=created_at,
  4929. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  4930. )
  4931. )
  4932. return spools
  4933. async def _emit_stock_alerts(
  4934. self,
  4935. db: AsyncSession,
  4936. forecasts: stock_forecast.ForecastMap,
  4937. wanted: dict[str, bool],
  4938. ) -> None:
  4939. """Send the notifications for each SKU that has moved into a stock alert condition.
  4940. A SKU in break has also reached its reorder point, so both events apply to
  4941. it: the break event goes to providers that have it on, and the reorder event
  4942. to the providers that have only that one on. A provider with both on gets the
  4943. break and no second message.
  4944. What is remembered per SKU is the condition and which events had a
  4945. subscriber when it was sent. An event with no subscriber is forgotten, so
  4946. switching it on later reports the SKUs already in that condition.
  4947. """
  4948. active_events = {event for event, on in wanted.items() if on}
  4949. for key, (forecast, spool) in forecasts.items():
  4950. kind: str | None = None
  4951. if not forecast.snoozed:
  4952. if forecast.stock_break_alert:
  4953. kind = "break"
  4954. elif forecast.reorder_alert:
  4955. kind = "reorder"
  4956. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  4957. events = applicable & active_events
  4958. if not events:
  4959. self._notified_stock_alerts.pop(key, None)
  4960. continue
  4961. previous = self._notified_stock_alerts.get(key)
  4962. told = (previous[1] & active_events) if previous else frozenset()
  4963. # Trimmed to the events this condition can send. That is what makes easing from
  4964. # break back to reorder silent (the reorder event was told with the break) and
  4965. # worsening again news again (the break event is no longer remembered).
  4966. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  4967. # Recorded before sending, for the reason _emit_filament_low gives: a
  4968. # provider that is down should lose this alert, not repeat it every hour.
  4969. to_send = events - told
  4970. # Both flags imply a positive rate and so a day count.
  4971. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  4972. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  4973. color = None if spool.color_name_is_synthesized else spool.color_name
  4974. try:
  4975. if "break" in to_send:
  4976. await notification_service.on_stock_break_alert(
  4977. spool.material,
  4978. spool.brand,
  4979. forecast.remaining_g,
  4980. rate,
  4981. days_left,
  4982. forecast.effective_lead_time_days,
  4983. db,
  4984. subtype=spool.subtype,
  4985. color=color,
  4986. )
  4987. if "reorder" in to_send:
  4988. await notification_service.on_stock_reorder_alert(
  4989. spool.material,
  4990. spool.brand,
  4991. forecast.remaining_g,
  4992. rate,
  4993. days_left,
  4994. db,
  4995. subtype=spool.subtype,
  4996. color=color,
  4997. skip_break_subscribers=kind == "break",
  4998. )
  4999. except Exception as e:
  5000. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5001. # A SKU with no spools left is no longer alerting.
  5002. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5003. del self._notified_stock_alerts[key]
  5004. async def _check_auto_drying(
  5005. self,
  5006. db: AsyncSession,
  5007. queue_items: list[PrintQueueItem],
  5008. dispatching_printers: set[int],
  5009. ):
  5010. """Start drying on idle printers based on humidity.
  5011. Three modes (can all be enabled independently):
  5012. - queue_drying_enabled: Dry between scheduled queue prints
  5013. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5014. - print_drying_enabled: Also evaluate printers that are currently printing,
  5015. when model+firmware supports "Print While Drying" (gated by
  5016. supports_drying_while_printing). Drying temperature is capped at
  5017. max(40, preset_temp - 5) to protect spools mid-print.
  5018. """
  5019. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5020. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5021. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5022. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5023. # The wait belongs to ambient drying: the settings UI only shows it while
  5024. # ambient drying is on, so a value left behind when ambient is turned off
  5025. # must not keep delaying the one path that still reaches the wait gate
  5026. # without it (a mid-print start under print_drying).
  5027. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5028. # Clear every streak as soon as the wait is inactive. An early return (or
  5029. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5030. # a quick toggle-on inherit an old streak.
  5031. if not sustained_wait_active:
  5032. self._auto_dry_above.clear()
  5033. if not queue_drying_enabled and not ambient_drying_enabled:
  5034. # Stop active drying on all printers if both features disabled
  5035. if self._drying_in_progress:
  5036. for pid in list(self._drying_in_progress):
  5037. if pid in self._scheduled_drying_printer_ids:
  5038. continue
  5039. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5040. await self._stop_drying(pid)
  5041. return
  5042. # Update drying state from printer status (handles backend restart)
  5043. self._sync_drying_state()
  5044. # Find printers with scheduled items (for queue drying mode)
  5045. printers_with_scheduled: set[int] = set()
  5046. printers_with_items: set[int] = set()
  5047. for item in queue_items:
  5048. if item.printer_id:
  5049. printers_with_items.add(item.printer_id)
  5050. if item.scheduled_time and not item.manual_start:
  5051. printers_with_scheduled.add(item.printer_id)
  5052. # If only queue mode is on and no printers have scheduled items, stop drying
  5053. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5054. # may still be eligible for mid-print drying regardless of queue state).
  5055. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5056. for pid in list(self._drying_in_progress):
  5057. if pid in self._scheduled_drying_printer_ids:
  5058. continue
  5059. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5060. await self._stop_drying(pid)
  5061. return
  5062. # Get humidity threshold (global fallback)
  5063. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5064. setting = result.scalar_one_or_none()
  5065. global_humidity_threshold = int(setting.value) if setting else 60
  5066. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5067. # to the global threshold for every AMS unit.
  5068. per_type_thresholds = await self._get_humidity_thresholds(db)
  5069. # Get drying presets
  5070. presets = await self._get_drying_presets(db)
  5071. # Determine if drying should be skipped for printers with pending items
  5072. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5073. # Get all active printers
  5074. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5075. for printer in all_printers.scalars():
  5076. pid = printer.id
  5077. # Resolve model+firmware up front — needed to decide whether this printer
  5078. # qualifies for mid-print drying (busy printer on capable hardware).
  5079. state = printer_manager.get_status(pid)
  5080. if not state:
  5081. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5082. continue
  5083. model = printer_manager.get_model(pid)
  5084. firmware = state.firmware_version
  5085. # "Mid-print" has to mean the printer is actually printing (#2801).
  5086. # It used to be inferred from the dispatch set, which also holds
  5087. # printers that merely could not be dispatched to -- so a printer
  5088. # sitting in FINISH behind an unacknowledged plate was treated as
  5089. # printing, had its drying temperature capped by the mid-print
  5090. # spool protection, and was logged as (mid-print) while idle.
  5091. is_printing = state.state in _ACTIVE_PRINT_STATES
  5092. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5093. # A printer whose print is running or imminent is left alone unless
  5094. # it can dry through it. `dispatching_printers` is deliberately the
  5095. # narrow set: running, held post-dispatch, or mid-upload.
  5096. if (is_printing or pid in dispatching_printers) and not mid_print:
  5097. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5098. continue
  5099. if not mid_print:
  5100. # In queue-only mode, only dry printers that have scheduled prints
  5101. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5102. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5103. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5104. await self._stop_drying(pid)
  5105. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5106. continue
  5107. # When block mode is on, don't START new drying on printers with pending items.
  5108. # But allow already-drying printers through so humidity auto-stop logic still runs.
  5109. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  5110. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  5111. continue
  5112. if not printer_manager.is_connected(pid):
  5113. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5114. continue
  5115. # Plate-clear is deliberately ignored here (#2801). It answers
  5116. # "is the bed ready for the next job", which says nothing about
  5117. # whether the AMS may heat -- and the gap between a finished print
  5118. # and the acknowledgment is exactly when drying is most useful,
  5119. # because the printer is free and nobody is waiting on it. Leaving
  5120. # the plate unacknowledged is also how people hold the queue by
  5121. # hand, and that hold should not cost them their drying.
  5122. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5123. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5124. continue
  5125. # Check drying capability. For mid-print path, supports_drying_while_printing
  5126. # was already verified when computing mid_print above.
  5127. if not mid_print and not supports_drying(model, firmware):
  5128. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5129. continue
  5130. # Check each AMS unit from raw_data
  5131. ams_list = state.raw_data.get("ams", [])
  5132. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5133. for ams_data in ams_list:
  5134. module_type = str(ams_data.get("module_type") or "")
  5135. ams_id = int(ams_data.get("id", 0))
  5136. # Only n3f/n3s support drying
  5137. if module_type not in ("n3f", "n3s"):
  5138. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5139. continue
  5140. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5141. # Most-restrictive of all loaded tray types; falls back to the
  5142. # global threshold when no overrides are configured.
  5143. trays = ams_data.get("tray", []) or []
  5144. humidity_threshold = self.resolve_humidity_threshold(
  5145. trays, per_type_thresholds, global_humidity_threshold
  5146. )
  5147. dry_time = int(ams_data.get("dry_time") or 0)
  5148. # Read humidity as a percentage. The 1-5 index is never
  5149. # substituted: it is inverted, and being unable to exceed any
  5150. # threshold it would read as "dry" forever (#3140). ``None``
  5151. # already means "skip this unit" everywhere below.
  5152. humidity_pct = ams_humidity_percent(ams_data)
  5153. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5154. unit_key = (pid, ams_id)
  5155. unit_state = self._auto_dry_units.get(unit_key)
  5156. # Already drying — let it run to its configured duration (#1892).
  5157. #
  5158. # We deliberately do NOT stop drying from a humidity re-check here.
  5159. # Relative humidity drops steeply in heated air, so the AMS sensor
  5160. # reads ~15-20% within minutes of the dryer starting even while the
  5161. # filament is still saturated. A humidity-based early-stop therefore
  5162. # always fires at the minimum-time floor, truncating both user-started
  5163. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5164. # The firmware stops when the configured duration elapses; scheduling
  5165. # stops (print takes priority, queue no longer needs drying) are
  5166. # handled separately via _stop_drying().
  5167. if dry_time > 0:
  5168. if pid not in self._drying_in_progress:
  5169. # Drying we didn't start (manual or from before restart) —
  5170. # track it so scheduling stops still apply; never auto-stop it.
  5171. self._drying_in_progress[pid] = time.monotonic()
  5172. if unit_state is not None:
  5173. unit_state["running"] = True
  5174. logger.debug(
  5175. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5176. pid,
  5177. ams_id,
  5178. dry_time,
  5179. humidity,
  5180. )
  5181. continue
  5182. # Nothing is drying. Close out a cycle we armed ourselves and
  5183. # judge whether it achieved anything (#2770).
  5184. #
  5185. # "Achieved anything" is measured against the LOWEST reading any
  5186. # cycle on this unit has ended at, not against the threshold and
  5187. # not against the previous cycle. A spool that is genuinely wet
  5188. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5189. # allowed to keep going for as long as it is still coming down,
  5190. # however far it still is from the threshold. What must not
  5191. # continue is a cycle that ends exactly where the last one did,
  5192. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5193. # Comparing against the running minimum rather than the previous
  5194. # end is what stops a sensor oscillating by one point between two
  5195. # values from reading as progress every other cycle.
  5196. if unit_state is not None and unit_state.pop("running", False):
  5197. unit_state["ended_at"] = time.monotonic()
  5198. # The streak that armed this cycle is spent; the next one
  5199. # starts fresh (and accumulates through the re-arm cooldown
  5200. # below, so the wait overlaps the cooldown, never stacks on
  5201. # top of it).
  5202. self._auto_dry_above.pop(unit_key, None)
  5203. if humidity is not None and humidity > humidity_threshold:
  5204. best = unit_state.get("best_end_humidity")
  5205. if isinstance(best, int) and humidity < best:
  5206. # Still coming down. Keep going, however far the
  5207. # threshold still is.
  5208. unproductive = 0
  5209. else:
  5210. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5211. if not isinstance(best, int) or humidity < best:
  5212. unit_state["best_end_humidity"] = humidity
  5213. unit_state["unproductive"] = unproductive
  5214. logger.info(
  5215. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5216. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5217. pid,
  5218. ams_id,
  5219. humidity,
  5220. humidity_threshold,
  5221. unit_state.get("best_end_humidity"),
  5222. unproductive,
  5223. )
  5224. # A cycle that ended at or below the threshold needs no
  5225. # counter reset here: the branch below drops the whole entry.
  5226. # Humidity below threshold — no need to start drying. This is
  5227. # also the only thing that lifts a suspension: the reading we
  5228. # gave up on has come down, so auto-drying works again and the
  5229. # unit goes back to having no history at all.
  5230. if humidity is None or humidity <= humidity_threshold:
  5231. if unit_state is not None and unit_state.get("suspended"):
  5232. logger.info(
  5233. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5234. "threshold, resuming automatic drying",
  5235. pid,
  5236. ams_id,
  5237. humidity,
  5238. humidity_threshold,
  5239. )
  5240. # Clear the judgement, keep the clock (#2801). Dropping the
  5241. # whole entry also dropped `ended_at`, and with it the
  5242. # 30-minute cooldown -- so a reading that dips to the
  5243. # threshold as the AMS cools and comes back above it once
  5244. # warm wiped its own history and re-armed immediately. That
  5245. # oscillation is the very thing #2770's cooldown exists to
  5246. # ride out, and it is worst at exactly the margin that makes
  5247. # a unit dry repeatedly: a point or two above the threshold.
  5248. if unit_state is not None:
  5249. unit_state.pop("suspended", None)
  5250. unit_state.pop("unproductive", None)
  5251. unit_state.pop("best_end_humidity", None)
  5252. # A real below-threshold reading ends any sustained-wait
  5253. # streak (#2518) -- "continuously above" means exactly that.
  5254. # An absent reading (humidity is None) is no-information and
  5255. # leaves the streak alone; the observation-gap guard handles
  5256. # a prolonged sensor silence.
  5257. if humidity is not None:
  5258. _above = self._auto_dry_above.pop(unit_key, None)
  5259. if _above is not None and sustained_wait_active:
  5260. logger.info(
  5261. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5262. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5263. pid,
  5264. ams_id,
  5265. humidity,
  5266. time.monotonic() - _above["since"],
  5267. sustained_minutes,
  5268. humidity_threshold,
  5269. )
  5270. logger.debug(
  5271. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5272. pid,
  5273. ams_id,
  5274. humidity,
  5275. humidity_threshold,
  5276. )
  5277. continue
  5278. # Sustained-humidity streak (#2518): updated on every pass that
  5279. # observes the reading above the threshold, BEFORE the
  5280. # suspension/cooldown gates below -- a suspended or cooling-down
  5281. # unit still accumulates streak time, so the wait overlaps those
  5282. # gates instead of stacking after them. Inert when the feature
  5283. # is off: no entries are written, and an entry left over from a
  5284. # toggle-off is dropped so it cannot seed a stale streak later.
  5285. if sustained_wait_active:
  5286. _now = time.monotonic()
  5287. # Four missed scheduler passes, floored: a single slow pass
  5288. # must not void a streak, but the ceiling has to scale with
  5289. # the cadence or a slow loop silently restarts every streak.
  5290. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5291. _above = self._auto_dry_above.get(unit_key)
  5292. if _above is None:
  5293. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5294. elif _now - _above["last"] > _gap_ceiling:
  5295. # Restart, and say so at the same level as the dip
  5296. # reset: a silent restart voids the streak invisibly,
  5297. # and a user who set a long wait and never gets a dry
  5298. # has no way to see why.
  5299. logger.info(
  5300. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5301. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5302. pid,
  5303. ams_id,
  5304. _now - _above["last"],
  5305. _gap_ceiling,
  5306. sustained_minutes,
  5307. )
  5308. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5309. else:
  5310. _above["last"] = _now
  5311. else:
  5312. self._auto_dry_above.pop(unit_key, None)
  5313. if unit_state is not None:
  5314. if unit_state.get("suspended"):
  5315. logger.debug(
  5316. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5317. "above the %d%% threshold",
  5318. pid,
  5319. ams_id,
  5320. int(unit_state.get("unproductive", 0)),
  5321. humidity_threshold,
  5322. )
  5323. continue
  5324. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5325. unit_state["suspended"] = True
  5326. logger.warning(
  5327. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5328. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5329. "higher while it is warm, so a threshold in that range can never be reached and "
  5330. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5331. pid,
  5332. ams_id,
  5333. int(unit_state.get("unproductive", 0)),
  5334. humidity,
  5335. humidity_threshold,
  5336. )
  5337. await self._notify_auto_drying_suspended(
  5338. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5339. )
  5340. continue
  5341. ended_at = unit_state.get("ended_at")
  5342. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5343. logger.debug(
  5344. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5345. "cycle before the humidity reading is worth acting on",
  5346. pid,
  5347. ams_id,
  5348. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5349. )
  5350. continue
  5351. # Check cannot-dry reasons (power constraints etc.). Sits
  5352. # ahead of the sustained wait so a unit the firmware refuses
  5353. # to dry never logs a wait it was never going to cash in.
  5354. sf_reasons = ams_data.get("dry_sf_reason", [])
  5355. if sf_reasons:
  5356. logger.debug(
  5357. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5358. pid,
  5359. ams_id,
  5360. sf_reasons,
  5361. )
  5362. continue
  5363. # Sustained-humidity wait (#2518): ambient-triggered starts
  5364. # wait; only a printer with a scheduled queue item pending
  5365. # keeps the instant behavior, because that drying has a real
  5366. # deadline. Mid-print is deliberately NOT exempt while ambient
  5367. # drying is on: a humidity start on a printer that happens to be
  5368. # printing is as vulnerable to a lid-open spike as one on an idle
  5369. # printer (proven live: a 2-point threshold crossing mid-print
  5370. # bought a parked 12h command). Inactive when ambient drying is
  5371. # off: print_drying then still starts mid-print cycles on its own
  5372. # (#1816, "regardless of queue state"), and those stay instant.
  5373. if sustained_wait_active and pid not in printers_with_scheduled:
  5374. _above = self._auto_dry_above.get(unit_key)
  5375. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5376. if _waited < sustained_minutes * 60:
  5377. logger.debug(
  5378. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5379. "threshold for %.0fs of the required %dm",
  5380. pid,
  5381. ams_id,
  5382. humidity,
  5383. humidity_threshold,
  5384. _waited,
  5385. sustained_minutes,
  5386. )
  5387. continue
  5388. # Get conservative drying params for mixed filaments
  5389. params = self._get_conservative_drying_params(trays, module_type, presets)
  5390. if not params:
  5391. logger.debug(
  5392. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5393. )
  5394. continue
  5395. temp, duration_hours, filament_type = params
  5396. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5397. # "drying temperature must not exceed the filament's softening temperature"
  5398. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5399. # ineffective and firmware will reject anyway.
  5400. if mid_print:
  5401. temp = max(40, temp - 5)
  5402. # Start drying
  5403. logger.info(
  5404. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5405. "starting %s drying at %d°C for %dh%s",
  5406. pid,
  5407. ams_id,
  5408. humidity,
  5409. humidity_threshold,
  5410. filament_type,
  5411. temp,
  5412. duration_hours,
  5413. " (mid-print)" if mid_print else "",
  5414. )
  5415. success = printer_manager.send_drying_command(
  5416. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5417. )
  5418. if success:
  5419. self._drying_in_progress[pid] = time.monotonic()
  5420. armed = self._auto_dry_units.setdefault(
  5421. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5422. )
  5423. armed["running"] = True
  5424. async def _notify_auto_drying_suspended(
  5425. self,
  5426. db: AsyncSession,
  5427. printer: Printer,
  5428. ams_id: int,
  5429. humidity: int,
  5430. threshold: int,
  5431. cycles: int,
  5432. ) -> None:
  5433. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5434. Fires once per suspension — the caller sets ``suspended`` before calling
  5435. and every later pass short-circuits on it — because the whole point is
  5436. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5437. building needs that to reach them, and the hourly humidity alarm they
  5438. are already getting says the opposite of what happened here.
  5439. Never raises: a notification provider being down must not stop the
  5440. suspension itself from taking effect.
  5441. """
  5442. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5443. try:
  5444. await notification_service.on_ams_drying_suspended(
  5445. printer.id,
  5446. printer.name,
  5447. ams_label,
  5448. float(humidity),
  5449. float(threshold),
  5450. cycles,
  5451. db,
  5452. )
  5453. except Exception as e:
  5454. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5455. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5456. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5457. The unproductive-cycle counter exists to notice that *drying* is not
  5458. moving the humidity reading. A cycle that ended because somebody sent a
  5459. stop says nothing about that — it was cut short before it had a chance —
  5460. so counting it would suspend auto-drying for a reason that has nothing to
  5461. do with the loop the counter is there to break.
  5462. Two callers, both of them a stop Bambuddy is responsible for: the
  5463. print-takes-priority stop below, and the manual Stop button. Left
  5464. uncalled, an install that dries between queue jobs would suspend its own
  5465. auto-drying after two prints interrupted a dry — exactly the install
  5466. queue-drying exists for.
  5467. The rest of the unit's history is kept: the cooldown before re-arming
  5468. still applies, and an earlier count still stands.
  5469. """
  5470. state = self._auto_dry_units.get((printer_id, ams_id))
  5471. if state is not None:
  5472. state.pop("running", None)
  5473. state["ended_at"] = time.monotonic()
  5474. # A stopped cycle spends the streak that armed it, same as a completed
  5475. # one (#2518).
  5476. self._auto_dry_above.pop((printer_id, ams_id), None)
  5477. def _sync_drying_state(self):
  5478. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5479. One direction only: it prunes, it never adds. A printer drying without an
  5480. entry here — because the user started the cycle from Studio, the printer's
  5481. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5482. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5483. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5484. That is deliberate for now rather than an oversight: populating this from
  5485. telemetry would hand the scheduler authority to stop drying a user started
  5486. by hand. It also means the backend-restart case this used to claim to
  5487. handle is not handled.
  5488. """
  5489. to_remove = []
  5490. for pid in self._drying_in_progress:
  5491. state = printer_manager.get_status(pid)
  5492. if not state:
  5493. to_remove.append(pid)
  5494. continue
  5495. # Check if any AMS unit is still drying
  5496. ams_list = state.raw_data.get("ams", [])
  5497. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5498. if not any_drying:
  5499. to_remove.append(pid)
  5500. for pid in to_remove:
  5501. self._drying_in_progress.pop(pid, None)
  5502. # A printer that has gone away entirely takes its per-AMS auto-drying
  5503. # history with it (#2770), so a printer deleted and re-added does not
  5504. # inherit a suspension it never earned.
  5505. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5506. self._auto_dry_units.pop(key, None)
  5507. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5508. # printer starts a fresh wait, and vanished printers do not leak
  5509. # entries.
  5510. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5511. self._auto_dry_above.pop(key, None)
  5512. @staticmethod
  5513. def _drying_is_only_parked(printer_id: int) -> bool:
  5514. """True when every AMS unit with a drying timer on this printer is parked.
  5515. A parked timer (#2896: the command was taken but the countdown never
  5516. runs) does not end on its own, so nothing may wait on it. False when no
  5517. unit reports a timer yet -- a command just sent that the firmware has not
  5518. reported back is real drying about to begin.
  5519. """
  5520. state = printer_manager.get_status(printer_id)
  5521. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5522. timed = []
  5523. for unit in units:
  5524. try:
  5525. if int(unit.get("dry_time") or 0) > 0:
  5526. timed.append(unit)
  5527. except (TypeError, ValueError):
  5528. continue
  5529. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5530. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5531. """True when a running cycle can be left alone while the next print runs.
  5532. Some hardware dries happily through a print and #2758 settled that we
  5533. should not tear those cycles down: the X2D there was refusing to
  5534. *start* a job, which is a different problem, and stopping drying before
  5535. every dispatch would throw away cycles the printer was content to run.
  5536. Where the model cannot do it, or the user has not enabled it, the print
  5537. takes priority and the cycle stops -- which is what the queue_drying_block
  5538. setting has always promised in its off position.
  5539. """
  5540. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5541. return False
  5542. status = printer_manager.get_status(printer_id)
  5543. return supports_drying_while_printing(
  5544. printer_manager.get_model(printer_id),
  5545. status.firmware_version if status else None,
  5546. )
  5547. async def _stop_drying(self, printer_id: int):
  5548. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5549. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5550. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5551. enough to kill a cycle the user had started by hand on a *different*
  5552. unit of the same printer (#2801). That contradicted the contract
  5553. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5554. only knows about cycles Bambuddy began, so the action must not reach
  5555. past them either.
  5556. """
  5557. state = printer_manager.get_status(printer_id)
  5558. if not state:
  5559. self._drying_in_progress.pop(printer_id, None)
  5560. return
  5561. ams_list = state.raw_data.get("ams", [])
  5562. for ams_data in ams_list:
  5563. dry_time = int(ams_data.get("dry_time") or 0)
  5564. if dry_time > 0:
  5565. ams_id = int(ams_data.get("id", 0))
  5566. if (printer_id, ams_id) not in self._auto_dry_units:
  5567. logger.debug(
  5568. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5569. printer_id,
  5570. ams_id,
  5571. )
  5572. continue
  5573. logger.info(
  5574. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5575. printer_id,
  5576. ams_id,
  5577. )
  5578. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5579. self.forget_auto_dry_cycle(printer_id, ams_id)
  5580. self._drying_in_progress.pop(printer_id, None)
  5581. # Scheduled manual drying (#2638) -----------------------------------
  5582. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5583. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5584. async def _check_scheduled_dryings(self, db: AsyncSession):
  5585. """Dispatch due scheduled drying runs and track running ones."""
  5586. now = utcnow_naive()
  5587. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5588. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5589. since_prune = time.monotonic()
  5590. if (
  5591. self._last_scheduled_drying_prune is None
  5592. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5593. ):
  5594. self._last_scheduled_drying_prune = since_prune
  5595. await db.execute(
  5596. delete(ScheduledDrying).where(
  5597. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5598. ScheduledDrying.completed_at.is_not(None),
  5599. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5600. )
  5601. )
  5602. # Same order as the list route: with two rows due on one printer the
  5603. # earliest scheduled wins rather than whatever the DB hands back first.
  5604. result = await db.execute(
  5605. select(ScheduledDrying)
  5606. .where(ScheduledDrying.status.in_(("pending", "running")))
  5607. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5608. )
  5609. rows = list(result.scalars().all())
  5610. # Rebuild from the DB every tick so route-side cancels and completions
  5611. # show up. Auto-drying's stop-all branches check this set before
  5612. # stopping anything (#2638).
  5613. # Kept from the previous pass so a run that ended between passes — a
  5614. # cancel through the route, say — can still be released below.
  5615. previously_running = self._scheduled_drying_printer_ids
  5616. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5617. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5618. # Model and firmware come from the printer row, not the live state.
  5619. printer_ids = {row.printer_id for row in rows}
  5620. printers_by_id: dict[int, Printer] = {}
  5621. if printer_ids:
  5622. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5623. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5624. for row in rows:
  5625. if row.status == "running":
  5626. self._update_running_scheduled_drying(row, now)
  5627. continue
  5628. if row.start_after is not None and row.start_after > now:
  5629. continue
  5630. state = printer_manager.get_status(row.printer_id)
  5631. if not state:
  5632. row.waiting_reason = "printer_offline"
  5633. continue
  5634. # Same preflight the immediate endpoint runs. Without it the publish
  5635. # succeeds, the row goes to running, the printer ignores the command
  5636. # and the run silently cancels itself after the grace window.
  5637. printer = printers_by_id.get(row.printer_id)
  5638. unsupported = drying_preflight.check_drying_supported(
  5639. printer.model if printer else None, state.firmware_version
  5640. )
  5641. if unsupported:
  5642. row.status = "failed"
  5643. row.error_message = unsupported
  5644. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5645. row.completed_at = now
  5646. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5647. continue
  5648. if (
  5649. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5650. ) or row.printer_id in running_printer_ids:
  5651. row.waiting_reason = "already_drying"
  5652. continue
  5653. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5654. row.waiting_reason = "printer_busy"
  5655. continue
  5656. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5657. if target is None:
  5658. row.waiting_reason = "ams_not_found"
  5659. continue
  5660. blocking = drying_preflight.blocking_reason_codes(target)
  5661. if blocking:
  5662. # Keep the power case distinct; it needs the user to act, so the
  5663. # card can say so instead of waiting silently.
  5664. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5665. continue
  5666. filament = drying_preflight.resolve_filament(target, row.filament)
  5667. logger.info(
  5668. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5669. row.id,
  5670. row.printer_id,
  5671. row.ams_id,
  5672. row.temp,
  5673. row.duration_hours,
  5674. )
  5675. success = printer_manager.send_drying_command(
  5676. row.printer_id,
  5677. row.ams_id,
  5678. row.temp,
  5679. row.duration_hours,
  5680. mode=1,
  5681. filament=filament,
  5682. rotate_tray=row.rotate_tray,
  5683. )
  5684. if success:
  5685. row.status = "running"
  5686. row.started_at = now
  5687. row.waiting_reason = None
  5688. row.filament = filament
  5689. self._drying_in_progress[row.printer_id] = time.monotonic()
  5690. self._scheduled_drying_printer_ids.add(row.printer_id)
  5691. running_printer_ids.add(row.printer_id)
  5692. else:
  5693. row.waiting_reason = "printer_offline"
  5694. # Release the printers whose run has ended. `_drying_in_progress` is
  5695. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5696. # but that call sits behind the auto-drying enabled check, and this
  5697. # method is the one writer that runs whether auto-drying is on or not.
  5698. # With it off, nothing would ever drop the entry short of a print being
  5699. # dispatched to the same printer, so the next scheduled run would wait
  5700. # on "already_drying" forever and `queue_drying_block` would hold the
  5701. # printer's prints too. Covers a run that ended during this pass and one
  5702. # cancelled through the route between passes.
  5703. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5704. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5705. self._drying_in_progress.pop(printer_id, None)
  5706. await db.commit()
  5707. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5708. """Detect completion or interruption of a running scheduled drying.
  5709. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5710. drying. Within the grace window after start we ignore dry_time==0
  5711. (the status lags the command). After that, dry_time==0 near the end
  5712. of the configured duration means completed. Much earlier means the
  5713. run was stopped: re-queue it if a print preempted the dryer, but a
  5714. stop while the printer is idle was deliberate, so cancel the row
  5715. rather than restart drying the user just stopped.
  5716. """
  5717. if row.started_at is None:
  5718. row.started_at = now
  5719. return
  5720. elapsed = (now - row.started_at).total_seconds()
  5721. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5722. return
  5723. state = printer_manager.get_status(row.printer_id)
  5724. if not state:
  5725. return # offline mid-dry; resolve when it reconnects
  5726. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5727. # throw on a malformed id would cost the whole pass including print
  5728. # dispatch, every tick.
  5729. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5730. try:
  5731. dry_time = int(target.get("dry_time") or 0) if target else 0
  5732. except (TypeError, ValueError):
  5733. dry_time = 0
  5734. if dry_time > 0 and is_countdown_parked(target):
  5735. # The printer took the command but the countdown is not running
  5736. # (#2896) and will never reach 0, so the run would stay "running"
  5737. # forever. A print in progress is the likely cause (the power budget
  5738. # is spent), so re-queue it like any interruption; the next start
  5739. # waits for the printer to be idle. Parked on an idle printer is a
  5740. # refusal, not something a retry fixes. The timer itself is left on
  5741. # the printer: it may yet start once power frees up.
  5742. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5743. logger.info(
  5744. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5745. row.id,
  5746. row.ams_id,
  5747. )
  5748. row.status = "pending"
  5749. row.started_at = None
  5750. row.waiting_reason = "interrupted"
  5751. else:
  5752. logger.warning(
  5753. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5754. row.id,
  5755. row.ams_id,
  5756. )
  5757. row.status = "failed"
  5758. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5759. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5760. row.completed_at = now
  5761. return
  5762. if dry_time > 0:
  5763. return
  5764. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5765. row.status = "completed"
  5766. row.completed_at = now
  5767. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5768. row.status = "pending"
  5769. row.started_at = None
  5770. row.waiting_reason = "interrupted"
  5771. else:
  5772. row.status = "cancelled"
  5773. row.completed_at = now
  5774. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5775. """Get all smart plugs associated with a printer."""
  5776. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5777. return list(result.scalars().all())
  5778. @staticmethod
  5779. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5780. """Pick the plug to power-cycle a printer back online with (#2629).
  5781. Only a plug flagged ``controls_printer_power`` can actually bring the
  5782. printer back; waiting for a boot on an accessory (filter fan, lights)
  5783. just burns the power-on timeout and fails the dispatch. Falls back to
  5784. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5785. Callers must pass a non-empty list.
  5786. """
  5787. for plug in auto_on_plugs:
  5788. if plug.controls_printer_power:
  5789. return plug
  5790. return auto_on_plugs[0]
  5791. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5792. # chamber-temperature recommendations BambuStudio ships for the matching
  5793. # filament profile; users can override via Settings → Workflow → Preheat
  5794. # card. "default" applies when a loaded tray's normalised type isn't in
  5795. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5796. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5797. "PLA": 0,
  5798. "PETG": 0,
  5799. "PETG-CF": 40,
  5800. "ABS": 45,
  5801. "ASA": 45,
  5802. "PA": 50,
  5803. "PA-CF": 55,
  5804. "PC": 50,
  5805. "PC-FR": 50,
  5806. "TPU": 0,
  5807. "PVA": 0,
  5808. "default": 0,
  5809. }
  5810. @classmethod
  5811. def _bundled_preheat_targets(cls) -> dict[str, int]:
  5812. """The bundled map under the same key casing a parsed one gets.
  5813. The constant is declared with a lowercase ``default`` because that is
  5814. the key the Settings editor writes and displays. Every read of the map
  5815. happens after ``str(key).upper()``, so handing the constant back as
  5816. declared broke the contract the parser documents: an install that had
  5817. never touched the setting returned a dict with no ``DEFAULT`` in it,
  5818. and the resolution loop's fallback silently found nothing. It read the
  5819. right number only because the bundled default happens to be 0 -- change
  5820. that constant and every unconfigured install would keep preheating to
  5821. zero with no way to tell why.
  5822. """
  5823. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  5824. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  5825. """Parse the user-configured filament→chamber-target map, falling back
  5826. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  5827. are uppercased and the 'default' fallback is always present in the
  5828. returned dict so the resolution loop can index it unconditionally."""
  5829. raw = await self._get_setting(db, "preheat_filament_targets")
  5830. if not raw:
  5831. return self._bundled_preheat_targets()
  5832. try:
  5833. parsed = json.loads(raw)
  5834. if not isinstance(parsed, dict):
  5835. raise ValueError("not an object")
  5836. except (json.JSONDecodeError, ValueError) as exc:
  5837. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  5838. return self._bundled_preheat_targets()
  5839. # Coerce values to int; drop unparseable rows so a stray string
  5840. # doesn't crash the loop.
  5841. out: dict[str, int] = {}
  5842. for key, value in parsed.items():
  5843. try:
  5844. out[str(key).upper()] = int(value)
  5845. except (TypeError, ValueError):
  5846. continue
  5847. if "DEFAULT" not in out:
  5848. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  5849. return out
  5850. @staticmethod
  5851. def _normalize_filament_type(tray_type: str) -> str:
  5852. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  5853. existing drying-preset normalisation (split-at-space, upper-case) so
  5854. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  5855. "PA-CF" (no space to split on).
  5856. This is the first stage of ``_resolve_filament_key``, which goes on to
  5857. drop the suffix and consult the alias map; on its own it only decides
  5858. what the tray is called, not which row answers for it.
  5859. Indexing the split rather than testing the input: a tray_type of spaces
  5860. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  5861. it through to an IndexError.
  5862. """
  5863. words = (tray_type or "").split()
  5864. return words[0].upper() if words else ""
  5865. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  5866. """Per-filament chamber target for one tray's reported type, or 0 when
  5867. the tray is empty / RFID-less and reports no type at all.
  5868. A filled or foamed variant wants its base material's chamber when the
  5869. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  5870. not the 0 an unknown type falls to. The specific type is still tried
  5871. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  5872. (#2902).
  5873. That lookup is now the shared one, which adds the polyamide aliases on
  5874. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  5875. too, rather than the catch-all it was landing on (#3067).
  5876. """
  5877. if not self._normalize_filament_type(tray_type or ""):
  5878. return 0
  5879. key = self._resolve_filament_key(tray_type, targets)
  5880. if key is not None:
  5881. return targets[key]
  5882. # A type the map does not list at all, which is not the same as a tray
  5883. # with nothing in it -- that already returned 0 above.
  5884. return targets.get("DEFAULT", 0)
  5885. def _derive_chamber_target(
  5886. self,
  5887. printer: Printer,
  5888. targets: dict[str, int],
  5889. item: PrintQueueItem | None = None,
  5890. ) -> int:
  5891. """Chamber target for the trays this print actually loads: the max of
  5892. their per-filament targets. Returns 0 when there is nothing to read (no
  5893. status, no AMS telemetry — e.g. external-spool prints) or when every
  5894. tray considered maps to 0, and the chamber phase then short-circuits in
  5895. the main loop.
  5896. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  5897. Scanning the whole unit instead meant one ASA spool parked in the AMS
  5898. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  5899. plus soak burned ahead of each upload, on a printer whose chamber never
  5900. reaches the target anyway (#2886). An item with no usable mapping falls
  5901. back to scanning every loaded tray: that is the only signal left, and
  5902. narrowing to nothing would skip preheat on prints that genuinely need
  5903. it.
  5904. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  5905. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  5906. less slots have empty `tray_type` and contribute nothing. The external
  5907. spool is consulted only when the mapping names it (>= 254); it stays
  5908. out of the unnarrowed scan, so an item without a mapping derives from
  5909. the AMS alone exactly as before.
  5910. """
  5911. state = printer_manager.get_status(printer.id)
  5912. if state is None:
  5913. return 0
  5914. raw_data = state.raw_data or {}
  5915. used = _used_global_tray_ids(item)
  5916. ams_list = raw_data.get("ams")
  5917. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  5918. if isinstance(ams_list, dict):
  5919. ams_list = ams_list.get("ams") or []
  5920. if not isinstance(ams_list, list):
  5921. ams_list = []
  5922. best = 0
  5923. for ams in ams_list:
  5924. if not isinstance(ams, dict):
  5925. continue
  5926. ams_id = _int_or(ams.get("id"), 0)
  5927. for tray in ams.get("tray") or []:
  5928. # A non-dict entry has never been seen from real firmware, but
  5929. # `.get` on one raises, and nothing between here and
  5930. # `_dispatch_one`'s try/finally catches it — the item would be
  5931. # left holding its dispatch claim. Preheat is best-effort by
  5932. # contract, so step over it instead.
  5933. if not isinstance(tray, dict):
  5934. continue
  5935. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  5936. continue
  5937. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  5938. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  5939. for vt in raw_data.get("vt_tray") or []:
  5940. if not isinstance(vt, dict):
  5941. continue
  5942. # `_build_loaded_filaments` addresses external feeds by the id
  5943. # the firmware reports — 255 main, 254 deputy — defaulting to
  5944. # 254 when the field is absent. Same expression here so the two
  5945. # agree on which entry a mapping's 254/255 refers to.
  5946. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  5947. continue
  5948. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  5949. return best
  5950. def _release_keep_warm(self, pid: int) -> None:
  5951. """Release keep-warm on a printer that left the candidate set.
  5952. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  5953. reports the target we set (``entry.held_target``), so a user or
  5954. subsequent print that changed the bed target since is not clobbered.
  5955. Best-effort, never raises.
  5956. The entry is kept, not dropped, when the printer cannot be reached
  5957. right now: a printer that is briefly offline still has a hot bed, and
  5958. holding the entry is what keeps the max-duration timeout applying and
  5959. lets a later tick retry the release. Only a printer that has left the
  5960. manager entirely gives up on that, in ``_sample_chamber_temps``.
  5961. """
  5962. entry = self._keep_warm.get(pid)
  5963. if entry is None:
  5964. return
  5965. state = printer_manager.get_status(pid)
  5966. client = printer_manager.get_client(pid)
  5967. if state is None or client is None:
  5968. logger.debug(
  5969. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  5970. pid,
  5971. )
  5972. return
  5973. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  5974. if int(cur_bed_target) != entry.held_target:
  5975. # Someone else owns the bed now, so there is nothing of ours to
  5976. # undo and nothing left to track.
  5977. logger.info(
  5978. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  5979. pid,
  5980. int(cur_bed_target),
  5981. entry.held_target,
  5982. )
  5983. self._keep_warm.pop(pid, None)
  5984. return
  5985. try:
  5986. client.set_bed_temperature(0)
  5987. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  5988. self._keep_warm.pop(pid, None)
  5989. except Exception as exc:
  5990. # Keep the entry so the next tick tries again rather than leaving
  5991. # the bed hot with nothing tracking it.
  5992. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  5993. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  5994. """Release printers that dropped out of the keep-warm candidate set.
  5995. Called from ``_apply_keep_warm`` on every tick (with the current
  5996. candidate set), and from ``check_queue``'s no-pending-items early
  5997. return (with an empty candidate set) so orphaned holds still get
  5998. released when the queue empties. Also called with an empty candidate
  5999. set when any of the three gate settings toggles off, so a printer
  6000. whose feature was disabled mid-hold gets its bed released.
  6001. Printers being dispatched this tick are excluded from the bed-off
  6002. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6003. transient 0 in between would just churn against preheat. Ownership of
  6004. the hot bed transfers to the preheat rollback pin instead — if the
  6005. dispatch aborts before the print starts (failed upload, cancelled
  6006. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6007. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6008. is the ONLY thing standing between an aborted dispatch and a bed
  6009. left hot with no owner. A successful print start clears the pin and
  6010. the print's own gcode takes over, as usual.
  6011. """
  6012. for _pid in list(self._keep_warm):
  6013. if _pid in active_candidates:
  6014. continue
  6015. if _pid in dispatched:
  6016. handed_over = self._keep_warm.pop(_pid, None)
  6017. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6018. if handed_over is not None:
  6019. self._preheat_pin_bed[_pid] = handed_over.held_target
  6020. continue
  6021. self._release_keep_warm(_pid)
  6022. async def _apply_keep_warm(
  6023. self,
  6024. db: AsyncSession,
  6025. items: list[PrintQueueItem],
  6026. dispatch_ids: list[int] | set[int],
  6027. busy_printers: set[int],
  6028. require_plate_clear: bool,
  6029. ) -> None:
  6030. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6031. When a printer just finished a job (FINISH state) and the next queued
  6032. item needs chamber heating, hold the bed hot so the chamber stays warm
  6033. during the bed-clearing window. The bed is the chamber's heating
  6034. element here, not a print surface — nothing is printing during the
  6035. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6036. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6037. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6038. aftermarket chamber heaters), raised to the item's own parsed
  6039. bed_temperature when that is higher. Items whose archive metadata has
  6040. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6041. get a hold — chamber need is what gates the feature, not metadata.
  6042. Skips entirely for filaments that map to a 0°C chamber target
  6043. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6044. names, so a hot-chamber spool it never touches does not hold the bed of
  6045. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6046. whole unit, as every item was before. Printers being dispatched this
  6047. cycle are excluded:
  6048. ``_preheat_and_soak`` already handles their bed temperature.
  6049. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6050. released to 0 and the entry is latched ``expired=True`` so
  6051. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6052. MQTT: publish is skipped when firmware already has the target.
  6053. The release sweep runs BEFORE the engagement gate so a printer that
  6054. was owned by keep-warm still gets its bed released when any of the
  6055. three gate settings is toggled off mid-hold. The
  6056. ``check_queue`` early-return-when-no-items path also calls
  6057. ``_sweep_keep_warm`` directly to release orphaned holds.
  6058. """
  6059. dispatch_set = set(dispatch_ids)
  6060. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6061. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6062. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6063. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6064. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6065. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6066. # Release sweep first — must run even when gate_open is False so a
  6067. # printer owned by keep-warm when a gate toggles off gets released.
  6068. self._sweep_keep_warm(
  6069. active_candidates=warm_candidates if gate_open else set(),
  6070. dispatched=dispatched_printers,
  6071. )
  6072. if not gate_open:
  6073. return
  6074. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6075. max_hold_seconds = (
  6076. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6077. )
  6078. now_mono = time.monotonic()
  6079. filament_targets: dict[str, int] | None = None
  6080. for pid in warm_candidates:
  6081. entry = self._keep_warm.get(pid)
  6082. # Latched-expired: max-duration timeout already fired for this
  6083. # printer. Skip until the release sweep drops the entry (i.e.
  6084. # until the printer leaves the candidate set).
  6085. if entry is not None and entry.expired:
  6086. continue
  6087. # These two guards sit ahead of the max-duration check below, so an
  6088. # engaged hold only ages out while its printer is still reachable
  6089. # and still in FINISH. That is deliberate rather than a hole: with
  6090. # no status or no client there is no M140 to send anyway, and the
  6091. # elapsed check runs off `entry.started` so it fires on the first
  6092. # tick after the printer comes back. Leaving FINISH means the plate
  6093. # was cleared, which drops the printer out of `warm_candidates` and
  6094. # hands it to `_release_keep_warm` instead. The invariant worth
  6095. # preserving if this is ever reordered: every path out of an
  6096. # engaged hold ends in a bed-off, whether by timeout or release.
  6097. state = printer_manager.get_status(pid)
  6098. if state is None or state.state != "FINISH":
  6099. continue
  6100. client = printer_manager.get_client(pid)
  6101. if client is None:
  6102. continue
  6103. next_item = next((it for it in items if it.printer_id == pid), None)
  6104. if next_item is None:
  6105. continue
  6106. # Hold temperature: the configured keep-warm temp, raised to the
  6107. # item's own bed temp when the metadata reports a higher one. A
  6108. # missing bed_temperature (Orca gcode.3mf exports parse without
  6109. # one) does NOT skip the hold — chamber need gates the feature.
  6110. archive = next_item.archive
  6111. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6112. bed_target = max(item_bed, hold_temp)
  6113. if bed_target <= 0:
  6114. continue
  6115. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6116. if explicit is not None:
  6117. chamber_needed = int(explicit) > 0
  6118. else:
  6119. if filament_targets is None:
  6120. filament_targets = await self._get_preheat_filament_targets(db)
  6121. printer_obj = await self._get_printer(db, pid)
  6122. chamber_needed = (
  6123. printer_obj is not None
  6124. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6125. )
  6126. if not chamber_needed:
  6127. continue
  6128. # Seed the timer on first engagement; keep it on subsequent ticks
  6129. # (never re-seed — that would defeat the max-duration cap).
  6130. if entry is None:
  6131. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6132. self._keep_warm[pid] = entry
  6133. elapsed = now_mono - entry.started
  6134. if elapsed > max_hold_seconds:
  6135. # Timeout: publish bed → 0 once (if firmware still holds our
  6136. # target) and latch expired. The entry stays until the release
  6137. # sweep drops it, preventing the next tick from re-seeding.
  6138. logger.warning(
  6139. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6140. pid,
  6141. elapsed,
  6142. )
  6143. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6144. if int(cur_bed_target) == entry.held_target:
  6145. try:
  6146. client.set_bed_temperature(0)
  6147. except Exception as exc:
  6148. logger.warning(
  6149. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6150. pid,
  6151. exc,
  6152. )
  6153. else:
  6154. logger.info(
  6155. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6156. pid,
  6157. int(cur_bed_target),
  6158. entry.held_target,
  6159. )
  6160. entry.expired = True
  6161. continue
  6162. # Idempotence: skip publish when firmware already has our target.
  6163. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6164. if int(cur_bed_target) == bed_target:
  6165. entry.held_target = bed_target
  6166. continue
  6167. try:
  6168. client.set_bed_temperature(bed_target)
  6169. entry.held_target = bed_target
  6170. logger.info(
  6171. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6172. bed_target,
  6173. pid,
  6174. )
  6175. except Exception as exc:
  6176. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6177. def _sample_chamber_temps(self) -> None:
  6178. """Record a chamber temperature sample for every connected printer.
  6179. Called once per scheduler tick (every 3–30 s). Entries older than
  6180. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6181. Also evicts per-printer state whose printer_id is no longer registered
  6182. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6183. """
  6184. now = time.monotonic()
  6185. cutoff = now - self._chamber_history_ttl
  6186. statuses = printer_manager.get_all_statuses()
  6187. known_pids = set(statuses.keys())
  6188. for pid, status in statuses.items():
  6189. if status is None or not status.connected:
  6190. continue
  6191. temps = status.temperatures or {}
  6192. chamber = temps.get("chamber")
  6193. if chamber is None:
  6194. continue
  6195. hist = self._chamber_history.setdefault(pid, deque())
  6196. hist.append((now, float(chamber)))
  6197. while hist and hist[0][0] < cutoff:
  6198. hist.popleft()
  6199. # Evict state for printers that are no longer registered with the manager.
  6200. # This is the one place a keep-warm entry is dropped without releasing
  6201. # the bed: the printer is gone from the manager, so there is no client
  6202. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6203. # for printers that are merely unreachable, which is what makes this
  6204. # the terminal case rather than a silent leak.
  6205. for pid in list(self._chamber_history):
  6206. if pid not in known_pids:
  6207. self._chamber_history.pop(pid, None)
  6208. for pid in list(self._keep_warm):
  6209. if pid not in known_pids:
  6210. logger.info(
  6211. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6212. pid,
  6213. )
  6214. self._keep_warm.pop(pid, None)
  6215. for pid in list(self._preheat_pin):
  6216. if pid not in known_pids:
  6217. self._preheat_pin.pop(pid, None)
  6218. self._preheat_pin_bed.pop(pid, None)
  6219. def _chamber_soak_remaining(
  6220. self,
  6221. printer_id: int,
  6222. chamber_target: float,
  6223. soak_seconds: int,
  6224. tolerance: float = 2.0,
  6225. ) -> int:
  6226. """Return how many seconds of soak time are still needed.
  6227. Credits the time the chamber has already spent at temperature against
  6228. the configured soak. The credit may not start earlier than any of:
  6229. * **The newest sample.** Nothing recent means the printer stopped
  6230. reporting mid-observation and the chamber may have cooled unseen, so
  6231. the full soak is required. (A 2 h history whose last reading is half
  6232. an hour old is not evidence of anything — the measured cooling rate
  6233. is fast enough to cross the threshold in that time.)
  6234. * **The most recent contiguous run of samples.** A gap wider than
  6235. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6236. far side is not evidence of temperature.
  6237. * **The end of the most recent real dip below the threshold.**
  6238. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6239. — see that constant for the thermal reasoning. A stray low reading is
  6240. an artifact, and treating it as cooling would discard a soak that
  6241. actually happened.
  6242. Returns ``soak_seconds`` when nothing can be credited (no history,
  6243. stale history, or the chamber is below the threshold right now) and 0
  6244. once the credited time covers the whole soak.
  6245. """
  6246. hist = self._chamber_history.get(printer_id)
  6247. if not hist:
  6248. return soak_seconds
  6249. now = time.monotonic()
  6250. newest_ts, newest_temp = hist[-1]
  6251. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6252. return soak_seconds # stale — no fresh evidence to credit
  6253. threshold = chamber_target - tolerance
  6254. if newest_temp < threshold:
  6255. return soak_seconds # below target right now; nothing is soaked
  6256. samples = list(hist)
  6257. # Earliest point we have unbroken observations for.
  6258. credit_from = samples[-1][0]
  6259. for i in range(len(samples) - 1, 0, -1):
  6260. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6261. break
  6262. credit_from = samples[i - 1][0]
  6263. # Pull the credit forward to the end of the last significant dip. Each
  6264. # excursion is measured between the in-range readings that bracket it,
  6265. # so a lone stray sample is charged one sampling interval rather than
  6266. # zero, and the comparison errs towards calling a dip real.
  6267. i = 0
  6268. while i < len(samples):
  6269. if samples[i][1] >= threshold:
  6270. i += 1
  6271. continue
  6272. j = i
  6273. while j < len(samples) and samples[j][1] < threshold:
  6274. j += 1
  6275. # `newest_temp >= threshold` was checked above, so j is in range.
  6276. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6277. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6278. # Credit resumes at the last below-threshold sample rather than
  6279. # the first good one after it, so a recovered dip over-credits
  6280. # by up to one sampling interval — the opposite lean to the
  6281. # bracketing above. Both are bounded by the sample cadence and
  6282. # dwarfed by the grace period, so neither is worth the extra
  6283. # arithmetic to remove.
  6284. credit_from = max(credit_from, samples[j - 1][0])
  6285. i = j
  6286. return max(0, soak_seconds - int(now - credit_from))
  6287. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6288. """Tell an in-flight dispatch that its item no longer wants to print.
  6289. Called by the queue's cancel and delete routes. Those only write to the
  6290. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6291. observe — so preheat would keep heating for the rest of max_wait + soak
  6292. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6293. blocking every other queued item behind a print that is not happening.
  6294. Signalling in memory rather than re-reading the row keeps this off the
  6295. database entirely: no second session, no transaction held across a long
  6296. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6297. Bambuddy serves from a single uvicorn process with one scheduler task,
  6298. so the route and the dispatch always share this object. The flag is
  6299. advisory — dropping it (e.g. after a restart) only costs a wasted
  6300. preheat, never a wrongly-abandoned print.
  6301. Only ids with a dispatch actually in flight are recorded, so the set
  6302. stays bounded by the upload pool rather than growing once per cancelled
  6303. item for the life of the process. Skipping the rest loses nothing: an
  6304. item that is not in flight cannot start heating later either, because
  6305. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6306. the caller has already committed a terminal status (or deleted the row)
  6307. before calling this.
  6308. """
  6309. if item_id in self._inflight:
  6310. self._cancelled_dispatches.add(item_id)
  6311. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6312. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6313. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6314. while it is parked, so the wait is chopped into
  6315. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6316. """
  6317. remaining = float(seconds)
  6318. while remaining > 0:
  6319. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6320. await asyncio.sleep(slice_secs)
  6321. remaining -= slice_secs
  6322. if item_id in self._cancelled_dispatches:
  6323. return False
  6324. return True
  6325. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6326. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6327. The full preheat stage does this as part of its own dispatch: an H2D
  6328. left in heating mode by the ABS job before it would otherwise cook the
  6329. PLA that follows. The skip path never reaches that code, so it calls
  6330. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6331. add to the rollback pin, because a flap set to cooling for a print that
  6332. needs no heat is where it should have been either way.
  6333. Best-effort like everything else in the stage: a refused command logs
  6334. and the dispatch carries on.
  6335. """
  6336. model = printer.model or ""
  6337. if not supports_airduct(model):
  6338. return
  6339. state = printer_manager.get_status(printer.id)
  6340. current = getattr(state, "airduct_mode", None) if state else None
  6341. if current == _AIRDUCT_MODE_COOLING:
  6342. return
  6343. client = printer_manager.get_client(printer.id)
  6344. if client is None:
  6345. return
  6346. try:
  6347. client.set_airduct_mode("cooling")
  6348. except Exception as exc:
  6349. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6350. async def _preheat_and_soak(
  6351. self,
  6352. db: AsyncSession,
  6353. item: PrintQueueItem,
  6354. printer: Printer,
  6355. archive: PrintArchive | None,
  6356. ) -> bool:
  6357. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6358. Returns True when the dispatch should carry on to the upload — including
  6359. every case where preheat is skipped, since a skipped preheat is not a
  6360. reason to abandon the print. Returns False only when the item stopped
  6361. wanting to be printed while the stage was waiting (cancelled or
  6362. deleted); the caller must then abandon the dispatch, and
  6363. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6364. Resolution order:
  6365. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6366. to the global `preheat_enabled` setting; 'on' forces the stage on
  6367. even if the global is off.
  6368. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6369. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6370. across the trays `item.ams_mapping` names (every loaded slot when
  6371. it names none).
  6372. 3. A target of 0 off the filament map skips the whole stage: the
  6373. materials this print loads want no chamber, so there is nothing to
  6374. soak for and the bed phase would only delay the upload (#3041).
  6375. An explicit 0 typed into the per-item override, or a per-item
  6376. 'on', still runs the bed phase and the soak — both are the user
  6377. asking for a warm bed in so many words.
  6378. 4. Three hardware tiers branch the wait loop:
  6379. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6380. send M141 to the resolved target, then wait for the chamber sensor
  6381. to reach it (or the max-wait timeout to elapse).
  6382. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6383. no M141; the bed is the only heat source, so we wait for the chamber
  6384. sensor to rise via bed radiation OR fall through on timeout.
  6385. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6386. temperature; the function just heats the bed and holds for the
  6387. configured soak duration.
  6388. The bed target comes from the archive's parsed metadata
  6389. (`bed_temperature`); if missing the preheat stage logs and returns
  6390. without dispatching anything, rather than guessing at a default that
  6391. might wreck filament setup.
  6392. Failures are logged but never re-raised — preheat is best-effort. A
  6393. printer that goes offline mid-soak, a refused gcode command, or a
  6394. missing temperature reading must not turn into a failed queue item; the
  6395. normal upload + start path runs immediately after this method returns.
  6396. """
  6397. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6398. if override == "off":
  6399. return True
  6400. if override == "inherit":
  6401. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6402. if not enabled:
  6403. return True
  6404. # override == "on" forces the stage on regardless of the global setting.
  6405. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6406. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6407. # Chamber target resolution:
  6408. # 1. Explicit per-item override beats everything (user knows best).
  6409. # 2. Otherwise derive from the filament types this print loads, via
  6410. # the per-filament target map. A PLA-only print derives 0 and the
  6411. # block below skips the stage without the user touching anything,
  6412. # even when an ASA spool is sitting in another slot of the same
  6413. # AMS (#2886).
  6414. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6415. if explicit_target is not None and explicit_target > 0:
  6416. chamber_target = int(explicit_target)
  6417. chamber_source = "item-override"
  6418. elif explicit_target == 0:
  6419. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6420. chamber_source = "item-override-zero"
  6421. else:
  6422. targets = await self._get_preheat_filament_targets(db)
  6423. chamber_target = self._derive_chamber_target(printer, targets, item)
  6424. chamber_source = "filament-map"
  6425. # Nothing to preheat *for*. A zero that came out of the filament map is
  6426. # the map saying this print's materials want no chamber conditioning --
  6427. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6428. # anyway heated the bed and then held it for the full soak, which
  6429. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6430. # own G-code sets the bed the moment it starts, so preheating it here
  6431. # only moves that heating ahead of the upload instead of overlapping
  6432. # with it, and the soak has no chamber to condition (#3041).
  6433. #
  6434. # An explicit statement from the user still runs the stage. Forcing the
  6435. # per-item override to 'on', or typing a chamber target of exactly 0,
  6436. # both mean "preheat the bed for this print" -- the second is
  6437. # documented as doing precisely that. Only the automatic path, the
  6438. # global toggle plus the filament map, short-circuits here.
  6439. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6440. logger.info(
  6441. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6442. "target, so there is nothing to soak for (override=%s model=%s)",
  6443. item.id,
  6444. override,
  6445. printer.model or "",
  6446. )
  6447. self._preheat_flap_to_cooling(item.id, printer)
  6448. return True
  6449. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6450. if bed_target <= 0:
  6451. # No bed temperature in the slicer metadata. When the print needs a
  6452. # hot chamber the bed is simply how we heat it, so fall back to the
  6453. # configured chamber-heating bed temperature rather than skipping
  6454. # the whole stage — otherwise the print starts with a cold chamber,
  6455. # which is exactly what preheat exists to prevent. Without a chamber
  6456. # requirement there is nothing to preheat *for*, so skip as before
  6457. # rather than guess a bed temperature for the print itself.
  6458. if chamber_target <= 0:
  6459. logger.info(
  6460. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6461. item.id,
  6462. )
  6463. return True
  6464. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6465. logger.info(
  6466. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6467. "%d°C to drive the chamber to %d°C",
  6468. item.id,
  6469. bed_target,
  6470. chamber_target,
  6471. )
  6472. client = printer_manager.get_client(printer.id)
  6473. if client is None:
  6474. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6475. return True
  6476. model = printer.model or ""
  6477. has_heater = supports_chamber_heater(model)
  6478. has_sensor = supports_chamber_temp(model)
  6479. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6480. # Fast path: if the chamber has been continuously above target for at
  6481. # least soak_seconds and the bed is already at temperature, skip the
  6482. # entire preheat stage. Typical case: keep-warm held the bed between
  6483. # consecutive same-material prints and the chamber never dropped.
  6484. if do_chamber and has_sensor and soak_seconds > 0:
  6485. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6486. if remaining == 0:
  6487. cur = printer_manager.get_status(printer.id)
  6488. if cur:
  6489. cur_temps = cur.temperatures or {}
  6490. if (
  6491. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6492. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6493. ):
  6494. logger.info(
  6495. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6496. "and bed is already at temperature (chamber history fast-path)",
  6497. item.id,
  6498. chamber_target,
  6499. soak_seconds,
  6500. )
  6501. # Still set targets to prevent cooling during the 3MF upload window.
  6502. # Register each successful set in the preheat pin so `_dispatch_one`
  6503. # unwinds them on any non-success exit.
  6504. pin = self._preheat_pin.setdefault(printer.id, set())
  6505. try:
  6506. client.set_bed_temperature(bed_target)
  6507. pin.add("bed")
  6508. self._preheat_pin_bed[printer.id] = bed_target
  6509. except Exception as exc:
  6510. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6511. if supports_airduct(model):
  6512. cur_airduct = getattr(cur, "airduct_mode", None)
  6513. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6514. try:
  6515. client.set_airduct_mode("heating")
  6516. # Only undo what we can see we replaced. `None`
  6517. # means no mode has been observed yet, and
  6518. # rolling that back to cooling would assert a
  6519. # state the printer never reported.
  6520. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6521. pin.add("airduct")
  6522. except Exception as exc:
  6523. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6524. if has_heater:
  6525. try:
  6526. client.set_chamber_temperature(chamber_target)
  6527. pin.add("chamber")
  6528. except Exception as exc:
  6529. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6530. return True
  6531. logger.info(
  6532. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6533. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6534. item.id,
  6535. bed_target,
  6536. chamber_target if do_chamber else 0,
  6537. chamber_source,
  6538. override,
  6539. model,
  6540. has_heater,
  6541. has_sensor,
  6542. max_wait,
  6543. soak_seconds,
  6544. )
  6545. # Preheat rollback registry: everything we set below is recorded here so
  6546. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6547. # (bed off, chamber off, airduct back to cooling) on any non-success
  6548. # exit. Populated as each command succeeds; consumed and cleared by
  6549. # `_dispatch_one`.
  6550. pin = self._preheat_pin.setdefault(printer.id, set())
  6551. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6552. # cache the target locally so the polling reads below see consistent
  6553. # state (firmware MQTT echoes lag by ~1s).
  6554. try:
  6555. client.set_bed_temperature(bed_target)
  6556. pin.add("bed")
  6557. self._preheat_pin_bed[printer.id] = bed_target
  6558. except Exception as exc:
  6559. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6560. return True
  6561. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6562. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6563. # left it on, regardless of M141. Default cooling actively vents the
  6564. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6565. # cooling never converges — the heater fights the open exhaust. We
  6566. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6567. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6568. # on an H2D that was previously running ABS would otherwise stay in
  6569. # heating mode and overheat PLA). The current-state read keeps the
  6570. # command idempotent — no MQTT chatter when the flap is already where
  6571. # we want it.
  6572. if supports_airduct(model):
  6573. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6574. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6575. current_state = printer_manager.get_status(printer.id)
  6576. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6577. if current_airduct != desired_id:
  6578. try:
  6579. client.set_airduct_mode(desired_airduct)
  6580. # As in the fast path: only pin a rollback for a flap we
  6581. # saw in cooling. `current_airduct` of None means no mode
  6582. # has been observed, so there is nothing to restore to.
  6583. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6584. pin.add("airduct")
  6585. except Exception as exc:
  6586. logger.warning(
  6587. "Queue item %s: preheat airduct %s mode failed: %s",
  6588. item.id,
  6589. desired_airduct,
  6590. exc,
  6591. )
  6592. if do_chamber and has_heater:
  6593. try:
  6594. client.set_chamber_temperature(chamber_target)
  6595. pin.add("chamber")
  6596. except Exception as exc:
  6597. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6598. # Release the pooled DB connection before the (potentially many-minute)
  6599. # heat-soak wait below (#2572). Every setting this method needs is read
  6600. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6601. # it never touches the DB. Without this the caller's transaction sat
  6602. # "idle in transaction" for the whole soak, pinning one pooled connection
  6603. # per preheating printer. expire_on_commit=False keeps item/printer
  6604. # readable afterwards; there are no pending writes to lose here.
  6605. await db.commit()
  6606. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6607. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6608. # Poll every 3s — frequent enough for responsive logging without
  6609. # spamming the MQTT state stream. The "converged" predicate is:
  6610. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6611. # AND
  6612. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6613. BED_TOLERANCE = 2.0
  6614. CHAMBER_TOLERANCE = 2.0
  6615. POLL_INTERVAL = 3.0
  6616. deadline = asyncio.get_event_loop().time() + max_wait
  6617. while True:
  6618. state = printer_manager.get_status(printer.id)
  6619. if state is None:
  6620. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6621. break
  6622. temps = state.temperatures or {}
  6623. bed_now = float(temps.get("bed", 0) or 0)
  6624. chamber_now = float(temps.get("chamber", 0) or 0)
  6625. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6626. if not do_chamber:
  6627. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6628. elif not has_sensor:
  6629. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6630. else:
  6631. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6632. if bed_ok and chamber_ok:
  6633. logger.info(
  6634. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6635. item.id,
  6636. bed_now,
  6637. chamber_now,
  6638. )
  6639. break
  6640. if asyncio.get_event_loop().time() >= deadline:
  6641. logger.info(
  6642. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6643. item.id,
  6644. bed_now,
  6645. bed_target,
  6646. chamber_now,
  6647. chamber_target if do_chamber else 0,
  6648. )
  6649. break
  6650. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6651. logger.info(
  6652. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6653. item.id,
  6654. )
  6655. return False
  6656. if soak_seconds > 0:
  6657. if do_chamber and has_sensor:
  6658. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6659. else:
  6660. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6661. if remaining > 0:
  6662. logger.info(
  6663. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6664. "has been above target for ~%ds already)",
  6665. item.id,
  6666. remaining,
  6667. soak_seconds,
  6668. soak_seconds - remaining,
  6669. )
  6670. if not await self._preheat_sleep(item.id, remaining):
  6671. logger.info(
  6672. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6673. item.id,
  6674. )
  6675. return False
  6676. else:
  6677. logger.info(
  6678. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6679. item.id,
  6680. chamber_target,
  6681. soak_seconds,
  6682. )
  6683. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6684. return True
  6685. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6686. """Turn on smart plug and wait for printer to connect.
  6687. Returns True if printer connected successfully within timeout.
  6688. """
  6689. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6690. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6691. # Check current plug state
  6692. status = await service.get_status(plug)
  6693. if not status.get("reachable"):
  6694. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6695. return False
  6696. # Turn on if not already on
  6697. if status.get("state") != "ON":
  6698. success = await service.turn_on(plug)
  6699. if not success:
  6700. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6701. return False
  6702. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  6703. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6704. # Get printer from database for connection
  6705. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6706. printer = result.scalar_one_or_none()
  6707. if not printer:
  6708. logger.error("Printer %s not found in database", printer_id)
  6709. return False
  6710. # Wait for printer to boot (give it some time before trying to connect)
  6711. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6712. await asyncio.sleep(30)
  6713. # Try to connect to the printer periodically
  6714. elapsed = 30 # Already waited 30s
  6715. while elapsed < self._power_on_wait_time:
  6716. # Try to connect
  6717. logger.info("Attempting to connect to printer %s...", printer_id)
  6718. try:
  6719. connected = await printer_manager.connect_printer(printer)
  6720. if connected:
  6721. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6722. # Give it a moment to stabilize and get status
  6723. await asyncio.sleep(5)
  6724. return True
  6725. except Exception as e:
  6726. logger.debug("Connection attempt failed: %s", e)
  6727. await asyncio.sleep(self._power_on_check_interval)
  6728. elapsed += self._power_on_check_interval
  6729. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6730. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6731. return False
  6732. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  6733. """Check if the previous print on this printer succeeded.
  6734. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6735. deliberate action, not a failure, so subsequent items should still
  6736. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6737. a skip isn't an actual print attempt, so it must not gate downstream
  6738. items — counting it as a failed predecessor was the cascade bug that
  6739. let a single cancellation block 18 items over 3 days for the reporter.
  6740. Only `failed` and `aborted` — real print-attempt failures — block.
  6741. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6742. action — #1818) are also excluded from the lookback so the user can
  6743. clear the gate after fixing the physical issue without having to
  6744. re-queue every downstream job.
  6745. """
  6746. result = await db.execute(
  6747. select(PrintQueueItem)
  6748. .where(PrintQueueItem.printer_id == item.printer_id)
  6749. .where(PrintQueueItem.id != item.id)
  6750. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6751. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6752. .order_by(PrintQueueItem.completed_at.desc())
  6753. .limit(1)
  6754. )
  6755. prev_item = result.scalar_one_or_none()
  6756. # If no previous item, assume success (first in queue)
  6757. if not prev_item:
  6758. return True
  6759. return prev_item.status in ("completed", "cancelled")
  6760. async def _repoint_siblings_at_archive(
  6761. self,
  6762. db: AsyncSession,
  6763. *,
  6764. consumed_library_file_id: int,
  6765. archive_id: int,
  6766. dispatched_item_id: int,
  6767. ) -> int:
  6768. """Move the other queue items off a library row that is about to be deleted (#2819).
  6769. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6770. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6771. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6772. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6773. clones, so the first dispatch could pull the file out from under rows that
  6774. had not run yet. What those rows did next depended on the database, and
  6775. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6776. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6777. they were left pointing at a row that no longer existed, failing with
  6778. "Library file not found" whenever someone started them -- or sitting
  6779. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6780. constraint, so there the rows were deleted outright and the queued copies
  6781. simply vanished, with no error and no history.
  6782. The archive holds its own copy of the 3MF, so the remaining copies can print
  6783. from it instead. Two things happen here, and both must happen *before* the
  6784. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6785. * every row still naming the file has ``library_file_id`` cleared, which is
  6786. what takes it out of the cascade's reach. That covers rows this cannot
  6787. re-point as well -- a copy already printing from its own archive, and the
  6788. finished ones, which are not spare parts but the record a batch order
  6789. counts its progress from.
  6790. * the rows that still need something to print are pointed at the archive.
  6791. Returns how many items were re-pointed.
  6792. """
  6793. variant_item_ids = (
  6794. (
  6795. await db.execute(
  6796. select(PrintQueueVariant.queue_item_id).where(
  6797. PrintQueueVariant.library_file_id == consumed_library_file_id
  6798. )
  6799. )
  6800. )
  6801. .scalars()
  6802. .all()
  6803. )
  6804. # Candidate rows naming the consumed file have to go rather than be
  6805. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  6806. # one out of the cascade. This is what PostgreSQL already does, and
  6807. # _candidates_for skips such a variant on SQLite anyway, so no selection
  6808. # outcome changes -- the two backends simply stop disagreeing about
  6809. # whether the row is still there.
  6810. #
  6811. # It also has to happen before the re-point below: a cross-model item
  6812. # (#671) picks a variant every pass and folds it onto the row, and
  6813. # _resolve_variant clears archive_id as it does so, which would undo the
  6814. # re-point on the very next lap.
  6815. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  6816. # An item left with other candidates still has somewhere to go, and those
  6817. # carry their own target model -- pointing it at this archive would print a
  6818. # file the matcher never chose. It is excluded from the re-point and simply
  6819. # re-resolves against what is left.
  6820. surviving_variant_item_ids = set(
  6821. (
  6822. await db.execute(
  6823. select(PrintQueueVariant.queue_item_id).where(
  6824. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  6825. )
  6826. )
  6827. )
  6828. .scalars()
  6829. .all()
  6830. )
  6831. repoint_ids = set(
  6832. (
  6833. await db.execute(
  6834. select(PrintQueueItem.id)
  6835. .where(PrintQueueItem.id != dispatched_item_id)
  6836. .where(PrintQueueItem.archive_id.is_(None))
  6837. # "skipped" belongs here with the two live states: it is not
  6838. # terminal. Clearing a printer's previous-success gate puts
  6839. # every item skipped by it back to "pending"
  6840. # (resume_after_failure), and one restored onto a deleted
  6841. # file is the same orphan by a slower route. "failed",
  6842. # "cancelled", "aborted" and "completed" never return.
  6843. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  6844. .where(
  6845. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  6846. )
  6847. .where(
  6848. or_(
  6849. PrintQueueItem.library_file_id == consumed_library_file_id,
  6850. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  6851. )
  6852. )
  6853. )
  6854. )
  6855. .scalars()
  6856. .all()
  6857. )
  6858. if repoint_ids:
  6859. await db.execute(
  6860. update(PrintQueueItem)
  6861. .where(PrintQueueItem.id.in_(repoint_ids))
  6862. .values(
  6863. archive_id=archive_id,
  6864. library_file_id=None,
  6865. # The file this flag named is already consumed. Leaving it set
  6866. # would arm every re-pointed copy to delete whatever library
  6867. # row it is next given.
  6868. cleanup_library_after_dispatch=False,
  6869. )
  6870. )
  6871. logger.info(
  6872. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  6873. sorted(repoint_ids),
  6874. archive_id,
  6875. consumed_library_file_id,
  6876. dispatched_item_id,
  6877. )
  6878. # Everything else that still names the file: taken out of the cascade's
  6879. # reach without touching what it prints. The file is gone either way; what
  6880. # this preserves is the row.
  6881. await db.execute(
  6882. update(PrintQueueItem)
  6883. .where(PrintQueueItem.id != dispatched_item_id)
  6884. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  6885. .values(library_file_id=None)
  6886. )
  6887. return len(repoint_ids)
  6888. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  6889. """Schedule power-off if the queue item enabled auto_off_after.
  6890. Delegates to the smart-plug manager so the off honours each plug's
  6891. configured strategy (time delay or temperature threshold), is cancelled
  6892. if the printer starts printing again, and never cuts power on a loaded
  6893. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  6894. powered off on the timeout regardless of print state.
  6895. """
  6896. if not item.auto_off_after:
  6897. return
  6898. try:
  6899. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  6900. except Exception as e:
  6901. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  6902. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  6903. """Get a human-readable name for a queue item."""
  6904. if item.archive_id:
  6905. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  6906. archive = result.scalar_one_or_none()
  6907. if archive:
  6908. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6909. if item.library_file_id:
  6910. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  6911. library_file = result.scalar_one_or_none()
  6912. if library_file:
  6913. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6914. # A cross-model item (#671) holds no file of its own until a printer is
  6915. # picked, so name it after its first candidate — otherwise every waiting
  6916. # notification for one reads "Job #12". Queried rather than read off
  6917. # item.variants because callers outside the selection loop have not
  6918. # eager-loaded them, and a lazy load raises in async.
  6919. first_variant_name = (
  6920. await db.execute(
  6921. select(LibraryFile.filename)
  6922. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  6923. .where(PrintQueueVariant.queue_item_id == item.id)
  6924. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  6925. .limit(1)
  6926. )
  6927. ).scalar_one_or_none()
  6928. if first_variant_name:
  6929. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  6930. return f"Job #{item.id}"
  6931. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  6932. """Get printer by ID."""
  6933. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6934. return result.scalar_one_or_none()
  6935. async def _notify_dispatch_gave_up(
  6936. self,
  6937. queue_item_id: int,
  6938. printer_id: int,
  6939. created_by_id: int | None,
  6940. reason: str = "Printer accepted the file but never started printing",
  6941. ) -> None:
  6942. """Tell the user the queue item was failed after exhausting its dispatch retries.
  6943. Called from the watchdog, which is a background task with no session of
  6944. its own — hence the fresh one here. Best-effort throughout: the row is
  6945. already marked failed and that is the load-bearing part; a notification
  6946. provider being down must not resurrect the retry loop we just stopped.
  6947. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  6948. path passes its own, because "accepted the file but never started" is the
  6949. opposite of what happened there — the printer refused it outright (#2732).
  6950. """
  6951. try:
  6952. async with async_session() as db:
  6953. item = await db.get(PrintQueueItem, queue_item_id)
  6954. if not item:
  6955. return
  6956. job_name = await self._get_job_name(db, item)
  6957. printer = await self._get_printer(db, printer_id)
  6958. await notification_service.on_queue_job_failed(
  6959. job_name=job_name,
  6960. printer_id=printer_id,
  6961. printer_name=printer.name if printer else "Unknown",
  6962. reason=reason,
  6963. db=db,
  6964. )
  6965. except Exception as e:
  6966. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  6967. try:
  6968. await ws_manager.send_queue_item_failed(
  6969. user_id=created_by_id,
  6970. queue_item_id=queue_item_id,
  6971. printer_id=printer_id,
  6972. reason="never_started",
  6973. )
  6974. except Exception:
  6975. pass # toast is best-effort
  6976. async def _filament_short_on(
  6977. self,
  6978. db: AsyncSession,
  6979. item: PrintQueueItem,
  6980. printer_id: int,
  6981. *,
  6982. require_known: bool = False,
  6983. ) -> bool:
  6984. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  6985. Asks what ``_block_on_filament_deficit`` would answer once the item is
  6986. assigned there, with the mapping the item would get there, but changes
  6987. nothing. The model-based matcher uses it to prefer a printer whose
  6988. spools can finish the job.
  6989. False whenever the gate would let the item through: "Print Anyway",
  6990. no mapping, or a check that fails. With ``require_known`` all three of
  6991. those, and any printed slot whose remaining amount is unknown, count
  6992. as short instead: releasing a held job starts it with nobody asked, so
  6993. it needs the amount on record, not merely nothing against it.
  6994. """
  6995. if item.skip_filament_check:
  6996. return False
  6997. try:
  6998. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  6999. if not mapping:
  7000. return require_known
  7001. deficit = await compute_deficit_for_queue_item(
  7002. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7003. )
  7004. except Exception as e:
  7005. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7006. return require_known
  7007. return bool(deficit)
  7008. async def _release_short_model_hold(
  7009. self,
  7010. db: AsyncSession,
  7011. item: PrintQueueItem,
  7012. unavailable: set[int],
  7013. require_plate_clear: bool,
  7014. printer_scope: PrinterScope,
  7015. ) -> bool:
  7016. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7017. The deficit gate holds a model-based job on the printer the matcher
  7018. gave it, because "Print Anyway" needs a printer to print on. When
  7019. another idle printer of the job's model has the filament, the job is
  7020. moved to that printer and its hold lifted, and the fixed-printer
  7021. branch dispatches it in this same pass, through the same checks a
  7022. held job meets when the user presses Start. It is moved rather than
  7023. put back in the pool because the model-based branch would pick again
  7024. without requiring the amounts on record (below), and could pick a
  7025. different printer. Only the deficit gate sets ``filament_short``, so a
  7026. job held for any other reason stays held.
  7027. The printer it is held on is left out: a spool loaded there is started
  7028. with Start, as before, rather than while someone may still be loading
  7029. the next one. Each job is checked at most every
  7030. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7031. on each idle printer again.
  7032. Cross-model jobs (#671) stay held: checking a variant writes its file
  7033. onto the item, which would leave a job that is not moved holding
  7034. another variant's file for the printer it waits on.
  7035. A printer qualifies only on a positive finding: every slot the plate
  7036. prints mapped to a spool whose remaining amount is on record and
  7037. enough. A printer whose spools Bambuddy does not track is not one.
  7038. Returns True when the job was moved. A check that fails keeps the hold
  7039. rather than stopping the queue pass.
  7040. """
  7041. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7042. return False
  7043. if not item.target_model or item.variants:
  7044. return False
  7045. now = time.monotonic()
  7046. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7047. return False
  7048. self._short_hold_checked_at[item.id] = now
  7049. try:
  7050. candidates = _candidates_for(item)
  7051. if not candidates:
  7052. return False
  7053. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7054. async def is_short(pid: int) -> bool:
  7055. return await self._filament_short_on(db, item, pid, require_known=True)
  7056. match_id, _ = await self._find_idle_printer_for_model(
  7057. db,
  7058. item.target_model,
  7059. unavailable | {item.printer_id},
  7060. effective_types,
  7061. item.target_location,
  7062. filament_overrides=filament_overrides,
  7063. require_plate_clear=require_plate_clear,
  7064. printer_scope=printer_scope,
  7065. is_short=is_short,
  7066. )
  7067. # Every idle printer short comes back as the first of them.
  7068. if match_id is None or await is_short(match_id):
  7069. return False
  7070. except Exception as e:
  7071. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7072. return False
  7073. logger.info(
  7074. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7075. item.id,
  7076. match_id,
  7077. item.printer_id,
  7078. )
  7079. self._short_hold_checked_at.pop(item.id, None)
  7080. item.printer_id = match_id
  7081. # Resolved against the printer it leaves (#3239).
  7082. item.ams_mapping = None
  7083. item.manual_start = False
  7084. item.filament_short = False
  7085. item.waiting_reason = None
  7086. await db.commit()
  7087. try:
  7088. printer = await self._get_printer(db, match_id)
  7089. await notification_service.on_queue_job_assigned(
  7090. job_name=await self._get_job_name(db, item),
  7091. printer_id=match_id,
  7092. printer_name=printer.name if printer else "Unknown",
  7093. target_model=item.target_model,
  7094. db=db,
  7095. )
  7096. except Exception as e:
  7097. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7098. return True
  7099. async def _block_on_filament_deficit(
  7100. self,
  7101. db: AsyncSession,
  7102. item: PrintQueueItem,
  7103. ) -> bool:
  7104. """Promote the item to manual_start when the assigned spool is short (#1496).
  7105. Returns True when this dispatch attempt was blocked, False when the
  7106. item is clear to start. A previously-flagged item whose spool has
  7107. since been swapped to one with enough material clears the flag here
  7108. so the next scheduler tick dispatches it.
  7109. """
  7110. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7111. # don't re-flag, don't even compute. Without this short-circuit the
  7112. # scheduler bounces between "user said anyway" (route clears
  7113. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7114. # on identical spool state) (#1698-followup).
  7115. if item.skip_filament_check:
  7116. # #1762 diagnostic: surface the short-circuit at INFO so a
  7117. # future "Print Anyway didn't work" report (e.g. issue #1762
  7118. # comment 3) has actionable evidence in the support bundle
  7119. # without needing DEBUG enabled.
  7120. logger.info(
  7121. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7122. item.id,
  7123. )
  7124. return False
  7125. try:
  7126. deficit = await compute_deficit_for_queue_item(db, item)
  7127. except Exception as e:
  7128. # Never let a flaky deficit check wedge the queue — log and let
  7129. # dispatch proceed. The PrintModal-side check still runs on the
  7130. # manual paths.
  7131. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7132. return False
  7133. if deficit:
  7134. item.filament_short = True
  7135. item.manual_start = True
  7136. await db.commit()
  7137. job_name = await self._get_job_name(db, item)
  7138. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7139. logger.info(
  7140. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7141. item.id,
  7142. len(deficit),
  7143. )
  7144. try:
  7145. await notification_service.on_queue_job_waiting(
  7146. job_name=job_name,
  7147. target_model=(printer.model if printer else "") or "",
  7148. waiting_reason="filament_short",
  7149. db=db,
  7150. )
  7151. except Exception as e:
  7152. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7153. return True
  7154. # No deficit — clear any stale flag from a previous tick.
  7155. if item.filament_short:
  7156. item.filament_short = False
  7157. await db.commit()
  7158. return False
  7159. async def _block_on_unmatched_filament(
  7160. self,
  7161. db: AsyncSession,
  7162. item: PrintQueueItem,
  7163. release_assignment: bool = False,
  7164. ) -> bool:
  7165. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7166. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7167. goes ahead, letting the printer choose — which is how a job prints in the
  7168. wrong material without anyone being asked. Holding is the same answer the
  7169. deficit gate already gives for "the spool is too light", so it reuses the
  7170. same promote-and-notify machinery.
  7171. Keyed off unresolved slots in the *computed* mapping intersected with the
  7172. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7173. read: on its own it also pads slots this plate does not print, so the
  7174. array alone would hold perfectly good jobs. Reading the mapping rather
  7175. than the printer's loaded filament types also inherits the matcher's
  7176. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7177. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7178. type-only scan would wave that through.
  7179. A mapping that resolved *nothing* is the same finding arriving as an
  7180. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7181. could not replace, and dispatch then goes out as ``use_ams`` with no
  7182. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7183. That is held too, but only once live status positively reports loaded
  7184. trays: #2589's mapping is bogus precisely because the AMS was not known
  7185. yet, and its empty loaded list is that ignorance rather than a miss.
  7186. ``release_assignment`` is for the model-based path, which commits its
  7187. printer choice before the gates run. Holding an "any P2S" job would
  7188. otherwise pin it to the one P2S that could not run it.
  7189. Returns True when this dispatch attempt was blocked.
  7190. """
  7191. if item.skip_filament_check or not item.printer_id:
  7192. return False
  7193. if item.ams_mapping:
  7194. try:
  7195. mapping = json.loads(item.ams_mapping)
  7196. except (json.JSONDecodeError, TypeError):
  7197. return False
  7198. if not isinstance(mapping, list):
  7199. return False
  7200. else:
  7201. # Nothing resolved, or nothing survived revalidation. Only a printer
  7202. # that reported loaded trays makes that a finding — see the
  7203. # docstring on why an empty list is not one.
  7204. status = printer_manager.get_status(item.printer_id)
  7205. if status is None or not self._build_loaded_filaments(status):
  7206. return False
  7207. # Every required slot reads unresolved against an empty mapping.
  7208. mapping = []
  7209. required = await self._get_filament_requirements(db, item)
  7210. if not required:
  7211. return False
  7212. self._apply_filament_overrides(item, required)
  7213. unmatched = _unresolved_required(required, mapping)
  7214. if not unmatched:
  7215. # No cleanup needed here: once start is pressed the item is no
  7216. # longer staged, and whichever exit runs next overwrites the reason
  7217. # (`hold_item` on the fixed-printer branch, the assignment on the
  7218. # model-based one), as does dispatch.
  7219. return False
  7220. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7221. held_by = item.printer_id
  7222. item.manual_start = True
  7223. # Human-readable: this renders on the queue row.
  7224. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7225. if release_assignment:
  7226. # "Any P2S" means any, so the job returns to the pool rather than
  7227. # waiting on the printer that could not take it. The mapping goes
  7228. # with the assignment: its tray IDs were resolved against the
  7229. # printer being released and mean nothing on the next one (#2799),
  7230. # and keeping them would hold the job again even on a printer that
  7231. # has the filament, since an unresolved slot is deliberately not a
  7232. # conflict worth recomputing over.
  7233. item.printer_id = None
  7234. item.ams_mapping = None
  7235. await db.commit()
  7236. job_name = await self._get_job_name(db, item)
  7237. printer = await self._get_printer(db, held_by)
  7238. logger.info(
  7239. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7240. item.id,
  7241. held_by,
  7242. wanted,
  7243. )
  7244. try:
  7245. await notification_service.on_queue_job_waiting(
  7246. job_name=job_name,
  7247. target_model=(printer.model if printer else "") or "",
  7248. waiting_reason=f"needs {wanted}",
  7249. db=db,
  7250. )
  7251. except Exception as e:
  7252. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7253. return True
  7254. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7255. """Hand the queue item's owner to printer_manager so the
  7256. print-complete callback can credit the user in PrintLogEntry (#1670).
  7257. No-ops when the item has no `created_by_id` or the referenced user
  7258. row is missing (e.g. user deleted between queue-add and dispatch —
  7259. in that case the print log row falls back to the existing un-credited
  7260. behaviour rather than crashing the dispatch).
  7261. """
  7262. if not item.created_by_id:
  7263. return
  7264. from backend.app.models.user import User
  7265. owner = await db.get(User, item.created_by_id)
  7266. if owner:
  7267. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  7268. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7269. """Upload file and start print for a queue item.
  7270. Supports two sources:
  7271. - archive_id: Print from an existing archive
  7272. - library_file_id: Print from a library file (file manager)
  7273. """
  7274. logger.info("Starting queue item %s", item.id)
  7275. # Also covers a reservation left active by a process interruption
  7276. # during an earlier attempt. `_dispatch_one` releases this marker on
  7277. # every exit unless start_print() confirms that the command was sent.
  7278. self._unconfirmed_budget_reservations.add(item.id)
  7279. try:
  7280. from backend.app.models.user import User
  7281. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7282. # Recompute at the final authorization boundary as well as enqueue
  7283. # time. This covers rows created before the server-side estimate
  7284. # migration and prevents any alternate write path from weakening
  7285. # the budget reservation.
  7286. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7287. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7288. item.estimated_cost = await estimate_queue_source_cost(
  7289. db,
  7290. archive=archive,
  7291. library_file=library_file,
  7292. plate_id=item.plate_id,
  7293. ams_mapping=item.ams_mapping,
  7294. printer_id=item.printer_id,
  7295. )
  7296. await validate_print_budget(
  7297. db,
  7298. cost_center_id=item.cost_center_id,
  7299. estimated_cost=item.estimated_cost,
  7300. current_user=queue_user,
  7301. exclude_queue_item_id=item.id,
  7302. exclude_reservation_source_type="print_queue",
  7303. exclude_reservation_source_id=item.id,
  7304. )
  7305. budget_reservation = await create_budget_reservation(
  7306. db,
  7307. cost_center_id=item.cost_center_id,
  7308. estimated_cost=item.estimated_cost,
  7309. current_user=queue_user,
  7310. source_type="print_queue",
  7311. source_id=item.id,
  7312. print_archive_id=item.archive_id,
  7313. exclude_queue_item_id=item.id,
  7314. )
  7315. await db.commit()
  7316. except HTTPException as exc:
  7317. item.status = "failed"
  7318. item.error_message = str(exc.detail)
  7319. item.completed_at = datetime.now(timezone.utc)
  7320. await db.commit()
  7321. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7322. await self._power_off_if_needed(db, item)
  7323. return
  7324. # Get printer first (needed for both paths)
  7325. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7326. printer = result.scalar_one_or_none()
  7327. if not printer:
  7328. item.status = "failed"
  7329. item.error_message = "Printer not found"
  7330. item.completed_at = datetime.now(timezone.utc)
  7331. await db.commit()
  7332. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7333. await self._power_off_if_needed(db, item)
  7334. return
  7335. # Check printer is connected
  7336. if not printer_manager.is_connected(item.printer_id):
  7337. item.status = "failed"
  7338. item.error_message = "Printer not connected"
  7339. item.completed_at = datetime.now(timezone.utc)
  7340. await db.commit()
  7341. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7342. await self._power_off_if_needed(db, item)
  7343. return
  7344. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7345. # `items` was taken at the top of check_queue, but the user can /cancel
  7346. # any pending row in the gap before we reach this point. Re-read the
  7347. # row and bail out cleanly instead of starting an FTP upload for a row
  7348. # that's already cancelled. The atomic CAS at the pending→printing
  7349. # transition (below, before start_print) is the load-bearing guard;
  7350. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7351. await db.refresh(item)
  7352. if item.status != "pending":
  7353. logger.info(
  7354. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7355. item.id,
  7356. item.status,
  7357. )
  7358. return
  7359. # Busy-printer guard (#2598). check_queue gates dispatch on
  7360. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7361. # keep reporting FINISH for tens of seconds *after* it accepted a
  7362. # project_file (see the watchdog's phase-B note). A watchdog revert
  7363. # (#2555) also releases the dispatch hold, so a re-selected item can
  7364. # reach here while its printer has actually started printing. Uploading
  7365. # and dispatching then collides with the live job — the firmware answers
  7366. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7367. # live state right before the expensive FTP upload: if the printer is
  7368. # busy, leave the item pending and let a later tick dispatch it once the
  7369. # printer is genuinely idle. No wasted upload, no collision.
  7370. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7371. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7372. logger.info(
  7373. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7374. "leaving item pending for a later tick (#2598)",
  7375. item.id,
  7376. item.printer_id,
  7377. pre_dispatch_state,
  7378. )
  7379. return
  7380. # Determine source: archive or library file
  7381. archive = None
  7382. library_file = None
  7383. file_path = None
  7384. filename = None
  7385. cleanup_disk_paths: list[Path] = []
  7386. # Set when a dispatch consumes its library file, so the photos can be
  7387. # carried over after the commit that removes the row (#3077).
  7388. consumed_library_file_id: int | None = None
  7389. consumed_photos: list[str] = []
  7390. if item.archive_id:
  7391. # Print from archive
  7392. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7393. archive = result.scalar_one_or_none()
  7394. if not archive:
  7395. item.status = "failed"
  7396. item.error_message = "Archive not found"
  7397. item.completed_at = datetime.now(timezone.utc)
  7398. await db.commit()
  7399. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7400. await self._power_off_if_needed(db, item)
  7401. return
  7402. # Persist the queue item's selected plate onto the archive so Print
  7403. # History can show the actual plate after cancel/fail/complete (#2603).
  7404. # Only when the archive doesn't already carry one, so a reprint of a
  7405. # plate-specific archive isn't relabelled by a differently-plated
  7406. # queue row.
  7407. if archive.plate_id is None and item.plate_id is not None:
  7408. archive.plate_id = item.plate_id
  7409. # Ask-for-outcome opt-in rides from the queue item to the archive
  7410. # the same way (#1898); never cleared here so a reprint of an
  7411. # archive that already asked keeps asking.
  7412. if item.confirm_outcome:
  7413. archive.confirm_requested = True
  7414. file_path = settings.base_dir / archive.file_path
  7415. filename = archive.filename
  7416. elif item.library_file_id:
  7417. # Print from library file (file manager)
  7418. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7419. library_file = result.scalar_one_or_none()
  7420. if not library_file:
  7421. # "Not found" covers two different situations and only one of
  7422. # them is recoverable, so say which. A trashed file is still
  7423. # there and restoring it makes a re-queued job work; a file that
  7424. # is really gone needs a different one. Neither is knowable from
  7425. # the queue, which is the whole complaint about this message.
  7426. trashed = (
  7427. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7428. ).scalar_one_or_none()
  7429. item.status = "failed"
  7430. item.error_message = (
  7431. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7432. if trashed
  7433. else "Library file not found — it was deleted after this job was queued"
  7434. )
  7435. item.completed_at = datetime.now(timezone.utc)
  7436. await db.commit()
  7437. logger.error(
  7438. "Queue item %s: library file %s is %s",
  7439. item.id,
  7440. item.library_file_id,
  7441. "in the trash" if trashed else "gone",
  7442. )
  7443. await self._power_off_if_needed(db, item)
  7444. return
  7445. # Library files store absolute paths
  7446. lib_path = Path(library_file.file_path)
  7447. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7448. filename = library_file.filename
  7449. # Create archive from library file so usage tracking has access to the 3MF
  7450. queue_item_id = item.id
  7451. # Held separately: a cleanup dispatch clears item.library_file_id
  7452. # below, and the log line at the end of this block reported that
  7453. # cleared field -- so every consumed print logged "from library
  7454. # file None", which is the one case worth being able to trace.
  7455. source_library_file_id = item.library_file_id
  7456. try:
  7457. from backend.app.services.archive import ArchiveService
  7458. archive_service = ArchiveService(db)
  7459. archive = await archive_service.archive_print(
  7460. printer_id=item.printer_id,
  7461. source_file=file_path,
  7462. original_filename=filename,
  7463. created_by_id=item.created_by_id,
  7464. project_id=item.project_id,
  7465. cost_center_id=item.cost_center_id,
  7466. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7467. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7468. )
  7469. if archive:
  7470. item.archive_id = archive.id
  7471. if item.confirm_outcome:
  7472. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7473. if budget_reservation is not None:
  7474. budget_reservation.print_archive_id = archive.id
  7475. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7476. consumed_library_file_id = library_file.id
  7477. item.library_file_id = None
  7478. cleanup_disk_paths.append(file_path)
  7479. if library_file.thumbnail_path:
  7480. thumb_path = Path(library_file.thumbnail_path)
  7481. if not thumb_path.is_absolute():
  7482. thumb_path = settings.base_dir / library_file.thumbnail_path
  7483. cleanup_disk_paths.append(thumb_path)
  7484. # Before the delete, not after: on PostgreSQL the FK
  7485. # cascade would already have taken these rows (#2819).
  7486. await self._repoint_siblings_at_archive(
  7487. db,
  7488. consumed_library_file_id=consumed_library_file_id,
  7489. archive_id=archive.id,
  7490. dispatched_item_id=item.id,
  7491. )
  7492. # Read while the row is still here; the photos move
  7493. # below, once the delete has actually committed.
  7494. consumed_photos = list(library_file.photos or [])
  7495. await db.delete(library_file)
  7496. file_path = settings.base_dir / archive.file_path
  7497. filename = archive.filename
  7498. # Commit, not flush — flush opens the SQLite write
  7499. # transaction (item.archive_id update + library_file
  7500. # delete) and would hold the WAL writer lock through the
  7501. # FTP upload below, causing "database is locked" cascades
  7502. # for sensor history + concurrent cancels (#1853).
  7503. await db.commit()
  7504. logger.info(
  7505. "Queue item %s: Created archive %s from library file %s",
  7506. item.id,
  7507. archive.id,
  7508. source_library_file_id,
  7509. )
  7510. except Exception as e:
  7511. logger.warning(
  7512. "Queue item %s: Failed to create archive from library file: %s",
  7513. queue_item_id,
  7514. e,
  7515. exc_info=True,
  7516. )
  7517. await db.rollback()
  7518. item = await db.get(PrintQueueItem, queue_item_id)
  7519. if item:
  7520. item.status = "failed"
  7521. item.error_message = "Failed to create archive from library file"
  7522. item.completed_at = datetime.now(timezone.utc)
  7523. await db.commit()
  7524. await self._power_off_if_needed(db, item)
  7525. return
  7526. if not archive:
  7527. item.status = "failed"
  7528. item.error_message = "Failed to create archive from library file"
  7529. item.completed_at = datetime.now(timezone.utc)
  7530. await db.commit()
  7531. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7532. await self._power_off_if_needed(db, item)
  7533. return
  7534. # The photos follow the file into the archive that replaces it, for
  7535. # the same reason the siblings do (#3077). After the commit above,
  7536. # never before it: that commit can fail ("database is locked",
  7537. # #1853) and roll the library row back, and photos already moved
  7538. # would leave it naming a directory that no longer exists. The
  7539. # file and thumbnail unlinks are deferred for the same reason.
  7540. if consumed_library_file_id is not None and consumed_photos:
  7541. # Held as a plain int, read here while the session is still
  7542. # healthy, because the handler below may not touch an ORM
  7543. # instance at all. The commit it exists for fails inside the
  7544. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7545. # first DML statement, so a busy writer surfaces as "database
  7546. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7547. # internally through safe_reraise before re-raising, which
  7548. # expires every loaded instance and leaves the session in
  7549. # pending-rollback state -- so `archive.id` inside the except
  7550. # would itself raise PendingRollbackError and the rollback
  7551. # below would never be reached.
  7552. archive_id = archive.id
  7553. try:
  7554. carried_photos = move_library_photos(
  7555. consumed_library_file_id,
  7556. consumed_photos,
  7557. archive_photos_dir(archive),
  7558. )
  7559. if carried_photos:
  7560. archive.photos = list(archive.photos or []) + carried_photos
  7561. await db.commit()
  7562. except Exception as e:
  7563. # The archive and the delete are already committed; the
  7564. # print goes ahead either way. Worst case the pictures sit
  7565. # unnamed in the archive's own directory.
  7566. #
  7567. # Ints only until the rollback has run, per the note above,
  7568. # which is why this logs queue_item_id and not item.id --
  7569. # the sibling handler forty lines up does the same.
  7570. logger.warning(
  7571. "Queue item %s: failed to carry library photos into archive %s: %s",
  7572. queue_item_id,
  7573. archive_id,
  7574. e,
  7575. )
  7576. await db.rollback()
  7577. # rollback() expires every loaded instance, and in async
  7578. # SQLAlchemy the next plain attribute read is lazy IO
  7579. # outside the greenlet -- MissingGreenlet, which would turn
  7580. # this cosmetic failure into a dispatch crash in exactly the
  7581. # "database is locked" case the block exists for (#1853).
  7582. # The nozzle guard, the upload and the start all keep
  7583. # reading item, archive and printer, so all three go back
  7584. # into the session before falling through.
  7585. item = await db.get(PrintQueueItem, queue_item_id)
  7586. archive = await db.get(PrintArchive, archive_id)
  7587. printer = await db.get(Printer, item.printer_id) if item else None
  7588. if not item or not archive or not printer:
  7589. logger.error(
  7590. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7591. queue_item_id,
  7592. archive_id,
  7593. )
  7594. return
  7595. else:
  7596. # Neither archive nor library file specified
  7597. item.status = "failed"
  7598. item.error_message = "No source file specified"
  7599. item.completed_at = datetime.now(timezone.utc)
  7600. await db.commit()
  7601. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7602. await self._power_off_if_needed(db, item)
  7603. return
  7604. # Check file exists on disk
  7605. if not file_path.exists():
  7606. item.status = "failed"
  7607. item.error_message = "Source file not found on disk"
  7608. item.completed_at = datetime.now(timezone.utc)
  7609. await db.commit()
  7610. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7611. await self._power_off_if_needed(db, item)
  7612. return
  7613. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7614. # size dispatched to a printer with a different nozzle installed is
  7615. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7616. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7617. # gives the user no idea what went wrong. Catch it here, before we spend
  7618. # time preheating and uploading, and fail with an actionable message.
  7619. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7620. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7621. # the printer hasn't reported its nozzles yet, we fall through and let the
  7622. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7623. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7624. # as one of the two hotends is a 0.6.
  7625. #
  7626. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7627. # (#2885): the printer fetches one as part of starting the print, so the
  7628. # set to test against is "reachable", not "currently mounted". This runs
  7629. # well before the rack picker at the bottom of this method, so without
  7630. # the rack in scope here that picker never got the chance to run.
  7631. sliced_nozzle = archive.nozzle_diameter if archive else None
  7632. if sliced_nozzle:
  7633. nozzle_status = printer_manager.get_status(item.printer_id)
  7634. installed = _installed_nozzle_diameters(nozzle_status)
  7635. rack = _rack_nozzle_diameters(nozzle_status)
  7636. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7637. if mismatch_msg:
  7638. item.status = "failed"
  7639. item.error_message = mismatch_msg
  7640. item.completed_at = datetime.now(timezone.utc)
  7641. await db.commit()
  7642. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7643. await notification_service.on_queue_job_failed(
  7644. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7645. printer_id=printer.id,
  7646. printer_name=printer.name,
  7647. reason=mismatch_msg,
  7648. db=db,
  7649. )
  7650. try:
  7651. await ws_manager.send_queue_item_failed(
  7652. user_id=item.created_by_id,
  7653. queue_item_id=item.id,
  7654. printer_id=item.printer_id,
  7655. reason="nozzle_mismatch",
  7656. )
  7657. except Exception:
  7658. pass
  7659. await self._power_off_if_needed(db, item)
  7660. return
  7661. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7662. # bed (and chamber, if applicable) is at temperature when the firmware
  7663. # starts the actual print routine. Best-effort: any failure logs and
  7664. # falls through to the normal upload+start path rather than turning a
  7665. # configuration issue into a failed queue item.
  7666. # Returns False only when the item was cancelled or deleted while the
  7667. # stage was holding at temperature. Uploading and starting it anyway
  7668. # would print a job the user has already called off, so abandon the
  7669. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7670. if not await self._preheat_and_soak(db, item, printer, archive):
  7671. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7672. return
  7673. # See `_effective_plate_id` for why this is resolved once here rather
  7674. # than each site below repeating `item.plate_id or 1`.
  7675. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7676. # G-code injection for auto-print systems (#422)
  7677. injected_path = None
  7678. # #2547: tracked separately from `injected_path`, which is also set when
  7679. # only a START snippet was injected. Only an END snippet changes what the
  7680. # camera sees at print completion.
  7681. end_gcode_injected = False
  7682. if item.gcode_injection:
  7683. try:
  7684. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7685. if snippets_raw:
  7686. snippets = json.loads(snippets_raw)
  7687. model_snippets = snippets.get(printer.model, {})
  7688. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7689. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7690. if start_gc or end_gc:
  7691. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7692. injected_path = inject_gcode_into_3mf(
  7693. file_path, effective_plate_id, start_gc or None, end_gc or None
  7694. )
  7695. if injected_path:
  7696. file_path = injected_path
  7697. end_gcode_injected = bool(end_gc)
  7698. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7699. else:
  7700. logger.warning(
  7701. "Queue item %s: G-code injection returned no result, using original", item.id
  7702. )
  7703. except Exception as e:
  7704. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7705. # #2547: the finish-photo path can't learn from telemetry that this print
  7706. # ends with user End G-code — which means the plate may be gone by the
  7707. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7708. # the print once the printer confirms it running.
  7709. if end_gcode_injected:
  7710. print_dispatch_context.mark_pending(printer.id)
  7711. # Upload to root directory (not /cache/) - the start_print command references
  7712. # files by name only (ftp://{filename}), so they must be in the root
  7713. remote_filename = derive_remote_filename(filename)
  7714. remote_path = f"/{remote_filename}"
  7715. # Get FTP retry settings
  7716. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7717. logger.info(
  7718. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7719. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7720. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7721. )
  7722. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7723. # Every read this method needs (printer, archive/library, preheat) is
  7724. # done, and the library-file branch already committed its archive
  7725. # creation. Without this the transaction opened by the first SELECT above
  7726. # stays "idle in transaction" for the entire upload — multiple seconds
  7727. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7728. # a farm dispatching many jobs at once then exhausts the pool. This was
  7729. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7730. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7731. # readable; the status writes below (upload-failure path and the
  7732. # pending->printing CAS) transparently open a fresh transaction.
  7733. await db.commit()
  7734. # Delete existing file if present (avoids 553 error on overwrite)
  7735. try:
  7736. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  7737. delete_result = await delete_file_async(
  7738. printer.ip_address,
  7739. printer.access_code,
  7740. remote_path,
  7741. socket_timeout=ftp_timeout,
  7742. printer_model=printer.model,
  7743. # This delete and the upload below are one bounded, user-initiated
  7744. # unit -- at most nine connections -- so neither skips on the
  7745. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  7746. # trace this delete took the TLS failure and armed the cool-off,
  7747. # and the upload's four attempts were then spent against it
  7748. # without a socket being opened.
  7749. respect_handshake_cooloff=False,
  7750. )
  7751. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  7752. except Exception as e:
  7753. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  7754. # Dispatch toast — announce the upload start with the total byte
  7755. # count so the frontend can render an honest progress bar.
  7756. toast_uid = item.created_by_id
  7757. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7758. try:
  7759. total_bytes = file_path.stat().st_size
  7760. except OSError:
  7761. total_bytes = 0
  7762. try:
  7763. await ws_manager.send_queue_item_uploading(
  7764. user_id=toast_uid,
  7765. queue_item_id=item.id,
  7766. printer_id=item.printer_id,
  7767. printer_name=printer.name,
  7768. file_name=toast_file_name,
  7769. total_bytes=total_bytes,
  7770. )
  7771. except Exception:
  7772. pass # toast is best-effort
  7773. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  7774. # A deadline expiry gets its own message: "check your SD card" is the
  7775. # wrong advice for a link that was simply too slow to finish (#2529).
  7776. upload_error: str | None = None
  7777. # Why the upload failed, straight from the client rather than inferred.
  7778. # Owned here, so a background fetch for another print cannot overwrite
  7779. # it between the failure and the sentence built from it (#2899).
  7780. upload_failure = FtpFailureReport()
  7781. try:
  7782. if ftp_retry_enabled:
  7783. uploaded = await with_ftp_retry(
  7784. upload_file_async,
  7785. printer.ip_address,
  7786. printer.access_code,
  7787. file_path,
  7788. remote_path,
  7789. socket_timeout=ftp_timeout,
  7790. printer_model=printer.model,
  7791. progress_callback=progress_bridge,
  7792. respect_handshake_cooloff=False,
  7793. failure=upload_failure,
  7794. max_retries=ftp_retry_count,
  7795. retry_delay=ftp_retry_delay,
  7796. operation_name=f"Upload print to {printer.name}",
  7797. )
  7798. else:
  7799. uploaded = await upload_file_async(
  7800. printer.ip_address,
  7801. printer.access_code,
  7802. file_path,
  7803. remote_path,
  7804. socket_timeout=ftp_timeout,
  7805. printer_model=printer.model,
  7806. progress_callback=progress_bridge,
  7807. respect_handshake_cooloff=False,
  7808. failure=upload_failure,
  7809. )
  7810. except UploadCancelled as e:
  7811. uploaded = False
  7812. upload_error = (
  7813. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  7814. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  7815. )
  7816. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  7817. except Exception as e:
  7818. uploaded = False
  7819. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  7820. # Clean up injected temp file after upload attempt
  7821. if injected_path and injected_path.exists():
  7822. injected_path.unlink(missing_ok=True)
  7823. if not uploaded:
  7824. # This used to be one string for every upload failure, telling
  7825. # everyone to check the SD card. The client knows which of seven
  7826. # things went wrong and logs each one differently; it just had no
  7827. # way to say so here, so the card got named even for a TLS
  7828. # handshake that never reached the printer's filesystem (#2899).
  7829. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  7830. failure = upload_failure.failure
  7831. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  7832. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  7833. return
  7834. item.status = "failed"
  7835. item.error_message = error_msg
  7836. item.completed_at = datetime.now(timezone.utc)
  7837. await db.commit()
  7838. logger.error(
  7839. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  7840. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  7841. )
  7842. # Send failure notification
  7843. await notification_service.on_queue_job_failed(
  7844. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7845. printer_id=printer.id,
  7846. printer_name=printer.name,
  7847. # The same sentence the queue shows. A push notification saying
  7848. # something different from the UI is its own small bug (#2899).
  7849. reason=error_msg,
  7850. db=db,
  7851. )
  7852. try:
  7853. await ws_manager.send_queue_item_failed(
  7854. user_id=toast_uid,
  7855. queue_item_id=item.id,
  7856. printer_id=item.printer_id,
  7857. reason="upload_failed",
  7858. )
  7859. except Exception:
  7860. pass
  7861. await self._power_off_if_needed(db, item)
  7862. return
  7863. # The printer took a file, so any run of refused uploads is over: the
  7864. # next refusal starts again at the shortest backoff, and notifies (#3210).
  7865. self._upload_refusals.pop(printer.id, None)
  7866. self._upload_refusal_notified.discard(printer.id)
  7867. # Parse AMS mapping if stored
  7868. ams_mapping = None
  7869. if item.ams_mapping:
  7870. try:
  7871. ams_mapping = json.loads(item.ams_mapping)
  7872. except json.JSONDecodeError:
  7873. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  7874. # Register as expected print so we don't create a duplicate archive
  7875. # Only applicable for archive-based prints
  7876. if archive:
  7877. from backend.app.main import register_expected_print
  7878. register_expected_print(
  7879. item.printer_id,
  7880. remote_filename,
  7881. archive.id,
  7882. ams_mapping=ams_mapping,
  7883. created_by_id=item.created_by_id,
  7884. cost_center_id=item.cost_center_id,
  7885. # The plate actually dispatched, not the queue item's raw
  7886. # column: on None, `register_expected_print` stores nothing,
  7887. # and `extract_filament_usage_from_3mf` then books every
  7888. # filament in the file rather than the one plate that printed.
  7889. plate_id=effective_plate_id,
  7890. )
  7891. # Registration happens before the print command by necessity (the
  7892. # printer can report the print before the send returns), so record
  7893. # what to undo if we never get as far as sending. `_dispatch_one`
  7894. # rolls back anything still pending here on every exit — exception,
  7895. # early return, or cancel winning the CAS below.
  7896. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  7897. # Propagate the queue item's owner into printer_manager so the
  7898. # print-complete callback can credit the user in the PrintLogEntry
  7899. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  7900. # items) or when the user clicks the manual-start button.
  7901. await self._propagate_owner_to_printer_manager(db, item)
  7902. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  7903. # This prevents phantom reprints if the backend crashes/restarts after the
  7904. # print command is sent but before the status update is committed.
  7905. # If we crash after this commit but before start_print(), the item will be
  7906. # in "printing" status without actually printing - but that's safer than
  7907. # accidentally reprinting the same file hours later.
  7908. #
  7909. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  7910. # initial pending read at the top of check_queue and this point) flips
  7911. # the row to "cancelled" in a separate session. Without the WHERE
  7912. # status='pending' clause, the unconditional update here would silently
  7913. # overwrite that cancellation and we'd ship the MQTT start_print below
  7914. # — printer obeys, user sees "I pressed cancel and the print started".
  7915. # rowcount==0 means the user won the race; bail out, best-effort delete
  7916. # the file we just uploaded, do NOT send start_print.
  7917. now_utc = datetime.now(timezone.utc)
  7918. billing_run_id = str(uuid.uuid4())
  7919. cas = await db.execute(
  7920. update(PrintQueueItem)
  7921. .where(PrintQueueItem.id == item.id)
  7922. .where(PrintQueueItem.status == "pending")
  7923. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  7924. )
  7925. await db.commit()
  7926. if cas.rowcount == 0:
  7927. logger.info(
  7928. "Queue item %s no longer pending at print-command time "
  7929. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  7930. item.id,
  7931. )
  7932. try:
  7933. await delete_file_async(
  7934. printer.ip_address,
  7935. printer.access_code,
  7936. remote_path,
  7937. socket_timeout=ftp_timeout,
  7938. printer_model=printer.model,
  7939. )
  7940. except Exception as cleanup_err:
  7941. logger.debug(
  7942. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  7943. item.id,
  7944. cleanup_err,
  7945. )
  7946. try:
  7947. await ws_manager.send_queue_item_failed(
  7948. user_id=toast_uid,
  7949. queue_item_id=item.id,
  7950. printer_id=item.printer_id,
  7951. reason="cancelled_mid_dispatch",
  7952. )
  7953. except Exception:
  7954. pass
  7955. return
  7956. # Sync the in-memory item so subsequent code that reads item.status /
  7957. # item.started_at sees the values we just persisted.
  7958. item.status = "printing"
  7959. item.started_at = now_utc
  7960. item.billing_run_id = billing_run_id
  7961. if archive is not None:
  7962. archive.billing_run_id = billing_run_id
  7963. # Legacy transaction deletion used an archive-wide skip flag.
  7964. # A newly dispatched run has its own UUID/tombstone, so it must be
  7965. # billable independently of any older deleted run on this archive.
  7966. archive.wallet_charge_skipped = False
  7967. # Persist before MQTT send so completion and restart recovery can
  7968. # always recover the internal billing identity.
  7969. await db.commit()
  7970. for cleanup_path in cleanup_disk_paths:
  7971. try:
  7972. if cleanup_path.exists():
  7973. cleanup_path.unlink()
  7974. except OSError as cleanup_err:
  7975. logger.warning(
  7976. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  7977. json.dumps(
  7978. {
  7979. "queue_item_id": item.id,
  7980. "path": str(cleanup_path),
  7981. "error": str(cleanup_err),
  7982. },
  7983. sort_keys=True,
  7984. ),
  7985. )
  7986. # Clear the awaiting-plate-clear flag now that we're starting a new print
  7987. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  7988. # #1898: with the opt-in default-good setting, moving on to the next
  7989. # print resolves the previous print's unanswered outcome prompt as
  7990. # "good" — this path also covers the camera-based plate detection,
  7991. # which releases the gate by allowing dispatch rather than by an
  7992. # explicit acknowledgment. Rides on the dispatch transaction.
  7993. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  7994. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  7995. await resolve_pending_confirmation_as_good(db, item.printer_id)
  7996. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  7997. # Capture state before dispatch so the watchdog can detect whether the
  7998. # printer actually transitioned (#967). Also capture subtask_id so the
  7999. # watchdog can recognise "command landed but state hasn't flipped yet"
  8000. # on slow H2D transitions (#1078).
  8001. pre_status = printer_manager.get_status(item.printer_id)
  8002. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8003. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8004. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8005. # #1721: respect the user's explicit timelapse choice. The #1397
  8006. # force-on at dispatch was removed because it caused per-layer nozzle
  8007. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8008. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8009. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8010. # FINISH-state fallback — no need to force a video.
  8011. effective_timelapse = bool(item.timelapse)
  8012. # Nozzle-rack fallback (#2800). A job that never passed through the
  8013. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8014. # dispatches with no nozzle field at all and chooses for itself — which
  8015. # is how a print levelled on one hotend and then printed on another,
  8016. # millimetres above the plate. Derive the per-slot extruder assignment
  8017. # from the file being dispatched.
  8018. #
  8019. # Done here rather than at queue time because this is the first point
  8020. # that knows both the actual printer and the actual file: an item can
  8021. # be created without a printer (model-based assignment), reassigned
  8022. # afterwards, or have its file swapped for a G-code-injected copy just
  8023. # above. Every queue-creation path — the print dialog, a bulk library
  8024. # add, the webhook, a pipeline run — is covered by the one call.
  8025. # Skipped when the item already carries a Bambu Studio capture: that
  8026. # one wins downstream anyway, so reading the 3MF again would be work
  8027. # thrown away on every dispatch.
  8028. # Rack position resolution (#1784), tried before the #2800 fallback
  8029. # below because it can express what that one cannot: a plate wanting a
  8030. # *different* hotend off the rack per filament group. The position per
  8031. # group is the operator's pick — the 3MF states it nowhere, proven by
  8032. # sending one plate twice with different picks and finding the two
  8033. # files identical bar float noise — so it is resolved here against the
  8034. # rack as it stands right now, after the upload, not at queue time.
  8035. resolved_nozzle_mapping = None
  8036. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8037. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8038. if rack_plan is not None:
  8039. try:
  8040. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8041. except (json.JSONDecodeError, TypeError):
  8042. stored_choice = {}
  8043. logger.warning(
  8044. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8045. item.id,
  8046. item.nozzle_rack_choice,
  8047. )
  8048. # JSON object keys are strings; the groups are ints.
  8049. choice: dict[int, int] = {}
  8050. for key, value in (stored_choice or {}).items():
  8051. try:
  8052. choice[int(key)] = int(value)
  8053. except (TypeError, ValueError):
  8054. continue
  8055. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8056. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8057. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8058. )
  8059. if resolved_nozzle_mapping is None and choice:
  8060. # An explicit pick that no longer holds stops the print. The
  8061. # operator named a hotend; printing from a different one is
  8062. # how a plate gets levelled on one nozzle and drawn with
  8063. # another, millimetres above the bed. Nothing has been sent
  8064. # to the printer yet, so failing here costs only the upload.
  8065. item.status = "failed"
  8066. item.error_message = (
  8067. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8068. "Edit the item to choose another position."
  8069. )
  8070. item.completed_at = datetime.now(timezone.utc)
  8071. await db.commit()
  8072. logger.warning(
  8073. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8074. item.id,
  8075. printer.name,
  8076. rack_error,
  8077. choice,
  8078. [slot.get("id") for slot in live_rack],
  8079. )
  8080. await notification_service.on_queue_job_failed(
  8081. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8082. printer_id=printer.id,
  8083. printer_name=printer.name,
  8084. reason=item.error_message,
  8085. db=db,
  8086. )
  8087. try:
  8088. await ws_manager.send_queue_item_failed(
  8089. user_id=toast_uid,
  8090. queue_item_id=item.id,
  8091. printer_id=item.printer_id,
  8092. reason="nozzle_rack_pick_stale",
  8093. )
  8094. except Exception:
  8095. pass # Best-effort — don't fail the error handler
  8096. # The file is already on the SD card by this point, and a
  8097. # 3MF left there is a phantom print waiting to be started
  8098. # from the touchscreen. Same cleanup the start_print
  8099. # failure path below does, for the same reason.
  8100. try:
  8101. await delete_file_async(
  8102. printer.ip_address,
  8103. printer.access_code,
  8104. remote_path,
  8105. printer_model=printer.model,
  8106. )
  8107. except Exception:
  8108. pass # Best-effort — don't fail the error handler
  8109. return
  8110. if resolved_nozzle_mapping is None:
  8111. # Nothing was picked and nothing could be assigned. Falls
  8112. # through to the #2800 path, which is what ran before this
  8113. # existed — strictly not worse than today.
  8114. logger.info(
  8115. "Queue item %s: no rack positions assignable (%s); falling back",
  8116. item.id,
  8117. rack_error,
  8118. )
  8119. else:
  8120. logger.info(
  8121. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8122. item.id,
  8123. resolved_nozzle_mapping,
  8124. rack_plan.slot_groups,
  8125. choice or "auto",
  8126. )
  8127. nozzle_slot_extruders = None
  8128. if (
  8129. not item.nozzle_mapping
  8130. and resolved_nozzle_mapping is None
  8131. and file_path is not None
  8132. and is_nozzle_rack_model(printer.model)
  8133. ):
  8134. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8135. if slot_extruders:
  8136. nozzle_slot_extruders = json.dumps(slot_extruders)
  8137. # Every filament this plate prints is on the external spool -> the print
  8138. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8139. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8140. # table", which is what held the reporter's P1S at Heatbed preheating
  8141. # for ten minutes before it gave up (#3087). The MQTT command builder
  8142. # already downgrades a mapping that is *only* external ([254]), but a
  8143. # multi-filament project pads the slots this plate does not print with
  8144. # -1 — BambuStudio's own convention — and down there a -1 is
  8145. # indistinguishable from a slot that never resolved, which must never be
  8146. # sent to the spool holder (#2589). Here the plate's filament list says
  8147. # which is which, so the answer is exact rather than a guess.
  8148. #
  8149. # Deliberately narrow: this fires only when every consumed slot is an
  8150. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8151. # alone and the firmware still rejects the print, exactly as today. And
  8152. # only for single-nozzle printers, mirroring the builder's own reconcile
  8153. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8154. # whether to use the AMS, so it is not ours to rewrite.
  8155. effective_use_ams = item.use_ams
  8156. if (
  8157. effective_use_ams
  8158. and ams_mapping
  8159. and file_path is not None
  8160. # Cheap gate before opening the file: with nothing on the spool
  8161. # holder anywhere in the mapping, no subset of it can be all
  8162. # external, so most dispatches never pay for the parse. The
  8163. # isinstance also keeps a malformed stored mapping (a bare number
  8164. # from a hand-edited row) failing where it always failed, in the
  8165. # command builder, rather than here.
  8166. and isinstance(ams_mapping, list)
  8167. and any(_is_external_tray(t) for t in ams_mapping)
  8168. and not _might_be_dual_nozzle(printer.model, pre_status)
  8169. ):
  8170. from backend.app.services.filament_requirements import extract_filament_requirements
  8171. consumed = _consumed_mapping_entries(
  8172. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8173. )
  8174. if consumed and all(_is_external_tray(t) for t in consumed):
  8175. effective_use_ams = False
  8176. logger.info(
  8177. "Queue item %s: every filament plate %s prints is on the external spool "
  8178. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8179. item.id,
  8180. effective_plate_id,
  8181. ams_mapping,
  8182. )
  8183. # A slot that lost its K-profile selection (a power cycle resets every
  8184. # slot to the default K) would print on the default. The idle check in
  8185. # the status handler normally restores it first, but nothing guarantees
  8186. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8187. # Never allowed to stop the print it is protecting.
  8188. try:
  8189. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8190. except Exception:
  8191. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8192. # Start the print with AMS mapping, plate_id and print options.
  8193. # nozzle_mapping rides through verbatim — JSON string captured from
  8194. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8195. # parses + injects it only for dual-nozzle models so a null on every
  8196. # other model is a transparent pass-through. The rack fallback is
  8197. # resolved down there too, where the live rack position is known.
  8198. started = printer_manager.start_print(
  8199. item.printer_id,
  8200. remote_filename,
  8201. plate_id=effective_plate_id,
  8202. ams_mapping=ams_mapping,
  8203. bed_levelling=item.bed_levelling,
  8204. flow_cali=item.flow_cali,
  8205. vibration_cali=item.vibration_cali,
  8206. layer_inspect=item.layer_inspect,
  8207. timelapse=effective_timelapse,
  8208. use_ams=effective_use_ams,
  8209. nozzle_offset_cali=item.nozzle_offset_cali,
  8210. nozzle_mapping=item.nozzle_mapping
  8211. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8212. nozzle_slot_extruders=nozzle_slot_extruders,
  8213. )
  8214. if started:
  8215. # The command is away, so the expectation is now legitimate and must
  8216. # survive. Anything still in this dict when _dispatch_one exits gets
  8217. # rolled back.
  8218. self._unconfirmed_expected_print.pop(item.id, None)
  8219. self._unconfirmed_budget_reservations.discard(item.id)
  8220. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8221. # target, chamber target, airduct heating) — the gcode owns
  8222. # heater/flap control from here. Clearing the pin prevents
  8223. # `_dispatch_one`'s finally from unwinding a live print.
  8224. self._preheat_pin.pop(item.printer_id, None)
  8225. self._preheat_pin_bed.pop(item.printer_id, None)
  8226. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8227. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8228. # status='processing' from upload start until the printer acked
  8229. # (or timed out). The frontend derives "Awaiting printer…" purely
  8230. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8231. # event would push the status chip out of 'PROCESSING' prematurely
  8232. # — which is exactly what the screenshot at #1625-followup
  8233. # complained about.
  8234. # Register the local 3MF in the cover-cache so /cover skips FTP
  8235. # (#1166 follow-up). file_path was resolved earlier from either the
  8236. # archive or the library file row.
  8237. if file_path is not None:
  8238. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8239. # Hold the printer against further dispatches until the watchdog
  8240. # confirms the printer transitioned (or until the hard timeout).
  8241. # Prevents multi-plate batches from triple-dispatching onto the
  8242. # same H2D Pro while it digests the first project_file (#1157).
  8243. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8244. # Watchdog: if the printer never transitions out of pre_state AND
  8245. # never advances subtask_id, the MQTT publish was accepted locally but
  8246. # didn't reach the printer (half-broken session — same shape as
  8247. # #887/#936). Revert the queue item so the next dispatch can pick it
  8248. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8249. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8250. # that would otherwise cause the item to re-dispatch as a reprint
  8251. # of the just-finished job (#1078).
  8252. if pre_state:
  8253. spawn_background_task(
  8254. self._watchdog_print_start(
  8255. item.id,
  8256. item.printer_id,
  8257. pre_state,
  8258. pre_subtask_id,
  8259. pre_gcode_file,
  8260. created_by_id=toast_uid,
  8261. ),
  8262. name=f"watchdog-print-start-{item.id}",
  8263. )
  8264. # Get estimated time for notification.
  8265. #
  8266. # This used to fall back to `library_file.print_time_seconds`, a column
  8267. # LibraryFile does not have — the print time it knows about lives in
  8268. # `file_metadata`. So a library print whose archive carried no parseable
  8269. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8270. # AttributeError right here, *after* the printer had already been sent
  8271. # the job: the started-notification never fired, and the exception
  8272. # unwound the whole queue pass, so every other printer still waiting to
  8273. # be dispatched on that tick silently missed its turn.
  8274. #
  8275. # The queue item caches the print time at creation ("Cached from
  8276. # archive/library"), which is the value this was reaching for.
  8277. estimated_time = None
  8278. if archive and archive.print_time_seconds:
  8279. estimated_time = archive.print_time_seconds
  8280. elif item.print_time_seconds:
  8281. estimated_time = item.print_time_seconds
  8282. # Send job started notification
  8283. await notification_service.on_queue_job_started(
  8284. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8285. printer_id=printer.id,
  8286. printer_name=printer.name,
  8287. db=db,
  8288. estimated_time=estimated_time,
  8289. )
  8290. # MQTT relay - publish queue job started
  8291. try:
  8292. await mqtt_relay.on_queue_job_started(
  8293. job_id=item.id,
  8294. filename=filename,
  8295. printer_id=printer.id,
  8296. printer_name=printer.name,
  8297. printer_serial=printer.serial_number,
  8298. )
  8299. except Exception:
  8300. pass # Don't fail if MQTT fails
  8301. else:
  8302. # Clean up uploaded file from SD card to prevent phantom prints
  8303. try:
  8304. await delete_file_async(
  8305. printer.ip_address,
  8306. printer.access_code,
  8307. remote_path,
  8308. printer_model=printer.model,
  8309. )
  8310. except Exception:
  8311. pass # Best-effort — don't fail the error handler
  8312. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8313. # state can flip from idle to active in the window between the
  8314. # pre-dispatch check above and this publish (the FTP upload takes
  8315. # seconds); start_print() then refuses to send project_file to the
  8316. # now-busy printer and returns False. Failing the item here would be
  8317. # wrong — the printer is fine, it is simply busy — so revert to
  8318. # pending and let a later tick dispatch it once the printer is idle,
  8319. # exactly like the pre-dispatch guard. Only a start_print() False on
  8320. # an idle/unknown printer is a genuine command failure.
  8321. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8322. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8323. logger.info(
  8324. "Queue item %s: printer %s became busy (state=%s) before the start "
  8325. "command was sent — deferring, reverting item to pending (#2598)",
  8326. item.id,
  8327. item.printer_id,
  8328. post_dispatch_state,
  8329. )
  8330. item.status = "pending"
  8331. item.started_at = None
  8332. await db.commit()
  8333. return
  8334. # Print command failed - revert status
  8335. item.status = "failed"
  8336. item.error_message = "Failed to send print command to printer"
  8337. item.completed_at = datetime.now(timezone.utc)
  8338. await db.commit()
  8339. logger.error(
  8340. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8341. f"printer_manager.start_print() returned False. "
  8342. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8343. f"Check printer status and backend logs for details."
  8344. )
  8345. # Send failure notification
  8346. await notification_service.on_queue_job_failed(
  8347. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8348. printer_id=printer.id,
  8349. printer_name=printer.name,
  8350. reason="Failed to send print command to printer - check printer connection and status",
  8351. db=db,
  8352. )
  8353. try:
  8354. await ws_manager.send_queue_item_failed(
  8355. user_id=toast_uid,
  8356. queue_item_id=item.id,
  8357. printer_id=item.printer_id,
  8358. reason="start_command_failed",
  8359. )
  8360. except Exception:
  8361. pass
  8362. await self._power_off_if_needed(db, item)
  8363. @staticmethod
  8364. async def _watchdog_print_start(
  8365. queue_item_id: int,
  8366. printer_id: int,
  8367. pre_state: str,
  8368. pre_subtask_id: str | None = None,
  8369. pre_gcode_file: str | None = None,
  8370. timeout: float = 90.0,
  8371. phase_b_timeout: float = 180.0,
  8372. poll_interval: float = 3.0,
  8373. created_by_id: int | None = None,
  8374. ) -> None:
  8375. """Revert a queue item if the printer never acknowledges the start command.
  8376. Bambuddy optimistically marks the queue item as "printing" right after the
  8377. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8378. Phase A (up to ``timeout``): wait for either an active-state transition
  8379. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8380. primary signal; subtask_id advance handles the H2D case where state can
  8381. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8382. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8383. was lost on a half-broken session (#887/#936) — revert and force
  8384. reconnect (the #967 recovery path).
  8385. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8386. alone): keep watching for the active-state transition. subtask_id alone
  8387. proves the file landed but not that the printer started — and a printer
  8388. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8389. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8390. used to leave the queue item stuck in 'printing' forever because the
  8391. old watchdog returned success as soon as subtask_id advanced. If Phase
  8392. B times out, revert the queue item so the user can retry without
  8393. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8394. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8395. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8396. transitions that also don't emit an early subtask_id tick.
  8397. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8398. refuses to verify our commands will never start this job or any other,
  8399. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8400. burns an upload slot the rest of the farm is queued behind — that path
  8401. is for a printer that might still come good, which this one cannot
  8402. (#2732). It fails the item on the spot with the actual reason instead.
  8403. """
  8404. last_status = None
  8405. landed_on_subtask = False
  8406. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8407. # every push carrying an `hms` key, so the fault can come and go between
  8408. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8409. command_rejected = False
  8410. # Latched for the same reason as command_rejected: drying can finish, or
  8411. # be stopped by the user, part-way through the dispatch window. Seeing it
  8412. # once is what matters — it is the state the printer was in when it
  8413. # declined to start (#2758).
  8414. drying_ams_ids: list[int] = []
  8415. deadline = time.monotonic() + timeout
  8416. while time.monotonic() < deadline:
  8417. await asyncio.sleep(poll_interval)
  8418. status = printer_manager.get_status(printer_id)
  8419. if not status:
  8420. # Printer disconnected — don't mess with the DB. Drop the
  8421. # in-memory dispatch hold too so a fresh dispatch can retry
  8422. # once the printer comes back; the hard timeout would
  8423. # otherwise hold the printer unnecessarily.
  8424. scheduler._release_dispatch_hold(printer_id)
  8425. return
  8426. last_status = status
  8427. if status.state in _ACTIVE_PRINT_STATES:
  8428. # Printer is actively processing the job — release the
  8429. # post-dispatch hold so the next pending item for this printer
  8430. # can be evaluated normally. We do NOT accept arbitrary state
  8431. # transitions: a printer going FINISH -> IDLE (user dismissed
  8432. # the post-print prompt without accepting our project_file)
  8433. # would otherwise look like "command landed" and leave the
  8434. # queue item stuck in 'printing' forever (#1370).
  8435. scheduler._release_dispatch_hold(printer_id)
  8436. try:
  8437. await ws_manager.send_queue_item_acked(
  8438. user_id=created_by_id,
  8439. queue_item_id=queue_item_id,
  8440. printer_id=printer_id,
  8441. )
  8442. except Exception:
  8443. pass
  8444. return
  8445. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8446. # Checked only after the active-state exit above: a stale HMS left
  8447. # over from an earlier job must never abort a print that is visibly
  8448. # running. An actually-refused command leaves the printer idle, so
  8449. # this ordering costs the detection nothing.
  8450. if _mqtt_commands_rejected(status):
  8451. command_rejected = True
  8452. break
  8453. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8454. # Phase A exit — printer accepted the file (subtask_id flipped
  8455. # to our submission id). Don't return yet: the printer may
  8456. # have accepted the command but never actually start (e.g.
  8457. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8458. # B watches for the active-state transition.
  8459. landed_on_subtask = True
  8460. break
  8461. if landed_on_subtask and not command_rejected:
  8462. phase_b_deadline = time.monotonic() + phase_b_timeout
  8463. while time.monotonic() < phase_b_deadline:
  8464. await asyncio.sleep(poll_interval)
  8465. status = printer_manager.get_status(printer_id)
  8466. if not status:
  8467. scheduler._release_dispatch_hold(printer_id)
  8468. return
  8469. last_status = status
  8470. if status.state in _ACTIVE_PRINT_STATES:
  8471. scheduler._release_dispatch_hold(printer_id)
  8472. try:
  8473. await ws_manager.send_queue_item_acked(
  8474. user_id=created_by_id,
  8475. queue_item_id=queue_item_id,
  8476. printer_id=printer_id,
  8477. )
  8478. except Exception:
  8479. pass
  8480. return
  8481. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8482. # Same ordering rule as Phase A: a running print wins over a
  8483. # lingering HMS.
  8484. if _mqtt_commands_rejected(status):
  8485. command_rejected = True
  8486. break
  8487. # No active-state transition. Revert the item so the scheduler can retry.
  8488. # Drop the in-memory hold so the retry isn't blocked by it.
  8489. scheduler._release_dispatch_hold(printer_id)
  8490. # Logged on every failed dispatch window, not just the last one, so a
  8491. # support bundle shows the correlation from the first attempt rather than
  8492. # only after the retry budget is spent (#2758).
  8493. if drying_ams_ids:
  8494. logger.info(
  8495. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8496. queue_item_id,
  8497. printer_id,
  8498. ", ".join(str(i) for i in drying_ams_ids),
  8499. )
  8500. # Four outcomes from the revert attempt, each routed differently:
  8501. # "reverted": row flipped from printing -> pending, run recovery
  8502. # "gave_up": same, but the retry budget is spent — row failed
  8503. # rather than pending, so it stops going round again
  8504. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8505. # on_print_complete or user). Skip recovery entirely
  8506. # — the print clearly landed somewhere even if the
  8507. # watchdog didn't see the active-state transition.
  8508. # "revert_failed": SQLite contention exhausted retries. Still run
  8509. # recovery so the MQTT session gets a fresh client_id
  8510. # on the half-broken-session path.
  8511. #
  8512. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8513. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8514. # the watchdog again. For a printer that is genuinely wedged that loop never
  8515. # ends — the reporter had one printer "since this morning still not launch"
  8516. # — and each lap also consumes an upload slot that the other printers in the
  8517. # farm are waiting on. Retrying is right; retrying forever is not.
  8518. async def _do_revert(db):
  8519. item = await db.get(PrintQueueItem, queue_item_id)
  8520. if not item or item.status != "printing":
  8521. return "already_moved_on"
  8522. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8523. item.started_at = None
  8524. # Charge the attempt to the candidate that was actually dispatched, so
  8525. # a cross-model item (#671) reaches for its other file next lap instead
  8526. # of retrying the printer that just failed to start. Matched by file
  8527. # because that is what the resolver copied onto the row.
  8528. if item.library_file_id is not None:
  8529. await db.execute(
  8530. update(PrintQueueVariant)
  8531. .where(PrintQueueVariant.queue_item_id == item.id)
  8532. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8533. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8534. )
  8535. if command_rejected:
  8536. # No retry budget for this one: the printer refused to verify the
  8537. # command, and re-uploading the same 3MF to the same printer will
  8538. # be refused the same way. Fail now with the fix rather than after
  8539. # three laps of a message about SD cards (#2732).
  8540. item.status = "failed"
  8541. item.error_message = (
  8542. "The printer rejected the print command: MQTT command verification failed "
  8543. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8544. "then start the job again."
  8545. )
  8546. item.completed_at = datetime.now(timezone.utc)
  8547. await db.commit()
  8548. return "command_rejected"
  8549. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8550. item.status = "failed"
  8551. if drying_ams_ids:
  8552. # #2758: the generic message below sent the reporter looking
  8553. # at the SD card while the actual obstacle — AMS units in a
  8554. # drying cycle — was on screen the whole time. Name what we
  8555. # observed and let the user judge it; Bambuddy does not stop
  8556. # the cycle itself, because on this hardware drying can run
  8557. # alongside a print and stopping it may not be the fix.
  8558. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8559. item.error_message = (
  8560. f"The printer accepted the file but never started printing, after "
  8561. f"{item.dispatch_attempts} attempts. {units} "
  8562. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8563. f"some printers refuse to begin a print while an AMS is in a drying "
  8564. f"cycle, and an AMS drying without its external power supply can also "
  8565. f"leave too little power for the start-of-print calibration. Stop the "
  8566. f"drying, or connect the AMS power supply, and start the job again."
  8567. )
  8568. else:
  8569. item.error_message = (
  8570. f"The printer accepted the file but never started printing, after "
  8571. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8572. f"prompt or error, confirm its SD card is readable, and start the job again."
  8573. )
  8574. item.completed_at = datetime.now(timezone.utc)
  8575. await release_budget_reservation(
  8576. db,
  8577. source_type="print_queue",
  8578. source_id=item.id,
  8579. status="released",
  8580. )
  8581. await db.commit()
  8582. return "gave_up"
  8583. item.status = "pending"
  8584. await db.commit()
  8585. return "reverted"
  8586. try:
  8587. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8588. except Exception as e:
  8589. logger.warning(
  8590. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8591. "scheduler may keep treating this item as in-flight",
  8592. queue_item_id,
  8593. printer_id,
  8594. e,
  8595. )
  8596. revert_outcome = "revert_failed"
  8597. if revert_outcome == "already_moved_on":
  8598. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8599. # other path) already moved the item past 'printing', don't run the
  8600. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8601. # session breaks ongoing prints on the same printer.
  8602. return
  8603. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8604. if revert_outcome == "command_rejected":
  8605. logger.error(
  8606. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8607. "failed) — the print command was rejected, not lost. Failing the item "
  8608. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8609. queue_item_id,
  8610. printer_id,
  8611. HMS_MQTT_VERIFY_FAILED,
  8612. )
  8613. await scheduler._notify_dispatch_gave_up(
  8614. queue_item_id,
  8615. printer_id,
  8616. created_by_id,
  8617. reason="Printer rejected the print command (MQTT command verification failed)",
  8618. )
  8619. # Same reasoning as the landed_on_subtask path below: the file is on
  8620. # the printer and a forced reconnect would only add 0500_4003 to a
  8621. # problem that has nothing to do with the MQTT session (#1150).
  8622. return
  8623. if revert_outcome == "gave_up":
  8624. logger.error(
  8625. "Queue item %s: printer %d never started the print after %d dispatch "
  8626. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8627. "re-uploading it again (#2555)",
  8628. queue_item_id,
  8629. printer_id,
  8630. DISPATCH_MAX_ATTEMPTS,
  8631. total_timeout,
  8632. )
  8633. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8634. elif revert_outcome == "reverted":
  8635. if landed_on_subtask:
  8636. logger.warning(
  8637. "Queue item %s: printer %d accepted project_file (subtask_id "
  8638. "advanced) but never transitioned to an active state within "
  8639. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8640. "for retry (#1678)",
  8641. queue_item_id,
  8642. printer_id,
  8643. total_timeout,
  8644. )
  8645. else:
  8646. logger.warning(
  8647. "Queue item %s: printer %d did not respond to print command within "
  8648. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8649. "for retry (#967)",
  8650. queue_item_id,
  8651. printer_id,
  8652. timeout,
  8653. pre_state,
  8654. pre_subtask_id,
  8655. )
  8656. # Phase B was entered iff subtask_id advanced, which means the
  8657. # project_file landed on the printer. A forced reconnect at this point
  8658. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8659. # skip the recovery entirely.
  8660. if landed_on_subtask:
  8661. return
  8662. # Phase A timeout path: if the printer's gcode_file changed since
  8663. # pre-dispatch, the project_file command landed and the printer is
  8664. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8665. # If gcode_file is unchanged, the publish was silently swallowed
  8666. # (#887/#936) and force_reconnect recovery is what we want.
  8667. client = printer_manager.get_client(printer_id)
  8668. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8669. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8670. if publish_landed:
  8671. logger.warning(
  8672. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8673. "received the command and is parsing slowly. Skipping forced "
  8674. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8675. queue_item_id,
  8676. current_gcode_file,
  8677. pre_gcode_file,
  8678. )
  8679. elif client and hasattr(client, "force_reconnect_stale_session"):
  8680. client.force_reconnect_stale_session(
  8681. f"queue print command unacknowledged after {timeout:.0f}s "
  8682. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8683. )
  8684. # Global scheduler instance
  8685. scheduler = PrintScheduler()