print_scheduler.py 494 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762
  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 typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import derive_remote_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. select_plate_gcode_name,
  90. )
  91. logger = logging.getLogger(__name__)
  92. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  93. """Human slot name for an assignment tuple, in the spelling already in use.
  94. Composed from the notification side's own pair rather than spelled out again
  95. here. The hand-rolled version this replaces got three real slot kinds wrong:
  96. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  97. ``chr(191)``; both externals collapsed to one label, because an external
  98. assignment stores ams_id 255 with tray_id picking left or right
  99. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  100. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  101. Naming the same slot two ways is its own defect once an alert and the
  102. Inventory page are meant to be talking about the same tray, so this defers
  103. rather than adding a fifth spelling.
  104. """
  105. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  106. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  107. # interval: the fast path runs every 3 s while an upload is in flight, and a
  108. # low spool does not need answering at that resolution (#2913).
  109. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  110. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  111. # days, so a finer check would only repeat the same answer.
  112. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  113. # The settings row that holds which stock alerts have already been sent (#2955).
  114. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  115. # The Inventory page asks for this many usage records and the forecast panel
  116. # builds its rates from them; the alert reads the same window so the two agree.
  117. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  118. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  119. """Remaining filament as a percentage of the label weight.
  120. The same arithmetic the Inventory page's Low Stock count uses, and it works
  121. unchanged in both inventory modes: internal spools store ``weight_used``
  122. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  123. ``remaining_weight`` so the shape matches. Returns None when there is no
  124. label weight to be a percentage of -- a spool that cannot say how full it
  125. started cannot say how empty it is.
  126. """
  127. if not label_weight or label_weight <= 0:
  128. return None
  129. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  130. return remaining / float(label_weight) * 100.0
  131. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  132. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  133. # byte gate) from before the scheduler unification. Time gate keeps small
  134. # files from going silent (a single 8 KB chunk fires once and that's it);
  135. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  136. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  137. # sub-200 ms files.
  138. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  139. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  140. # How far back chamber temperature samples are retained. 2h comfortably spans
  141. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  142. # before the next print.
  143. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  144. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  145. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  146. # who clear plates promptly will want far less than this; it is deliberately
  147. # the cautious end, since the cost of it being too short is only a re-soak.
  148. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  149. # Max acceptable gap between two consecutive chamber samples before we treat
  150. # the older one as belonging to a separate observation run (printer went
  151. # offline and came back). Above ~30s cadence with a safety margin.
  152. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  153. # How long the chamber must read below target before we accept that it really
  154. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  155. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  156. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  157. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  158. # sub-target readings are therefore a door opening or noise, not lost soak,
  159. # and a plate swap (exactly when keep-warm is running) produces one. Six
  160. # minutes clears the longest such artifact observed (~5 min once bracketed by
  161. # its neighbouring samples) and still sits far below the 23-minute floor for
  162. # real cooling.
  163. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  164. # How often the preheat stage re-checks that the item it is heating for still
  165. # wants to be printed. Cancelling only writes `status` to the database — it
  166. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  167. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  168. # and the printer stays in `busy_printers`, blocking every other queued item
  169. # behind a print that is not happening.
  170. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  171. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  172. _AIRDUCT_MODE_COOLING = 0
  173. _AIRDUCT_MODE_HEATING = 1
  174. # How long a queue row may stay 'printing' while its printer sits in a terminal
  175. # state before the scheduler closes it itself (#2829).
  176. #
  177. # A real completion arrives within seconds of the printer going terminal, so
  178. # five minutes is far outside the normal path — this only ever sees a row whose
  179. # completion was refused or never delivered. It is the whole cost of the
  180. # failure to the user, though: a stranded row blocks every later job for that
  181. # printer, so it should not be raised without reason.
  182. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  183. # gcode_state values that mean the print is over, mapped to the queue status
  184. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  185. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  186. # which the queue calls cancelled) so a recovered row cannot disagree with one
  187. # closed by the normal path.
  188. _TERMINAL_STATE_QUEUE_STATUS = {
  189. "FINISH": "completed",
  190. "FAILED": "failed",
  191. "IDLE": "cancelled",
  192. }
  193. def _terminal_queue_status(state) -> str | None:
  194. """Queue status implied by *state*, or None if the print is not over.
  195. None for a disconnected printer as well as a busy one: a printer we are not
  196. talking to has a stale ``state`` field that proves nothing about what it is
  197. doing now.
  198. """
  199. if state is None or not getattr(state, "connected", False):
  200. return None
  201. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  202. @dataclass
  203. class _KeepWarmEntry:
  204. """Per-printer keep-warm state.
  205. - ``started``: monotonic time when keep-warm first fired for this printer.
  206. Used by the max-duration timeout.
  207. - ``held_target``: last bed target we successfully published. On release
  208. we only send bed-off when firmware still reports this value, so a user
  209. or subsequent print that changed the target isn't clobbered.
  210. - ``expired``: latched True when the max-duration timeout fires. Prevents
  211. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  212. release sweep drops the entry entirely once the printer leaves the
  213. candidate set.
  214. """
  215. started: float
  216. held_target: int
  217. expired: bool = False
  218. # Auto-drying re-arm guards (#2770).
  219. #
  220. # An AMS reports HIGHER relative humidity while it is warm than once it has
  221. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  222. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  223. # threshold set inside that band therefore cannot be satisfied while the box is
  224. # hot, and the firmware is free to end a cycle whenever it decides the filament
  225. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  226. # the threshold and arms another cycle. The reporter's log has five 12-hour
  227. # cycles armed inside four hours, one of them six seconds after the previous
  228. # ended.
  229. #
  230. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  231. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  232. # manual or firmware-run dry is untouched.
  233. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  234. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  235. # Sustained-humidity wait (#2518): an above-threshold streak is only
  236. # "continuous" if some pass observed it within the gap ceiling. A unit that
  237. # goes unobserved longer (print running, printer disconnected, sensor silent)
  238. # restarts its streak rather than inheriting a stale one. The ceiling is
  239. # derived from the scheduler cadence — four missed passes — with this floor so
  240. # a fast-polling configuration does not void streaks on a single hiccup.
  241. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  242. # How long a finished scheduled drying row is kept before it is pruned.
  243. SCHEDULED_DRYING_RETENTION_DAYS = 7
  244. # How often that prune actually runs. The check itself is called on every queue
  245. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  246. # write transaction, which SQLite serialises against every other writer. Rows
  247. # only become prunable a week after they finish, so anything short of hourly is
  248. # paying that cost for nothing.
  249. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  250. class _UploadProgressBridge:
  251. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  252. ``upload_file_async`` runs the FTP transfer in an executor thread and
  253. invokes its ``progress_callback`` from that thread, so the callback
  254. body cannot ``await`` directly. This bridge captures the asyncio loop
  255. at construction (on the scheduler thread) and uses
  256. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  257. matches the legacy background_dispatch.py path 1:1 so the toast feels
  258. identical to the pre-#1625 experience.
  259. Failures inside the emit are swallowed — progress is a UX nicety, the
  260. upload itself must not fail because of a WS hiccup.
  261. """
  262. def __init__(self, user_id: int | None, queue_item_id: int):
  263. self._user_id = user_id
  264. self._queue_item_id = queue_item_id
  265. try:
  266. self._loop = asyncio.get_running_loop()
  267. except RuntimeError:
  268. self._loop = None
  269. self._last_emit_bytes = 0
  270. self._last_emit_monotonic = 0.0
  271. self._has_emitted = False
  272. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  273. if self._loop is None or total_bytes <= 0:
  274. return
  275. now = time.monotonic()
  276. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  277. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  278. # the four matter most: first-call so the user sees something even
  279. # for sub-chunk-size files; uploaded >= total so the bar locks at
  280. # 100% even when the throttle would otherwise eat it.
  281. should_emit = (
  282. not self._has_emitted
  283. or bytes_transferred >= total_bytes
  284. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  285. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  286. )
  287. if not should_emit:
  288. return
  289. self._has_emitted = True
  290. self._last_emit_bytes = bytes_transferred
  291. self._last_emit_monotonic = now
  292. try:
  293. asyncio.run_coroutine_threadsafe(
  294. ws_manager.send_queue_item_upload_progress(
  295. user_id=self._user_id,
  296. queue_item_id=self._queue_item_id,
  297. bytes_transferred=bytes_transferred,
  298. total_bytes=total_bytes,
  299. ),
  300. self._loop,
  301. )
  302. except Exception:
  303. pass # progress is best-effort, never block the upload
  304. # Bambu firmware states that mean the project_file has actually been accepted
  305. # and the printer is now processing / running / paused mid-print. Used by the
  306. # dispatch watchdog (#1370): a transition into one of these states means the
  307. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  308. # a post-print prompt) is NOT a valid "command landed" signal even though the
  309. # state value did change. SLICING is included because some firmwares park
  310. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  311. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  312. # How many times the start-watchdog may revert an item to 'pending' before it
  313. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  314. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  315. # both never recovers and starves the other printers of dispatch slots. Three
  316. # is chosen to clear the transient causes the watchdog already recovers from —
  317. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  318. # force-reconnect on the very next attempt — while still bounding the loop.
  319. DISPATCH_MAX_ATTEMPTS = 3
  320. # Upload failures that mean the file never reached the printer's storage: the
  321. # file service refused or never answered (#3210). These put the item back in
  322. # the queue instead of failing it, because nothing about the job is wrong --
  323. # and failing it left the printer idle, so the next pass handed it the next
  324. # item, which failed the same way. One P2S whose file service was out of
  325. # connection slots ate 43 queued jobs in ten minutes that way.
  326. #
  327. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  328. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  329. # and an upload that overran its deadline -- each of those would fail the same
  330. # way on every retry.
  331. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  332. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  333. )
  334. # How long a printer whose upload was put back stays out of dispatch (#3210).
  335. # The first window matches the FTP client's own handshake cool-off, so the
  336. # retry lands after the client would talk to the printer again anyway. Each
  337. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  338. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  339. # five connection attempts and a page of log. A successful upload resets it.
  340. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  341. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  342. def _upload_backoff_seconds(refusals: int) -> int:
  343. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  344. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  345. @dataclass(slots=True)
  346. class _ModelCandidate:
  347. """One (file, printer model) pair the model-based matcher may try.
  348. Model-based assignment used to have exactly one of these per item, held
  349. directly in the item's own columns. Cross-model queue items (#671) have
  350. several, held in ``print_queue_variants``. Both shapes are normalised into
  351. this so the matching, the cross-model gate and the waiting-reason handling
  352. are written once and an item without variants provably takes the same path
  353. it took before variants existed.
  354. ``variant`` is None for the item's own columns and set for a real variant
  355. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  356. item once that candidate wins.
  357. """
  358. target_model: str | None
  359. sliced_for: str | None
  360. required_filament_types: str | None
  361. filament_overrides: str | None
  362. variant: "PrintQueueVariant | None" = None
  363. def _sliced_for_model(archive, library_file) -> str | None:
  364. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  365. if archive is not None:
  366. return archive.sliced_for_model
  367. if library_file is not None and library_file.file_metadata:
  368. return library_file.file_metadata.get("sliced_for_model")
  369. return None
  370. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  371. """The filament a candidate needs, as ``(types, overrides)``.
  372. Both columns are JSON text written by the slicer step. Malformed content is
  373. treated as no constraint rather than as an error: a job whose overrides
  374. cannot be parsed still prints, it just gets no filament-based narrowing.
  375. Overrides carry their own types, so the returned type list is the union of
  376. the two — an override on one slot must not drop the requirements of the
  377. slots it says nothing about.
  378. Shared by the matcher and by the smart-plug wake step so both ask a printer
  379. for the same filament (#2876). Waking a printer the matcher would then
  380. reject on colour is the bug this exists to prevent.
  381. """
  382. required_types = None
  383. if candidate.required_filament_types:
  384. try:
  385. required_types = json.loads(candidate.required_filament_types)
  386. except json.JSONDecodeError:
  387. pass
  388. filament_overrides = None
  389. if candidate.filament_overrides:
  390. try:
  391. filament_overrides = json.loads(candidate.filament_overrides)
  392. except json.JSONDecodeError:
  393. pass
  394. effective_types = required_types
  395. if filament_overrides:
  396. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  397. if override_types:
  398. effective_types = sorted(set(required_types or []) | set(override_types))
  399. return effective_types, filament_overrides
  400. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  401. """Whether ``item`` was competing for the printer another item just took.
  402. The SJF starvation guard marks a job as jumped when a shorter one lower in
  403. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  404. compete for the same printer, so the guard has to look across both lanes
  405. (#3200); looking only inside the dispatched item's own lane let a stream of
  406. short model-based jobs hold a longer pinned job back indefinitely.
  407. Location filters are not checked: over-marking only lifts an item that was
  408. going to wait anyway, while under-marking is the starvation this prevents.
  409. """
  410. if item.printer_id is not None:
  411. return item.printer_id == printer_id
  412. if not printer_model:
  413. return False
  414. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  415. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  416. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  417. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  418. """Candidate files for ``item``, best first.
  419. An item with no variant rows yields exactly one candidate built from its own
  420. columns — the pre-#671 behaviour, unchanged.
  421. Variants come back least-attempted first, ties broken by the user's
  422. ``position``. On the first pass every count is zero, so this is purely the
  423. user's priority order. After a start-watchdog bounce the printer that failed
  424. drops behind, so the next lap tries the other machine rather than spending the
  425. item's whole retry budget on the one that is wedged. Once every candidate has
  426. been tried equally often they cycle again, which keeps the item-level
  427. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  428. still gives up, it just does not give up without trying them.
  429. """
  430. if not item.variants:
  431. if not item.archive_id and not item.library_file_id:
  432. # Nothing to print at all. Dispatching would fail deep in the upload
  433. # on "No archive_id or library_file_id"; the caller holds the item
  434. # with an explanation instead.
  435. return []
  436. return [
  437. _ModelCandidate(
  438. target_model=item.target_model,
  439. sliced_for=_sliced_for_model(item.archive, item.library_file),
  440. required_filament_types=item.required_filament_types,
  441. filament_overrides=item.filament_overrides,
  442. )
  443. ]
  444. # Drop candidates whose file is gone or in the trash. Both are reachable and
  445. # neither is covered by the schema: library deletes are soft (the row lives
  446. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  447. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  448. # fires there and a hard delete leaves the variant row pointing at nothing.
  449. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  450. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  451. return [
  452. _ModelCandidate(
  453. target_model=v.target_model,
  454. sliced_for=_sliced_for_model(None, v.library_file),
  455. required_filament_types=v.required_filament_types,
  456. filament_overrides=v.filament_overrides,
  457. variant=v,
  458. )
  459. for v in ordered
  460. ]
  461. # Why a job for any printer of a model waits when every free one's last print
  462. # failed. The queue page matches it to offer Resume for the model.
  463. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  464. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  465. """Fold one waiting reason per candidate into a single line for the item.
  466. A cross-model item produces a reason per candidate, and pasting them
  467. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  468. — on which machine?). Each reason is prefixed with its model, except in the
  469. single-candidate case where the item already displays its target model and
  470. the prefix would be noise.
  471. Identical reasons collapse rather than repeat, so three idle-less models
  472. read as one clause.
  473. When *every* candidate is merely busy the parts are joined with the ``" | "``
  474. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  475. unprefixed. That case must keep testing busy-only: a fleet that is simply
  476. printing needs no user action, and labelling the clauses would turn each pass
  477. over a two-model item into a "job waiting" notification.
  478. """
  479. reasons = [(model, reason) for model, reason in per_model if reason]
  480. if not reasons:
  481. return None
  482. if len(reasons) == 1:
  483. return reasons[0][1]
  484. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  485. if len(distinct) == 1:
  486. return distinct[0]
  487. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  488. return " | ".join(distinct)
  489. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  490. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  491. """Human label for the models an item is waiting on ("H2S or H2C").
  492. Notifications take a single target model. For a cross-model item the item's
  493. own ``target_model`` is whichever variant happens to be first, which reads as
  494. a lie once it is the H2C that actually runs — so name all of them.
  495. """
  496. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  497. if not models:
  498. return None
  499. return " or ".join(models)
  500. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  501. """True if ``mapping`` is a non-empty list whose every entry is the
  502. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  503. Such a mapping is a bug artifact: a frontend status-load race can serialize
  504. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  505. recomputed from live status at dispatch rather than trusted, otherwise it
  506. reaches the print command and is silently downgraded to external-spool mode.
  507. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  508. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  509. explicit external selection (``>= 254``) is NOT unresolved either — those
  510. keep their meaning.
  511. """
  512. if not isinstance(mapping, list) or not mapping:
  513. return False
  514. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  515. def _is_tray_id(value: object) -> bool:
  516. """True when ``value`` can be read as a global tray ID.
  517. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  518. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  519. against whatever happens to be loaded there.
  520. """
  521. return isinstance(value, int) and not isinstance(value, bool)
  522. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  523. # stages an item (#2799). The manual_start branch clears every other reason on
  524. # a staged item (#3074); this one is the reason it was staged, so it stays.
  525. _UNMATCHED_HOLD_PREFIX = "Needs "
  526. # How often an "any model" job held for low filament looks for another printer
  527. # of its model that has enough (#3137). Each look matches its filament on every
  528. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  529. _SHORT_HOLD_RECHECK_SECONDS = 120
  530. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  531. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  532. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  533. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  534. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  535. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  536. for a filament this plate does not use. A slot past the end of the mapping
  537. is unresolved too.
  538. """
  539. unresolved = []
  540. for req in required:
  541. slot_id = req.get("slot_id") or 0
  542. if slot_id <= 0:
  543. continue
  544. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  545. if not _is_tray_id(tray) or tray < 0:
  546. unresolved.append(req)
  547. return unresolved
  548. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  549. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  550. # on `_mapping_is_all_unresolved`.
  551. _EXTERNAL_TRAY_ID_MIN = 254
  552. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  553. """The ``mapping`` entries for the slots this plate actually prints.
  554. ``required`` comes from ``extract_filament_requirements``, which drops any
  555. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  556. consumes, and one absent from it is padding. That distinction is why this
  557. decision lives here and not in the MQTT command builder: a ``-1`` in the
  558. mapping means either "this plate does not print filament N" or "we never
  559. worked out which tray", and only the plate's own filament list separates
  560. them. The builder sees both as the same byte, which is how a plate whose one
  561. printed filament sat on the external spool went out as `use_ams=true` with a
  562. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  563. with 07FF_8012 (#3087).
  564. Returns None whenever the two cannot be lined up — no mapping, no parsed
  565. requirements, or a requirement the mapping is too short to cover — so every
  566. caller falls back to existing behaviour rather than acting on a guess.
  567. """
  568. if not isinstance(mapping, list) or not mapping or not required:
  569. return None
  570. entries = []
  571. for filament in required:
  572. slot_id = filament.get("slot_id")
  573. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  574. # The mapping and the requirements disagree about how many filaments
  575. # the file has. They came from different reads, so judge nothing.
  576. return None
  577. entries.append(mapping[slot_id - 1])
  578. return entries or None
  579. def _is_external_tray(tray_id) -> bool:
  580. """True for an explicit external-spool selection (254/255), not for an
  581. unresolved slot and not for an AMS tray."""
  582. if tray_id is None:
  583. return False
  584. try:
  585. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  586. except (TypeError, ValueError):
  587. return False
  588. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  589. """Whether this printer could have two extruders, judged generously.
  590. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  591. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  592. why the MQTT command builder skips its own use_ams reconcile there. Anything
  593. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  594. with, external spools or not.
  595. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  596. behaviour it has always had, while a wrong "no" would rewrite a field that
  597. steers which nozzle prints. The model name is the first answer (it is what
  598. the command builder falls back to as well), then the same live evidence the
  599. dispatcher's extruder annotation uses — a second nozzle reporting a
  600. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  601. since a single-nozzle printer has exactly one.
  602. """
  603. if is_dual_nozzle_model(printer_model):
  604. return True
  605. nozzles = getattr(status, "nozzles", None) or []
  606. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  607. return True
  608. raw = getattr(status, "raw_data", None) or {}
  609. if raw.get("ams_extruder_map"):
  610. return True
  611. vt_trays = raw.get("vt_tray") or []
  612. return isinstance(vt_trays, list) and len(vt_trays) > 1
  613. def _int_or(value, default: int) -> int:
  614. """``int(value)``, or ``default`` when the field is missing or junk.
  615. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  616. the next — and a tray id that fails to parse must not take the whole
  617. derivation down with it.
  618. """
  619. try:
  620. return int(value)
  621. except (TypeError, ValueError):
  622. return default
  623. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  624. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  625. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  626. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  627. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  628. agree or a mapping cannot be read back against live tray telemetry.
  629. """
  630. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  631. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  632. """The global tray ids ``item`` actually prints from, or None if unknown.
  633. ``ams_mapping`` is the array the print command carries: position = filament
  634. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  635. not use. None means "no usable statement" — no mapping, unparseable JSON,
  636. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  637. documents), or one that resolves to no tray at all. Callers must treat None
  638. as "consider every loaded tray" rather than "consider none": narrowing on
  639. an absent mapping would silently drop requirements the print really has.
  640. """
  641. raw = getattr(item, "ams_mapping", None)
  642. if not raw:
  643. return None
  644. if isinstance(raw, str):
  645. try:
  646. mapping = json.loads(raw)
  647. except (json.JSONDecodeError, TypeError):
  648. return None
  649. else:
  650. mapping = raw
  651. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  652. return None
  653. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  654. return used or None
  655. def _mqtt_commands_rejected(status) -> bool:
  656. """True when the printer is currently reporting that it refused a command.
  657. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  658. a control command it could not verify. Queries still answer, so the printer
  659. looks connected and idle while project_file, gcode_line and
  660. ams_change_filament are all dropped — no amount of waiting or re-uploading
  661. changes that (#2732).
  662. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  663. ``print_error`` path builds HMSError differently), so this is safe to call on
  664. every watchdog poll.
  665. """
  666. for err in getattr(status, "hms_errors", None) or []:
  667. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  668. return True
  669. return False
  670. def _drying_ams_ids(status) -> list[int]:
  671. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  672. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  673. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  674. started (#2758) — it is a diagnostic, not a gate.
  675. Deliberately not used to block or stop drying before dispatch. This printer
  676. class supports drying concurrently with an active print
  677. (``supports_drying_while_printing``), so drying is not incompatible with
  678. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  679. while two AMS units were drying, one of them without its external PSU. Until
  680. it is known whether the blocker is drying itself or the power budget
  681. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  682. hardware is perfectly happy to continue.
  683. """
  684. ids: list[int] = []
  685. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  686. if not isinstance(unit, dict):
  687. continue
  688. try:
  689. if int(unit.get("dry_time") or 0) > 0:
  690. ids.append(int(unit.get("id", 0)))
  691. except (TypeError, ValueError):
  692. continue
  693. return ids
  694. def _parse_diameter(raw) -> float | None:
  695. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  696. try:
  697. value = float(raw)
  698. except (TypeError, ValueError):
  699. return None
  700. return value if value > 0 else None
  701. def _nozzle_info_by_id(status) -> dict[int, dict]:
  702. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  703. The field name is historical: on the H2 series ``nozzle_info`` carries an
  704. entry for *every* nozzle the printer knows about — the L/R hotends under
  705. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  706. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  707. :func:`_installed_nozzle_diameters` each take the half they need.
  708. """
  709. by_id: dict[int, dict] = {}
  710. for entry in getattr(status, "nozzle_rack", None) or []:
  711. if not isinstance(entry, dict):
  712. continue
  713. try:
  714. by_id[int(entry.get("id"))] = entry
  715. except (TypeError, ValueError):
  716. continue
  717. return by_id
  718. # What the firmware puts in a nozzle's serial number when the carriage or dock
  719. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  720. # its nozzle back in the rack (#2885).
  721. _EMPTY_NOZZLE_SERIAL = "N/A"
  722. def _nozzle_is_mounted(entry: dict | None) -> bool:
  723. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  724. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  725. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  726. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  727. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  728. the dock. So the diameter is not a presence signal (#2885).
  729. Emptiness has to be stated, not merely unstated. The serial must be the
  730. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  731. absent — an empty serial only means the printer didn't say, and a firmware
  732. that reports neither field normalises to exactly that. Treating "didn't
  733. say" as "empty" would silently switch the #1899 guard off on any such
  734. machine, so everything we cannot positively call empty counts as mounted.
  735. """
  736. if entry is None:
  737. return True
  738. serial = str(entry.get("serial_number") or "").strip().upper()
  739. if serial != _EMPTY_NOZZLE_SERIAL:
  740. return True
  741. try:
  742. max_temp = float(entry.get("max_temp") or 0)
  743. except (TypeError, ValueError):
  744. return True
  745. return max_temp > 0
  746. def _installed_nozzle_diameters(status) -> list[float]:
  747. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  748. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  749. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  750. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  751. told us its nozzle hardware" — callers must treat that as unknown, not as a
  752. mismatch, so we never block a print on missing data.
  753. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  754. though ``nozzles`` still carries a diameter for it: that value is stale, and
  755. counting it would let a slice match a nozzle the machine does not have
  756. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  757. """
  758. info = _nozzle_info_by_id(status)
  759. diameters: list[float] = []
  760. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  761. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  762. try:
  763. value = float(raw)
  764. except (TypeError, ValueError):
  765. continue
  766. if value > 0 and _nozzle_is_mounted(info.get(index)):
  767. diameters.append(value)
  768. return diameters
  769. def _rack_nozzle_diameters(status) -> list[float]:
  770. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  771. Keyed off the nozzle ids themselves rather than the printer model: only a
  772. rack machine ever reports ids 16-21, so there is no model registry to keep
  773. in sync. An empty dock is simply absent from the payload — measured on an
  774. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  775. present — so appearing here already means "a nozzle is in that dock".
  776. ``stat`` is deliberately not interpreted: its values aren't known, and
  777. reading it wrongly could hide a nozzle the printer would happily fetch.
  778. """
  779. diameters: list[float] = []
  780. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  781. if nozzle_id not in _RACK_NOZZLE_IDS:
  782. continue
  783. # PrinterState spells it "diameter"; the REST schema renames it to
  784. # "nozzle_diameter". Accept either so a caller holding the serialised
  785. # shape gets the same answer.
  786. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  787. if value is not None:
  788. diameters.append(value)
  789. return diameters
  790. def _format_diameters(diameters: list[float]) -> str:
  791. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  792. Deduplicated because a loaded rack holds several nozzles of the same size,
  793. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  794. short form doesn't. Matching still runs over the full list.
  795. """
  796. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  797. def _nozzle_mismatch_message(
  798. sliced_nozzle: float | None,
  799. installed: list[float],
  800. rack: list[float] | None = None,
  801. ) -> str | None:
  802. """Return an actionable error message when the sliced nozzle can't be
  803. printed on any nozzle the machine can reach, else None (#1899).
  804. Fail-safe: returns None whenever we lack the data to judge — no sliced
  805. diameter, or the printer reported no nozzles — so a print is only ever
  806. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  807. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  808. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  809. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  810. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  811. as reachable: the printer fetches one as part of starting the print, so a
  812. slice that matches a docked nozzle is not a mismatch. Without this the
  813. guard blocked every job whose nozzle happened not to be on a hotend at
  814. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  815. diameter already mounted could ever print, and the user had to fetch the
  816. nozzle by hand on the printer's own UI first (#2885).
  817. """
  818. reachable = [*installed, *(rack or [])]
  819. if not sliced_nozzle or not reachable:
  820. return None
  821. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  822. return None
  823. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  824. if rack:
  825. where += f" and {_format_diameters(rack)} in the nozzle rack"
  826. return (
  827. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  828. f"{where}. Re-slice for an available nozzle, or fit the matching "
  829. f"nozzle before printing."
  830. )
  831. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  832. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  833. Shared by the required and loaded sides, which name their extruder
  834. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  835. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  836. 1 the left/deputy — and both are absent on single-nozzle printers, where
  837. naming a nozzle would be noise.
  838. """
  839. parts = [(entry.get("type") or "filament").upper()]
  840. if entry.get("color"):
  841. parts.append(str(entry["color"]))
  842. nozzle = entry.get(nozzle_key)
  843. if nozzle == 0:
  844. parts.append("(right nozzle)")
  845. elif nozzle == 1:
  846. parts.append("(left nozzle)")
  847. return " ".join(parts)
  848. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  849. """Explain that nothing loaded matches what the file needs (#2771).
  850. Only ever built for a printer with no AMS, where the loaded list is short
  851. enough to quote in full and there is no "load another spool and hit Resume"
  852. recovery — the external spool holder is all there is, so the user needs to
  853. be told which filament to put on it.
  854. """
  855. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  856. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  857. return (
  858. f"No filament loaded on this printer matches the file. It needs {want}; "
  859. f"the printer has {have} and no AMS. Load the required filament on the "
  860. f"external spool holder, or send this job to a printer that has it."
  861. )
  862. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  863. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  864. every call site below it: G-code injection, usage registration, rack-plan
  865. lookup, slot-extruder lookup, the external-spool check, and the actual
  866. print command.
  867. A positive explicit ``plate_id`` on the queue item always wins. A
  868. non-positive one is treated as "not set" and resolved from the archive,
  869. the way the rest of the queue code already reads it (``if item.plate_id:``
  870. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  871. field, and passing a 0 straight through would build a print command for
  872. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  873. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  874. Falling back to a bare ``1`` instead of reading the archive assumes a
  875. single-plate file's one G-code is numbered 1, which only holds for a
  876. plate exported on its own: one cut out of a larger project keeps its
  877. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  878. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  879. the file, throws an HMS error, and sits wedged in IDLE until
  880. power-cycled (#2947).
  881. The call sites agreed on a fallback only by accident before this:
  882. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  883. the archive's own default plate internally whenever the plate id it's
  884. handed isn't in the file, so it could silently inject into a different
  885. plate than the one the print command itself asked for.
  886. Falls back to 1 when the archive can't be read, holds no G-code member at
  887. all, or its default member doesn't follow the ``plate_N`` naming
  888. convention (a slicer that doesn't use it has no number to dispatch).
  889. An explicit plate the archive doesn't hold is logged and then sent
  890. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  891. to a plate that is in the file would print a model nobody asked for,
  892. which is the worse of the two.
  893. """
  894. try:
  895. with zipfile.ZipFile(file_path, "r") as zf:
  896. names = zf.namelist()
  897. except (OSError, zipfile.BadZipFile) as exc:
  898. logger.warning(
  899. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  900. "is unavailable; dispatching plate %s",
  901. file_path,
  902. exc,
  903. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  904. )
  905. names = None
  906. if explicit_plate_id is not None and explicit_plate_id > 0:
  907. if (
  908. names is not None
  909. and default_plate_number(names) is not None
  910. and select_plate_gcode_name(names, explicit_plate_id) is None
  911. ):
  912. logger.warning(
  913. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  914. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  915. "file, since printing a different plate would print the wrong model (#2947)",
  916. file_path,
  917. explicit_plate_id,
  918. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  919. explicit_plate_id,
  920. )
  921. return explicit_plate_id
  922. resolved = default_plate_number(names) if names is not None else None
  923. return resolved if resolved is not None else 1
  924. class PrintScheduler:
  925. """Background scheduler that processes the print queue."""
  926. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  927. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  928. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  929. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  930. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  931. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  932. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  933. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  934. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  935. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  936. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  937. }
  938. def __init__(self):
  939. self._running = False
  940. self._check_interval = 30 # seconds
  941. # After a pass that actually dispatched something, loop again almost
  942. # immediately instead of sleeping the full interval (#2555). A dispatch
  943. # changes printer state — a batch launch fans out over several passes as
  944. # printers free up, a wedged head-of-line job reverts to pending, an
  945. # upload slot opens — and the next batch of ready work should not have to
  946. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  947. # pending items are behind printers that are genuinely busy printing),
  948. # there is nothing to react to, so we fall back to the normal interval;
  949. # that also means this can never tight-loop, since fast ticks only
  950. # continue while dispatches keep happening and the queue is draining.
  951. self._fast_check_interval = 3 # seconds
  952. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  953. self._power_on_check_interval = 10 # seconds between connection checks
  954. # Printers whose class-target power-on failed, mapped to the monotonic
  955. # time their cool-off expires (#2786).
  956. #
  957. # Without this, one printer with an unreachable plug starves every
  958. # sibling of its model forever: the wake step walks candidates in id
  959. # order, spends the pass's single attempt on the same broken printer
  960. # every time, and the healthy one two slots down is never reached. It
  961. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  962. # which delays the whole queue, not just this job.
  963. #
  964. # Entries expire on read rather than being cleared on success: a printer
  965. # inside its cool-off is skipped before the power-on is reached, so a
  966. # live entry can never be overwritten by a success anyway. A printer
  967. # that comes back by any other route stops being a wake candidate the
  968. # moment it connects.
  969. self._wake_failures: dict[int, float] = {}
  970. self._wake_failure_cooloff = 600 # seconds
  971. # Printers whose last upload never reached them, mapped to the monotonic
  972. # time they may be dispatched to again (#3210). Same expire-on-read shape
  973. # as `_wake_failures`. Without it, a printer that cannot take files is
  974. # idle on every pass, so it is picked on every pass.
  975. self._upload_backoff: dict[int, float] = {}
  976. # Refused uploads in a row per printer, which sets the next backoff
  977. # window. Cleared by a successful upload to that printer.
  978. self._upload_refusals: dict[int, int] = {}
  979. # Printers whose current run of refusals has already sent its one
  980. # "job waiting" notification. Each retry clears the item's waiting
  981. # reason and the next refusal sets it again, which `hold_item` reads as
  982. # a new reason; without this, every retry would notify. Cleared with
  983. # `_upload_refusals`.
  984. self._upload_refusal_notified: set[int] = set()
  985. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  986. self._drying_in_progress: dict[int, float] = {}
  987. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  988. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  989. # cycle and the humidity finally coming down, so the normal steady
  990. # state is an empty dict. Fields:
  991. # running — a cycle we armed is (or should be) on the firmware
  992. # ended_at — monotonic when we observed that cycle end
  993. # unproductive — consecutive armed cycles that ended with the reading
  994. # still above the threshold
  995. # suspended — we have stopped arming this unit and said so
  996. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  997. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  998. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  999. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1000. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1001. # arming setdefault all act on that meaning -- a unit that is merely
  1002. # waiting out its streak must not become stoppable or judgeable.
  1003. # since -- monotonic stamp when the current continuous above-threshold
  1004. # streak began
  1005. # last -- monotonic stamp of the last pass that observed the streak
  1006. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1007. # Slots already notified as low on filament:
  1008. # {(printer_id, ams_id, tray_id, spool_id)}.
  1009. # Cleared when the slot goes back above its threshold rather than on a
  1010. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1011. # boundary must not produce an alert on every pass, and a slot that has
  1012. # been refilled has to be able to alert again. See #2913.
  1013. #
  1014. # The spool id is part of the key because the slot alone cannot clear
  1015. # itself. Pull a low spool and put a different part-used one in the same
  1016. # slot: the key survives the pass where the slot resolves to nothing --
  1017. # deliberately, so a brief Spoolman outage does not re-alert everything
  1018. # when it returns -- and the replacement never goes above the threshold,
  1019. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1020. # different key and the stale one is inert.
  1021. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1022. # The same, for the MQTT relay's filament/low event: its own record, so
  1023. # one channel having been told never silences the other.
  1024. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1025. # Earliest monotonic time the next low-filament check may run (#2913).
  1026. self._filament_low_next_check: float = 0.0
  1027. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1028. # condition is "reorder" or "break", the events are those that had a
  1029. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1030. # condition clears, so it can alert again, and when nobody wants either
  1031. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1032. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1033. # re-send one message per SKU that is still low.
  1034. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1035. # The JSON last read from or written to that row; None until it has been read.
  1036. self._stock_alerts_persisted: str | None = None
  1037. # Earliest monotonic time the next stock forecast check may run (#2955).
  1038. self._stock_forecast_next_check: float = 0.0
  1039. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1040. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1041. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1042. # both features share _drying_in_progress.
  1043. self._scheduled_drying_printer_ids: set[int] = set()
  1044. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1045. # the first pass after a restart reaps anything left behind.
  1046. self._last_scheduled_drying_prune: float | None = None
  1047. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1048. # a project_file command must not get a second dispatch until either it
  1049. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1050. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1051. # during that window the DB busy_printers seed is empirically unreliable
  1052. # (multi-plate batches double-/triple-dispatched onto the same printer
  1053. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1054. # or revert.
  1055. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1056. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1057. # Minimum cooldown between dispatches to the same printer (covers the
  1058. # H2D's project_file digestion window).
  1059. self._dispatch_min_cooldown = 60.0
  1060. # Hard timeout — drop the hold even if we never observed a transition,
  1061. # so a lost MQTT session can't lock a printer out of the queue forever.
  1062. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1063. # watchdog runs first on the unhappy path.
  1064. self._dispatch_max_hold = 180.0
  1065. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1066. # an earlier pass and is still running. `_start_print` flips the row
  1067. # pending -> printing only *after* the upload completes, so until then
  1068. # the row stays `pending`: each tick, check_queue excludes these
  1069. # item_ids from re-selection and their printers from new dispatch /
  1070. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1071. # freed slots refill on the next fast tick. check_queue is the sole,
  1072. # sequential caller and the prune done-callbacks run in the same
  1073. # event-loop thread, so this dict needs no lock.
  1074. # item_id -> (task, printer_id)
  1075. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1076. # Expected prints registered by `_start_print` that have not yet had a
  1077. # print command sent. Populated at registration, dropped once
  1078. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1079. # other exit. Same threading argument as `_inflight` above: one
  1080. # sequential caller, callbacks on the same loop, so no lock.
  1081. # item_id -> (printer_id, remote_filename, archive_id)
  1082. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1083. # Budget reservations created for a dispatch whose print command has
  1084. # not been confirmed yet. `_dispatch_one` releases these on every
  1085. # unsuccessful exit; a successful start removes the item id and leaves
  1086. # the reservation for finance_billing to consume with the archive.
  1087. self._unconfirmed_budget_reservations: set[int] = set()
  1088. # The print user `_start_print` handed to printer_manager for an item
  1089. # whose print command has not been sent yet (item_id -> printer_id).
  1090. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1091. # expected print above: it marks the printer's next print as Bambuddy's.
  1092. self._unconfirmed_print_user: dict[int, int] = {}
  1093. # Prints whose command went out but which the printer has not been
  1094. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1095. # the file and archive None for a library print. The watchdog drops the
  1096. # entry once the print runs, and withdraws what it stands for when the
  1097. # print never starts (see `_forget_unstarted_print`).
  1098. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1099. # Chamber temperature history for smart soak-time reduction.
  1100. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1101. # Entries older than _chamber_history_ttl are pruned on write.
  1102. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1103. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1104. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1105. # Populated on engagement in `_apply_keep_warm`, cleared by
  1106. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1107. # when a gate setting toggles off mid-hold — the release publishes
  1108. # bed → 0 first).
  1109. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1110. # Preheat rollback registry: printer_id -> subset of
  1111. # {"bed", "chamber", "airduct"} listing which preheat commands
  1112. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1113. # every entry still present at exit unless the print successfully
  1114. # started, so a failed upload / cancel / exception never leaves the
  1115. # printer heating for a job that isn't happening.
  1116. self._preheat_pin: dict[int, set[str]] = {}
  1117. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1118. # rollback can tell its own target from one someone else has since
  1119. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1120. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1121. self._preheat_pin_bed: dict[int, int] = {}
  1122. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1123. # its preheat was still holding at temperature. Set by
  1124. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1125. # `_preheat_sleep`, and cleared when the dispatch exits.
  1126. self._cancelled_dispatches: set[int] = set()
  1127. # printer_id -> monotonic time it was first seen terminal while one of
  1128. # its queue rows was still 'printing'. Reset by any non-terminal
  1129. # observation, so it measures an unbroken run rather than a total.
  1130. # In-memory on purpose: a restart re-arms the grace period, which only
  1131. # delays a recovery that is already the exceptional path (#2829).
  1132. self._terminal_since: dict[int, float] = {}
  1133. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1134. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1135. # across idle printers repeats that for every one of them in a single
  1136. # pass. Cleared at the top of each pass so a re-sliced file is never
  1137. # served from a previous tick.
  1138. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1139. # When each "any model" job held for low filament last looked for
  1140. # another printer (#3137), by queue item id.
  1141. self._short_hold_checked_at: dict[int, float] = {}
  1142. async def run(self):
  1143. """Main loop - check queue every interval."""
  1144. self._running = True
  1145. logger.info("Print scheduler started")
  1146. await self._clear_stale_dispatch_claims(at_startup=True)
  1147. while self._running:
  1148. dispatched = False
  1149. try:
  1150. self._sample_chamber_temps()
  1151. # No-op while any upload is in flight; on a quiet tick it releases
  1152. # a claim whose best-effort clear failed (e.g. the database was
  1153. # briefly unreachable), instead of leaving the row wedged until
  1154. # the next restart.
  1155. await self._clear_stale_dispatch_claims()
  1156. await self._close_stranded_printing_items()
  1157. dispatched = await self.check_queue()
  1158. except Exception as e:
  1159. logger.error("Scheduler error: %s", e)
  1160. # Re-check quickly after a productive pass so a draining batch does
  1161. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1162. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1163. async def _close_stranded_printing_items(self) -> None:
  1164. """Close a ``printing`` row the completion event never closed (#2829).
  1165. ``on_print_complete`` refuses to close a row when the completion's
  1166. subtask name disagrees with the file the row was dispatched with, so a
  1167. completion meant for something else (the printer's own
  1168. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1169. The refusal has no way back, though: nothing else ever closes the row,
  1170. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1171. one bad comparison wedges that printer's queue until a human presses
  1172. cancel. That is what #2829's reporters hit, and the guard's own
  1173. docstring already called stranding the worse of the two failures.
  1174. This is the way back. When a row has been ``printing`` while its
  1175. printer sat in a terminal state for the whole grace period, the print
  1176. is over however the event was read, and the row is closed with the
  1177. status the printer's own state implies.
  1178. Deliberately conservative:
  1179. * Only a connected printer counts. A disconnected one has a stale
  1180. ``state`` and proves nothing.
  1181. * The clock is reset by any non-terminal observation, so this cannot
  1182. fire on a printer that is merely between stages.
  1183. * The grace period is far longer than the gap between a printer
  1184. finishing and its completion arriving, so the normal path always
  1185. wins the race and this only ever sees genuine strandings.
  1186. What it does *not* do is replay the completion's side effects --
  1187. notifications, billing, auto-off. It restores the queue, which is the
  1188. harm being undone; the archive was updated by the normal path
  1189. regardless, since only the queue block refuses. A recovery that
  1190. silently re-fired notifications minutes late would be its own bug.
  1191. """
  1192. try:
  1193. async with async_session() as db:
  1194. result = await db.execute(
  1195. select(PrintQueueItem)
  1196. .where(PrintQueueItem.status == "printing")
  1197. .where(PrintQueueItem.printer_id.is_not(None))
  1198. )
  1199. items = list(result.scalars().all())
  1200. if not items:
  1201. self._terminal_since.clear()
  1202. return
  1203. now = time.monotonic()
  1204. seen_printers: set[int] = set()
  1205. closed = False
  1206. for item in items:
  1207. printer_id = item.printer_id
  1208. seen_printers.add(printer_id)
  1209. state = printer_manager.get_status(printer_id)
  1210. status = _terminal_queue_status(state)
  1211. if status is None:
  1212. self._terminal_since.pop(printer_id, None)
  1213. continue
  1214. since = self._terminal_since.setdefault(printer_id, now)
  1215. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1216. continue
  1217. item.status = status
  1218. item.completed_at = datetime.now(timezone.utc)
  1219. closed = True
  1220. # The printer is idle: nothing it prints next is this item's.
  1221. self._forget_unstarted_print(item.id, unless_printing=True)
  1222. logger.warning(
  1223. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1224. "closing it as %s. Its completion event was never matched to it, which blocks "
  1225. "every later job for this printer (#2829).",
  1226. item.id,
  1227. printer_id,
  1228. getattr(state, "state", None),
  1229. now - since,
  1230. status,
  1231. )
  1232. if closed:
  1233. await db.commit()
  1234. from backend.app.services.print_batch import refresh_batches_after
  1235. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1236. for printer_id in list(self._terminal_since):
  1237. if printer_id not in seen_printers:
  1238. del self._terminal_since[printer_id]
  1239. except Exception as e:
  1240. # Best-effort, same as the claim sweep beside it: a recovery path
  1241. # that can itself break the scheduler loop is worse than the strand.
  1242. logger.error("Stranded-item sweep failed: %s", e)
  1243. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1244. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1245. A claim is only ever held by a live dispatch coroutine, so when this
  1246. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1247. is stale. At startup that is trivially true — no coroutine survives a
  1248. restart. It is equally true on any later tick where no upload is running,
  1249. which is what makes this safe to repeat rather than only run once.
  1250. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1251. the database is briefly unreachable at exactly the moment dispatch ends,
  1252. the claim survives and the row is wedged out of the selection query. That
  1253. used to last until the next restart (#2702 follow-up, seen when
  1254. PostgreSQL refused a connection mid-dispatch).
  1255. ``_inflight`` is populated when the task is spawned, before the coroutine
  1256. claims its row, and pruned by a done-callback that cannot run before the
  1257. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1258. race window and needs no age threshold. A size-derived upload deadline
  1259. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1260. """
  1261. if self._inflight:
  1262. return
  1263. try:
  1264. async with async_session() as db:
  1265. res = await db.execute(
  1266. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1267. )
  1268. await db.commit()
  1269. if res.rowcount:
  1270. logger.info(
  1271. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1272. res.rowcount,
  1273. " at startup" if at_startup else "",
  1274. )
  1275. except Exception as exc:
  1276. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1277. def stop(self):
  1278. """Stop the scheduler."""
  1279. self._running = False
  1280. logger.info("Print scheduler stopped")
  1281. def forget_printer(self, printer_id: int) -> None:
  1282. """Drop what is kept for a deleted printer, so the next printer given its
  1283. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1284. would keep it out of dispatch for up to an hour.
  1285. A dispatch already in flight keeps its own state (_inflight, the preheat
  1286. pins, unconfirmed prints): it unwinds that when it ends.
  1287. """
  1288. for keyed in (
  1289. self._upload_backoff,
  1290. self._upload_refusals,
  1291. self._wake_failures,
  1292. self._drying_in_progress,
  1293. self._dispatch_holds,
  1294. self._chamber_history,
  1295. self._keep_warm,
  1296. self._terminal_since,
  1297. ):
  1298. keyed.pop(printer_id, None)
  1299. self._upload_refusal_notified.discard(printer_id)
  1300. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1301. for key in [key for key in keyed if key[0] == printer_id]:
  1302. del keyed[key]
  1303. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1304. del self._sent_unstarted_print[item_id]
  1305. async def check_queue(self) -> bool:
  1306. """Check for prints ready to start.
  1307. Returns True if this pass dispatched at least one item, so the caller
  1308. can loop again quickly instead of sleeping the full interval (#2555).
  1309. """
  1310. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1311. self._filament_req_memo.clear()
  1312. async with async_session() as db:
  1313. # Check if shortest-job-first scheduling is enabled
  1314. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1315. # Get all pending items in the one order the queue page shows them
  1316. # in (#3200). The first eligible item takes a printer, so this order
  1317. # decides who wins a printer that a pinned job and an "Any <model>"
  1318. # job both want. It used to start with ``printer_id``, which made the
  1319. # lane outrank the position: SQLite sorts NULL first, so model-based
  1320. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1321. # Neither is what the user dragged into place.
  1322. if sjf_enabled:
  1323. # SJF: items already jumped get top priority (starvation guard),
  1324. # then sort by print_time ascending. Items with no print time go
  1325. # last, and position breaks ties.
  1326. result = await db.execute(
  1327. select(PrintQueueItem)
  1328. .where(PrintQueueItem.status == "pending")
  1329. # Never re-select a row a dispatch worker has already claimed
  1330. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1331. # below, and the guard that lets an orphaned claim be ignored
  1332. # until startup reconciliation clears it.
  1333. .where(PrintQueueItem.dispatching_at.is_(None))
  1334. # archive/library_file are read by the cross-model gate
  1335. # (#2578); eager-load once per pass instead of a lazy-load
  1336. # (which would raise in async) per item.
  1337. .options(
  1338. selectinload(PrintQueueItem.archive),
  1339. selectinload(PrintQueueItem.library_file),
  1340. # Cross-model candidates (#671), plus each candidate's file
  1341. # for the same cross-model gate. Lazy-loading either would
  1342. # raise in async.
  1343. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1344. )
  1345. .order_by(
  1346. PrintQueueItem.been_jumped.desc(),
  1347. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1348. PrintQueueItem.position,
  1349. PrintQueueItem.id,
  1350. )
  1351. )
  1352. else:
  1353. result = await db.execute(
  1354. select(PrintQueueItem)
  1355. .where(PrintQueueItem.status == "pending")
  1356. # Skip rows already claimed by a dispatch worker (#2615).
  1357. .where(PrintQueueItem.dispatching_at.is_(None))
  1358. .options(
  1359. selectinload(PrintQueueItem.archive),
  1360. selectinload(PrintQueueItem.library_file),
  1361. # Cross-model candidates (#671), plus each candidate's file
  1362. # for the same cross-model gate. Lazy-loading either would
  1363. # raise in async.
  1364. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1365. )
  1366. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1367. )
  1368. items = list(result.scalars().all())
  1369. # Drop rows whose upload is still in flight from an earlier pass
  1370. # (#2602). They stay `pending` until the upload finishes, so without
  1371. # this a fast tick would re-select and re-dispatch the same row.
  1372. # Belt-and-suspenders with the printer exclusion below.
  1373. if self._inflight:
  1374. inflight_ids = set(self._inflight)
  1375. items = [it for it in items if it.id not in inflight_ids]
  1376. # Read plate-clear setting once per queue check. Default MUST be
  1377. # False to match the schema (SettingsSchema.require_plate_clear
  1378. # defaults False) and the frontend (toggle + card badge both treat a
  1379. # missing value as off). When no settings row exists, a True default
  1380. # here re-enabled the plate-clear gate the UI showed as disabled,
  1381. # blocking dispatch to FINISH-state printers forever with no UI path
  1382. # to clear it (#1865).
  1383. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1384. # Dispatch and track scheduled drying runs (#2638)
  1385. await self._check_scheduled_dryings(db)
  1386. if not items:
  1387. # No dispatchable pending items — still check auto-drying on idle
  1388. # printers, but keep any printer with an upload still in flight
  1389. # from an earlier pass out of it (#2602): its print is imminent,
  1390. # so it must not be auto-dried in the gap before the row flips to
  1391. # printing. Report the pass as productive while uploads run so the
  1392. # loop stays on the fast interval.
  1393. #
  1394. # Also release any keep-warm holds that got orphaned by the queue
  1395. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1396. # this early return, so call it directly with an empty candidate
  1397. # set. Without this, a printer whose queued item was cancelled or
  1398. # deleted would keep its bed at target until the max-duration
  1399. # timeout expired.
  1400. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1401. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1402. await self._check_auto_drying(db, [], inflight_printers)
  1403. await self._check_filament_low(db)
  1404. await self._check_stock_forecast(db)
  1405. return bool(self._inflight)
  1406. logger.info(
  1407. "Queue check: found %d pending items: %s",
  1408. len(items),
  1409. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1410. )
  1411. # Forget jobs that left the queue since they were last checked.
  1412. pending_ids = {i.id for i in items}
  1413. self._short_hold_checked_at = {
  1414. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1415. }
  1416. # Seed busy_printers with printers that already have an item in 'printing'
  1417. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1418. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1419. # lag several seconds behind the print command, so the next check_queue
  1420. # tick still sees IDLE and would double-dispatch onto the same printer.
  1421. # Without this guard, two pending items targeting the same printer
  1422. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1423. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1424. busy_result = await db.execute(
  1425. select(PrintQueueItem.printer_id)
  1426. .where(PrintQueueItem.status == "printing")
  1427. .where(PrintQueueItem.printer_id.is_not(None))
  1428. )
  1429. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1430. # Why each printer left this pass, recorded where the decision is
  1431. # made rather than re-derived when the summary is logged. #3018's
  1432. # bundle shows what the old summary produced: "printer 1 not
  1433. # available -- connected=True, state=IDLE" immediately followed by a
  1434. # dispatch to printer 1. Two things went wrong at once. The line read
  1435. # live state at log time, which by then no longer matched the state
  1436. # the decision was made on; and `busy_printers` holds both printers
  1437. # that cannot take work and printers this pass has claimed for it,
  1438. # which are opposite facts. It is the first line anyone greps for
  1439. # "why did my item not go out", so it has to say which.
  1440. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1441. # Printers this pass is dispatching to. They are in busy_printers so
  1442. # nothing else in the pass targets them -- that is a reservation, not
  1443. # an obstruction, and the summary says so.
  1444. claimed_printers: set[int] = set()
  1445. def mark_busy(printer_id: int, reason: str) -> None:
  1446. """Take ``printer_id`` out of this pass, recording why.
  1447. First reason wins: a printer already excluded by a stronger fact
  1448. -- a print running on it -- must not be relabelled by a weaker
  1449. check that ran later and would have excluded it anyway.
  1450. """
  1451. busy_printers.add(printer_id)
  1452. busy_reasons.setdefault(printer_id, reason)
  1453. def claim_printer(printer_id: int) -> None:
  1454. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1455. claimed_printers.add(printer_id)
  1456. mark_busy(printer_id, "selected for dispatch in this pass")
  1457. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1458. # worded for a different audience: the log wants "still inside its
  1459. # post-dispatch hold window", the queue row wants to know the printer
  1460. # is taken and nothing is broken. Only the cases that would read wrong
  1461. # as a plain "Busy" are recorded here; the rest fall back to it.
  1462. item_hold_reasons: dict[int, str] = {}
  1463. # Names and models for the printers this pass may have to write a
  1464. # waiting reason about, read once rather than per skip per tick. The
  1465. # model-based branch already has its names from `_printers_for_model`.
  1466. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1467. pinned_printers: dict[int, tuple[str, str]] = {}
  1468. if pinned_printer_ids:
  1469. pinned_rows = await db.execute(
  1470. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1471. )
  1472. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1473. def printer_label(printer_id: int) -> str:
  1474. """What to call this printer in a queue row."""
  1475. entry = pinned_printers.get(printer_id)
  1476. return (entry[0] if entry else "") or f"printer {printer_id}"
  1477. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1478. """Record why *item* is not going out, in the words the queue row shows.
  1479. The fixed-printer branch's single writer for ``waiting_reason``
  1480. (#3074). Before this, the sensor interlock was the only thing that
  1481. wrote the field there, so an item pinned to a printer that was
  1482. merely printing sat at `pending` with nothing to show for it —
  1483. indistinguishable from a queue that had stopped working — while
  1484. the same job queued as "Any <model>" explained itself.
  1485. Every exit from that branch now calls this, which is also what
  1486. replaced the interlock's old habit of clearing the field up front:
  1487. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1488. because whichever exit runs next overwrites it and the dispatch
  1489. path clears it.
  1490. A notification goes out when this item starts asking for
  1491. something, and only then: the new reason needs the user, and what
  1492. it replaced did not. "What it replaced did not" has to include a
  1493. busy-only reason, not just an empty one. The sequence this branch
  1494. actually produces is a print running (``Busy: X1C-01``) and then
  1495. the plate it left behind (``Waiting for plate confirmation``), and
  1496. testing "was the field empty" would call that no transition at all
  1497. and stay quiet through the one case worth saying out loud.
  1498. The cost is that a printer dropping offline, coming back busy and
  1499. dropping again asks twice rather than once. That is the honest
  1500. reading — it went wrong twice — and the alternative was a rule
  1501. that never fired for the case this was built for.
  1502. *notify* is how a caller opts out. The sensor interlock does: it
  1503. has never sent this notification, and a change about what the
  1504. queue *displays* is not the place to start (#1148).
  1505. """
  1506. if item.waiting_reason == reason:
  1507. return
  1508. # Busy-only and empty are the same thing here: neither is the
  1509. # queue asking the user for anything.
  1510. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1511. item.waiting_reason = reason
  1512. await db.commit()
  1513. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1514. return
  1515. try:
  1516. job_name = await self._get_job_name(db, item)
  1517. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1518. await notification_service.on_queue_job_waiting(
  1519. job_name=job_name,
  1520. target_model=(entry[1] if entry else "") or "",
  1521. waiting_reason=reason,
  1522. db=db,
  1523. )
  1524. except Exception as e:
  1525. # A queue that cannot say why it is waiting is the bug being
  1526. # fixed here; a queue that stops dispatching because a
  1527. # notification provider is down would be a worse one.
  1528. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1529. async def hold_for_printer(
  1530. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1531. ) -> None:
  1532. """Take *printer_id* out of this pass and tell the item's owner why."""
  1533. mark_busy(printer_id, log_reason)
  1534. item_hold_reasons.setdefault(printer_id, item_reason)
  1535. await hold_item(item, item_reason)
  1536. # Defense-in-depth (#1157): augment busy_printers with any printer
  1537. # still in its post-dispatch hold window. Empirically, the DB seed
  1538. # above can miss in-flight items in a multi-plate batch — same-file
  1539. # plates were being dispatched 30 s apart while the H2D was still
  1540. # digesting the first project_file. The hold is keyed in-memory and
  1541. # released by the watchdog on the success path, so it adds a layer
  1542. # that doesn't depend on DB row visibility or completion-callback
  1543. # timing.
  1544. for held_printer_id in list(self._dispatch_holds.keys()):
  1545. if self._printer_in_dispatch_hold(held_printer_id):
  1546. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1547. # Exclude printers whose upload is still in flight from an earlier
  1548. # pass (#2602). The row is `pending` until the upload finishes and
  1549. # the printing-state seed / dispatch hold above only arm once the
  1550. # upload completes, so this is what holds the printer (and, via
  1551. # busy_printers, its auto-drying) out of the pass during the upload.
  1552. for _task, inflight_pid in self._inflight.values():
  1553. if inflight_pid is not None:
  1554. mark_busy(inflight_pid, "an upload to it is still in flight")
  1555. # Snapshot taken here, before the item loop adds anything (#2801).
  1556. #
  1557. # The three sources above all mean the same thing: a print on this
  1558. # printer is running or imminent. Everything the loop adds below
  1559. # means only "the queue could not dispatch to it this pass", which
  1560. # is a different statement -- a printer waiting on a plate-clear
  1561. # acknowledgment, an offline printer, one with no matching file.
  1562. #
  1563. # Auto-drying must only see the first kind. Reading the whole set
  1564. # as "is currently printing" is what put a plate-held printer down
  1565. # the mid-print path: it capped the drying temperature, logged the
  1566. # cycle as (mid-print), and skipped the very gate that was supposed
  1567. # to hold it. The interlock block below already documents the same
  1568. # hazard and works around it by staying out of busy_printers; this
  1569. # generalises that workaround instead of repeating it per case.
  1570. dispatching_printers: set[int] = set(busy_printers)
  1571. # Printers whose last upload never reached them (#3210). After the
  1572. # snapshot above on purpose: such a printer is idle, not about to
  1573. # print, and auto-drying must keep treating it as idle.
  1574. now_mono = time.monotonic()
  1575. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1576. # can leave them out: there is no print to keep a bed warm for.
  1577. backoff_printers: set[int] = set()
  1578. # In backoff, and the "job waiting" notification for this run of
  1579. # refusals has gone out already. Their holds are written silently.
  1580. silent_hold_printers: set[int] = set()
  1581. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1582. if now_mono >= retry_at:
  1583. del self._upload_backoff[backoff_pid]
  1584. continue
  1585. backoff_printers.add(backoff_pid)
  1586. if backoff_pid in self._upload_refusal_notified:
  1587. silent_hold_printers.add(backoff_pid)
  1588. else:
  1589. self._upload_refusal_notified.add(backoff_pid)
  1590. mark_busy(
  1591. backoff_pid,
  1592. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1593. )
  1594. item_hold_reasons.setdefault(
  1595. backoff_pid,
  1596. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1597. )
  1598. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1599. # enclosure door left open, say. The fixed-printer branch turns
  1600. # this into a waiting_reason the user can act on; the model-based
  1601. # branch hides these printers from the matcher so an "Any <model>"
  1602. # job runs on a sibling instead of queueing behind the held one.
  1603. #
  1604. # Deliberately NOT merged into busy_printers, even though that set
  1605. # already means "unavailable this pass". _check_auto_drying reads
  1606. # it as "is currently printing" and would put an idle-but-held
  1607. # printer down the mid-print drying path, which caps the drying
  1608. # temperature and skips the queue-only gating. A held printer is
  1609. # idle; it should dry exactly as it did before.
  1610. #
  1611. # Only sensors we actually read and found alerting appear here; see
  1612. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1613. # holds nothing.
  1614. interlocked: dict[int, str] = {}
  1615. try:
  1616. interlocked = await ha_sensor_manager.blocked_printers(db)
  1617. except Exception as e:
  1618. # Never let the interlock stop the queue running. A broken
  1619. # lookup means no holds, not no dispatches.
  1620. logger.warning("Home Assistant interlock check failed: %s", e)
  1621. interlocked = {}
  1622. # Printers a smart plug can bring back, read once for the whole pass
  1623. # (#2786). Used by the model-based branch both to word "Offline" in
  1624. # the waiting reason and to decide what the wake step may switch on.
  1625. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1626. # At most one power-on per queue check. Each one blocks this loop
  1627. # for the boot wait, so a queue of ten class-targeted jobs must not
  1628. # switch on ten printers inside a single pass — the next pass wakes
  1629. # the next one (#2786).
  1630. power_on_attempted = False
  1631. # Log skip reasons once per queue check (not per item)
  1632. skip_reasons: dict[str, int] = {}
  1633. # Items selected for dispatch in this pass, one per printer. The
  1634. # loop below only *decides* — the uploads happen afterwards, in
  1635. # parallel (#2555). See _dispatch_selected().
  1636. dispatch_ids: list[int] = []
  1637. # Library rows queued with `cleanup_library_after_dispatch` (the
  1638. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1639. # that prints them: the row is deleted and the 3MF is unlinked from
  1640. # disk. That was safe only because dispatch was serial. Run two of
  1641. # them against the same row at once and the second DELETE matches no
  1642. # row (StaleDataError), and the winner's unlink can pull the file out
  1643. # from under the loser's in-flight upload.
  1644. #
  1645. # Only the cleanup flag mutates the row. An ordinary library print
  1646. # just reads it, so the common fan-out — one file, many printers,
  1647. # which is exactly the reporter's workload — still goes out fully in
  1648. # parallel. Narrow the guard to the mutating case; do not serialise
  1649. # the case the whole fix exists for.
  1650. dispatch_libs: set[int] = set()
  1651. consumed_libs: set[int] = set()
  1652. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1653. """True if dispatching `candidate` now would race another item's cleanup."""
  1654. lib_id = candidate.library_file_id
  1655. if lib_id is None:
  1656. return False
  1657. if candidate.cleanup_library_after_dispatch:
  1658. # We would delete a row someone else in this pass is reading.
  1659. return lib_id in dispatch_libs
  1660. # Someone else in this pass will delete the row out from under us.
  1661. return lib_id in consumed_libs
  1662. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1663. lib_id = candidate.library_file_id
  1664. if lib_id is None:
  1665. return
  1666. dispatch_libs.add(lib_id)
  1667. if candidate.cleanup_library_after_dispatch:
  1668. consumed_libs.add(lib_id)
  1669. # Printer scope of each job's creator (#1727), so an "any <model>"
  1670. # job only lands on a printer its creator may use. Loaded lazily,
  1671. # once per creator per pass.
  1672. from backend.app.core.auth import is_auth_enabled
  1673. scope_auth_enabled = await is_auth_enabled(db)
  1674. creator_scopes: dict[int, PrinterScope] = {}
  1675. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1676. if not scope_auth_enabled or user_id is None:
  1677. return ALL_PRINTERS
  1678. if user_id not in creator_scopes:
  1679. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1680. return creator_scopes[user_id]
  1681. for item in items:
  1682. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1683. if item.scheduled_time:
  1684. sched = item.scheduled_time
  1685. if sched.tzinfo is None:
  1686. sched = sched.replace(tzinfo=timezone.utc)
  1687. if sched > datetime.now(timezone.utc):
  1688. # Waiting on the clock, not on a printer.
  1689. await hold_item(item, None)
  1690. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1691. continue
  1692. # Skip items that require manual start, except an "any model"
  1693. # job held for low filament that another idle printer can now
  1694. # run: that one is moved there and carries on below (#3137).
  1695. if item.manual_start and not (
  1696. item.filament_short
  1697. and await self._release_short_model_hold(
  1698. db,
  1699. item,
  1700. busy_printers | interlocked.keys(),
  1701. require_plate_clear,
  1702. await _creator_scope(item.created_by_id),
  1703. )
  1704. ):
  1705. # Waiting on the user, not on a printer. Cleared here because
  1706. # this is the last pass that will look at the row: a staged
  1707. # item never reaches the branches below again, so a reason
  1708. # left from before it was staged would stand forever (#3074).
  1709. # The one exception is the unmatched-filament hold, whose
  1710. # reason was written at staging and is why the item waits:
  1711. # it names the filament to load (#2799). Pressing start
  1712. # clears manual_start, and the branches below overwrite it.
  1713. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1714. await hold_item(item, keep)
  1715. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1716. continue
  1717. if item.printer_id and item.printer_id not in pinned_printers:
  1718. # Moved by the release above to a printer no row named when
  1719. # the labels were read.
  1720. moved_to = await self._get_printer(db, item.printer_id)
  1721. if moved_to is not None:
  1722. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1723. if item.printer_id:
  1724. # Its creator may no longer use this printer (#1727): an
  1725. # admin took it away from their group after the job was
  1726. # queued, say to keep it free for a training session. Held,
  1727. # not failed, so it starts if access comes back or the user
  1728. # moves it to a printer they still have.
  1729. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1730. await hold_item(
  1731. item,
  1732. "Its owner no longer has access to this printer — move it to another printer",
  1733. notify=False,
  1734. )
  1735. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1736. continue
  1737. # Held by a sensor interlock (#1148). Checked before the
  1738. # busy_printers test that would otherwise swallow it
  1739. # silently — "waiting for a printer" and "waiting for you
  1740. # to shut the enclosure" need to read differently, and only
  1741. # one of them is something the user can fix.
  1742. #
  1743. # It used to be the only thing that wrote a waiting_reason on
  1744. # this branch, and it cleared the field up front so a lifted
  1745. # hold could not leave a shut door reading "Waiting on
  1746. # Enclosure Door". `hold_item` carries that guarantee now —
  1747. # every exit below writes — so the clear is gone and the
  1748. # interlock is an ordinary hold like the rest (#3074).
  1749. interlock_reason = interlocked.get(item.printer_id)
  1750. if interlock_reason:
  1751. # Silent, exactly as it has always been. #1148 built this
  1752. # as a hold that shows on the row, never as an alert, and
  1753. # routing it through the shared writer must not quietly
  1754. # turn every open door into a notification.
  1755. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1756. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1757. continue
  1758. # Specific printer assignment (existing behavior)
  1759. if item.printer_id in busy_printers:
  1760. # Whatever took the printer out of this pass — a print
  1761. # already running on it, a post-dispatch hold, an upload
  1762. # still in flight, an item ahead of this one in the same
  1763. # pass — reads the same way from the queue: the printer is
  1764. # taken and this item is in line for it. The exceptions
  1765. # that do not (an offline printer, say) recorded their own
  1766. # wording in `item_hold_reasons` when they held it.
  1767. await hold_item(
  1768. item,
  1769. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1770. notify=item.printer_id not in silent_hold_printers,
  1771. )
  1772. continue
  1773. # Check if printer is idle
  1774. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1775. printer_connected = printer_manager.is_connected(item.printer_id)
  1776. # If printer not connected, try to power on via smart plug
  1777. if not printer_connected:
  1778. plugs = await self._get_smart_plugs(db, item.printer_id)
  1779. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1780. if auto_on_plugs:
  1781. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1782. # Power on using the plug that actually feeds the printer, and
  1783. # wait for it to boot on that one only (#2629).
  1784. primary_plug = self._pick_power_plug(auto_on_plugs)
  1785. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1786. if powered_on:
  1787. # Also turn on any remaining auto_on plugs (e.g., filter)
  1788. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1789. try:
  1790. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1791. if await service.turn_on(extra_plug):
  1792. await publish_plug_state(
  1793. extra_plug.id,
  1794. extra_plug.name,
  1795. extra_plug.printer_id,
  1796. on=True,
  1797. ha_entity_id=extra_plug.ha_entity_id,
  1798. )
  1799. logger.info(
  1800. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1801. )
  1802. except Exception as e:
  1803. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1804. printer_connected = True
  1805. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1806. else:
  1807. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1808. await hold_for_printer(
  1809. item,
  1810. item.printer_id,
  1811. "smart-plug power-on failed",
  1812. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1813. )
  1814. continue
  1815. else:
  1816. # No plug or auto_on disabled. Worded exactly as the
  1817. # model-based branch words it (#2786): this is the one
  1818. # entry on that list the user has to act on, because
  1819. # Bambuddy will never switch this printer on itself.
  1820. await hold_for_printer(
  1821. item,
  1822. item.printer_id,
  1823. "offline, with no smart plug to power it on",
  1824. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1825. )
  1826. continue
  1827. # Check if printer is idle (busy with another print)
  1828. if not printer_idle:
  1829. await hold_for_printer(
  1830. item,
  1831. item.printer_id,
  1832. "not idle",
  1833. self._pinned_hold_reason(
  1834. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1835. ),
  1836. )
  1837. continue
  1838. # Drying blocks the queue, if the user asked it to. A hold
  1839. # is a skip like any other, so it belongs here with the
  1840. # rest of the availability checks.
  1841. # A parked timer (#2896) never ends, so it must not hold the
  1842. # queue; it stays tracked so the stop paths still reach it.
  1843. if (
  1844. self._drying_in_progress.get(item.printer_id)
  1845. and not self._drying_is_only_parked(item.printer_id)
  1846. and await self._get_bool_setting(db, "queue_drying_block")
  1847. ):
  1848. # Busy-shaped on purpose: the cycle ends on its own and
  1849. # the job goes out, so there is nothing to alert about.
  1850. await hold_for_printer(
  1851. item,
  1852. item.printer_id,
  1853. "drying, and drying is set to block the queue",
  1854. f"Busy: {printer_label(item.printer_id)} (drying)",
  1855. )
  1856. continue
  1857. # Check condition (previous print success)
  1858. if item.require_previous_success:
  1859. if not await self._check_previous_success(db, item):
  1860. item.status = "skipped"
  1861. item.error_message = "Previous print failed or was aborted"
  1862. item.completed_at = datetime.now(timezone.utc)
  1863. # Not pending any more, so not waiting for anything.
  1864. item.waiting_reason = None
  1865. await db.commit()
  1866. logger.info("Skipped queue item %s - previous print failed", item.id)
  1867. # Send notification
  1868. job_name = await self._get_job_name(db, item)
  1869. printer = await self._get_printer(db, item.printer_id)
  1870. await notification_service.on_queue_job_skipped(
  1871. job_name=job_name,
  1872. printer_id=item.printer_id,
  1873. printer_name=printer.name if printer else "Unknown",
  1874. reason="Previous print failed or was aborted",
  1875. db=db,
  1876. )
  1877. continue
  1878. # Resolve the AMS mapping when it's missing OR unresolved
  1879. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1880. # frontend status-load race can persist [-1] (#2589) — and
  1881. # must be recomputed from live trays rather than trusted.
  1882. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1883. if unmappable:
  1884. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1885. continue
  1886. # Filament-deficit pre-dispatch check (#1496). If the
  1887. # assigned spool can't satisfy any required slot grams,
  1888. # promote the item to manual_start so the user must
  1889. # acknowledge via the ▶ button (which re-checks live).
  1890. if await self._block_on_filament_deficit(db, item):
  1891. # Now staged for the user to start by hand, and the row
  1892. # shows the filament-short badge instead. Cleared because
  1893. # a staged item never reaches this branch again.
  1894. await hold_item(item, None)
  1895. continue
  1896. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1897. # than let the printer pick a substitute for a slot the
  1898. # matcher could not resolve on this printer.
  1899. if await self._block_on_unmatched_filament(db, item):
  1900. continue
  1901. # Hold this item back for the next pass rather than racing
  1902. # another dispatch over the same transient library row. The
  1903. # printer is still marked busy so a later item does not jump
  1904. # its place in this printer's queue.
  1905. if _library_row_conflict(item):
  1906. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1907. await hold_for_printer(
  1908. item,
  1909. item.printer_id,
  1910. "holding its place while another item releases a library row",
  1911. f"Busy: {printer_label(item.printer_id)}",
  1912. )
  1913. continue
  1914. # Print takes priority: stop a cycle Bambuddy armed, now
  1915. # that this item is definitely going out.
  1916. #
  1917. # Placement is the whole point (#2801). This used to sit up
  1918. # with the availability checks, inside the not-idle branch
  1919. # -- so it fired only on the passes where the print was NOT
  1920. # going to start, and never on the ones where it was.
  1921. # Drying is not one of the things `_is_printer_idle` looks
  1922. # at, so a stop could never have unblocked that printer
  1923. # anyway; the cycle was spent for nothing, auto-drying
  1924. # re-armed on the next tick, and a plate left
  1925. # unacknowledged turned that into a loop on the scheduler
  1926. # interval. Every skip between there and here -- a failed
  1927. # previous print, an unmappable item, a filament deficit, a
  1928. # contested library row -- is another way to lose a cycle
  1929. # for a print that never happens, which is why this waits
  1930. # until the decision is actually made.
  1931. if self._drying_in_progress.get(
  1932. item.printer_id
  1933. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1934. await self._stop_drying(item.printer_id)
  1935. # Queue the dispatch instead of running it here — see
  1936. # _dispatch_selected(). busy_printers still gets the printer
  1937. # immediately, so nothing else in this pass can target it.
  1938. #
  1939. # The reason goes first: this item is not waiting for anything
  1940. # any more, and the model-based branch clears its own at the
  1941. # equivalent moment (#3074).
  1942. await hold_item(item, None)
  1943. _claim_library_row(item)
  1944. dispatch_ids.append(item.id)
  1945. claim_printer(item.printer_id)
  1946. # SJF starvation guard: mark items that were jumped
  1947. if sjf_enabled and item.print_time_seconds is not None:
  1948. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1949. for other in items:
  1950. if (
  1951. other.id != item.id
  1952. and other.id not in dispatch_ids
  1953. and other.status == "pending"
  1954. and _could_take_printer(other, item.printer_id, pinned_model)
  1955. and not other.been_jumped
  1956. and other.position < item.position
  1957. and (
  1958. other.print_time_seconds is None
  1959. or other.print_time_seconds > item.print_time_seconds
  1960. )
  1961. ):
  1962. other.been_jumped = True
  1963. await db.commit()
  1964. elif item.target_model or item.variants:
  1965. # Model-based assignment - find any idle printer of matching model.
  1966. # A plain model-based item has exactly one candidate, built from
  1967. # its own columns. A cross-model item (#671) has one per sliced
  1968. # variant and takes the first that matches, walking them in the
  1969. # user's priority order so the pick is reproducible when more
  1970. # than one printer is free in the same pass.
  1971. candidates = _candidates_for(item)
  1972. item_scope = await _creator_scope(item.created_by_id)
  1973. printer_id = None
  1974. chosen: _ModelCandidate | None = None
  1975. per_model_reasons: list[tuple[str | None, str]] = []
  1976. # Candidates that cleared the cross-model gate below. The
  1977. # smart-plug wake step may only consider these — waking a
  1978. # printer for a file that can never legally run on it is
  1979. # worse than not waking at all (#2786).
  1980. wakeable_candidates: list[_ModelCandidate] = []
  1981. # Printers passed over because their last print failed.
  1982. gate_blocked: set[int] = set()
  1983. if not candidates:
  1984. # Every candidate file has been deleted or trashed out from
  1985. # under this item. Hold it with something the user can act
  1986. # on rather than letting it look dispatchable forever.
  1987. per_model_reasons.append(
  1988. (
  1989. item.target_model,
  1990. "Every file for this job has been deleted — add a file back or remove the item",
  1991. )
  1992. )
  1993. for candidate in candidates:
  1994. effective_types, filament_overrides = _filament_constraints(candidate)
  1995. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1996. # for an incompatible model to a printer, no matter how the
  1997. # row got into the DB (old rows, direct API writes). Held
  1998. # as pending with an actionable waiting_reason — the user
  1999. # fixes it by editing the item's target model.
  2000. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2001. per_model_reasons.append(
  2002. (
  2003. candidate.target_model,
  2004. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2005. f"{candidate.target_model} — edit the item and fix its target model",
  2006. )
  2007. )
  2008. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2009. continue
  2010. wakeable_candidates.append(candidate)
  2011. async def is_short(
  2012. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2013. ) -> bool:
  2014. # The check reads the file and plate off the item,
  2015. # so it must hold this candidate's. Resolving is
  2016. # safe to repeat, and the winner is resolved again
  2017. # below.
  2018. self._resolve_variant(item, candidate)
  2019. return await self._filament_short_on(db, item, pid)
  2020. while True:
  2021. match_id, match_reason = await self._find_idle_printer_for_model(
  2022. db,
  2023. candidate.target_model,
  2024. # Sensor-held printers are unavailable to the
  2025. # matcher but stay out of busy_printers itself
  2026. # (#1148) — see where `interlocked` is built.
  2027. busy_printers | interlocked.keys() | gate_blocked,
  2028. effective_types,
  2029. item.target_location,
  2030. filament_overrides=filament_overrides,
  2031. require_plate_clear=require_plate_clear,
  2032. wakeable_ids=wakeable_printer_ids,
  2033. printer_scope=item_scope,
  2034. is_short=is_short,
  2035. )
  2036. # "Only if the previous print succeeded" is about the
  2037. # printer the job lands on: one whose last print failed
  2038. # is passed over for another of the model.
  2039. if (
  2040. match_id
  2041. and item.require_previous_success
  2042. and not await self._check_previous_success(db, item, printer_id=match_id)
  2043. ):
  2044. gate_blocked.add(match_id)
  2045. continue
  2046. break
  2047. if match_id:
  2048. printer_id = match_id
  2049. chosen = candidate
  2050. break
  2051. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2052. # Nothing is available and nothing has been woken this pass:
  2053. # switch one matching printer on. Assignment is left to the
  2054. # next pass, which sees the booted printer's live state
  2055. # instead of guessing at it seconds after connect (#2786).
  2056. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2057. woken_id, attempted_id = await self._wake_printer_for_model(
  2058. db,
  2059. wakeable_candidates,
  2060. item.target_location,
  2061. busy_printers | interlocked.keys(),
  2062. wakeable_printer_ids,
  2063. require_plate_clear,
  2064. printer_scope=item_scope,
  2065. )
  2066. # An attempt spends the pass's one wake whether or not
  2067. # it worked: it has already blocked the queue loop for
  2068. # the boot wait. A failed printer is held out of later
  2069. # passes by its own cool-off, deliberately NOT by
  2070. # busy_printers — it is off, not busy, and labelling it
  2071. # busy would both misdescribe it in every later item's
  2072. # waiting reason and suppress the notification, since
  2073. # an all-busy reason is treated as needing no action.
  2074. power_on_attempted = attempted_id is not None
  2075. if woken_id is not None:
  2076. # Hold this item back rather than dispatching onto a
  2077. # printer whose AMS has not reported yet.
  2078. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2079. continue
  2080. if printer_id is None and gate_blocked:
  2081. # The matcher reports the printers passed over as busy;
  2082. # what holds the job is their failed last print.
  2083. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2084. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2085. # Fold the winning variant's file and settings onto the item
  2086. # before anything else looks at them — the guards below and
  2087. # every step of the dispatch read the item's own columns.
  2088. if chosen is not None:
  2089. self._resolve_variant(item, chosen)
  2090. # Update waiting_reason if changed and send notification when first waiting
  2091. if item.waiting_reason != waiting_reason:
  2092. was_waiting = item.waiting_reason is not None
  2093. previous_reason = item.waiting_reason
  2094. item.waiting_reason = waiting_reason
  2095. await db.commit()
  2096. # Send waiting notification only when transitioning to waiting state
  2097. # and the reason requires user action (not just "all printers busy")
  2098. # Also when a job that only waited for a busy printer
  2099. # now waits on something the user has to do.
  2100. if (
  2101. waiting_reason
  2102. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2103. and not self._is_busy_only(waiting_reason)
  2104. ):
  2105. job_name = await self._get_job_name(db, item)
  2106. await notification_service.on_queue_job_waiting(
  2107. job_name=job_name,
  2108. target_model=_candidate_model_label(candidates) or item.target_model,
  2109. waiting_reason=waiting_reason,
  2110. db=db,
  2111. )
  2112. if printer_id:
  2113. # Before claiming the printer: hold back rather than race
  2114. # another dispatch over the same transient library row.
  2115. # Checked here so a held item does not get a printer
  2116. # assigned and then sit on it. See _library_row_conflict().
  2117. #
  2118. # No busy_printers.add() here, unlike the fixed-printer
  2119. # branch above: that one protects its printer's own queue
  2120. # ordering, but this item was never assigned to `printer_id`
  2121. # — the matcher merely offered it. Marking it busy would
  2122. # strand an idle printer for the rest of the pass.
  2123. if _library_row_conflict(item):
  2124. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2125. continue
  2126. # Assign printer and start - clear waiting reason
  2127. item.printer_id = printer_id
  2128. item.waiting_reason = None
  2129. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2130. # Send assignment notification
  2131. job_name = await self._get_job_name(db, item)
  2132. printer = await self._get_printer(db, printer_id)
  2133. await notification_service.on_queue_job_assigned(
  2134. job_name=job_name,
  2135. printer_id=printer_id,
  2136. printer_name=printer.name if printer else "Unknown",
  2137. target_model=item.target_model,
  2138. db=db,
  2139. )
  2140. # A mapping on this item was not made for the printer just
  2141. # picked: it came with a job moved here from a fixed
  2142. # printer, or from a variant. Its tray IDs can name a
  2143. # tray of the right type in another colour here, which
  2144. # the fit check lets through (#3239). Match afresh, by
  2145. # type and colour.
  2146. if item.ams_mapping:
  2147. logger.info(
  2148. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2149. item.id,
  2150. item.ams_mapping,
  2151. printer_id,
  2152. )
  2153. item.ams_mapping = None
  2154. # Resolve the AMS mapping for the assigned printer. It is
  2155. # always missing here, so this computes it, and it also
  2156. # self-heals a bogus stored [-1] (#2589).
  2157. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2158. if unmappable:
  2159. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2160. continue
  2161. # Filament-deficit pre-dispatch check (#1496).
  2162. if await self._block_on_filament_deficit(db, item):
  2163. continue
  2164. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2165. # selection already filters on filament type, so this is a
  2166. # backstop for an AMS that changed between assignment and
  2167. # dispatch, and for a type loaded on the wrong nozzle.
  2168. # The assignment made above is released with the hold —
  2169. # this item asked for a model, not this printer.
  2170. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2171. continue
  2172. _claim_library_row(item)
  2173. dispatch_ids.append(item.id)
  2174. claim_printer(printer_id)
  2175. # SJF starvation guard: mark items that were jumped
  2176. if sjf_enabled and item.print_time_seconds is not None:
  2177. for other in items:
  2178. if (
  2179. other.id != item.id
  2180. and other.id not in dispatch_ids
  2181. and other.status == "pending"
  2182. and _could_take_printer(other, printer_id, item.target_model)
  2183. and not other.been_jumped
  2184. and other.position < item.position
  2185. and (
  2186. other.print_time_seconds is None
  2187. or other.print_time_seconds > item.print_time_seconds
  2188. )
  2189. ):
  2190. other.been_jumped = True
  2191. await db.commit()
  2192. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2193. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2194. # skip summary that only lands after the transfers have finished is
  2195. # useless for working out why an item did not go out.
  2196. if skip_reasons:
  2197. logger.info("Queue skip summary: %s", skip_reasons)
  2198. for pid in sorted(busy_printers):
  2199. reason = busy_reasons.get(pid, "no reason recorded")
  2200. if pid in claimed_printers:
  2201. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2202. continue
  2203. # The three live fields stay, because they are what someone
  2204. # reading a bundle wants next -- but they are labelled as read
  2205. # now, not as the state the decision was made on, which is what
  2206. # made the old line contradict itself.
  2207. state = printer_manager.get_status(pid)
  2208. logger.info(
  2209. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2210. pid,
  2211. reason,
  2212. printer_manager.is_connected(pid),
  2213. state.state if state else "NO_STATUS",
  2214. printer_manager.is_awaiting_plate_clear(pid),
  2215. )
  2216. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2217. # selection and `_launch_uploads`, so anything raising here would
  2218. # discard this tick's selections — computed AMS mappings and all —
  2219. # and, on a persistent fault, stop the queue dispatching entirely.
  2220. # Same reasoning as the deficit check's guard below: never let an
  2221. # auxiliary check wedge the queue. The bed simply stays wherever it
  2222. # was, and the next tick tries again.
  2223. try:
  2224. await self._apply_keep_warm(
  2225. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2226. )
  2227. except Exception as e:
  2228. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2229. # Read the concurrency limit BEFORE the commit below, not inside
  2230. # _dispatch_selected(). A SELECT on this session after the commit
  2231. # implicitly opens a fresh transaction that nothing then closes, and
  2232. # it would stay open for the whole dispatch — minutes of "idle in
  2233. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2234. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2235. # checkpointed while every dispatch is writing to it.
  2236. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2237. # Selection is done; every decision above is recorded on `db`
  2238. # (model-based printer assignment, computed ams_mapping). Flush it
  2239. # before the dispatch tasks open their own sessions, or they will
  2240. # read a row that still says printer_id=None. This also releases the
  2241. # connection back to the pool for the duration of the dispatch.
  2242. await db.commit()
  2243. if dispatch_ids:
  2244. item_printers = {it.id: it.printer_id for it in items}
  2245. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2246. # Auto-drying: start drying on idle printers that have no pending queue items
  2247. await self._check_auto_drying(db, items, dispatching_printers)
  2248. # Low filament: alert on assigned spools that have crossed their
  2249. # low-stock threshold (#2913). Runs on both paths out of this method
  2250. # for the same reason auto-drying does — an empty queue does not mean
  2251. # the spools in the printers stopped mattering.
  2252. await self._check_filament_low(db)
  2253. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2254. # is about to run out before a replenishment could arrive (#2955).
  2255. await self._check_stock_forecast(db)
  2256. # Keep the loop on the fast interval while any upload is in flight so
  2257. # a slot freed mid-tick refills within seconds rather than after the
  2258. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2259. # deferred because the pool was full) also counts as productive.
  2260. return bool(dispatch_ids) or bool(self._inflight)
  2261. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2262. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2263. Dispatch used to happen inline in the selection loop: ``await
  2264. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2265. performs the FTP upload, that serialized every printer behind every
  2266. other printer's transfer even though the printers are independent
  2267. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2268. gather was awaited before ``check_queue`` returned, so the run loop
  2269. stayed blocked until the *slowest* upload in the batch finished — a
  2270. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2271. 93-printer farm even as other printers came free (#2602).
  2272. Each upload now runs as an independent background task tracked in
  2273. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2274. `pending` until their upload completes) and their printers from the
  2275. next pass's selection, and this method launches at most
  2276. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2277. the next fast tick instead of waiting out the whole batch. The bound
  2278. exists because the printers are independent but the host is not: each
  2279. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2280. file handle.
  2281. The no-overlapping-dispatch invariant the batch-await used to provide
  2282. is now carried by the in-flight exclusion in check_queue. Everything
  2283. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2284. per-printer hold, and each item's independent failure handling — still
  2285. lives in ``_start_print`` and runs per task exactly as before.
  2286. Synchronous on purpose: it registers every launched task into
  2287. ``self._inflight`` before returning, so the next (sequential) tick sees
  2288. an accurate in-flight count with no interleaving await.
  2289. """
  2290. free = limit - len(self._inflight)
  2291. if free <= 0:
  2292. logger.info(
  2293. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2294. len(self._inflight),
  2295. limit,
  2296. len(item_ids),
  2297. item_ids,
  2298. )
  2299. return
  2300. to_launch = item_ids[:free]
  2301. deferred = item_ids[free:]
  2302. logger.info(
  2303. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2304. len(to_launch),
  2305. len(self._inflight),
  2306. limit,
  2307. f" — deferring {deferred} to a later tick" if deferred else "",
  2308. )
  2309. for item_id in to_launch:
  2310. task = spawn_background_task(
  2311. self._dispatch_one(item_id, item_printers.get(item_id)),
  2312. name=f"queue-upload-{item_id}",
  2313. )
  2314. self._inflight[item_id] = (task, item_printers.get(item_id))
  2315. # Prune on completion so the freed slot is refillable next tick.
  2316. # spawn_background_task already logs any uncaught exception; this
  2317. # only reclaims the pool slot (fires on success, failure, or cancel).
  2318. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2319. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2320. """Upload + start one queue item in its own session (pool worker, #2602).
  2321. Its own session: pool workers run concurrently and an AsyncSession is
  2322. not safe to share across tasks; it also keeps a slow upload from pinning
  2323. the scheduler's session (and, on SQLite, its transaction) open for the
  2324. transfer's duration.
  2325. ``selected_printer_id`` is the printer this item was selected for, taken
  2326. from the same snapshot the caller used. It exists so the preheat pin can
  2327. be unwound on the paths that never reach the ``finally`` below — see the
  2328. claim failure a few lines down. Optional so the direct-call tests keep
  2329. working; when it is absent those paths simply behave as they did before.
  2330. """
  2331. async with async_session() as item_db:
  2332. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2333. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2334. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2335. # routes reject reassignment (409), so printer_id can't change out from
  2336. # under the in-flight upload and split the queue row from the
  2337. # archive/expected-print/physical command.
  2338. if not await self._claim_for_dispatch(item_db, item_id):
  2339. logger.info(
  2340. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2341. item_id,
  2342. )
  2343. # This return is outside the try/finally below, so the rollback
  2344. # has to happen here. Selecting this item already handed any
  2345. # keep-warm hold on its printer over to the preheat pin
  2346. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2347. # unwind it. Bailing without doing so leaves the bed hot with
  2348. # nothing tracking it: the keep-warm entry is gone, so the
  2349. # max-duration cap no longer applies, and if this was the
  2350. # printer's last pending item nothing else will ever turn it
  2351. # off. Reachable whenever a cancel or delete lands between
  2352. # selection and the claim.
  2353. if selected_printer_id is not None:
  2354. self._rollback_preheat_pin(item_id, selected_printer_id)
  2355. return
  2356. # Seeded from the caller's snapshot so the `item vanished` return
  2357. # below still unwinds the pin; overwritten with the row's own
  2358. # printer_id as soon as we have it.
  2359. item_printer_id: int | None = selected_printer_id
  2360. try:
  2361. item = await item_db.get(PrintQueueItem, item_id)
  2362. if not item:
  2363. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2364. return
  2365. item_printer_id = item.printer_id
  2366. await self._start_print(item_db, item)
  2367. finally:
  2368. # Undo an expected-print registration whose print command never
  2369. # went out. One choke point covers every way `_start_print` can
  2370. # end without sending: a raised exception (a DB failure mid-
  2371. # dispatch is the reported case), an early return, a cancel
  2372. # winning the #1853 CAS, or `start_print()` returning False.
  2373. # A confirmed send removes the entry itself, so this is a no-op
  2374. # on the happy path.
  2375. self._rollback_unconfirmed_expected_print(item_id)
  2376. # Likewise the print user it set: the printer's next print is
  2377. # not this item's.
  2378. self._rollback_unconfirmed_print_user(item_id)
  2379. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2380. # reservation survives only after start_print() accepted the
  2381. # command. Failure, cancellation, deferral, and exceptions all
  2382. # release it here.
  2383. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2384. # Unwind preheat state (bed/chamber/airduct) if the
  2385. # dispatch aborted before the print's own gcode took over.
  2386. # `_start_print` clears the pin on successful `start_print()`;
  2387. # anything still present here is by definition an aborted
  2388. # dispatch and gets rolled back so the printer isn't left
  2389. # heating for a job that isn't happening.
  2390. if item_printer_id is not None:
  2391. self._rollback_preheat_pin(item_id, item_printer_id)
  2392. # The cancellation flag only has meaning while this dispatch is
  2393. # running; drop it so the set cannot grow without bound and a
  2394. # re-queued item never inherits a stale cancellation.
  2395. self._cancelled_dispatches.discard(item_id)
  2396. # Release the claim on every exit. Once dispatch has finished the
  2397. # row's status carries the lock (printing/failed/cancelled are all
  2398. # != pending), so the token is only needed for the duration of the
  2399. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2400. # dispatchable again on the next tick.
  2401. await self._clear_dispatch_claim(item_db, item_id)
  2402. async def _requeue_after_upload_refused(
  2403. self,
  2404. db: AsyncSession,
  2405. item: PrintQueueItem,
  2406. printer: Printer,
  2407. error_msg: str,
  2408. toast_uid: int | None,
  2409. ) -> None:
  2410. """Put an item back in the queue after its file never reached the printer (#3210).
  2411. The item keeps its printer. Its AMS mapping was computed against that
  2412. printer's trays, and nothing on the row says whether a mapping was
  2413. computed or set by the user, so moving it to a sibling could print from
  2414. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2415. keeps every other item away from it; this one waits there and is the
  2416. only thing that knocks again, once per backoff window. The window
  2417. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2418. `dispatch_attempts` is not charged: that budget bounds a printer that
  2419. takes the file and then never starts, which this is not.
  2420. """
  2421. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2422. self._upload_refusals[printer.id] = refusals
  2423. backoff = _upload_backoff_seconds(refusals)
  2424. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2425. # The row is still `pending` -- it only moves to `printing` after a
  2426. # successful upload -- so there is no status to write back. Writing one
  2427. # anyway would undo a cancel that landed during the upload.
  2428. if item.error_message:
  2429. item.error_message = None
  2430. await db.commit()
  2431. logger.warning(
  2432. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2433. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2434. item.id,
  2435. printer.id,
  2436. printer.name,
  2437. error_msg,
  2438. refusals,
  2439. backoff,
  2440. )
  2441. try:
  2442. # Closes the dispatch toast for this attempt. Without it the toast
  2443. # keeps spinning on an upload that has ended.
  2444. await ws_manager.send_queue_item_failed(
  2445. user_id=toast_uid,
  2446. queue_item_id=item.id,
  2447. printer_id=item.printer_id,
  2448. reason="upload_failed",
  2449. )
  2450. except Exception:
  2451. pass # toast is best-effort
  2452. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2453. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2454. if printer_id is not None:
  2455. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2456. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2457. """Withdraw the expected print and print user of a sent print that never started.
  2458. Both tell the rest of Bambuddy that the printer's next print is this
  2459. item's: left behind, a print started by hand later is taken for it.
  2460. With ``unless_printing``, a printer that is printing after all keeps
  2461. them, as that print is most likely this one starting late.
  2462. ``keep_expected`` withdraws only the print user, which vouches for any
  2463. print on the printer. The expected print names this item's file, so a
  2464. late start of it is still matched to its archive.
  2465. """
  2466. sent = self._sent_unstarted_print.get(item_id)
  2467. if sent is None:
  2468. return
  2469. printer_id, remote_filename, archive_id = sent
  2470. if unless_printing:
  2471. status = printer_manager.get_status(printer_id)
  2472. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2473. return
  2474. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2475. if keep_expected:
  2476. return
  2477. del self._sent_unstarted_print[item_id]
  2478. if remote_filename is not None and archive_id is not None:
  2479. try:
  2480. from backend.app.main import unregister_expected_print
  2481. unregister_expected_print(printer_id, remote_filename, archive_id)
  2482. except Exception:
  2483. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2484. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2485. """Drop an expectation for a print command that was never sent.
  2486. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2487. where the interesting exception is usually the one already propagating.
  2488. """
  2489. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2490. if pending is None:
  2491. return
  2492. printer_id, remote_filename, archive_id = pending
  2493. try:
  2494. from backend.app.main import unregister_expected_print
  2495. unregister_expected_print(printer_id, remote_filename, archive_id)
  2496. except Exception:
  2497. logger.warning(
  2498. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2499. item_id,
  2500. printer_id,
  2501. remote_filename,
  2502. archive_id,
  2503. exc_info=True,
  2504. )
  2505. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2506. """Release a queue reservation without touching the dispatch session."""
  2507. if item_id not in self._unconfirmed_budget_reservations:
  2508. return
  2509. for attempt in range(1, 4):
  2510. async with async_session() as cleanup_db:
  2511. try:
  2512. await release_budget_reservation(
  2513. cleanup_db,
  2514. source_type="print_queue",
  2515. source_id=item_id,
  2516. status="released",
  2517. )
  2518. await cleanup_db.commit()
  2519. self._unconfirmed_budget_reservations.discard(item_id)
  2520. return
  2521. except Exception as exc:
  2522. try:
  2523. await cleanup_db.rollback()
  2524. except Exception:
  2525. pass
  2526. if attempt == 3:
  2527. logger.error(
  2528. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2529. item_id,
  2530. attempt,
  2531. exc,
  2532. )
  2533. return
  2534. await asyncio.sleep(0.5 * attempt)
  2535. @staticmethod
  2536. def _reported_bed_target(printer_id: int) -> int | None:
  2537. """The bed target firmware currently reports, or None if it can't be read.
  2538. None means "no evidence", not "zero" — callers must not treat it as a
  2539. temperature. Deliberately total: this feeds cleanup paths that run in a
  2540. ``finally``, where a malformed status must not become the exception the
  2541. caller sees.
  2542. """
  2543. try:
  2544. state = printer_manager.get_status(printer_id)
  2545. if state is None:
  2546. return None
  2547. temps = state.temperatures
  2548. if not isinstance(temps, dict):
  2549. return None
  2550. return int(float(temps.get("bed_target", 0) or 0))
  2551. except (TypeError, ValueError, AttributeError):
  2552. return None
  2553. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2554. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2555. Turns the bed heater off, the chamber heater off, and opens the
  2556. airduct flap back to cooling — for whichever of those preheat
  2557. actually applied. `_start_print` clears the pin on successful
  2558. `start_print()`; anything still present when `_dispatch_one` exits
  2559. is by definition an aborted dispatch and gets rolled back here.
  2560. The bed is the one action that can be declined: if firmware has since
  2561. been given a target other than the one we pinned, it belongs to someone
  2562. else and is left alone. See the comment at that branch.
  2563. Also called directly from `_dispatch_one`'s claim-failure return, which
  2564. never reaches the ``finally``.
  2565. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2566. """
  2567. pin = self._preheat_pin.pop(printer_id, set())
  2568. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2569. if not pin:
  2570. return
  2571. client = printer_manager.get_client(printer_id)
  2572. if client is None:
  2573. logger.info(
  2574. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2575. item_id,
  2576. printer_id,
  2577. )
  2578. return
  2579. if "bed" in pin:
  2580. # Only undo our own target. If firmware reports something else, the
  2581. # user or another writer owns the bed now and zeroing it would
  2582. # clobber their choice -- the same guard `_release_keep_warm`
  2583. # applies to a keep-warm hold.
  2584. #
  2585. # Every uncertain case switches the bed off rather than leaving it:
  2586. # no recorded target (a pin written before this bookkeeping, or a
  2587. # setter that raised after pinning) and an unreadable status both
  2588. # fall through. A bed left hot with no owner is the worse failure,
  2589. # and this runs in a `finally` where raising would mask the real
  2590. # exception.
  2591. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2592. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2593. logger.info(
  2594. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2595. item_id,
  2596. printer_id,
  2597. cur_bed_target,
  2598. pinned_bed,
  2599. )
  2600. else:
  2601. try:
  2602. client.set_bed_temperature(0)
  2603. except Exception as exc:
  2604. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2605. if "chamber" in pin:
  2606. try:
  2607. client.set_chamber_temperature(0)
  2608. except Exception as exc:
  2609. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2610. if "airduct" in pin:
  2611. try:
  2612. client.set_airduct_mode("cooling")
  2613. except Exception as exc:
  2614. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2615. logger.info(
  2616. "Dispatch item %s (printer %d): preheat rollback → %s",
  2617. item_id,
  2618. printer_id,
  2619. sorted(pin),
  2620. )
  2621. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  2622. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2623. Returns True if this call won the claim, False if the row was already
  2624. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2625. the load-bearing guard against reassign-during-dispatch (#2615)."""
  2626. res = await db.execute(
  2627. update(PrintQueueItem)
  2628. .where(PrintQueueItem.id == item_id)
  2629. .where(PrintQueueItem.status == "pending")
  2630. .where(PrintQueueItem.dispatching_at.is_(None))
  2631. .values(dispatching_at=datetime.now(timezone.utc))
  2632. )
  2633. await db.commit()
  2634. return res.rowcount > 0
  2635. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2636. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2637. mask the dispatch outcome.
  2638. Retried, because the failure mode in practice is transient and narrow: a
  2639. database that is momentarily unreachable — PostgreSQL out of connection
  2640. slots is the observed case — refuses this write for a second or two while
  2641. the dispatch that just ended is still holding the row out of the selection
  2642. query. One attempt was enough to wedge the item; a couple of spaced
  2643. attempts clear it. Each attempt rolls back first, since a failed write
  2644. leaves the session needing it before it can be reused.
  2645. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2646. on the next quiet tick.
  2647. """
  2648. for attempt in range(1, 4):
  2649. try:
  2650. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2651. await db.commit()
  2652. return
  2653. except Exception as exc:
  2654. try:
  2655. await db.rollback()
  2656. except Exception:
  2657. pass
  2658. if attempt == 3:
  2659. logger.warning(
  2660. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2661. "— a later quiet tick will release it",
  2662. item_id,
  2663. attempt,
  2664. exc,
  2665. )
  2666. return
  2667. await asyncio.sleep(0.5 * attempt)
  2668. async def _printers_for_model(
  2669. self,
  2670. db: AsyncSession,
  2671. model: str,
  2672. target_location: str | None = None,
  2673. printer_scope: PrinterScope = ALL_PRINTERS,
  2674. ) -> list[Printer]:
  2675. """Active printers of *model*, optionally narrowed to one location.
  2676. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2677. answer "which printers can this job run on" from one query — a job can
  2678. only be woken onto a printer the matcher would also have considered.
  2679. ``printer_scope`` is the job creator's (#1727).
  2680. """
  2681. normalized_model = normalize_printer_model(model) or model
  2682. query = (
  2683. select(Printer)
  2684. .where(func.lower(Printer.model) == normalized_model.lower())
  2685. .where(Printer.is_active == True) # noqa: E712
  2686. )
  2687. if target_location:
  2688. query = query.where(Printer.location == target_location)
  2689. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2690. query = query.where(clause)
  2691. result = await db.execute(query)
  2692. return list(result.scalars().all())
  2693. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2694. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2695. Read once per queue check rather than per printer: it decides both
  2696. whether the wake step has anything to do and how an offline printer is
  2697. worded in the waiting reason — "Offline" and "offline with no Auto On
  2698. plug" are different problems, and the second is the one the user has to
  2699. fix themselves (#2786).
  2700. """
  2701. result = await db.execute(
  2702. select(SmartPlug.printer_id)
  2703. .where(SmartPlug.printer_id.is_not(None))
  2704. .where(SmartPlug.enabled == True) # noqa: E712
  2705. .where(SmartPlug.auto_on == True) # noqa: E712
  2706. )
  2707. return {pid for (pid,) in result.all() if pid is not None}
  2708. def _wake_recently_failed(self, printer_id: int) -> bool:
  2709. """True while this printer's failed power-on is still cooling off (#2786)."""
  2710. deadline = self._wake_failures.get(printer_id)
  2711. if deadline is None:
  2712. return False
  2713. if time.monotonic() >= deadline:
  2714. del self._wake_failures[printer_id]
  2715. return False
  2716. return True
  2717. async def _wake_printer_for_model(
  2718. self,
  2719. db: AsyncSession,
  2720. candidates: list[_ModelCandidate],
  2721. target_location: str | None,
  2722. exclude_ids: set[int],
  2723. wakeable_ids: set[int],
  2724. require_plate_clear: bool,
  2725. printer_scope: PrinterScope = ALL_PRINTERS,
  2726. ) -> tuple[int | None, int | None]:
  2727. """Power on one offline printer a model-based item could run on (#2786).
  2728. The fixed-printer branch has powered a printer on since smart plugs
  2729. existed. The model-based branch never could: its matcher drops an
  2730. offline printer into the "Offline:" waiting reason and nothing looks at
  2731. its plugs, so a class-targeted job with every matching printer switched
  2732. off sat pending forever. The reporter's log is the controlled
  2733. experiment — the same item, same plug, same Auto On setting, dispatched
  2734. the moment they edited it onto a specific printer.
  2735. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2736. power-on was actually tried, so the caller can tell "nothing here was
  2737. wakeable" (both None — cheap, other items may still find something)
  2738. from "we tried and it did not come up" (only ``attempted_id`` — the
  2739. boot timeout has already been spent).
  2740. A printer whose last known trays cannot satisfy the job is passed over
  2741. rather than woken (#2876): the colours are readable while it is off, so
  2742. switching a farm on one machine at a time to discover them wakes
  2743. printers that could never have taken the job.
  2744. Deliberately does NOT go on to match the job once a printer is up: AMS
  2745. trays arrive with the first status push after connect, so a filament
  2746. check against a printer that booted seconds ago can reject the printer
  2747. we just woke. The next queue pass matches it with live state.
  2748. At most one printer per pass. Each wake blocks the queue loop for the
  2749. boot wait, and a queue of ten class-targeted jobs must not switch on
  2750. ten printers inside one check.
  2751. """
  2752. for candidate in candidates:
  2753. if not candidate.target_model:
  2754. continue
  2755. required_types, filament_overrides = _filament_constraints(candidate)
  2756. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2757. for printer in sorted(printers, key=lambda p: p.id):
  2758. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2759. continue
  2760. if printer_manager.is_connected(printer.id):
  2761. continue
  2762. if self._wake_recently_failed(printer.id):
  2763. # Its plug did not bring it back a moment ago. Move on to a
  2764. # sibling instead of spending this pass — and every pass —
  2765. # on the same printer.
  2766. continue
  2767. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2768. # Waking this one buys nothing: it would boot into IDLE and
  2769. # then be held by the plate-clear gate, which is exactly
  2770. # what the reporter's log shows happening for 80 minutes
  2771. # after a fixed-printer wake. The flag is Bambuddy-side and
  2772. # persisted, so it is readable while the printer is off.
  2773. logger.info(
  2774. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2775. printer.id,
  2776. candidate.target_model,
  2777. )
  2778. continue
  2779. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2780. if shortfall:
  2781. logger.info(
  2782. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2783. printer.id,
  2784. candidate.target_model,
  2785. ", ".join(shortfall),
  2786. )
  2787. continue
  2788. plugs = await self._get_smart_plugs(db, printer.id)
  2789. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2790. if not auto_on_plugs:
  2791. # wakeable_ids said otherwise — the plug changed under us
  2792. # mid-pass. Nothing to do but move on.
  2793. continue
  2794. logger.info(
  2795. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2796. candidate.target_model,
  2797. printer.id,
  2798. )
  2799. primary_plug = self._pick_power_plug(auto_on_plugs)
  2800. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2801. logger.warning(
  2802. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2803. printer.id,
  2804. self._wake_failure_cooloff,
  2805. )
  2806. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2807. return None, printer.id
  2808. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2809. try:
  2810. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2811. if await service.turn_on(extra_plug):
  2812. await publish_plug_state(
  2813. extra_plug.id,
  2814. extra_plug.name,
  2815. extra_plug.printer_id,
  2816. on=True,
  2817. ha_entity_id=extra_plug.ha_entity_id,
  2818. )
  2819. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2820. except Exception as e:
  2821. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2822. return printer.id, printer.id
  2823. return None, None
  2824. async def _find_idle_printer_for_model(
  2825. self,
  2826. db: AsyncSession,
  2827. model: str,
  2828. exclude_ids: set[int],
  2829. required_filament_types: list[str] | None = None,
  2830. target_location: str | None = None,
  2831. filament_overrides: list[dict] | None = None,
  2832. require_plate_clear: bool = True,
  2833. wakeable_ids: set[int] | None = None,
  2834. printer_scope: PrinterScope = ALL_PRINTERS,
  2835. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2836. ) -> tuple[int | None, str | None]:
  2837. """Find an idle, connected printer matching the model with compatible filaments.
  2838. Args:
  2839. db: Database session
  2840. model: Printer model to match (e.g., "X1C", "P1S")
  2841. exclude_ids: Printer IDs to exclude (already busy)
  2842. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2843. If provided, only printers with all required types loaded will match.
  2844. target_location: Optional location filter. If provided, only printers in this location are considered.
  2845. filament_overrides: Optional list of override dicts. Each entry may include
  2846. ``force_color_match: true`` to require an exact type+color match
  2847. on the printer for that slot. Without the flag the existing
  2848. colour-preference logic applies.
  2849. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2850. offline printer is worded: one Bambuddy will switch on reads
  2851. differently from one the user has to go and switch on themselves.
  2852. is_short: Says whether a printer's spools are too light for the job (#3137).
  2853. A printer it flags is passed over while another eligible one
  2854. is not. When every eligible printer is short, the first is
  2855. returned all the same, so the deficit gate holds the job there
  2856. and "Print Anyway" still has a printer to print on.
  2857. Returns:
  2858. Tuple of (printer_id, waiting_reason):
  2859. - (printer_id, None) if a matching printer was found
  2860. - (None, reason) if no printer is available, with explanation
  2861. """
  2862. normalized_model = normalize_printer_model(model) or model
  2863. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2864. location_suffix = f" in {target_location}" if target_location else ""
  2865. if not printers:
  2866. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2867. # Separate force-matched overrides from preference-only overrides
  2868. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2869. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2870. # Track reasons for skipping printers
  2871. printers_busy = []
  2872. printers_offline = []
  2873. printers_offline_no_plug = []
  2874. printers_missing_filament: list[tuple[str, list[str]]] = []
  2875. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2876. # The first eligible printer that is short on filament, kept in case
  2877. # every eligible printer is (#3137).
  2878. short_fallback: int | None = None
  2879. for printer in printers:
  2880. if printer.id in exclude_ids:
  2881. # Printer is already claimed by another job in this scheduling run.
  2882. # For force-color jobs, still check if the color would match — if not,
  2883. # report it as a color mismatch rather than plain "Busy" so the user
  2884. # knows the job needs a filament change, not just to wait for availability.
  2885. if force_overrides and not pref_overrides:
  2886. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2887. if missing_colors:
  2888. printers_missing_filament.append((printer.name, missing_colors))
  2889. continue
  2890. printers_busy.append(printer.name)
  2891. continue
  2892. is_connected = printer_manager.is_connected(printer.id)
  2893. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2894. if not is_connected:
  2895. # An offline printer whose last known filament cannot run this
  2896. # job is reported as needing filament rather than as offline
  2897. # (#2876). It is also the printer the smart-plug step will now
  2898. # decline to switch on, and "Offline:" on its own would leave
  2899. # that decision looking like nothing happening at all.
  2900. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2901. if shortfall:
  2902. printers_missing_filament.append((printer.name, shortfall))
  2903. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2904. printers_offline_no_plug.append(printer.name)
  2905. else:
  2906. printers_offline.append(printer.name)
  2907. continue
  2908. if not is_idle:
  2909. # Printer is currently printing. For force-color jobs, check whether the
  2910. # loaded color would satisfy the requirement — if not, surface it as a
  2911. # color-mismatch reason rather than plain "Busy" so the user understands
  2912. # that the job is waiting for a filament change, not just printer availability.
  2913. if force_overrides and not pref_overrides:
  2914. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2915. if missing_colors:
  2916. printers_missing_filament.append((printer.name, missing_colors))
  2917. logger.debug(
  2918. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2919. printer.id,
  2920. printer.name,
  2921. missing_colors,
  2922. )
  2923. continue
  2924. printers_busy.append(printer.name)
  2925. continue
  2926. # Validate filament compatibility if required types are specified
  2927. if required_filament_types:
  2928. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2929. if missing:
  2930. # When force_overrides are present, enrich missing entries with color info
  2931. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2932. if force_overrides:
  2933. force_color_map = {
  2934. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2935. for o in force_overrides
  2936. }
  2937. missing_enriched = [
  2938. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2939. for t in missing
  2940. ]
  2941. printers_missing_filament.append((printer.name, missing_enriched))
  2942. else:
  2943. printers_missing_filament.append((printer.name, missing))
  2944. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2945. continue
  2946. # Force color match: ALL flagged slots must have an exact type+color match
  2947. if force_overrides:
  2948. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2949. if missing_colors:
  2950. printers_missing_filament.append((printer.name, missing_colors))
  2951. logger.debug(
  2952. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2953. printer.id,
  2954. printer.name,
  2955. missing_colors,
  2956. )
  2957. continue
  2958. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2959. if pref_overrides:
  2960. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2961. if color_matches > 0:
  2962. candidates.append((printer.id, color_matches))
  2963. else:
  2964. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2965. printers_missing_filament.append((printer.name, override_colors))
  2966. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2967. continue
  2968. else:
  2969. # No preference ordering needed: the first eligible printer
  2970. # wins, unless its spools are too light for the job (#3137).
  2971. if is_short is not None and await is_short(printer.id):
  2972. if short_fallback is None:
  2973. short_fallback = printer.id
  2974. logger.info(
  2975. "Model-based assignment: passing over printer %s (%s), not enough filament",
  2976. printer.id,
  2977. printer.name,
  2978. )
  2979. continue
  2980. return printer.id, None
  2981. # If we have candidates from preference override matching, pick the one with most color matches
  2982. if candidates:
  2983. candidates.sort(key=lambda c: c[1], reverse=True)
  2984. if is_short is not None:
  2985. for candidate_id, _ in candidates:
  2986. if not await is_short(candidate_id):
  2987. return candidate_id, None
  2988. logger.info(
  2989. "Model-based assignment: passing over printer %s, not enough filament",
  2990. candidate_id,
  2991. )
  2992. return candidates[0][0], None
  2993. if short_fallback is not None:
  2994. return short_fallback, None
  2995. # Build waiting reason from what we found
  2996. reasons = []
  2997. if printers_missing_filament:
  2998. # Filament/color mismatch is most actionable - show first
  2999. if force_overrides and not pref_overrides:
  3000. # All mismatches are force-color failures — use descriptive message only;
  3001. # but only if there are no busy printers that DO have the matching color.
  3002. # If a printer has the right color but is busy, surface "Busy" instead so
  3003. # the user knows the job will start automatically once that printer is free.
  3004. # Same for a printer that is merely offline: Bambuddy switches that one on
  3005. # by itself, so the job is not actually waiting on anybody to change a
  3006. # spool (#2876 — offline printers reach this list now that a switched-off
  3007. # printer's own filament is read).
  3008. if not printers_busy and not printers_offline:
  3009. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3010. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3011. # else: fall through — the self-resolving entries are appended below
  3012. else:
  3013. names_and_missing = [
  3014. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3015. ]
  3016. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3017. if printers_busy:
  3018. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3019. if printers_offline:
  3020. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3021. if printers_offline_no_plug:
  3022. # Named separately because it is the one entry on this list the
  3023. # user has to act on: no enabled Auto On plug means Bambuddy will
  3024. # never power this printer on for the queue (#2786).
  3025. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3026. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3027. @staticmethod
  3028. def _is_busy_only(waiting_reason: str) -> bool:
  3029. """Check if the waiting reason only contains 'Busy' entries.
  3030. When all matching printers are simply busy printing, the queued job
  3031. will start automatically once a printer finishes — no user action
  3032. is required, so we skip the notification.
  3033. """
  3034. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3035. return all(p.startswith("Busy:") for p in parts)
  3036. def _get_missing_force_color_slots(
  3037. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3038. ) -> list[str]:
  3039. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3040. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3041. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3042. with an exact type+color match.
  3043. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3044. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3045. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3046. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3047. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3048. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3049. setups are unaffected.
  3050. Returns:
  3051. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3052. """
  3053. if raw_data is None:
  3054. status = printer_manager.get_status(printer_id)
  3055. if not status:
  3056. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3057. raw_data = status.raw_data
  3058. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3059. loaded: list[tuple[str, str, str]] = []
  3060. for ams_unit in raw_data.get("ams", []):
  3061. for tray in ams_unit.get("tray", []):
  3062. tray_type = tray.get("tray_type")
  3063. if tray_type:
  3064. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3065. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3066. for vt in raw_data.get("vt_tray") or []:
  3067. vt_type = vt.get("tray_type")
  3068. if vt_type:
  3069. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3070. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3071. missing = []
  3072. for o in force_overrides:
  3073. o_type = canonical_filament_type(o.get("type") or "")
  3074. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3075. o_idx = o.get("tray_info_idx") or ""
  3076. satisfied = any(
  3077. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  3078. for t_type, t_color, t_idx in loaded
  3079. )
  3080. if not satisfied:
  3081. color_label = o.get("color_name") or o.get("color", "?")
  3082. missing.append(f"{o_type} ({color_label})")
  3083. return missing
  3084. def _get_missing_filament_types(
  3085. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3086. ) -> list[str]:
  3087. """Get the list of required filament types that are not loaded on the printer.
  3088. Args:
  3089. printer_id: The printer ID
  3090. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3091. Returns:
  3092. List of missing filament types (empty if all are loaded)
  3093. """
  3094. if raw_data is None:
  3095. status = printer_manager.get_status(printer_id)
  3096. if not status:
  3097. return required_types # Can't determine, assume all missing
  3098. raw_data = status.raw_data
  3099. # Collect all filament types loaded on this printer (AMS units + external spool)
  3100. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3101. loaded_types: set[str] = set()
  3102. # Check AMS units (stored in raw_data["ams"])
  3103. ams_data = raw_data.get("ams", [])
  3104. if ams_data:
  3105. for ams_unit in ams_data:
  3106. for tray in ams_unit.get("tray", []):
  3107. tray_type = tray.get("tray_type")
  3108. if tray_type:
  3109. loaded_types.add(canonical_filament_type(tray_type))
  3110. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3111. for vt in raw_data.get("vt_tray") or []:
  3112. vt_type = vt.get("tray_type")
  3113. if vt_type:
  3114. loaded_types.add(canonical_filament_type(vt_type))
  3115. # Find which required types are missing (using canonical type for equivalence)
  3116. missing = []
  3117. for req_type in required_types:
  3118. if canonical_filament_type(req_type) not in loaded_types:
  3119. missing.append(req_type)
  3120. return missing
  3121. def _count_override_color_matches(
  3122. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3123. ) -> int:
  3124. """Count how many filament overrides have an exact color match on the printer.
  3125. Used to prefer printers that already have the desired override colors loaded.
  3126. """
  3127. if raw_data is None:
  3128. status = printer_manager.get_status(printer_id)
  3129. if not status:
  3130. return 0
  3131. raw_data = status.raw_data
  3132. # Collect loaded filaments' type+color pairs
  3133. loaded: set[tuple[str, str]] = set()
  3134. for ams_unit in raw_data.get("ams", []):
  3135. for tray in ams_unit.get("tray", []):
  3136. tray_type = tray.get("tray_type")
  3137. # `or ""`, not a dict default: a slot can carry the key with a
  3138. # null value, and this now runs against switched-off printers
  3139. # too, where nobody is watching for the AttributeError.
  3140. tray_color = tray.get("tray_color") or ""
  3141. if tray_type:
  3142. color_norm = tray_color.replace("#", "").lower()[:6]
  3143. loaded.add((tray_type.upper(), color_norm))
  3144. for vt in raw_data.get("vt_tray") or []:
  3145. vt_type = vt.get("tray_type")
  3146. if vt_type:
  3147. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3148. loaded.add((vt_type.upper(), color_norm))
  3149. matches = 0
  3150. for o in overrides:
  3151. o_type = (o.get("type") or "").upper()
  3152. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3153. if (o_type, o_color) in loaded:
  3154. matches += 1
  3155. return matches
  3156. @staticmethod
  3157. def _tray_reading(printer_id: int) -> dict:
  3158. """The best tray reading available for a printer that is not printing.
  3159. Live status first: a printer keeps its last status after the power
  3160. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3161. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3162. for when the client itself has been dropped and taken its status with
  3163. it — which is what every power-on attempt does.
  3164. An empty result means "we have never heard", not "nothing is loaded":
  3165. the two are indistinguishable from here, and only the second would be
  3166. safe to act on.
  3167. """
  3168. status = printer_manager.get_status(printer_id)
  3169. raw = (status.raw_data if status else None) or {}
  3170. for ams_unit in raw.get("ams") or []:
  3171. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3172. return raw
  3173. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3174. return raw
  3175. return printer_manager.last_known_trays(printer_id)
  3176. def _cached_filament_shortfall(
  3177. self,
  3178. printer_id: int,
  3179. required_types: list[str] | None,
  3180. filament_overrides: list[dict] | None,
  3181. ) -> list[str]:
  3182. """What a switched-off printer's last known filament cannot provide (#2876).
  3183. The smart-plug wake step used to consider only the model, so a job for a
  3184. colour loaded on the last printer in ID order switched on every earlier
  3185. one in turn, evaluated it, rejected it on colour and left it running.
  3186. Bambuddy knew those colours the whole time. This asks the same three
  3187. questions the matcher asks a live printer — required types, forced
  3188. colours, preferred colours — of the trays it last reported, and returns
  3189. the answers in the same shape the "Waiting for filament" reason uses.
  3190. Empty means the printer may still be able to take the job.
  3191. Fails open, and deliberately: with no tray reading (never connected
  3192. since Bambuddy started, or the cache dropped by a reconnect) this
  3193. returns nothing to report and the printer is treated as it was before.
  3194. A farm restarted while its printers were off must not conclude that
  3195. none of them can print.
  3196. """
  3197. if not required_types and not filament_overrides:
  3198. return []
  3199. raw_data = self._tray_reading(printer_id)
  3200. if not raw_data:
  3201. return []
  3202. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3203. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3204. if required_types:
  3205. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3206. if missing:
  3207. # Same enrichment the live path applies: a bare "PLA" is not
  3208. # much help when what is missing is a particular PLA.
  3209. force_color_map = {
  3210. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3211. }
  3212. return [
  3213. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3214. for t in missing
  3215. ]
  3216. if force_overrides:
  3217. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3218. if missing_colors:
  3219. return missing_colors
  3220. # Preference overrides read as a preference but the matcher treats zero
  3221. # matches as a skip, so a printer with none of the wanted colours is
  3222. # rejected there too. Waking it would only produce that same rejection.
  3223. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3224. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3225. return []
  3226. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3227. """Fold the winning candidate's file and settings onto the queue row (#671).
  3228. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3229. never escapes the selection loop. By the time the pass commits, the row
  3230. looks exactly like an ordinary single-file model-based item, so the upload,
  3231. archive creation, expected-print registration, print history and reprint
  3232. paths need no knowledge that variants exist.
  3233. No-ops for a non-variant candidate, which is already the item's own columns.
  3234. Safe to run and re-run: the item's file columns are only ever *read* when it
  3235. has no variants, so an item that gets resolved and then skipped (library-row
  3236. conflict, previous-print gate) is simply resolved again on the next pass.
  3237. """
  3238. variant = candidate.variant
  3239. if variant is None:
  3240. return
  3241. item.library_file_id = variant.library_file_id
  3242. item.library_file = variant.library_file
  3243. # The dispatcher checks archive_id first and would print that instead of
  3244. # the file we just picked. Creation refuses to combine the two, so this
  3245. # only ever fires on a hand-written row — clear it rather than silently
  3246. # dispatch something the matcher never considered.
  3247. item.archive_id = None
  3248. item.archive = None
  3249. item.target_model = variant.target_model
  3250. item.plate_id = variant.plate_id
  3251. item.ams_mapping = variant.ams_mapping
  3252. item.nozzle_mapping = variant.nozzle_mapping
  3253. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3254. item.filament_overrides = variant.filament_overrides
  3255. item.required_filament_types = variant.required_filament_types
  3256. if variant.print_time_seconds is not None:
  3257. # The row carried the shortest candidate's estimate so SJF could order
  3258. # it before a printer was known; now that one is chosen, record what is
  3259. # actually going to run so history and the ETA agree with reality.
  3260. item.print_time_seconds = variant.print_time_seconds
  3261. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3262. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3263. Recomputes from live printer status when the stored mapping is missing OR
  3264. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3265. frontend status-load race can serialize [-1] before the printer's AMS
  3266. trays are known (#2589) — and must not be trusted: downstream it would be
  3267. silently downgraded to external-spool mode and print against an empty
  3268. feed. A resolved mapping is re-checked against the target printer's
  3269. live trays before it is trusted (#2799) and recomputed when it does not
  3270. fit. When it does fit, its resolved slots are kept as they are and only
  3271. the slots the plate prints that are still unresolved are matched again;
  3272. all of it is left alone when the user has acknowledged it with "Print
  3273. Anyway".
  3274. When recompute cannot resolve it either (no compatible tray loaded), the
  3275. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3276. external selection. On a printer that reported loaded trays,
  3277. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3278. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3279. and the firmware surfaces a clear AMS-mapping error instead of silently
  3280. printing to the empty external feed.
  3281. Returns an actionable message when that firmware error is the only
  3282. possible outcome — the matcher ran, matched nothing, and the printer has
  3283. no AMS to load a different spool into (#2771). The caller fails the item
  3284. on it instead of spending an upload on a print that cannot start.
  3285. Returns None everywhere else, including every case where we simply lack
  3286. the data to judge, so dispatch is only ever blocked on a positive
  3287. finding.
  3288. """
  3289. stored_mapping: list | None = None
  3290. if item.ams_mapping:
  3291. try:
  3292. stored_mapping = json.loads(item.ams_mapping)
  3293. except (json.JSONDecodeError, TypeError):
  3294. stored_mapping = None
  3295. # Present and resolved. Global tray IDs only mean something relative to
  3296. # the printer they were resolved against, so "resolved" is not the same
  3297. # as "resolved *here*" — check the mapping still fits the printer that
  3298. # is about to run this item before trusting it (#2799). "Print anyway"
  3299. # is the user overriding exactly this judgement, so it short-circuits.
  3300. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3301. if item.skip_filament_check:
  3302. return None
  3303. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3304. if conflict is None:
  3305. # It fits, but a slot the plate prints may still be empty: the
  3306. # spool was missing when it was mapped, and has perhaps been
  3307. # loaded since. Nothing else would ever look at that slot again,
  3308. # so a job held for it would be held again on every Start.
  3309. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3310. if filled is not None:
  3311. item.ams_mapping = json.dumps(filled)
  3312. logger.info(
  3313. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3314. item.id,
  3315. stored_mapping,
  3316. printer_id,
  3317. filled,
  3318. )
  3319. await db.commit()
  3320. return None
  3321. logger.warning(
  3322. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3323. item.id,
  3324. stored_mapping,
  3325. printer_id,
  3326. conflict,
  3327. )
  3328. # Drop it before recomputing so a failed recompute cannot fall back
  3329. # to the mapping we just rejected.
  3330. item.ams_mapping = None
  3331. stored_mapping = None
  3332. await db.commit()
  3333. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3334. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3335. item.ams_mapping = json.dumps(computed_mapping)
  3336. logger.info(
  3337. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3338. item.id,
  3339. printer_id,
  3340. computed_mapping,
  3341. )
  3342. await db.commit()
  3343. return None
  3344. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3345. if external_only is not None:
  3346. item.ams_mapping = json.dumps(external_only)
  3347. logger.info(
  3348. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3349. "mapping every filament to it: %s",
  3350. item.id,
  3351. printer_id,
  3352. external_only,
  3353. )
  3354. await db.commit()
  3355. return None
  3356. if _mapping_is_all_unresolved(stored_mapping):
  3357. logger.warning(
  3358. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3359. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3360. item.id,
  3361. stored_mapping,
  3362. printer_id,
  3363. )
  3364. item.ams_mapping = None
  3365. await db.commit()
  3366. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3367. async def _external_spool_only_mapping(
  3368. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3369. ) -> list[int] | None:
  3370. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3371. A printer without an AMS prints from its external spool, and an external
  3372. spool whose filament was never set reports no type, so the matcher has
  3373. nothing to match. Sent without a mapping, the print goes out with the AMS
  3374. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3375. to carry such a job through; a job placed by model or location no longer
  3376. keeps one, and one queued that way never had one.
  3377. Only on a positive report: the printer has said it has no AMS, it has a
  3378. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3379. is not ours to pick), and no feed has a filament set — with one set, the
  3380. matcher has already given its answer. Not for a job that asked for its
  3381. colours to be matched strictly: a spool without a filament set has no
  3382. colour to check. Returns None otherwise.
  3383. """
  3384. if item.filament_overrides:
  3385. try:
  3386. overrides = json.loads(item.filament_overrides)
  3387. except (json.JSONDecodeError, TypeError):
  3388. return None
  3389. if not isinstance(overrides, list) or any(
  3390. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3391. ):
  3392. return None
  3393. status = printer_manager.get_status(printer_id)
  3394. if status is None or not isinstance(status.raw_data, dict):
  3395. return None
  3396. ams_units = status.raw_data.get("ams")
  3397. if not isinstance(ams_units, list) or ams_units:
  3398. return None
  3399. vt_trays = status.raw_data.get("vt_tray")
  3400. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3401. return None
  3402. if self._build_loaded_filaments(status):
  3403. return None
  3404. printer = await self._get_printer(db, printer_id)
  3405. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3406. return None
  3407. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3408. if external < _EXTERNAL_TRAY_ID_MIN:
  3409. return None
  3410. required = await self._get_filament_requirements(db, item)
  3411. slot_ids = [r.get("slot_id") for r in required or []]
  3412. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3413. if not slot_ids:
  3414. return None
  3415. mapping = [-1] * max(slot_ids)
  3416. for slot_id in slot_ids:
  3417. mapping[slot_id - 1] = external
  3418. return mapping
  3419. async def _fill_unresolved_slots(
  3420. self,
  3421. db: AsyncSession,
  3422. printer_id: int,
  3423. item: PrintQueueItem,
  3424. stored_mapping: list | None,
  3425. ) -> list | None:
  3426. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3427. Every resolved entry is kept, so a tray the user picked by hand stays
  3428. picked. Only the plate's unresolved slots are matched, and only against
  3429. trays the mapping does not already use: the matcher never gives two
  3430. slots one tray, and filling a gap with a tray the user assigned to
  3431. another slot would print that slot's filament twice.
  3432. Returns None when there is nothing to fill or nothing could be filled.
  3433. """
  3434. if not isinstance(stored_mapping, list) or not stored_mapping:
  3435. return None
  3436. required = await self._get_filament_requirements(db, item)
  3437. if not required:
  3438. return None
  3439. self._apply_filament_overrides(item, required)
  3440. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3441. if not gaps:
  3442. return None
  3443. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3444. computed = await self._compute_ams_mapping_for_printer(
  3445. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3446. )
  3447. if not computed:
  3448. return None
  3449. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3450. filled = False
  3451. for slot_id in gaps:
  3452. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3453. if _is_tray_id(tray) and tray >= 0:
  3454. merged[slot_id - 1] = tray
  3455. filled = True
  3456. return merged if filled else None
  3457. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3458. """What a staged item would be held for if it were started now (#2799).
  3459. The Start button asks this before releasing an item, so that a job whose
  3460. filament is still not loaded offers "Print Anyway" instead of being
  3461. released, held again by the scheduler and leaving no way past the hold.
  3462. It reaches the same answer the dispatch path would: a stored mapping
  3463. that fits is kept and only its gaps are matched again, and one that
  3464. does not fit (or is missing) is replaced by a fresh match.
  3465. Returns the missing filaments, described the way the queue row
  3466. describes them, or None when nothing is missing or there is not enough
  3467. evidence to say: no printer yet (a model-based item picks one at
  3468. dispatch), no status, no trays reported, or no readable 3MF.
  3469. """
  3470. if item.skip_filament_check or not item.printer_id:
  3471. return None
  3472. status = printer_manager.get_status(item.printer_id)
  3473. if status is None or not self._build_loaded_filaments(status):
  3474. return None
  3475. # Called from a request, not from a pass: drop whatever the last pass
  3476. # memoised so this reads the file as it is now. A pass running at the
  3477. # same time only loses its cache.
  3478. self._filament_req_memo.clear()
  3479. mapping: list | None = None
  3480. if item.ams_mapping:
  3481. try:
  3482. mapping = json.loads(item.ams_mapping)
  3483. except (json.JSONDecodeError, TypeError):
  3484. mapping = None
  3485. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3486. mapping = None
  3487. if mapping is not None:
  3488. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3489. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3490. else:
  3491. mapping = None
  3492. if mapping is None:
  3493. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3494. required = await self._get_filament_requirements(db, item)
  3495. if not required:
  3496. return None
  3497. self._apply_filament_overrides(item, required)
  3498. missing = _unresolved_required(required, mapping)
  3499. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3500. async def _stored_mapping_conflict(
  3501. self,
  3502. db: AsyncSession,
  3503. printer_id: int,
  3504. item: PrintQueueItem,
  3505. stored_mapping: list | None,
  3506. ) -> str | None:
  3507. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3508. A mapping is a list of global tray IDs, and those are only meaningful
  3509. relative to the printer they were resolved against — the same rule
  3510. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3511. arrives at a printer it was not resolved for:
  3512. * the print dialog stamps one mapping onto every selected printer, so a
  3513. mapping computed against the first printer is dispatched verbatim to
  3514. the rest, whose AMS slot order differs;
  3515. * a spool is moved between queueing and dispatch.
  3516. Both end the same way: the slot index still resolves, so nothing looks
  3517. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3518. the firmware's own type check, so a PETG slot happily prints in ASA.
  3519. Returns a short reason when the mapping names a tray this printer does
  3520. not have loaded, points a slot at a tray holding a different filament
  3521. type, or points it at an external spool this printer reports empty while
  3522. its AMS holds that slot's filament (#3239). Returns None when the
  3523. mapping fits, and — deliberately — whenever we lack the evidence to
  3524. judge, so a recompute only ever follows a positive finding.
  3525. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3526. matcher had nothing, not that the mapping belongs to another printer,
  3527. and destroying a partially hand-resolved mapping over it would lose the
  3528. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3529. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3530. item when that finds nothing.
  3531. """
  3532. if not isinstance(stored_mapping, list) or not stored_mapping:
  3533. return None
  3534. status = printer_manager.get_status(printer_id)
  3535. if status is None:
  3536. return None
  3537. loaded = self._build_loaded_filaments(status)
  3538. if not loaded:
  3539. # Nothing reported yet (reconnect, first push pending). Saying
  3540. # "tray not loaded" here would recompute against an AMS we cannot
  3541. # see, which is how #2589 produced a bogus all-[-1] in the first
  3542. # place.
  3543. return None
  3544. by_tray = {f["global_tray_id"]: f for f in loaded}
  3545. # Cheap pass first, on live status alone: every tray the mapping names
  3546. # has to exist here. This catches a foreign mapping without opening the
  3547. # 3MF, which is worth doing because the parse below is neither cached
  3548. # nor free.
  3549. for index, tray in enumerate(stored_mapping):
  3550. if not _is_tray_id(tray) or tray < 0:
  3551. continue
  3552. if tray in by_tray:
  3553. continue
  3554. if tray >= 254:
  3555. # An external feed we have not heard about is absence of
  3556. # evidence about *that slot* — the rest of the mapping is still
  3557. # worth judging, so skip it rather than abandoning the pass.
  3558. continue
  3559. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3560. # Only now is the 3MF worth opening: the type check needs to know what
  3561. # each slot actually asked for. The external spool is checked the same
  3562. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3563. # two printers with different filament in the external feed is the same
  3564. # failure this method exists to catch.
  3565. required = await self._get_filament_requirements(db, item)
  3566. if not required:
  3567. return None
  3568. self._apply_filament_overrides(item, required)
  3569. # External feeds the printer reports and reports as empty. That is
  3570. # evidence, unlike an external feed it says nothing about (#3239).
  3571. empty_external: set[int] = set()
  3572. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3573. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3574. if isinstance(vt, dict) and not vt.get("tray_type"):
  3575. try:
  3576. empty_external.add(int(vt.get("id", 254)))
  3577. except (TypeError, ValueError):
  3578. continue
  3579. for req in required:
  3580. slot_id = req.get("slot_id") or 0
  3581. if slot_id <= 0:
  3582. continue
  3583. if slot_id > len(stored_mapping):
  3584. return f"slot {slot_id} is not covered by the mapping"
  3585. tray = stored_mapping[slot_id - 1]
  3586. if not _is_tray_id(tray) or tray < 0:
  3587. continue
  3588. loaded_tray = by_tray.get(tray)
  3589. if loaded_tray is None:
  3590. # A mapping made for a printer that feeds this slot from its
  3591. # external spool, sent to one whose external spool is empty and
  3592. # whose AMS holds the filament (#3239). Only then: an external
  3593. # spool can be loaded without its filament set, and on a printer
  3594. # with nothing else to offer that job printed before. The colour
  3595. # has to match too: with only another colour in the AMS, the
  3596. # printer asking for the spool beats printing in that colour.
  3597. want = canonical_filament_type(req.get("type"))
  3598. if tray >= 254 and tray in empty_external and want:
  3599. ams_tray = next(
  3600. (
  3601. f
  3602. for f in loaded
  3603. if not f.get("is_external")
  3604. and canonical_filament_type(f.get("type")) == want
  3605. and self._colors_are_similar(f.get("color"), req.get("color"))
  3606. ),
  3607. None,
  3608. )
  3609. if ams_tray is not None:
  3610. return (
  3611. f"slot {slot_id} points at the external spool, which is empty, "
  3612. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3613. )
  3614. continue
  3615. want = canonical_filament_type(req.get("type"))
  3616. have = canonical_filament_type(loaded_tray.get("type"))
  3617. if want and have and want != have:
  3618. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3619. return None
  3620. async def _unmappable_without_ams_message(
  3621. self,
  3622. db: AsyncSession,
  3623. printer_id: int,
  3624. item: PrintQueueItem,
  3625. computed_mapping: list[int] | None,
  3626. ) -> str | None:
  3627. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3628. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3629. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3630. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3631. uploaded several megabytes and burned its dispatch retries. This method
  3632. speaks only for the AMS-less case: there is nothing to resume into — the
  3633. external spool holder is the whole inventory — so the useful answer is to
  3634. say which filament is missing and stop. With an AMS attached it returns
  3635. None: where live status reported loaded trays,
  3636. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3637. reported none the print goes out and the firmware error is the answer —
  3638. the user can load the right spool and press Resume.
  3639. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3640. every branch that lacks the evidence to be sure returns None.
  3641. """
  3642. # None means the matcher never ran (no requirements parsed from the 3MF,
  3643. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3644. # dispatch as they always have.
  3645. if not _mapping_is_all_unresolved(computed_mapping):
  3646. return None
  3647. status = printer_manager.get_status(printer_id)
  3648. if status is None:
  3649. return None
  3650. # "No AMS" has to be a fact the printer stated, not the absence of a
  3651. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3652. # handled and is preserved across partial pushes thereafter, so a missing
  3653. # key means we have not heard yet — most likely a reconnect, where the
  3654. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3655. # empty list is the positive report of a printer with no AMS.
  3656. ams_units = status.raw_data.get("ams")
  3657. if not isinstance(ams_units, list) or ams_units:
  3658. return None
  3659. required = await self._get_filament_requirements(db, item)
  3660. loaded = self._build_loaded_filaments(status)
  3661. if not required or not loaded:
  3662. # Both were non-empty moments ago or the matcher could not have run.
  3663. # If the picture changed under us, say nothing rather than fail an
  3664. # item on stale evidence.
  3665. return None
  3666. self._apply_filament_overrides(item, required)
  3667. return _unmatched_filament_message(required, loaded)
  3668. async def _fail_unmappable_item(
  3669. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3670. ) -> None:
  3671. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3672. This replaces a failure, not a success: without it the item is uploaded,
  3673. rejected by the firmware with 0700_8012, retried twice more and failed
  3674. anyway with "never started the print after N dispatch attempts". So this
  3675. applies on the model-based path too, even though it means an "Any <model>"
  3676. job stops at the first printer offered rather than trying its siblings —
  3677. deferring instead would need the check to move inside
  3678. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3679. re-assigns the same printer on the next tick.
  3680. """
  3681. item.status = "failed"
  3682. item.error_message = message
  3683. item.completed_at = datetime.now(timezone.utc)
  3684. item.waiting_reason = None
  3685. await db.commit()
  3686. from backend.app.services.print_batch import refresh_batches_after
  3687. await refresh_batches_after([item.id])
  3688. logger.warning(
  3689. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3690. item.id,
  3691. printer_id,
  3692. message,
  3693. )
  3694. job_name = await self._get_job_name(db, item)
  3695. printer = await self._get_printer(db, printer_id)
  3696. await notification_service.on_queue_job_failed(
  3697. job_name=job_name,
  3698. printer_id=printer_id,
  3699. printer_name=printer.name if printer else "Unknown",
  3700. reason=message,
  3701. db=db,
  3702. )
  3703. try:
  3704. await ws_manager.send_queue_item_failed(
  3705. user_id=item.created_by_id,
  3706. queue_item_id=item.id,
  3707. printer_id=printer_id,
  3708. reason="filament_unmappable",
  3709. )
  3710. except Exception:
  3711. pass
  3712. async def _compute_ams_mapping_for_printer(
  3713. self,
  3714. db: AsyncSession,
  3715. printer_id: int,
  3716. item: PrintQueueItem,
  3717. *,
  3718. only_slots: set[int] | None = None,
  3719. reserved_trays: set[int] | None = None,
  3720. ) -> list[int] | None:
  3721. """Compute AMS mapping for a printer based on filament requirements.
  3722. Called when a queue item has no ams_mapping set — either for model-based
  3723. items after printer assignment, or printer-specific items (e.g. from VP).
  3724. Args:
  3725. db: Database session
  3726. printer_id: The assigned printer ID
  3727. item: The queue item (contains archive_id or library_file_id)
  3728. only_slots: Match only these filament slots; every other slot comes
  3729. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3730. reserved_trays: Global tray IDs to leave out of the match, because
  3731. the stored mapping already gives them to another slot.
  3732. Returns:
  3733. AMS mapping array or None if no mapping needed/possible
  3734. """
  3735. # Get printer status
  3736. status = printer_manager.get_status(printer_id)
  3737. if not status:
  3738. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3739. return None
  3740. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3741. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3742. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3743. # an AMS on the *other* nozzle, and the matcher falls through to a
  3744. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3745. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3746. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3747. # Get filament requirements from source file
  3748. filament_reqs = await self._get_filament_requirements(db, item)
  3749. if not filament_reqs:
  3750. # When the 3MF can't be read but force-color overrides are present, build a
  3751. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3752. if item.filament_overrides:
  3753. try:
  3754. overrides = json.loads(item.filament_overrides)
  3755. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3756. if force_overrides:
  3757. logger.info(
  3758. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3759. "force-color override(s)",
  3760. item.id,
  3761. len(force_overrides),
  3762. )
  3763. return self._build_override_direct_mapping(force_overrides, status)
  3764. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3765. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3766. logger.debug("No filament requirements found for queue item %s", item.id)
  3767. return None
  3768. self._apply_filament_overrides(item, filament_reqs)
  3769. if only_slots is not None:
  3770. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3771. if not filament_reqs:
  3772. return None
  3773. # Build loaded filaments from printer status
  3774. loaded_filaments = self._build_loaded_filaments(status)
  3775. if reserved_trays:
  3776. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3777. if not loaded_filaments:
  3778. logger.debug("No filaments loaded on printer %s", printer_id)
  3779. return None
  3780. # Check if user prefers lowest remaining filament when multiple spools match
  3781. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3782. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3783. # Without backup, the printer will not switch to a second spool when the
  3784. # picked one runs out — so sorting toward the lowest leaves the print
  3785. # at risk of running dry mid-job. None (unknown: no status report with
  3786. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3787. if prefer_lowest and status.ams_filament_backup is False:
  3788. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3789. prefer_lowest = False
  3790. # When the preference is on, surface Bambuddy's inventory-side
  3791. # remaining for each slot that's bound to a tracked spool, so the
  3792. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3793. # entirely when the preference is off — no behaviour change for
  3794. # users who haven't opted in.
  3795. inventory_remain_overrides: dict[int, float] | None = None
  3796. if prefer_lowest:
  3797. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3798. # Compute mapping: match required filaments to available slots
  3799. return self._match_filaments_to_slots(
  3800. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3801. )
  3802. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3803. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3804. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3805. diagnosis (#2771) describes the filament the matcher actually looked
  3806. for, not the one the 3MF was sliced with — naming the pre-override
  3807. filament in a user-facing error would send the user to load the wrong
  3808. spool.
  3809. """
  3810. if not item.filament_overrides:
  3811. return
  3812. try:
  3813. overrides = json.loads(item.filament_overrides)
  3814. override_map = {o["slot_id"]: o for o in overrides}
  3815. for req in filament_reqs:
  3816. if req["slot_id"] in override_map:
  3817. override = override_map[req["slot_id"]]
  3818. req["type"] = override["type"]
  3819. req["color"] = override["color"]
  3820. # A manual/preference override SWAPS the slot's filament, so the
  3821. # 3MF's original tray_info_idx now points at the old spool and must
  3822. # be cleared — matching then falls back to type+colour. A
  3823. # force_color_match override is not a swap: it carries the 3MF's
  3824. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3825. # it here too, letting the matcher pin the correct variant slot on a
  3826. # printer holding two same-colour spools of different variants (#2650).
  3827. # If that variant isn't loaded the matcher falls back to type+colour,
  3828. # so an eligible printer never fails to map.
  3829. req["tray_info_idx"] = (
  3830. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3831. )
  3832. logger.debug(
  3833. "Queue item %s: Override slot %d -> %s %s",
  3834. item.id,
  3835. req["slot_id"],
  3836. override["type"],
  3837. override["color"],
  3838. )
  3839. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3840. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3841. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3842. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3843. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3844. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3845. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3846. treated as the filament requirement for that slot and matched against the
  3847. current AMS state of the printer.
  3848. Returns the same format as ``_match_filaments_to_slots``, or None when
  3849. the AMS has no loaded filaments.
  3850. """
  3851. loaded = self._build_loaded_filaments(status)
  3852. if not loaded:
  3853. return None
  3854. reqs = [
  3855. {
  3856. "slot_id": o["slot_id"],
  3857. "type": o.get("type", ""),
  3858. "color": o.get("color", ""),
  3859. # These are all force_color_match overrides, so the idx (when the
  3860. # 3MF carried one) is the intended variant, not a stale swap —
  3861. # keep it so the matcher pins the right variant slot, falling back
  3862. # to type+colour when it isn't loaded (#2650).
  3863. "tray_info_idx": o.get("tray_info_idx", ""),
  3864. }
  3865. for o in force_overrides
  3866. ]
  3867. return self._match_filaments_to_slots(reqs, loaded)
  3868. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3869. """Resolve the queue item's source 3MF and parse the per-slot
  3870. filament requirements out of it. Thin DB-resolver wrapper around
  3871. ``filament_requirements.extract_filament_requirements`` so the VP
  3872. queue-mode write path (#1188) can reuse the same parser at upload
  3873. time.
  3874. """
  3875. from backend.app.services.filament_requirements import extract_filament_requirements
  3876. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3877. # so every caller gets its own copy — a shared list would leak one
  3878. # item's overrides into the next item that happens to print the same
  3879. # plate.
  3880. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3881. if memo_key in self._filament_req_memo:
  3882. cached = self._filament_req_memo[memo_key]
  3883. return [dict(r) for r in cached] if cached else None
  3884. file_path: Path | None = None
  3885. if item.archive_id:
  3886. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3887. archive = result.scalar_one_or_none()
  3888. if archive:
  3889. file_path = settings.base_dir / archive.file_path
  3890. elif item.library_file_id:
  3891. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3892. library_file = result.scalar_one_or_none()
  3893. if library_file:
  3894. lib_path = Path(library_file.file_path)
  3895. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3896. if not file_path or not file_path.exists():
  3897. self._filament_req_memo[memo_key] = None
  3898. return None
  3899. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3900. self._filament_req_memo[memo_key] = filaments or None
  3901. return [dict(r) for r in filaments] if filaments else None
  3902. def _build_loaded_filaments(self, status) -> list[dict]:
  3903. """Build list of loaded filaments from printer status.
  3904. Args:
  3905. status: PrinterState from printer_manager
  3906. Returns:
  3907. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3908. """
  3909. filaments = []
  3910. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3911. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3912. # Routes external spools to an extruder (#2771). Mirrors
  3913. # `buildLoadedFilaments` in the frontend.
  3914. vt_trays = status.raw_data.get("vt_tray") or []
  3915. is_dual_nozzle = reports_two_nozzles(status)
  3916. # Parse AMS units from raw_data
  3917. ams_data = status.raw_data.get("ams", [])
  3918. for ams_unit in ams_data:
  3919. ams_id = int(ams_unit.get("id", 0))
  3920. trays = ams_unit.get("tray", [])
  3921. is_ht = len(trays) == 1 # AMS-HT has single tray
  3922. for tray in trays:
  3923. tray_type = tray.get("tray_type")
  3924. if tray_type:
  3925. tray_id = int(tray.get("id", 0))
  3926. tray_color = tray.get("tray_color", "")
  3927. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  3928. tray_info_idx = tray.get("tray_info_idx", "")
  3929. # Normalize color: remove alpha, add hash
  3930. color = self._normalize_color(tray_color)
  3931. # Calculate global tray ID
  3932. # AMS-HT units have IDs starting at 128 with a single tray
  3933. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  3934. filaments.append(
  3935. {
  3936. "type": tray_type,
  3937. "color": color,
  3938. "tray_info_idx": tray_info_idx,
  3939. "ams_id": ams_id,
  3940. "tray_id": tray_id,
  3941. "is_ht": is_ht,
  3942. "is_external": False,
  3943. "global_tray_id": global_tray_id,
  3944. "extruder_id": ams_extruder_map.get(str(ams_id)),
  3945. "remain": tray.get("remain", -1),
  3946. }
  3947. )
  3948. # Check external spool(s) (vt_tray is a list)
  3949. for idx, vt in enumerate(vt_trays):
  3950. if vt.get("tray_type"):
  3951. color = self._normalize_color(vt.get("tray_color", ""))
  3952. tray_id = int(vt.get("id", 254))
  3953. filaments.append(
  3954. {
  3955. "type": vt["tray_type"],
  3956. "color": color,
  3957. "tray_info_idx": vt.get("tray_info_idx", ""),
  3958. "ams_id": -1,
  3959. "tray_id": idx,
  3960. "is_ht": False,
  3961. "is_external": True,
  3962. "global_tray_id": tray_id,
  3963. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  3964. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  3965. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  3966. "remain": vt.get("remain", -1),
  3967. }
  3968. )
  3969. return filaments
  3970. def _normalize_color(self, color: str | None) -> str:
  3971. """Normalize color to #RRGGBB format."""
  3972. if not color:
  3973. return "#808080"
  3974. hex_color = color.replace("#", "")[:6]
  3975. return f"#{hex_color}"
  3976. def _normalize_color_for_compare(self, color: str | None) -> str:
  3977. """Normalize color for comparison (lowercase, no hash)."""
  3978. if not color:
  3979. return ""
  3980. return color.replace("#", "").lower()[:6]
  3981. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  3982. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  3983. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  3984. stays the per-channel box that shipped — this only decides which of
  3985. several eligible spools is closest, so nothing becomes usable or
  3986. unusable because of it.
  3987. It ranks by how far apart the colours *look*, not how far apart their
  3988. numbers are. RGB distance overweights blue badly enough to invert the
  3989. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  3990. the nearer of two eligible spools by RGB and the further by a factor of
  3991. four once measured perceptually.
  3992. Alpha is ignored, deliberately: the alpha a slicer writes for a
  3993. transparent filament is not a colour the user chose, and counting it
  3994. would stop a transparent filament matching itself.
  3995. """
  3996. return perceptual_color_distance(color1, color2)
  3997. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  3998. """Check if two colors are visually similar within a threshold."""
  3999. hex1 = self._normalize_color_for_compare(color1)
  4000. hex2 = self._normalize_color_for_compare(color2)
  4001. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4002. return False
  4003. try:
  4004. r1 = int(hex1[0:2], 16)
  4005. g1 = int(hex1[2:4], 16)
  4006. b1 = int(hex1[4:6], 16)
  4007. r2 = int(hex2[0:2], 16)
  4008. g2 = int(hex2[2:4], 16)
  4009. b2 = int(hex2[4:6], 16)
  4010. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4011. except ValueError:
  4012. return False
  4013. async def _build_inventory_remain_overrides(
  4014. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4015. ) -> dict[int, float]:
  4016. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4017. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4018. The MQTT ``remain`` field on a tray is the printer firmware's
  4019. RFID-decremented value, which has two limitations the "Prefer Lowest
  4020. Remaining Filament" feature has been ignoring (#1508):
  4021. - it's only meaningful for Bambu RFID spools; everything else reports
  4022. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4023. compare equal and the sort collapses to AMS-slot order — the user
  4024. who's curating inventory weights gets the lower-slot pick instead
  4025. of the lower-remaining pick;
  4026. - even when set, it's the *printer's* counter, not Bambuddy's
  4027. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4028. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4029. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4030. When the user has bound a spool to a slot, their own inventory
  4031. tracking is authoritative; this helper surfaces that value so the
  4032. sort can prefer it. Slots without a binding are absent from the
  4033. returned map — the caller then falls back to MQTT ``remain`` for
  4034. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4035. Returns an empty map on any failure (no inventory bindings, DB
  4036. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4037. is a preference, not a guarantee.
  4038. """
  4039. if not loaded:
  4040. return {}
  4041. # External / virtual-tray slots are tracked separately from AMS — skip
  4042. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4043. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4044. # match is fiddly and out of scope for this fix).
  4045. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4046. if not tracked_slots:
  4047. return {}
  4048. is_spoolman = await self._is_spoolman_mode(db)
  4049. overrides: dict[int, float] = {}
  4050. if is_spoolman:
  4051. result = await db.execute(
  4052. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4053. )
  4054. assignments = list(result.scalars().all())
  4055. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4056. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4057. for ams_id, tray_id, gtid in tracked_slots:
  4058. spoolman_id = by_slot.get((ams_id, tray_id))
  4059. if spoolman_id is None:
  4060. continue
  4061. grams = await _spoolman_remaining_grams(spoolman_id)
  4062. if grams is not None:
  4063. overrides[gtid] = grams
  4064. return overrides
  4065. # Internal inventory mode (default). selectinload matches the pattern
  4066. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4067. # plus an eager-loaded relationship rather than an explicit join, so
  4068. # the row-attribute shape is exactly what those routes already rely on.
  4069. result = await db.execute(
  4070. select(SpoolAssignment)
  4071. .options(selectinload(SpoolAssignment.spool))
  4072. .where(SpoolAssignment.printer_id == printer_id)
  4073. )
  4074. assignments = list(result.scalars().all())
  4075. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4076. for ams_id, tray_id, gtid in tracked_slots:
  4077. spool = by_slot.get((ams_id, tray_id))
  4078. if spool is None:
  4079. continue
  4080. label = float(spool.label_weight or 0)
  4081. used = float(spool.weight_used or 0)
  4082. overrides[gtid] = max(0.0, label - used)
  4083. return overrides
  4084. @staticmethod
  4085. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4086. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4087. here to avoid making this module import-dependent on that private
  4088. helper's signature."""
  4089. try:
  4090. from backend.app.api.routes.settings import get_setting
  4091. v = await get_setting(db, "spoolman_enabled")
  4092. return bool(v) and v.lower() == "true"
  4093. except Exception:
  4094. return False
  4095. @staticmethod
  4096. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4097. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4098. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4099. so a tied sort produces the same physical-position order the pre-#1508
  4100. stable sort did (preserves the regression-free baseline):
  4101. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4102. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4103. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4104. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4105. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4106. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4107. """
  4108. if ams_id is None or ams_id < 0:
  4109. return 10_000
  4110. if ams_id >= 128:
  4111. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4112. return ams_id * 4 + (tray_id or 0)
  4113. @staticmethod
  4114. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4115. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4116. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4117. non-tracked spools (the user has told us they care about these
  4118. specifically), then ascending by remaining within each tier, then
  4119. ascending by AMS slot position as the deterministic tie-breaker.
  4120. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4121. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4122. because the tier flag dominates — which is what lets us mix grams
  4123. (inventory) and percent (MQTT) without a unit conversion.
  4124. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4125. spools the printer DOES know something about sort ahead of those
  4126. it knows nothing about — preserves pre-#1508 behaviour for the
  4127. no-inventory-binding case.
  4128. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4129. external on ties, matching the legacy emission-order stable sort.
  4130. """
  4131. gtid = f.get("global_tray_id")
  4132. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4133. if overrides and gtid in overrides:
  4134. return (0, overrides[gtid], slot_order)
  4135. remain = f.get("remain", -1)
  4136. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4137. def _match_filaments_to_slots(
  4138. self,
  4139. required: list[dict],
  4140. loaded: list[dict],
  4141. prefer_lowest: bool = False,
  4142. inventory_remain_overrides: dict[int, float] | None = None,
  4143. fts_installed: bool = False,
  4144. ) -> list[int] | None:
  4145. """Match required filaments to loaded filaments and build AMS mapping.
  4146. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4147. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4148. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4149. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4150. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4151. matching among those trays.
  4152. Args:
  4153. required: List of required filaments with slot_id, type, color, tray_info_idx
  4154. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4155. Returns:
  4156. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4157. """
  4158. if not required:
  4159. return None
  4160. # Track used trays to avoid duplicate assignment
  4161. used_tray_ids: set[int] = set()
  4162. comparisons = []
  4163. for req in required:
  4164. req_type = (req.get("type") or "").upper()
  4165. req_color = req.get("color", "")
  4166. req_tray_info_idx = req.get("tray_info_idx", "")
  4167. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4168. idx_match = None
  4169. exact_match = None
  4170. similar_match = None
  4171. similar_distance = float("inf")
  4172. type_only_match = None
  4173. # Get available trays (not already used)
  4174. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4175. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4176. # Hard filter — cross-nozzle assignment causes print failures
  4177. # ("position of left hotend is abnormal"), so never fall back.
  4178. # Skipped when an FTS is installed: it routes any AMS slot to either
  4179. # extruder, so restricting to one nozzle would wrongly exclude the
  4180. # correct spool sitting in the other nozzle's AMS (#2186).
  4181. req_nozzle_id = req.get("nozzle_id")
  4182. if req_nozzle_id is not None and not fts_installed:
  4183. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4184. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4185. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4186. # _prefer_lowest_sort_key for the full rationale.
  4187. if prefer_lowest:
  4188. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4189. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4190. # One line per filament req so a bug report can be diagnosed
  4191. # without enabling debug logging: shows what the matcher saw
  4192. # (req shape + sorted candidate trays with their remain values
  4193. # and any inventory override that was applied). Mirrored by
  4194. # the picked-match log at the bottom of the loop.
  4195. logger.info(
  4196. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4197. req.get("slot_id"),
  4198. req_type,
  4199. req_color,
  4200. req_tray_info_idx,
  4201. req_nozzle_id,
  4202. [
  4203. {
  4204. "gtid": f.get("global_tray_id"),
  4205. "type": f.get("type"),
  4206. "color": f.get("color"),
  4207. "tii": f.get("tray_info_idx"),
  4208. "remain": f.get("remain"),
  4209. "inv_g": (
  4210. inventory_remain_overrides.get(f.get("global_tray_id"))
  4211. if inventory_remain_overrides
  4212. else None
  4213. ),
  4214. }
  4215. for f in available
  4216. ],
  4217. )
  4218. # Check if tray_info_idx is unique among available trays
  4219. if req_tray_info_idx:
  4220. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4221. if len(idx_matches) == 1:
  4222. # Unique tray_info_idx - use it as definitive match
  4223. idx_match = idx_matches[0]
  4224. logger.debug(
  4225. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4226. f"-> tray {idx_match['global_tray_id']}"
  4227. )
  4228. elif len(idx_matches) > 1:
  4229. # Multiple trays with same tray_info_idx - use color matching among them
  4230. logger.debug(
  4231. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4232. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4233. )
  4234. if prefer_lowest:
  4235. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4236. # Use color matching within this subset
  4237. for f in idx_matches:
  4238. f_color = f.get("color", "")
  4239. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4240. if not exact_match:
  4241. exact_match = f
  4242. elif self._colors_are_similar(f_color, req_color):
  4243. distance = self._color_distance(f_color, req_color)
  4244. if distance is not None and distance < similar_distance:
  4245. similar_match = f
  4246. similar_distance = distance
  4247. elif not type_only_match:
  4248. type_only_match = f
  4249. # If no idx_match yet, do standard type/color matching on all available trays
  4250. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4251. for f in available:
  4252. f_type = (f.get("type") or "").upper()
  4253. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4254. continue
  4255. # Type matches - check color
  4256. f_color = f.get("color", "")
  4257. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4258. if not exact_match:
  4259. exact_match = f
  4260. elif self._colors_are_similar(f_color, req_color):
  4261. # Nearest wins, not first-in-tray-order. `available` is
  4262. # already in the caller's order (slot order, or the
  4263. # prefer-lowest sort), and `<` keeps the earliest of
  4264. # equally close spools — so that order survives as the
  4265. # tie-break (#2804).
  4266. distance = self._color_distance(f_color, req_color)
  4267. if distance is not None and distance < similar_distance:
  4268. similar_match = f
  4269. similar_distance = distance
  4270. elif not type_only_match:
  4271. type_only_match = f
  4272. match = idx_match or exact_match or similar_match or type_only_match
  4273. if match:
  4274. used_tray_ids.add(match["global_tray_id"])
  4275. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4276. else:
  4277. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4278. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4279. # "Why did it pick that spool" is the question every wrong-filament
  4280. # report starts with, and a `similar_color` win is now a ranked
  4281. # choice among several eligible spools rather than whichever tray
  4282. # came first, so it is worth being able to see after the fact.
  4283. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4284. # is on (#1766).
  4285. if match:
  4286. bucket = (
  4287. "idx"
  4288. if idx_match is not None
  4289. else "exact_color"
  4290. if exact_match is not None
  4291. else "similar_color"
  4292. if similar_match is not None
  4293. else "type_only"
  4294. )
  4295. logger.info(
  4296. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4297. match["global_tray_id"],
  4298. bucket,
  4299. req.get("slot_id"),
  4300. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4301. )
  4302. else:
  4303. logger.info(
  4304. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4305. req.get("slot_id"),
  4306. req_type,
  4307. req_color,
  4308. req_tray_info_idx,
  4309. )
  4310. # Build mapping array
  4311. if not comparisons:
  4312. return None
  4313. max_slot_id = max(c["slot_id"] for c in comparisons)
  4314. if max_slot_id <= 0:
  4315. return None
  4316. mapping = [-1] * max_slot_id
  4317. for c in comparisons:
  4318. slot_id = c["slot_id"]
  4319. if slot_id and slot_id > 0:
  4320. mapping[slot_id - 1] = c["global_tray_id"]
  4321. return mapping
  4322. def _mark_printer_dispatched(
  4323. self,
  4324. printer_id: int,
  4325. pre_state: str | None,
  4326. pre_subtask_id: str | None,
  4327. ) -> None:
  4328. """Record that a print command was just sent to ``printer_id``.
  4329. Held until either the watchdog observes a state/subtask transition
  4330. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4331. """
  4332. if not pre_state:
  4333. # No pre_state means we can't detect a transition — fall back to a
  4334. # pure time-based hold using empty string as a sentinel that won't
  4335. # match any real printer state.
  4336. pre_state = ""
  4337. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4338. def _release_dispatch_hold(self, printer_id: int) -> None:
  4339. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4340. self._dispatch_holds.pop(printer_id, None)
  4341. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4342. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4343. Returns False (and clears the hold) once any of these are true:
  4344. - hard timeout (``_dispatch_max_hold``) has elapsed
  4345. - the printer has transitioned out of pre_state and we're past the
  4346. minimum cooldown
  4347. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4348. past the minimum cooldown
  4349. Otherwise the printer is held — caller should treat it as busy.
  4350. """
  4351. entry = self._dispatch_holds.get(printer_id)
  4352. if not entry:
  4353. return False
  4354. started_at, pre_state, pre_subtask_id = entry
  4355. elapsed = time.monotonic() - started_at
  4356. if elapsed >= self._dispatch_max_hold:
  4357. self._dispatch_holds.pop(printer_id, None)
  4358. return False
  4359. # Without a pre_state we can't detect a transition — fall back to the
  4360. # min cooldown alone, then drop the hold.
  4361. if not pre_state:
  4362. if elapsed >= self._dispatch_min_cooldown:
  4363. self._dispatch_holds.pop(printer_id, None)
  4364. return False
  4365. return True
  4366. status = printer_manager.get_status(printer_id)
  4367. current_state = getattr(status, "state", None) if status else None
  4368. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4369. transitioned = (current_state is not None and current_state != pre_state) or (
  4370. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4371. )
  4372. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4373. self._dispatch_holds.pop(printer_id, None)
  4374. return False
  4375. return True
  4376. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4377. """Check if a printer is connected and idle."""
  4378. if not printer_manager.is_connected(printer_id):
  4379. logger.debug("Printer %d: not connected", printer_id)
  4380. return False
  4381. state = printer_manager.get_status(printer_id)
  4382. if not state:
  4383. logger.debug("Printer %d: no status available", printer_id)
  4384. return False
  4385. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4386. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4387. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4388. # printer, it boots back into IDLE with no memory of the previous finish; without
  4389. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4390. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4391. logger.debug(
  4392. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4393. printer_id,
  4394. state.state,
  4395. )
  4396. return False
  4397. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4398. if not idle:
  4399. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4400. return idle
  4401. @staticmethod
  4402. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4403. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4404. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4405. and that the fixed-printer branch has already found connected, so the two
  4406. offline cases answer at their own exits and never arrive here.
  4407. The default is the model-based branch's ``Busy:`` wording, which
  4408. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4409. the right answer for the connected-but-no-telemetry second or two after a
  4410. reconnect: the model-based branch has always reported it that way, and it
  4411. is not something to wake anybody up for.
  4412. A plate nobody has confirmed is the one case here that does not resolve
  4413. itself — somebody has to walk over to the printer — so it is worded as
  4414. itself and allowed to notify.
  4415. """
  4416. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4417. return f"Waiting for plate confirmation: {printer_name}"
  4418. return f"Busy: {printer_name}"
  4419. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4420. """Read a setting value from the database."""
  4421. result = await db.execute(select(Settings).where(Settings.key == key))
  4422. setting = result.scalar_one_or_none()
  4423. return setting.value if setting else None
  4424. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4425. """Read a boolean setting from the database."""
  4426. result = await db.execute(select(Settings).where(Settings.key == key))
  4427. setting = result.scalar_one_or_none()
  4428. if setting:
  4429. return setting.value.lower() == "true"
  4430. return default
  4431. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4432. """Read an int setting; falls back to default on missing/unparseable rows."""
  4433. result = await db.execute(select(Settings).where(Settings.key == key))
  4434. setting = result.scalar_one_or_none()
  4435. if setting and setting.value:
  4436. try:
  4437. return int(setting.value)
  4438. except ValueError:
  4439. pass
  4440. return default
  4441. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4442. """Get drying presets (user-configured or built-in defaults)."""
  4443. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4444. setting = result.scalar_one_or_none()
  4445. if setting and setting.value:
  4446. try:
  4447. presets = json.loads(setting.value)
  4448. if isinstance(presets, dict) and presets:
  4449. return presets
  4450. except json.JSONDecodeError:
  4451. pass
  4452. return self.DEFAULT_DRYING_PRESETS
  4453. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4454. """Per-filament humidity thresholds (#1605).
  4455. Returns the user-configured overrides map keyed by normalized filament
  4456. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4457. unknown / unmapped types. Empty / unset → empty dict, in which case
  4458. callers fall back to ``ams_humidity_fair``.
  4459. """
  4460. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4461. setting = result.scalar_one_or_none()
  4462. if not setting or not setting.value:
  4463. return {}
  4464. try:
  4465. data = json.loads(setting.value)
  4466. except json.JSONDecodeError:
  4467. return {}
  4468. if not isinstance(data, dict):
  4469. return {}
  4470. out: dict[str, int] = {}
  4471. for key, value in data.items():
  4472. try:
  4473. out[str(key).upper() if key != "default" else "default"] = int(value)
  4474. except (TypeError, ValueError):
  4475. continue
  4476. return out
  4477. # Materials whose AMS spelling differs from the key the tables above use.
  4478. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4479. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4480. # good PA row (#3067).
  4481. #
  4482. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4483. # The drying popover has resolved these correctly since #2774 and the
  4484. # scheduler never did, which is exactly why #3067's reporter could dry a
  4485. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4486. #
  4487. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4488. # of nylon, so it is the one entry that is a judgement rather than a
  4489. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4490. # way, and PA's row is the hottest the table has. Drying it there is closer
  4491. # to right than not drying it at all, which is what it got before.
  4492. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4493. "NYLON": "PA",
  4494. "PA6": "PA",
  4495. "PA11": "PA",
  4496. "PA12": "PA",
  4497. "PAHT": "PA",
  4498. "PPA": "PA",
  4499. }
  4500. @classmethod
  4501. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4502. """The key in *table* that answers for this tray's material, or None.
  4503. The printer reports the material in ``tray_type``, and it spells filled
  4504. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4505. tables here are keyed by base material, so matching the raw string alone
  4506. found a row for 8 of the 41 types a printer can report and skipped the
  4507. rest -- silently, because every caller reads "no row" as "nothing to do
  4508. for this tray". Auto-drying therefore ignored every composite spool on
  4509. the install (#3067).
  4510. Exact match first, so a table the user has extended with a row of its
  4511. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4512. base material's. Then the suffix is dropped, then the alias map above
  4513. answers for the polyamide spellings.
  4514. Returns None rather than a default: what to do with an unrecognised
  4515. material differs per caller, and only the caller knows whether "no row"
  4516. means skip the tray or fall back to a catch-all. Nothing here invents a
  4517. temperature for a material the table does not list.
  4518. """
  4519. raw = cls._normalize_filament_type(tray_type or "")
  4520. if not raw:
  4521. return None
  4522. for candidate in (raw, raw.split("-")[0]):
  4523. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4524. if key in table:
  4525. return key
  4526. return None
  4527. @staticmethod
  4528. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4529. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4530. For mixed filament types loaded into one AMS, returns the most
  4531. restrictive (lowest) threshold across all loaded tray types — matches
  4532. the conservative-params strategy already used for drying temp/hours.
  4533. Empty / unloaded trays contribute no constraint. Unknown types use the
  4534. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4535. when no per-type map is configured at all.
  4536. """
  4537. default = thresholds.get("default", fallback)
  4538. if not thresholds:
  4539. return fallback
  4540. candidates: list[int] = []
  4541. for tray in trays:
  4542. tray_type = str(tray.get("tray_type") or "").strip()
  4543. if not tray_type:
  4544. continue
  4545. # A composite carries its base material's threshold when it has no
  4546. # row of its own, the same way it takes its drying preset (#3067).
  4547. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4548. candidates.append(thresholds[key] if key is not None else default)
  4549. if not candidates:
  4550. return default
  4551. return min(candidates)
  4552. def _get_conservative_drying_params(
  4553. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4554. ) -> tuple[int, int, str] | None:
  4555. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4556. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4557. """
  4558. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4559. hours_key = f"{temp_key}_hours"
  4560. min_temp = None
  4561. max_hours = None
  4562. filament_type = ""
  4563. for tray in trays:
  4564. tray_type = tray.get("tray_type", "")
  4565. if not tray_type:
  4566. continue
  4567. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4568. # which is what stopped auto-drying on every composite spool (#3067).
  4569. base_type = self._resolve_filament_key(tray_type, presets)
  4570. if base_type is None:
  4571. continue
  4572. # The table is user-editable JSON with no per-row validation, so a
  4573. # row can be present and empty. That has always meant "skip this
  4574. # material", and it has to keep meaning it: the reads below fall
  4575. # back to 55C/12h per missing field, which is a temperature nobody
  4576. # chose and would deform a PLA spool.
  4577. preset = presets[base_type]
  4578. if not preset:
  4579. continue
  4580. temp = preset.get(temp_key, 55)
  4581. hours = preset.get(hours_key, 12)
  4582. # Conservative: lowest temp, longest duration
  4583. if min_temp is None or temp < min_temp:
  4584. min_temp = temp
  4585. if max_hours is None or hours > max_hours:
  4586. max_hours = hours
  4587. if not filament_type:
  4588. filament_type = base_type
  4589. if min_temp is None:
  4590. return None
  4591. return (min_temp, max_hours or 12, filament_type)
  4592. async def _check_filament_low(self, db: AsyncSession) -> None:
  4593. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4594. ``on_filament_low`` has had a column, a schema field, a route, a template
  4595. and a UI toggle since the notification system was built, and no caller --
  4596. so the toggle could be switched on and could never fire. This is the
  4597. producer.
  4598. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4599. ``low_stock_threshold_pct`` override is already exactly this decision:
  4600. already configurable, already surfaced, already driving the Inventory
  4601. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4602. consulted -- it has been measured up to 56 points out against a scale,
  4603. which is not a number to page someone on.
  4604. Only slots with an assigned spool produce an event. A slot Bambuddy
  4605. cannot resolve to a spool has no remaining weight it can stand behind,
  4606. and guessing one is how the remain percentage would have got in.
  4607. """
  4608. from backend.app.models.spool import Spool
  4609. # Time-gated rather than run on every pass. run() sleeps
  4610. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4611. # early-return path counts as productive while an upload is in flight
  4612. # (#2602), so an unthrottled check would re-read the whole spool
  4613. # collection every 3 seconds for the length of a batch drain. In
  4614. # Spoolman mode that is a request storm against a third-party service,
  4615. # which is the thing this producer's design note argues against; and
  4616. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4617. # check_queue holding the scheduler's session, so the outage would
  4618. # throttle the print queue itself. A low spool is not a 3-second
  4619. # concern -- the idle interval is the natural resolution.
  4620. now = time.monotonic()
  4621. if now < self._filament_low_next_check:
  4622. return
  4623. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4624. try:
  4625. # on_filament_low defaults to off on every provider, so on most
  4626. # installs nobody wants this alert. Without this the check would
  4627. # still read every assigned spool each interval -- the whole
  4628. # collection over HTTP in Spoolman mode -- for an event that is
  4629. # switched off. One query against the provider table settles it
  4630. # before any spool work, the same guard the bed-cooled waiter uses.
  4631. # No printer_id: this asks whether any provider wants the event at
  4632. # all; per-printer scoping is applied when the event is sent.
  4633. #
  4634. # While nobody wants it, no pass sees a slot go back above its
  4635. # threshold, so nothing can re-arm; a spool refilled under the same
  4636. # id in that time would stay silenced until a restart. Forgetting
  4637. # what was sent is right anyway: whoever switches the event back on
  4638. # is told about the spools that are low now.
  4639. #
  4640. # The MQTT relay publishes the same event, so a connected relay is
  4641. # reason enough to run the check. Its record is forgotten when the
  4642. # relay is switched off, not when the broker drops: a reconnect must
  4643. # not re-send every low slot.
  4644. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low"))
  4645. relay = mqtt_relay.enabled and mqtt_relay.connected
  4646. if not notify:
  4647. self._notified_filament_low.clear()
  4648. if not mqtt_relay.enabled:
  4649. self._relayed_filament_low.clear()
  4650. if not notify and not relay:
  4651. return
  4652. global_threshold = await self._get_low_stock_threshold(db)
  4653. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4654. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4655. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4656. if spoolman_on:
  4657. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4658. else:
  4659. rows = (
  4660. await db.execute(
  4661. select(SpoolAssignment, Spool)
  4662. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4663. # An archived spool is not stock. The Inventory page's
  4664. # Low Stock count skips them (InventoryPage.tsx:1089)
  4665. # and get_all_spools without allow_archived already
  4666. # excludes them in Spoolman mode, so without this the
  4667. # internal path is the only one that alerts on them.
  4668. .where(Spool.archived_at.is_(None))
  4669. )
  4670. ).all()
  4671. for assignment, spool in rows:
  4672. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4673. if pct is None:
  4674. continue
  4675. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4676. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4677. pct,
  4678. threshold,
  4679. spool.color_name,
  4680. )
  4681. if not slots:
  4682. # Nothing resolvable this pass. Deliberately not clearing the
  4683. # notified set: a Spoolman that is briefly unreachable would
  4684. # otherwise re-alert on every spool as soon as it came back.
  4685. return
  4686. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4687. except Exception as e:
  4688. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4689. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4690. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4691. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4692. if raw is None or raw.value is None:
  4693. return 20.0
  4694. try:
  4695. value = float(raw.value)
  4696. except (TypeError, ValueError):
  4697. return 20.0
  4698. return value if 0 < value <= 100 else 20.0
  4699. async def _filament_low_slots_spoolman(
  4700. self, db: AsyncSession, global_threshold: float
  4701. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4702. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4703. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4704. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4705. so the global threshold is the only one that applies here. That matches
  4706. what the Inventory page already does in this mode.
  4707. One ``get_all_spools`` call covers every slot rather than a request per
  4708. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4709. without ``allow_archived`` -- which is the behaviour the internal path
  4710. has to ask for explicitly.
  4711. An unreachable Spoolman returns no slots rather than raising. It is an
  4712. ordinary state for a third-party service, not an error in this pass: the
  4713. caller's "nothing resolvable" branch already leaves the notified set
  4714. alone, which is exactly right here, whereas letting it reach the broad
  4715. ``except`` would write a full traceback every time the check runs.
  4716. """
  4717. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4718. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4719. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4720. if not assignments:
  4721. return {}
  4722. client = await get_spoolman_client()
  4723. if client is None:
  4724. return {}
  4725. try:
  4726. all_spools = await client.get_all_spools()
  4727. except SpoolmanUnavailableError as e:
  4728. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4729. return {}
  4730. by_id: dict[int, dict] = {}
  4731. for raw in all_spools:
  4732. raw_id = raw.get("id")
  4733. if isinstance(raw_id, int):
  4734. by_id[raw_id] = raw
  4735. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4736. for assignment in assignments:
  4737. raw = by_id.get(assignment.spoolman_spool_id)
  4738. if raw is None:
  4739. continue
  4740. try:
  4741. mapped = _map_spoolman_spool(raw)
  4742. except ValueError:
  4743. continue
  4744. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4745. if pct is None:
  4746. continue
  4747. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4748. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4749. return slots
  4750. async def _emit_filament_low(
  4751. self,
  4752. db: AsyncSession,
  4753. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4754. *,
  4755. notify: bool = True,
  4756. relay: bool = False,
  4757. ) -> None:
  4758. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4759. printers: dict[int, Printer] = {}
  4760. for key, (pct, threshold, color) in slots.items():
  4761. printer_id, ams_id, tray_id, spool_id = key
  4762. if pct >= threshold:
  4763. # Back above the line: re-arm rather than expire on a timer, so a
  4764. # refilled slot can alert again and a spool sitting just under the
  4765. # threshold stays quiet.
  4766. self._notified_filament_low.discard(key)
  4767. self._relayed_filament_low.discard(key)
  4768. continue
  4769. send_notification = notify and key not in self._notified_filament_low
  4770. # Only while connected, so a crossing the relay missed reaches it
  4771. # after the reconnect.
  4772. send_relay = relay and key not in self._relayed_filament_low
  4773. if not send_notification and not send_relay:
  4774. continue
  4775. # Marked before sending, which is a choice rather than the only
  4776. # option, and it is the opposite failure mode from the one the
  4777. # debounce argues against: one transient provider failure loses this
  4778. # alert until the spool goes back above the threshold and crosses it
  4779. # again. Marking after a successful send would trade that for
  4780. # re-alerting on every pass while a provider is down -- which is the
  4781. # repetition the whole debounce exists to prevent, and the louder of
  4782. # the two failures. A spool that is low stays low, so the next real
  4783. # signal is not far away; a provider stuck retrying is a signal that
  4784. # never stops.
  4785. if send_notification:
  4786. self._notified_filament_low.add(key)
  4787. if send_relay:
  4788. self._relayed_filament_low.add(key)
  4789. if printer_id not in printers:
  4790. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4791. if printer is None:
  4792. continue
  4793. printers[printer_id] = printer
  4794. printer = printers[printer_id]
  4795. slot = _ams_slot_label(ams_id, tray_id)
  4796. if send_notification:
  4797. try:
  4798. await notification_service.on_filament_low(
  4799. printer_id,
  4800. printer.name,
  4801. slot,
  4802. int(pct),
  4803. db,
  4804. color=color,
  4805. )
  4806. except Exception as e:
  4807. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4808. if send_relay:
  4809. try:
  4810. await mqtt_relay.on_filament_low(
  4811. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  4812. )
  4813. except Exception as e:
  4814. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  4815. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4816. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4817. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4818. a schema field, a template and a UI toggle, and nothing that computes the
  4819. condition -- the Forecast panel does it in the browser, so with no page
  4820. open nothing could ever alert. This runs the same arithmetic
  4821. (``stock_forecast``) from the scheduler loop.
  4822. An alert is sent when a SKU *moves into* a condition, once, and again
  4823. after the condition has cleared. A SKU that worsens from reorder to break
  4824. alerts again as a break, because the panel treats the two as exclusive; one
  4825. that eases from break back to reorder does not alert again.
  4826. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4827. while it is still low tells you.
  4828. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4829. loop runs every 3 s while an upload is in flight, and the whole spool
  4830. collection is read over HTTP in Spoolman mode. Both events default to off
  4831. on every provider, so nothing is read unless a provider wants one.
  4832. """
  4833. now = time.monotonic()
  4834. if now < self._stock_forecast_next_check:
  4835. return
  4836. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4837. try:
  4838. if self._stock_alerts_persisted is None:
  4839. await self._load_stock_alerts(db)
  4840. wanted = {
  4841. "reorder": bool(await notification_service._get_providers_for_event(db, "on_stock_reorder_alert")),
  4842. "break": bool(await notification_service._get_providers_for_event(db, "on_stock_break_alert")),
  4843. }
  4844. if not any(wanted.values()):
  4845. # Nobody wants either event. Forget what was sent, so whoever
  4846. # switches one on is told about the SKUs that are low now.
  4847. self._notified_stock_alerts.clear()
  4848. await self._save_stock_alerts(db)
  4849. return
  4850. forecasts = await self._stock_forecasts(db)
  4851. if forecasts is None:
  4852. # Spoolman unreachable. Deliberately not clearing the notified
  4853. # set: a brief outage would otherwise re-alert every SKU when it
  4854. # came back.
  4855. return
  4856. await self._emit_stock_alerts(db, forecasts, wanted)
  4857. await self._save_stock_alerts(db)
  4858. except Exception as e:
  4859. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4860. def _serialize_stock_alerts(self) -> str:
  4861. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4862. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4863. return json.dumps(rows)
  4864. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4865. """Read the notified set saved by the last run, once per process.
  4866. A missing or unreadable row is an empty set: the worst that does is one
  4867. repeat of what a restart used to cause every time.
  4868. """
  4869. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4870. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4871. if raw and raw.value:
  4872. try:
  4873. for key, kind, events in json.loads(raw.value):
  4874. if len(key) == 4 and kind in ("reorder", "break"):
  4875. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4876. except (ValueError, TypeError):
  4877. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4878. loaded = {}
  4879. self._notified_stock_alerts = loaded
  4880. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4881. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4882. """Write the notified set to its settings row if it changed since it was last read or written."""
  4883. serialized = self._serialize_stock_alerts()
  4884. if serialized == self._stock_alerts_persisted:
  4885. return
  4886. from backend.app.core.db_dialect import upsert_setting
  4887. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4888. await db.commit()
  4889. self._stock_alerts_persisted = serialized
  4890. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4891. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4892. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4893. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4894. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4895. sku_settings = {
  4896. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4897. lead_time_days=row.lead_time_days,
  4898. safety_margin_value=row.safety_margin_value,
  4899. safety_margin_unit=row.safety_margin_unit,
  4900. alerts_snoozed=bool(row.alerts_snoozed),
  4901. )
  4902. for row in sku_rows
  4903. }
  4904. if await self._get_bool_setting(db, "spoolman_enabled"):
  4905. spools = await self._stock_spools_spoolman()
  4906. if spools is None:
  4907. return None
  4908. # Spoolman owns the usage in this mode and Bambuddy's own history
  4909. # table holds nothing for those spools, so the rate is always the
  4910. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4911. # are local spool ids, and a Spoolman id that happens to match one
  4912. # (left over from before Spoolman was switched on) would borrow an
  4913. # unrelated spool's history.
  4914. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4915. else:
  4916. spools = await self._stock_spools_internal(db)
  4917. history = await self._stock_usage_history(db)
  4918. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4919. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4920. from backend.app.models.spool import Spool
  4921. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4922. return [
  4923. stock_forecast.StockSpool(
  4924. id=spool.id,
  4925. material=spool.material,
  4926. subtype=spool.subtype,
  4927. brand=spool.brand,
  4928. color_name=spool.color_name,
  4929. label_weight=float(spool.label_weight or 0),
  4930. weight_used=float(spool.weight_used or 0),
  4931. weight_used_baseline=float(spool.weight_used_baseline or 0),
  4932. created_at=spool.created_at,
  4933. )
  4934. for spool in rows
  4935. ]
  4936. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  4937. from backend.app.models.spool_usage_history import SpoolUsageHistory
  4938. rows = (
  4939. await db.execute(
  4940. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  4941. .order_by(SpoolUsageHistory.created_at.desc())
  4942. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  4943. )
  4944. ).all()
  4945. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4946. for spool_id, created_at, weight_used in rows:
  4947. # A deleted spool's usage forecasts no stock. Skipped here rather than
  4948. # filtered before the limit, so the window matches the forecast panel's.
  4949. if created_at is None or spool_id is None:
  4950. continue
  4951. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  4952. return history
  4953. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  4954. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  4955. ``get_all_spools`` leaves archived spools out unless asked, which is the
  4956. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  4957. is the same mapping the Inventory page (and so the panel) reads.
  4958. """
  4959. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4960. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4961. client = await get_spoolman_client()
  4962. if client is None:
  4963. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  4964. return None
  4965. try:
  4966. raw_spools = await client.get_all_spools()
  4967. except SpoolmanUnavailableError as e:
  4968. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  4969. return None
  4970. spools: list[stock_forecast.StockSpool] = []
  4971. for raw in raw_spools:
  4972. try:
  4973. mapped = _map_spoolman_spool(raw)
  4974. except ValueError:
  4975. continue
  4976. created_at = None
  4977. if mapped.get("created_at"):
  4978. try:
  4979. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  4980. except ValueError:
  4981. created_at = None
  4982. spools.append(
  4983. stock_forecast.StockSpool(
  4984. id=mapped["id"],
  4985. material=mapped["material"],
  4986. subtype=mapped.get("subtype"),
  4987. brand=mapped.get("brand"),
  4988. color_name=mapped.get("color_name"),
  4989. label_weight=float(mapped.get("label_weight") or 0),
  4990. weight_used=float(mapped.get("weight_used") or 0),
  4991. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  4992. created_at=created_at,
  4993. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  4994. )
  4995. )
  4996. return spools
  4997. async def _emit_stock_alerts(
  4998. self,
  4999. db: AsyncSession,
  5000. forecasts: stock_forecast.ForecastMap,
  5001. wanted: dict[str, bool],
  5002. ) -> None:
  5003. """Send the notifications for each SKU that has moved into a stock alert condition.
  5004. A SKU in break has also reached its reorder point, so both events apply to
  5005. it: the break event goes to providers that have it on, and the reorder event
  5006. to the providers that have only that one on. A provider with both on gets the
  5007. break and no second message.
  5008. What is remembered per SKU is the condition and which events had a
  5009. subscriber when it was sent. An event with no subscriber is forgotten, so
  5010. switching it on later reports the SKUs already in that condition.
  5011. """
  5012. active_events = {event for event, on in wanted.items() if on}
  5013. for key, (forecast, spool) in forecasts.items():
  5014. kind: str | None = None
  5015. if not forecast.snoozed:
  5016. if forecast.stock_break_alert:
  5017. kind = "break"
  5018. elif forecast.reorder_alert:
  5019. kind = "reorder"
  5020. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5021. events = applicable & active_events
  5022. if not events:
  5023. self._notified_stock_alerts.pop(key, None)
  5024. continue
  5025. previous = self._notified_stock_alerts.get(key)
  5026. told = (previous[1] & active_events) if previous else frozenset()
  5027. # Trimmed to the events this condition can send. That is what makes easing from
  5028. # break back to reorder silent (the reorder event was told with the break) and
  5029. # worsening again news again (the break event is no longer remembered).
  5030. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5031. # Recorded before sending, for the reason _emit_filament_low gives: a
  5032. # provider that is down should lose this alert, not repeat it every hour.
  5033. to_send = events - told
  5034. # Both flags imply a positive rate and so a day count.
  5035. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5036. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5037. color = None if spool.color_name_is_synthesized else spool.color_name
  5038. try:
  5039. if "break" in to_send:
  5040. await notification_service.on_stock_break_alert(
  5041. spool.material,
  5042. spool.brand,
  5043. forecast.remaining_g,
  5044. rate,
  5045. days_left,
  5046. forecast.effective_lead_time_days,
  5047. db,
  5048. subtype=spool.subtype,
  5049. color=color,
  5050. )
  5051. if "reorder" in to_send:
  5052. await notification_service.on_stock_reorder_alert(
  5053. spool.material,
  5054. spool.brand,
  5055. forecast.remaining_g,
  5056. rate,
  5057. days_left,
  5058. db,
  5059. subtype=spool.subtype,
  5060. color=color,
  5061. skip_break_subscribers=kind == "break",
  5062. )
  5063. except Exception as e:
  5064. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5065. # A SKU with no spools left is no longer alerting.
  5066. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5067. del self._notified_stock_alerts[key]
  5068. async def _check_auto_drying(
  5069. self,
  5070. db: AsyncSession,
  5071. queue_items: list[PrintQueueItem],
  5072. dispatching_printers: set[int],
  5073. ):
  5074. """Start drying on idle printers based on humidity.
  5075. Three modes (can all be enabled independently):
  5076. - queue_drying_enabled: Dry between scheduled queue prints
  5077. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5078. - print_drying_enabled: Also evaluate printers that are currently printing,
  5079. when model+firmware supports "Print While Drying" (gated by
  5080. supports_drying_while_printing). Drying temperature is capped at
  5081. max(40, preset_temp - 5) to protect spools mid-print.
  5082. """
  5083. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5084. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5085. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5086. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5087. # The wait belongs to ambient drying: the settings UI only shows it while
  5088. # ambient drying is on, so a value left behind when ambient is turned off
  5089. # must not keep delaying the one path that still reaches the wait gate
  5090. # without it (a mid-print start under print_drying).
  5091. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5092. # Clear every streak as soon as the wait is inactive. An early return (or
  5093. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5094. # a quick toggle-on inherit an old streak.
  5095. if not sustained_wait_active:
  5096. self._auto_dry_above.clear()
  5097. if not queue_drying_enabled and not ambient_drying_enabled:
  5098. # Stop active drying on all printers if both features disabled
  5099. if self._drying_in_progress:
  5100. for pid in list(self._drying_in_progress):
  5101. if pid in self._scheduled_drying_printer_ids:
  5102. continue
  5103. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5104. await self._stop_drying(pid)
  5105. return
  5106. # Update drying state from printer status (handles backend restart)
  5107. self._sync_drying_state()
  5108. # Find printers with scheduled items (for queue drying mode)
  5109. printers_with_scheduled: set[int] = set()
  5110. printers_with_items: set[int] = set()
  5111. for item in queue_items:
  5112. if item.printer_id:
  5113. printers_with_items.add(item.printer_id)
  5114. if item.scheduled_time and not item.manual_start:
  5115. printers_with_scheduled.add(item.printer_id)
  5116. # If only queue mode is on and no printers have scheduled items, stop drying
  5117. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5118. # may still be eligible for mid-print drying regardless of queue state).
  5119. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5120. for pid in list(self._drying_in_progress):
  5121. if pid in self._scheduled_drying_printer_ids:
  5122. continue
  5123. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5124. await self._stop_drying(pid)
  5125. return
  5126. # Get humidity threshold (global fallback)
  5127. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5128. setting = result.scalar_one_or_none()
  5129. global_humidity_threshold = int(setting.value) if setting else 60
  5130. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5131. # to the global threshold for every AMS unit.
  5132. per_type_thresholds = await self._get_humidity_thresholds(db)
  5133. # Get drying presets
  5134. presets = await self._get_drying_presets(db)
  5135. # Determine if drying should be skipped for printers with pending items
  5136. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5137. # Get all active printers
  5138. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5139. for printer in all_printers.scalars():
  5140. pid = printer.id
  5141. # Resolve model+firmware up front — needed to decide whether this printer
  5142. # qualifies for mid-print drying (busy printer on capable hardware).
  5143. state = printer_manager.get_status(pid)
  5144. if not state:
  5145. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5146. continue
  5147. model = printer_manager.get_model(pid)
  5148. firmware = state.firmware_version
  5149. # "Mid-print" has to mean the printer is actually printing (#2801).
  5150. # It used to be inferred from the dispatch set, which also holds
  5151. # printers that merely could not be dispatched to -- so a printer
  5152. # sitting in FINISH behind an unacknowledged plate was treated as
  5153. # printing, had its drying temperature capped by the mid-print
  5154. # spool protection, and was logged as (mid-print) while idle.
  5155. is_printing = state.state in _ACTIVE_PRINT_STATES
  5156. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5157. # A printer whose print is running or imminent is left alone unless
  5158. # it can dry through it. `dispatching_printers` is deliberately the
  5159. # narrow set: running, held post-dispatch, or mid-upload.
  5160. if (is_printing or pid in dispatching_printers) and not mid_print:
  5161. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5162. continue
  5163. if not mid_print:
  5164. # In queue-only mode, only dry printers that have scheduled prints
  5165. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5166. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5167. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5168. await self._stop_drying(pid)
  5169. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5170. continue
  5171. # When block mode is on, don't START new drying on printers with pending items.
  5172. # But allow already-drying printers through so humidity auto-stop logic still runs.
  5173. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  5174. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  5175. continue
  5176. if not printer_manager.is_connected(pid):
  5177. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5178. continue
  5179. # Plate-clear is deliberately ignored here (#2801). It answers
  5180. # "is the bed ready for the next job", which says nothing about
  5181. # whether the AMS may heat -- and the gap between a finished print
  5182. # and the acknowledgment is exactly when drying is most useful,
  5183. # because the printer is free and nobody is waiting on it. Leaving
  5184. # the plate unacknowledged is also how people hold the queue by
  5185. # hand, and that hold should not cost them their drying.
  5186. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5187. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5188. continue
  5189. # Check drying capability. For mid-print path, supports_drying_while_printing
  5190. # was already verified when computing mid_print above.
  5191. if not mid_print and not supports_drying(model, firmware):
  5192. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5193. continue
  5194. # Check each AMS unit from raw_data
  5195. ams_list = state.raw_data.get("ams", [])
  5196. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5197. for ams_data in ams_list:
  5198. module_type = str(ams_data.get("module_type") or "")
  5199. ams_id = int(ams_data.get("id", 0))
  5200. # Only n3f/n3s support drying
  5201. if module_type not in ("n3f", "n3s"):
  5202. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5203. continue
  5204. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5205. # Most-restrictive of all loaded tray types; falls back to the
  5206. # global threshold when no overrides are configured.
  5207. trays = ams_data.get("tray", []) or []
  5208. humidity_threshold = self.resolve_humidity_threshold(
  5209. trays, per_type_thresholds, global_humidity_threshold
  5210. )
  5211. dry_time = int(ams_data.get("dry_time") or 0)
  5212. # Read humidity as a percentage. The 1-5 index is never
  5213. # substituted: it is inverted, and being unable to exceed any
  5214. # threshold it would read as "dry" forever (#3140). ``None``
  5215. # already means "skip this unit" everywhere below.
  5216. humidity_pct = ams_humidity_percent(ams_data)
  5217. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5218. unit_key = (pid, ams_id)
  5219. unit_state = self._auto_dry_units.get(unit_key)
  5220. # Already drying — let it run to its configured duration (#1892).
  5221. #
  5222. # We deliberately do NOT stop drying from a humidity re-check here.
  5223. # Relative humidity drops steeply in heated air, so the AMS sensor
  5224. # reads ~15-20% within minutes of the dryer starting even while the
  5225. # filament is still saturated. A humidity-based early-stop therefore
  5226. # always fires at the minimum-time floor, truncating both user-started
  5227. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5228. # The firmware stops when the configured duration elapses; scheduling
  5229. # stops (print takes priority, queue no longer needs drying) are
  5230. # handled separately via _stop_drying().
  5231. if dry_time > 0:
  5232. if pid not in self._drying_in_progress:
  5233. # Drying we didn't start (manual or from before restart) —
  5234. # track it so scheduling stops still apply; never auto-stop it.
  5235. self._drying_in_progress[pid] = time.monotonic()
  5236. if unit_state is not None:
  5237. unit_state["running"] = True
  5238. logger.debug(
  5239. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5240. pid,
  5241. ams_id,
  5242. dry_time,
  5243. humidity,
  5244. )
  5245. continue
  5246. # Nothing is drying. Close out a cycle we armed ourselves and
  5247. # judge whether it achieved anything (#2770).
  5248. #
  5249. # "Achieved anything" is measured against the LOWEST reading any
  5250. # cycle on this unit has ended at, not against the threshold and
  5251. # not against the previous cycle. A spool that is genuinely wet
  5252. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5253. # allowed to keep going for as long as it is still coming down,
  5254. # however far it still is from the threshold. What must not
  5255. # continue is a cycle that ends exactly where the last one did,
  5256. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5257. # Comparing against the running minimum rather than the previous
  5258. # end is what stops a sensor oscillating by one point between two
  5259. # values from reading as progress every other cycle.
  5260. if unit_state is not None and unit_state.pop("running", False):
  5261. unit_state["ended_at"] = time.monotonic()
  5262. # The streak that armed this cycle is spent; the next one
  5263. # starts fresh (and accumulates through the re-arm cooldown
  5264. # below, so the wait overlaps the cooldown, never stacks on
  5265. # top of it).
  5266. self._auto_dry_above.pop(unit_key, None)
  5267. if humidity is not None and humidity > humidity_threshold:
  5268. best = unit_state.get("best_end_humidity")
  5269. if isinstance(best, int) and humidity < best:
  5270. # Still coming down. Keep going, however far the
  5271. # threshold still is.
  5272. unproductive = 0
  5273. else:
  5274. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5275. if not isinstance(best, int) or humidity < best:
  5276. unit_state["best_end_humidity"] = humidity
  5277. unit_state["unproductive"] = unproductive
  5278. logger.info(
  5279. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5280. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5281. pid,
  5282. ams_id,
  5283. humidity,
  5284. humidity_threshold,
  5285. unit_state.get("best_end_humidity"),
  5286. unproductive,
  5287. )
  5288. # A cycle that ended at or below the threshold needs no
  5289. # counter reset here: the branch below drops the whole entry.
  5290. # Humidity below threshold — no need to start drying. This is
  5291. # also the only thing that lifts a suspension: the reading we
  5292. # gave up on has come down, so auto-drying works again and the
  5293. # unit goes back to having no history at all.
  5294. if humidity is None or humidity <= humidity_threshold:
  5295. if unit_state is not None and unit_state.get("suspended"):
  5296. logger.info(
  5297. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5298. "threshold, resuming automatic drying",
  5299. pid,
  5300. ams_id,
  5301. humidity,
  5302. humidity_threshold,
  5303. )
  5304. # Clear the judgement, keep the clock (#2801). Dropping the
  5305. # whole entry also dropped `ended_at`, and with it the
  5306. # 30-minute cooldown -- so a reading that dips to the
  5307. # threshold as the AMS cools and comes back above it once
  5308. # warm wiped its own history and re-armed immediately. That
  5309. # oscillation is the very thing #2770's cooldown exists to
  5310. # ride out, and it is worst at exactly the margin that makes
  5311. # a unit dry repeatedly: a point or two above the threshold.
  5312. if unit_state is not None:
  5313. unit_state.pop("suspended", None)
  5314. unit_state.pop("unproductive", None)
  5315. unit_state.pop("best_end_humidity", None)
  5316. # A real below-threshold reading ends any sustained-wait
  5317. # streak (#2518) -- "continuously above" means exactly that.
  5318. # An absent reading (humidity is None) is no-information and
  5319. # leaves the streak alone; the observation-gap guard handles
  5320. # a prolonged sensor silence.
  5321. if humidity is not None:
  5322. _above = self._auto_dry_above.pop(unit_key, None)
  5323. if _above is not None and sustained_wait_active:
  5324. logger.info(
  5325. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5326. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5327. pid,
  5328. ams_id,
  5329. humidity,
  5330. time.monotonic() - _above["since"],
  5331. sustained_minutes,
  5332. humidity_threshold,
  5333. )
  5334. logger.debug(
  5335. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5336. pid,
  5337. ams_id,
  5338. humidity,
  5339. humidity_threshold,
  5340. )
  5341. continue
  5342. # Sustained-humidity streak (#2518): updated on every pass that
  5343. # observes the reading above the threshold, BEFORE the
  5344. # suspension/cooldown gates below -- a suspended or cooling-down
  5345. # unit still accumulates streak time, so the wait overlaps those
  5346. # gates instead of stacking after them. Inert when the feature
  5347. # is off: no entries are written, and an entry left over from a
  5348. # toggle-off is dropped so it cannot seed a stale streak later.
  5349. if sustained_wait_active:
  5350. _now = time.monotonic()
  5351. # Four missed scheduler passes, floored: a single slow pass
  5352. # must not void a streak, but the ceiling has to scale with
  5353. # the cadence or a slow loop silently restarts every streak.
  5354. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5355. _above = self._auto_dry_above.get(unit_key)
  5356. if _above is None:
  5357. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5358. elif _now - _above["last"] > _gap_ceiling:
  5359. # Restart, and say so at the same level as the dip
  5360. # reset: a silent restart voids the streak invisibly,
  5361. # and a user who set a long wait and never gets a dry
  5362. # has no way to see why.
  5363. logger.info(
  5364. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5365. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5366. pid,
  5367. ams_id,
  5368. _now - _above["last"],
  5369. _gap_ceiling,
  5370. sustained_minutes,
  5371. )
  5372. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5373. else:
  5374. _above["last"] = _now
  5375. else:
  5376. self._auto_dry_above.pop(unit_key, None)
  5377. if unit_state is not None:
  5378. if unit_state.get("suspended"):
  5379. logger.debug(
  5380. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5381. "above the %d%% threshold",
  5382. pid,
  5383. ams_id,
  5384. int(unit_state.get("unproductive", 0)),
  5385. humidity_threshold,
  5386. )
  5387. continue
  5388. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5389. unit_state["suspended"] = True
  5390. logger.warning(
  5391. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5392. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5393. "higher while it is warm, so a threshold in that range can never be reached and "
  5394. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5395. pid,
  5396. ams_id,
  5397. int(unit_state.get("unproductive", 0)),
  5398. humidity,
  5399. humidity_threshold,
  5400. )
  5401. await self._notify_auto_drying_suspended(
  5402. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5403. )
  5404. continue
  5405. ended_at = unit_state.get("ended_at")
  5406. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5407. logger.debug(
  5408. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5409. "cycle before the humidity reading is worth acting on",
  5410. pid,
  5411. ams_id,
  5412. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5413. )
  5414. continue
  5415. # Check cannot-dry reasons (power constraints etc.). Sits
  5416. # ahead of the sustained wait so a unit the firmware refuses
  5417. # to dry never logs a wait it was never going to cash in.
  5418. sf_reasons = ams_data.get("dry_sf_reason", [])
  5419. if sf_reasons:
  5420. logger.debug(
  5421. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5422. pid,
  5423. ams_id,
  5424. sf_reasons,
  5425. )
  5426. continue
  5427. # Sustained-humidity wait (#2518): ambient-triggered starts
  5428. # wait; only a printer with a scheduled queue item pending
  5429. # keeps the instant behavior, because that drying has a real
  5430. # deadline. Mid-print is deliberately NOT exempt while ambient
  5431. # drying is on: a humidity start on a printer that happens to be
  5432. # printing is as vulnerable to a lid-open spike as one on an idle
  5433. # printer (proven live: a 2-point threshold crossing mid-print
  5434. # bought a parked 12h command). Inactive when ambient drying is
  5435. # off: print_drying then still starts mid-print cycles on its own
  5436. # (#1816, "regardless of queue state"), and those stay instant.
  5437. if sustained_wait_active and pid not in printers_with_scheduled:
  5438. _above = self._auto_dry_above.get(unit_key)
  5439. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5440. if _waited < sustained_minutes * 60:
  5441. logger.debug(
  5442. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5443. "threshold for %.0fs of the required %dm",
  5444. pid,
  5445. ams_id,
  5446. humidity,
  5447. humidity_threshold,
  5448. _waited,
  5449. sustained_minutes,
  5450. )
  5451. continue
  5452. # Get conservative drying params for mixed filaments
  5453. params = self._get_conservative_drying_params(trays, module_type, presets)
  5454. if not params:
  5455. logger.debug(
  5456. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5457. )
  5458. continue
  5459. temp, duration_hours, filament_type = params
  5460. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5461. # "drying temperature must not exceed the filament's softening temperature"
  5462. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5463. # ineffective and firmware will reject anyway.
  5464. if mid_print:
  5465. temp = max(40, temp - 5)
  5466. # Start drying
  5467. logger.info(
  5468. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5469. "starting %s drying at %d°C for %dh%s",
  5470. pid,
  5471. ams_id,
  5472. humidity,
  5473. humidity_threshold,
  5474. filament_type,
  5475. temp,
  5476. duration_hours,
  5477. " (mid-print)" if mid_print else "",
  5478. )
  5479. success = printer_manager.send_drying_command(
  5480. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5481. )
  5482. if success:
  5483. self._drying_in_progress[pid] = time.monotonic()
  5484. armed = self._auto_dry_units.setdefault(
  5485. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5486. )
  5487. armed["running"] = True
  5488. async def _notify_auto_drying_suspended(
  5489. self,
  5490. db: AsyncSession,
  5491. printer: Printer,
  5492. ams_id: int,
  5493. humidity: int,
  5494. threshold: int,
  5495. cycles: int,
  5496. ) -> None:
  5497. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5498. Fires once per suspension — the caller sets ``suspended`` before calling
  5499. and every later pass short-circuits on it — because the whole point is
  5500. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5501. building needs that to reach them, and the hourly humidity alarm they
  5502. are already getting says the opposite of what happened here.
  5503. Never raises: a notification provider being down must not stop the
  5504. suspension itself from taking effect.
  5505. """
  5506. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5507. try:
  5508. await notification_service.on_ams_drying_suspended(
  5509. printer.id,
  5510. printer.name,
  5511. ams_label,
  5512. float(humidity),
  5513. float(threshold),
  5514. cycles,
  5515. db,
  5516. )
  5517. except Exception as e:
  5518. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5519. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5520. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5521. The unproductive-cycle counter exists to notice that *drying* is not
  5522. moving the humidity reading. A cycle that ended because somebody sent a
  5523. stop says nothing about that — it was cut short before it had a chance —
  5524. so counting it would suspend auto-drying for a reason that has nothing to
  5525. do with the loop the counter is there to break.
  5526. Two callers, both of them a stop Bambuddy is responsible for: the
  5527. print-takes-priority stop below, and the manual Stop button. Left
  5528. uncalled, an install that dries between queue jobs would suspend its own
  5529. auto-drying after two prints interrupted a dry — exactly the install
  5530. queue-drying exists for.
  5531. The rest of the unit's history is kept: the cooldown before re-arming
  5532. still applies, and an earlier count still stands.
  5533. """
  5534. state = self._auto_dry_units.get((printer_id, ams_id))
  5535. if state is not None:
  5536. state.pop("running", None)
  5537. state["ended_at"] = time.monotonic()
  5538. # A stopped cycle spends the streak that armed it, same as a completed
  5539. # one (#2518).
  5540. self._auto_dry_above.pop((printer_id, ams_id), None)
  5541. def _sync_drying_state(self):
  5542. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5543. One direction only: it prunes, it never adds. A printer drying without an
  5544. entry here — because the user started the cycle from Studio, the printer's
  5545. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5546. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5547. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5548. That is deliberate for now rather than an oversight: populating this from
  5549. telemetry would hand the scheduler authority to stop drying a user started
  5550. by hand. It also means the backend-restart case this used to claim to
  5551. handle is not handled.
  5552. """
  5553. to_remove = []
  5554. for pid in self._drying_in_progress:
  5555. state = printer_manager.get_status(pid)
  5556. if not state:
  5557. to_remove.append(pid)
  5558. continue
  5559. # Check if any AMS unit is still drying
  5560. ams_list = state.raw_data.get("ams", [])
  5561. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5562. if not any_drying:
  5563. to_remove.append(pid)
  5564. for pid in to_remove:
  5565. self._drying_in_progress.pop(pid, None)
  5566. # A printer that has gone away entirely takes its per-AMS auto-drying
  5567. # history with it (#2770), so a printer deleted and re-added does not
  5568. # inherit a suspension it never earned.
  5569. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5570. self._auto_dry_units.pop(key, None)
  5571. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5572. # printer starts a fresh wait, and vanished printers do not leak
  5573. # entries.
  5574. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5575. self._auto_dry_above.pop(key, None)
  5576. @staticmethod
  5577. def _drying_is_only_parked(printer_id: int) -> bool:
  5578. """True when every AMS unit with a drying timer on this printer is parked.
  5579. A parked timer (#2896: the command was taken but the countdown never
  5580. runs) does not end on its own, so nothing may wait on it. False when no
  5581. unit reports a timer yet -- a command just sent that the firmware has not
  5582. reported back is real drying about to begin.
  5583. """
  5584. state = printer_manager.get_status(printer_id)
  5585. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5586. timed = []
  5587. for unit in units:
  5588. try:
  5589. if int(unit.get("dry_time") or 0) > 0:
  5590. timed.append(unit)
  5591. except (TypeError, ValueError):
  5592. continue
  5593. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5594. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5595. """True when a running cycle can be left alone while the next print runs.
  5596. Some hardware dries happily through a print and #2758 settled that we
  5597. should not tear those cycles down: the X2D there was refusing to
  5598. *start* a job, which is a different problem, and stopping drying before
  5599. every dispatch would throw away cycles the printer was content to run.
  5600. Where the model cannot do it, or the user has not enabled it, the print
  5601. takes priority and the cycle stops -- which is what the queue_drying_block
  5602. setting has always promised in its off position.
  5603. """
  5604. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5605. return False
  5606. status = printer_manager.get_status(printer_id)
  5607. return supports_drying_while_printing(
  5608. printer_manager.get_model(printer_id),
  5609. status.firmware_version if status else None,
  5610. )
  5611. async def _stop_drying(self, printer_id: int):
  5612. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5613. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5614. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5615. enough to kill a cycle the user had started by hand on a *different*
  5616. unit of the same printer (#2801). That contradicted the contract
  5617. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5618. only knows about cycles Bambuddy began, so the action must not reach
  5619. past them either.
  5620. """
  5621. state = printer_manager.get_status(printer_id)
  5622. if not state:
  5623. self._drying_in_progress.pop(printer_id, None)
  5624. return
  5625. ams_list = state.raw_data.get("ams", [])
  5626. for ams_data in ams_list:
  5627. dry_time = int(ams_data.get("dry_time") or 0)
  5628. if dry_time > 0:
  5629. ams_id = int(ams_data.get("id", 0))
  5630. if (printer_id, ams_id) not in self._auto_dry_units:
  5631. logger.debug(
  5632. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5633. printer_id,
  5634. ams_id,
  5635. )
  5636. continue
  5637. logger.info(
  5638. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5639. printer_id,
  5640. ams_id,
  5641. )
  5642. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5643. self.forget_auto_dry_cycle(printer_id, ams_id)
  5644. self._drying_in_progress.pop(printer_id, None)
  5645. # Scheduled manual drying (#2638) -----------------------------------
  5646. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5647. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5648. async def _check_scheduled_dryings(self, db: AsyncSession):
  5649. """Dispatch due scheduled drying runs and track running ones."""
  5650. now = utcnow_naive()
  5651. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5652. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5653. since_prune = time.monotonic()
  5654. if (
  5655. self._last_scheduled_drying_prune is None
  5656. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5657. ):
  5658. self._last_scheduled_drying_prune = since_prune
  5659. await db.execute(
  5660. delete(ScheduledDrying).where(
  5661. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5662. ScheduledDrying.completed_at.is_not(None),
  5663. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5664. )
  5665. )
  5666. # Same order as the list route: with two rows due on one printer the
  5667. # earliest scheduled wins rather than whatever the DB hands back first.
  5668. result = await db.execute(
  5669. select(ScheduledDrying)
  5670. .where(ScheduledDrying.status.in_(("pending", "running")))
  5671. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5672. )
  5673. rows = list(result.scalars().all())
  5674. # Rebuild from the DB every tick so route-side cancels and completions
  5675. # show up. Auto-drying's stop-all branches check this set before
  5676. # stopping anything (#2638).
  5677. # Kept from the previous pass so a run that ended between passes — a
  5678. # cancel through the route, say — can still be released below.
  5679. previously_running = self._scheduled_drying_printer_ids
  5680. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5681. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5682. # Model and firmware come from the printer row, not the live state.
  5683. printer_ids = {row.printer_id for row in rows}
  5684. printers_by_id: dict[int, Printer] = {}
  5685. if printer_ids:
  5686. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5687. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5688. for row in rows:
  5689. if row.status == "running":
  5690. self._update_running_scheduled_drying(row, now)
  5691. continue
  5692. if row.start_after is not None and row.start_after > now:
  5693. continue
  5694. state = printer_manager.get_status(row.printer_id)
  5695. if not state:
  5696. row.waiting_reason = "printer_offline"
  5697. continue
  5698. # Same preflight the immediate endpoint runs. Without it the publish
  5699. # succeeds, the row goes to running, the printer ignores the command
  5700. # and the run silently cancels itself after the grace window.
  5701. printer = printers_by_id.get(row.printer_id)
  5702. unsupported = drying_preflight.check_drying_supported(
  5703. printer.model if printer else None, state.firmware_version
  5704. )
  5705. if unsupported:
  5706. row.status = "failed"
  5707. row.error_message = unsupported
  5708. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5709. row.completed_at = now
  5710. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5711. continue
  5712. if (
  5713. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5714. ) or row.printer_id in running_printer_ids:
  5715. row.waiting_reason = "already_drying"
  5716. continue
  5717. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5718. row.waiting_reason = "printer_busy"
  5719. continue
  5720. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5721. if target is None:
  5722. row.waiting_reason = "ams_not_found"
  5723. continue
  5724. blocking = drying_preflight.blocking_reason_codes(target)
  5725. if blocking:
  5726. # Keep the power case distinct; it needs the user to act, so the
  5727. # card can say so instead of waiting silently.
  5728. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5729. continue
  5730. filament = drying_preflight.resolve_filament(target, row.filament)
  5731. logger.info(
  5732. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5733. row.id,
  5734. row.printer_id,
  5735. row.ams_id,
  5736. row.temp,
  5737. row.duration_hours,
  5738. )
  5739. success = printer_manager.send_drying_command(
  5740. row.printer_id,
  5741. row.ams_id,
  5742. row.temp,
  5743. row.duration_hours,
  5744. mode=1,
  5745. filament=filament,
  5746. rotate_tray=row.rotate_tray,
  5747. )
  5748. if success:
  5749. row.status = "running"
  5750. row.started_at = now
  5751. row.waiting_reason = None
  5752. row.filament = filament
  5753. self._drying_in_progress[row.printer_id] = time.monotonic()
  5754. self._scheduled_drying_printer_ids.add(row.printer_id)
  5755. running_printer_ids.add(row.printer_id)
  5756. else:
  5757. row.waiting_reason = "printer_offline"
  5758. # Release the printers whose run has ended. `_drying_in_progress` is
  5759. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5760. # but that call sits behind the auto-drying enabled check, and this
  5761. # method is the one writer that runs whether auto-drying is on or not.
  5762. # With it off, nothing would ever drop the entry short of a print being
  5763. # dispatched to the same printer, so the next scheduled run would wait
  5764. # on "already_drying" forever and `queue_drying_block` would hold the
  5765. # printer's prints too. Covers a run that ended during this pass and one
  5766. # cancelled through the route between passes.
  5767. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5768. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5769. self._drying_in_progress.pop(printer_id, None)
  5770. await db.commit()
  5771. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5772. """Detect completion or interruption of a running scheduled drying.
  5773. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5774. drying. Within the grace window after start we ignore dry_time==0
  5775. (the status lags the command). After that, dry_time==0 near the end
  5776. of the configured duration means completed. Much earlier means the
  5777. run was stopped: re-queue it if a print preempted the dryer, but a
  5778. stop while the printer is idle was deliberate, so cancel the row
  5779. rather than restart drying the user just stopped.
  5780. """
  5781. if row.started_at is None:
  5782. row.started_at = now
  5783. return
  5784. elapsed = (now - row.started_at).total_seconds()
  5785. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5786. return
  5787. state = printer_manager.get_status(row.printer_id)
  5788. if not state:
  5789. return # offline mid-dry; resolve when it reconnects
  5790. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5791. # throw on a malformed id would cost the whole pass including print
  5792. # dispatch, every tick.
  5793. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5794. try:
  5795. dry_time = int(target.get("dry_time") or 0) if target else 0
  5796. except (TypeError, ValueError):
  5797. dry_time = 0
  5798. if dry_time > 0 and is_countdown_parked(target):
  5799. # The printer took the command but the countdown is not running
  5800. # (#2896) and will never reach 0, so the run would stay "running"
  5801. # forever. A print in progress is the likely cause (the power budget
  5802. # is spent), so re-queue it like any interruption; the next start
  5803. # waits for the printer to be idle. Parked on an idle printer is a
  5804. # refusal, not something a retry fixes. The timer itself is left on
  5805. # the printer: it may yet start once power frees up.
  5806. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5807. logger.info(
  5808. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5809. row.id,
  5810. row.ams_id,
  5811. )
  5812. row.status = "pending"
  5813. row.started_at = None
  5814. row.waiting_reason = "interrupted"
  5815. else:
  5816. logger.warning(
  5817. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5818. row.id,
  5819. row.ams_id,
  5820. )
  5821. row.status = "failed"
  5822. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5823. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5824. row.completed_at = now
  5825. return
  5826. if dry_time > 0:
  5827. return
  5828. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5829. row.status = "completed"
  5830. row.completed_at = now
  5831. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5832. row.status = "pending"
  5833. row.started_at = None
  5834. row.waiting_reason = "interrupted"
  5835. else:
  5836. row.status = "cancelled"
  5837. row.completed_at = now
  5838. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5839. """Get all smart plugs associated with a printer."""
  5840. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5841. return list(result.scalars().all())
  5842. @staticmethod
  5843. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5844. """Pick the plug to power-cycle a printer back online with (#2629).
  5845. Only a plug flagged ``controls_printer_power`` can actually bring the
  5846. printer back; waiting for a boot on an accessory (filter fan, lights)
  5847. just burns the power-on timeout and fails the dispatch. Falls back to
  5848. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5849. Callers must pass a non-empty list.
  5850. """
  5851. for plug in auto_on_plugs:
  5852. if plug.controls_printer_power:
  5853. return plug
  5854. return auto_on_plugs[0]
  5855. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5856. # chamber-temperature recommendations BambuStudio ships for the matching
  5857. # filament profile; users can override via Settings → Workflow → Preheat
  5858. # card. "default" applies when a loaded tray's normalised type isn't in
  5859. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5860. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5861. "PLA": 0,
  5862. "PETG": 0,
  5863. "PETG-CF": 40,
  5864. "ABS": 45,
  5865. "ASA": 45,
  5866. "PA": 50,
  5867. "PA-CF": 55,
  5868. "PC": 50,
  5869. "PC-FR": 50,
  5870. "TPU": 0,
  5871. "PVA": 0,
  5872. "default": 0,
  5873. }
  5874. @classmethod
  5875. def _bundled_preheat_targets(cls) -> dict[str, int]:
  5876. """The bundled map under the same key casing a parsed one gets.
  5877. The constant is declared with a lowercase ``default`` because that is
  5878. the key the Settings editor writes and displays. Every read of the map
  5879. happens after ``str(key).upper()``, so handing the constant back as
  5880. declared broke the contract the parser documents: an install that had
  5881. never touched the setting returned a dict with no ``DEFAULT`` in it,
  5882. and the resolution loop's fallback silently found nothing. It read the
  5883. right number only because the bundled default happens to be 0 -- change
  5884. that constant and every unconfigured install would keep preheating to
  5885. zero with no way to tell why.
  5886. """
  5887. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  5888. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  5889. """Parse the user-configured filament→chamber-target map, falling back
  5890. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  5891. are uppercased and the 'default' fallback is always present in the
  5892. returned dict so the resolution loop can index it unconditionally."""
  5893. raw = await self._get_setting(db, "preheat_filament_targets")
  5894. if not raw:
  5895. return self._bundled_preheat_targets()
  5896. try:
  5897. parsed = json.loads(raw)
  5898. if not isinstance(parsed, dict):
  5899. raise ValueError("not an object")
  5900. except (json.JSONDecodeError, ValueError) as exc:
  5901. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  5902. return self._bundled_preheat_targets()
  5903. # Coerce values to int; drop unparseable rows so a stray string
  5904. # doesn't crash the loop.
  5905. out: dict[str, int] = {}
  5906. for key, value in parsed.items():
  5907. try:
  5908. out[str(key).upper()] = int(value)
  5909. except (TypeError, ValueError):
  5910. continue
  5911. if "DEFAULT" not in out:
  5912. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  5913. return out
  5914. @staticmethod
  5915. def _normalize_filament_type(tray_type: str) -> str:
  5916. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  5917. existing drying-preset normalisation (split-at-space, upper-case) so
  5918. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  5919. "PA-CF" (no space to split on).
  5920. This is the first stage of ``_resolve_filament_key``, which goes on to
  5921. drop the suffix and consult the alias map; on its own it only decides
  5922. what the tray is called, not which row answers for it.
  5923. Indexing the split rather than testing the input: a tray_type of spaces
  5924. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  5925. it through to an IndexError.
  5926. """
  5927. words = (tray_type or "").split()
  5928. return words[0].upper() if words else ""
  5929. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  5930. """Per-filament chamber target for one tray's reported type, or 0 when
  5931. the tray is empty / RFID-less and reports no type at all.
  5932. A filled or foamed variant wants its base material's chamber when the
  5933. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  5934. not the 0 an unknown type falls to. The specific type is still tried
  5935. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  5936. (#2902).
  5937. That lookup is now the shared one, which adds the polyamide aliases on
  5938. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  5939. too, rather than the catch-all it was landing on (#3067).
  5940. """
  5941. if not self._normalize_filament_type(tray_type or ""):
  5942. return 0
  5943. key = self._resolve_filament_key(tray_type, targets)
  5944. if key is not None:
  5945. return targets[key]
  5946. # A type the map does not list at all, which is not the same as a tray
  5947. # with nothing in it -- that already returned 0 above.
  5948. return targets.get("DEFAULT", 0)
  5949. def _derive_chamber_target(
  5950. self,
  5951. printer: Printer,
  5952. targets: dict[str, int],
  5953. item: PrintQueueItem | None = None,
  5954. ) -> int:
  5955. """Chamber target for the trays this print actually loads: the max of
  5956. their per-filament targets. Returns 0 when there is nothing to read (no
  5957. status, no AMS telemetry — e.g. external-spool prints) or when every
  5958. tray considered maps to 0, and the chamber phase then short-circuits in
  5959. the main loop.
  5960. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  5961. Scanning the whole unit instead meant one ASA spool parked in the AMS
  5962. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  5963. plus soak burned ahead of each upload, on a printer whose chamber never
  5964. reaches the target anyway (#2886). An item with no usable mapping falls
  5965. back to scanning every loaded tray: that is the only signal left, and
  5966. narrowing to nothing would skip preheat on prints that genuinely need
  5967. it.
  5968. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  5969. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  5970. less slots have empty `tray_type` and contribute nothing. The external
  5971. spool is consulted only when the mapping names it (>= 254); it stays
  5972. out of the unnarrowed scan, so an item without a mapping derives from
  5973. the AMS alone exactly as before.
  5974. """
  5975. state = printer_manager.get_status(printer.id)
  5976. if state is None:
  5977. return 0
  5978. raw_data = state.raw_data or {}
  5979. used = _used_global_tray_ids(item)
  5980. ams_list = raw_data.get("ams")
  5981. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  5982. if isinstance(ams_list, dict):
  5983. ams_list = ams_list.get("ams") or []
  5984. if not isinstance(ams_list, list):
  5985. ams_list = []
  5986. best = 0
  5987. for ams in ams_list:
  5988. if not isinstance(ams, dict):
  5989. continue
  5990. ams_id = _int_or(ams.get("id"), 0)
  5991. for tray in ams.get("tray") or []:
  5992. # A non-dict entry has never been seen from real firmware, but
  5993. # `.get` on one raises, and nothing between here and
  5994. # `_dispatch_one`'s try/finally catches it — the item would be
  5995. # left holding its dispatch claim. Preheat is best-effort by
  5996. # contract, so step over it instead.
  5997. if not isinstance(tray, dict):
  5998. continue
  5999. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6000. continue
  6001. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6002. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6003. for vt in raw_data.get("vt_tray") or []:
  6004. if not isinstance(vt, dict):
  6005. continue
  6006. # `_build_loaded_filaments` addresses external feeds by the id
  6007. # the firmware reports — 255 main, 254 deputy — defaulting to
  6008. # 254 when the field is absent. Same expression here so the two
  6009. # agree on which entry a mapping's 254/255 refers to.
  6010. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6011. continue
  6012. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6013. return best
  6014. def _release_keep_warm(self, pid: int) -> None:
  6015. """Release keep-warm on a printer that left the candidate set.
  6016. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6017. reports the target we set (``entry.held_target``), so a user or
  6018. subsequent print that changed the bed target since is not clobbered.
  6019. Best-effort, never raises.
  6020. The entry is kept, not dropped, when the printer cannot be reached
  6021. right now: a printer that is briefly offline still has a hot bed, and
  6022. holding the entry is what keeps the max-duration timeout applying and
  6023. lets a later tick retry the release. Only a printer that has left the
  6024. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6025. """
  6026. entry = self._keep_warm.get(pid)
  6027. if entry is None:
  6028. return
  6029. state = printer_manager.get_status(pid)
  6030. client = printer_manager.get_client(pid)
  6031. if state is None or client is None:
  6032. logger.debug(
  6033. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6034. pid,
  6035. )
  6036. return
  6037. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6038. if int(cur_bed_target) != entry.held_target:
  6039. # Someone else owns the bed now, so there is nothing of ours to
  6040. # undo and nothing left to track.
  6041. logger.info(
  6042. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6043. pid,
  6044. int(cur_bed_target),
  6045. entry.held_target,
  6046. )
  6047. self._keep_warm.pop(pid, None)
  6048. return
  6049. try:
  6050. client.set_bed_temperature(0)
  6051. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6052. self._keep_warm.pop(pid, None)
  6053. except Exception as exc:
  6054. # Keep the entry so the next tick tries again rather than leaving
  6055. # the bed hot with nothing tracking it.
  6056. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6057. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6058. """Release printers that dropped out of the keep-warm candidate set.
  6059. Called from ``_apply_keep_warm`` on every tick (with the current
  6060. candidate set), and from ``check_queue``'s no-pending-items early
  6061. return (with an empty candidate set) so orphaned holds still get
  6062. released when the queue empties. Also called with an empty candidate
  6063. set when any of the three gate settings toggles off, so a printer
  6064. whose feature was disabled mid-hold gets its bed released.
  6065. Printers being dispatched this tick are excluded from the bed-off
  6066. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6067. transient 0 in between would just churn against preheat. Ownership of
  6068. the hot bed transfers to the preheat rollback pin instead — if the
  6069. dispatch aborts before the print starts (failed upload, cancelled
  6070. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6071. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6072. is the ONLY thing standing between an aborted dispatch and a bed
  6073. left hot with no owner. A successful print start clears the pin and
  6074. the print's own gcode takes over, as usual.
  6075. """
  6076. for _pid in list(self._keep_warm):
  6077. if _pid in active_candidates:
  6078. continue
  6079. if _pid in dispatched:
  6080. handed_over = self._keep_warm.pop(_pid, None)
  6081. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6082. if handed_over is not None:
  6083. self._preheat_pin_bed[_pid] = handed_over.held_target
  6084. continue
  6085. self._release_keep_warm(_pid)
  6086. async def _apply_keep_warm(
  6087. self,
  6088. db: AsyncSession,
  6089. items: list[PrintQueueItem],
  6090. dispatch_ids: list[int] | set[int],
  6091. busy_printers: set[int],
  6092. require_plate_clear: bool,
  6093. ) -> None:
  6094. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6095. When a printer just finished a job (FINISH state) and the next queued
  6096. item needs chamber heating, hold the bed hot so the chamber stays warm
  6097. during the bed-clearing window. The bed is the chamber's heating
  6098. element here, not a print surface — nothing is printing during the
  6099. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6100. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6101. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6102. aftermarket chamber heaters), raised to the item's own parsed
  6103. bed_temperature when that is higher. Items whose archive metadata has
  6104. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6105. get a hold — chamber need is what gates the feature, not metadata.
  6106. Skips entirely for filaments that map to a 0°C chamber target
  6107. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6108. names, so a hot-chamber spool it never touches does not hold the bed of
  6109. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6110. whole unit, as every item was before. Printers being dispatched this
  6111. cycle are excluded:
  6112. ``_preheat_and_soak`` already handles their bed temperature.
  6113. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6114. released to 0 and the entry is latched ``expired=True`` so
  6115. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6116. MQTT: publish is skipped when firmware already has the target.
  6117. The release sweep runs BEFORE the engagement gate so a printer that
  6118. was owned by keep-warm still gets its bed released when any of the
  6119. three gate settings is toggled off mid-hold. The
  6120. ``check_queue`` early-return-when-no-items path also calls
  6121. ``_sweep_keep_warm`` directly to release orphaned holds.
  6122. """
  6123. dispatch_set = set(dispatch_ids)
  6124. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6125. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6126. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6127. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6128. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6129. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6130. # Release sweep first — must run even when gate_open is False so a
  6131. # printer owned by keep-warm when a gate toggles off gets released.
  6132. self._sweep_keep_warm(
  6133. active_candidates=warm_candidates if gate_open else set(),
  6134. dispatched=dispatched_printers,
  6135. )
  6136. if not gate_open:
  6137. return
  6138. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6139. max_hold_seconds = (
  6140. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6141. )
  6142. now_mono = time.monotonic()
  6143. filament_targets: dict[str, int] | None = None
  6144. for pid in warm_candidates:
  6145. entry = self._keep_warm.get(pid)
  6146. # Latched-expired: max-duration timeout already fired for this
  6147. # printer. Skip until the release sweep drops the entry (i.e.
  6148. # until the printer leaves the candidate set).
  6149. if entry is not None and entry.expired:
  6150. continue
  6151. # These two guards sit ahead of the max-duration check below, so an
  6152. # engaged hold only ages out while its printer is still reachable
  6153. # and still in FINISH. That is deliberate rather than a hole: with
  6154. # no status or no client there is no M140 to send anyway, and the
  6155. # elapsed check runs off `entry.started` so it fires on the first
  6156. # tick after the printer comes back. Leaving FINISH means the plate
  6157. # was cleared, which drops the printer out of `warm_candidates` and
  6158. # hands it to `_release_keep_warm` instead. The invariant worth
  6159. # preserving if this is ever reordered: every path out of an
  6160. # engaged hold ends in a bed-off, whether by timeout or release.
  6161. state = printer_manager.get_status(pid)
  6162. if state is None or state.state != "FINISH":
  6163. continue
  6164. client = printer_manager.get_client(pid)
  6165. if client is None:
  6166. continue
  6167. next_item = next((it for it in items if it.printer_id == pid), None)
  6168. if next_item is None:
  6169. continue
  6170. # Hold temperature: the configured keep-warm temp, raised to the
  6171. # item's own bed temp when the metadata reports a higher one. A
  6172. # missing bed_temperature (Orca gcode.3mf exports parse without
  6173. # one) does NOT skip the hold — chamber need gates the feature.
  6174. archive = next_item.archive
  6175. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6176. bed_target = max(item_bed, hold_temp)
  6177. if bed_target <= 0:
  6178. continue
  6179. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6180. if explicit is not None:
  6181. chamber_needed = int(explicit) > 0
  6182. else:
  6183. if filament_targets is None:
  6184. filament_targets = await self._get_preheat_filament_targets(db)
  6185. printer_obj = await self._get_printer(db, pid)
  6186. chamber_needed = (
  6187. printer_obj is not None
  6188. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6189. )
  6190. if not chamber_needed:
  6191. continue
  6192. # Seed the timer on first engagement; keep it on subsequent ticks
  6193. # (never re-seed — that would defeat the max-duration cap).
  6194. if entry is None:
  6195. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6196. self._keep_warm[pid] = entry
  6197. elapsed = now_mono - entry.started
  6198. if elapsed > max_hold_seconds:
  6199. # Timeout: publish bed → 0 once (if firmware still holds our
  6200. # target) and latch expired. The entry stays until the release
  6201. # sweep drops it, preventing the next tick from re-seeding.
  6202. logger.warning(
  6203. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6204. pid,
  6205. elapsed,
  6206. )
  6207. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6208. if int(cur_bed_target) == entry.held_target:
  6209. try:
  6210. client.set_bed_temperature(0)
  6211. except Exception as exc:
  6212. logger.warning(
  6213. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6214. pid,
  6215. exc,
  6216. )
  6217. else:
  6218. logger.info(
  6219. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6220. pid,
  6221. int(cur_bed_target),
  6222. entry.held_target,
  6223. )
  6224. entry.expired = True
  6225. continue
  6226. # Idempotence: skip publish when firmware already has our target.
  6227. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6228. if int(cur_bed_target) == bed_target:
  6229. entry.held_target = bed_target
  6230. continue
  6231. try:
  6232. client.set_bed_temperature(bed_target)
  6233. entry.held_target = bed_target
  6234. logger.info(
  6235. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6236. bed_target,
  6237. pid,
  6238. )
  6239. except Exception as exc:
  6240. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6241. def _sample_chamber_temps(self) -> None:
  6242. """Record a chamber temperature sample for every connected printer.
  6243. Called once per scheduler tick (every 3–30 s). Entries older than
  6244. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6245. Also evicts per-printer state whose printer_id is no longer registered
  6246. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6247. """
  6248. now = time.monotonic()
  6249. cutoff = now - self._chamber_history_ttl
  6250. statuses = printer_manager.get_all_statuses()
  6251. known_pids = set(statuses.keys())
  6252. for pid, status in statuses.items():
  6253. if status is None or not status.connected:
  6254. continue
  6255. temps = status.temperatures or {}
  6256. chamber = temps.get("chamber")
  6257. if chamber is None:
  6258. continue
  6259. hist = self._chamber_history.setdefault(pid, deque())
  6260. hist.append((now, float(chamber)))
  6261. while hist and hist[0][0] < cutoff:
  6262. hist.popleft()
  6263. # Evict state for printers that are no longer registered with the manager.
  6264. # This is the one place a keep-warm entry is dropped without releasing
  6265. # the bed: the printer is gone from the manager, so there is no client
  6266. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6267. # for printers that are merely unreachable, which is what makes this
  6268. # the terminal case rather than a silent leak.
  6269. for pid in list(self._chamber_history):
  6270. if pid not in known_pids:
  6271. self._chamber_history.pop(pid, None)
  6272. for pid in list(self._keep_warm):
  6273. if pid not in known_pids:
  6274. logger.info(
  6275. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6276. pid,
  6277. )
  6278. self._keep_warm.pop(pid, None)
  6279. for pid in list(self._preheat_pin):
  6280. if pid not in known_pids:
  6281. self._preheat_pin.pop(pid, None)
  6282. self._preheat_pin_bed.pop(pid, None)
  6283. def _chamber_soak_remaining(
  6284. self,
  6285. printer_id: int,
  6286. chamber_target: float,
  6287. soak_seconds: int,
  6288. tolerance: float = 2.0,
  6289. ) -> int:
  6290. """Return how many seconds of soak time are still needed.
  6291. Credits the time the chamber has already spent at temperature against
  6292. the configured soak. The credit may not start earlier than any of:
  6293. * **The newest sample.** Nothing recent means the printer stopped
  6294. reporting mid-observation and the chamber may have cooled unseen, so
  6295. the full soak is required. (A 2 h history whose last reading is half
  6296. an hour old is not evidence of anything — the measured cooling rate
  6297. is fast enough to cross the threshold in that time.)
  6298. * **The most recent contiguous run of samples.** A gap wider than
  6299. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6300. far side is not evidence of temperature.
  6301. * **The end of the most recent real dip below the threshold.**
  6302. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6303. — see that constant for the thermal reasoning. A stray low reading is
  6304. an artifact, and treating it as cooling would discard a soak that
  6305. actually happened.
  6306. Returns ``soak_seconds`` when nothing can be credited (no history,
  6307. stale history, or the chamber is below the threshold right now) and 0
  6308. once the credited time covers the whole soak.
  6309. """
  6310. hist = self._chamber_history.get(printer_id)
  6311. if not hist:
  6312. return soak_seconds
  6313. now = time.monotonic()
  6314. newest_ts, newest_temp = hist[-1]
  6315. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6316. return soak_seconds # stale — no fresh evidence to credit
  6317. threshold = chamber_target - tolerance
  6318. if newest_temp < threshold:
  6319. return soak_seconds # below target right now; nothing is soaked
  6320. samples = list(hist)
  6321. # Earliest point we have unbroken observations for.
  6322. credit_from = samples[-1][0]
  6323. for i in range(len(samples) - 1, 0, -1):
  6324. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6325. break
  6326. credit_from = samples[i - 1][0]
  6327. # Pull the credit forward to the end of the last significant dip. Each
  6328. # excursion is measured between the in-range readings that bracket it,
  6329. # so a lone stray sample is charged one sampling interval rather than
  6330. # zero, and the comparison errs towards calling a dip real.
  6331. i = 0
  6332. while i < len(samples):
  6333. if samples[i][1] >= threshold:
  6334. i += 1
  6335. continue
  6336. j = i
  6337. while j < len(samples) and samples[j][1] < threshold:
  6338. j += 1
  6339. # `newest_temp >= threshold` was checked above, so j is in range.
  6340. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6341. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6342. # Credit resumes at the last below-threshold sample rather than
  6343. # the first good one after it, so a recovered dip over-credits
  6344. # by up to one sampling interval — the opposite lean to the
  6345. # bracketing above. Both are bounded by the sample cadence and
  6346. # dwarfed by the grace period, so neither is worth the extra
  6347. # arithmetic to remove.
  6348. credit_from = max(credit_from, samples[j - 1][0])
  6349. i = j
  6350. return max(0, soak_seconds - int(now - credit_from))
  6351. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6352. """Tell an in-flight dispatch that its item no longer wants to print.
  6353. Called by the queue's cancel and delete routes. Those only write to the
  6354. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6355. observe — so preheat would keep heating for the rest of max_wait + soak
  6356. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6357. blocking every other queued item behind a print that is not happening.
  6358. Signalling in memory rather than re-reading the row keeps this off the
  6359. database entirely: no second session, no transaction held across a long
  6360. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6361. Bambuddy serves from a single uvicorn process with one scheduler task,
  6362. so the route and the dispatch always share this object. The flag is
  6363. advisory — dropping it (e.g. after a restart) only costs a wasted
  6364. preheat, never a wrongly-abandoned print.
  6365. Only ids with a dispatch actually in flight are recorded, so the set
  6366. stays bounded by the upload pool rather than growing once per cancelled
  6367. item for the life of the process. Skipping the rest loses nothing: an
  6368. item that is not in flight cannot start heating later either, because
  6369. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6370. the caller has already committed a terminal status (or deleted the row)
  6371. before calling this.
  6372. """
  6373. if item_id in self._inflight:
  6374. self._cancelled_dispatches.add(item_id)
  6375. # A print sent for it earlier that never started is not one any more.
  6376. self._forget_unstarted_print(item_id, unless_printing=False)
  6377. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6378. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6379. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6380. while it is parked, so the wait is chopped into
  6381. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6382. """
  6383. remaining = float(seconds)
  6384. while remaining > 0:
  6385. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6386. await asyncio.sleep(slice_secs)
  6387. remaining -= slice_secs
  6388. if item_id in self._cancelled_dispatches:
  6389. return False
  6390. return True
  6391. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6392. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6393. The full preheat stage does this as part of its own dispatch: an H2D
  6394. left in heating mode by the ABS job before it would otherwise cook the
  6395. PLA that follows. The skip path never reaches that code, so it calls
  6396. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6397. add to the rollback pin, because a flap set to cooling for a print that
  6398. needs no heat is where it should have been either way.
  6399. Best-effort like everything else in the stage: a refused command logs
  6400. and the dispatch carries on.
  6401. """
  6402. model = printer.model or ""
  6403. if not supports_airduct(model):
  6404. return
  6405. state = printer_manager.get_status(printer.id)
  6406. current = getattr(state, "airduct_mode", None) if state else None
  6407. if current == _AIRDUCT_MODE_COOLING:
  6408. return
  6409. client = printer_manager.get_client(printer.id)
  6410. if client is None:
  6411. return
  6412. try:
  6413. client.set_airduct_mode("cooling")
  6414. except Exception as exc:
  6415. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6416. async def _preheat_and_soak(
  6417. self,
  6418. db: AsyncSession,
  6419. item: PrintQueueItem,
  6420. printer: Printer,
  6421. archive: PrintArchive | None,
  6422. ) -> bool:
  6423. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6424. Returns True when the dispatch should carry on to the upload — including
  6425. every case where preheat is skipped, since a skipped preheat is not a
  6426. reason to abandon the print. Returns False only when the item stopped
  6427. wanting to be printed while the stage was waiting (cancelled or
  6428. deleted); the caller must then abandon the dispatch, and
  6429. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6430. Resolution order:
  6431. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6432. to the global `preheat_enabled` setting; 'on' forces the stage on
  6433. even if the global is off.
  6434. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6435. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6436. across the trays `item.ams_mapping` names (every loaded slot when
  6437. it names none).
  6438. 3. A target of 0 off the filament map skips the whole stage: the
  6439. materials this print loads want no chamber, so there is nothing to
  6440. soak for and the bed phase would only delay the upload (#3041).
  6441. An explicit 0 typed into the per-item override, or a per-item
  6442. 'on', still runs the bed phase and the soak — both are the user
  6443. asking for a warm bed in so many words.
  6444. 4. Three hardware tiers branch the wait loop:
  6445. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6446. send M141 to the resolved target, then wait for the chamber sensor
  6447. to reach it (or the max-wait timeout to elapse).
  6448. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6449. no M141; the bed is the only heat source, so we wait for the chamber
  6450. sensor to rise via bed radiation OR fall through on timeout.
  6451. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6452. temperature; the function just heats the bed and holds for the
  6453. configured soak duration.
  6454. The bed target comes from the archive's parsed metadata
  6455. (`bed_temperature`); if missing the preheat stage logs and returns
  6456. without dispatching anything, rather than guessing at a default that
  6457. might wreck filament setup.
  6458. Failures are logged but never re-raised — preheat is best-effort. A
  6459. printer that goes offline mid-soak, a refused gcode command, or a
  6460. missing temperature reading must not turn into a failed queue item; the
  6461. normal upload + start path runs immediately after this method returns.
  6462. """
  6463. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6464. if override == "off":
  6465. return True
  6466. if override == "inherit":
  6467. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6468. if not enabled:
  6469. return True
  6470. # override == "on" forces the stage on regardless of the global setting.
  6471. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6472. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6473. # Chamber target resolution:
  6474. # 1. Explicit per-item override beats everything (user knows best).
  6475. # 2. Otherwise derive from the filament types this print loads, via
  6476. # the per-filament target map. A PLA-only print derives 0 and the
  6477. # block below skips the stage without the user touching anything,
  6478. # even when an ASA spool is sitting in another slot of the same
  6479. # AMS (#2886).
  6480. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6481. if explicit_target is not None and explicit_target > 0:
  6482. chamber_target = int(explicit_target)
  6483. chamber_source = "item-override"
  6484. elif explicit_target == 0:
  6485. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6486. chamber_source = "item-override-zero"
  6487. else:
  6488. targets = await self._get_preheat_filament_targets(db)
  6489. chamber_target = self._derive_chamber_target(printer, targets, item)
  6490. chamber_source = "filament-map"
  6491. # Nothing to preheat *for*. A zero that came out of the filament map is
  6492. # the map saying this print's materials want no chamber conditioning --
  6493. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6494. # anyway heated the bed and then held it for the full soak, which
  6495. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6496. # own G-code sets the bed the moment it starts, so preheating it here
  6497. # only moves that heating ahead of the upload instead of overlapping
  6498. # with it, and the soak has no chamber to condition (#3041).
  6499. #
  6500. # An explicit statement from the user still runs the stage. Forcing the
  6501. # per-item override to 'on', or typing a chamber target of exactly 0,
  6502. # both mean "preheat the bed for this print" -- the second is
  6503. # documented as doing precisely that. Only the automatic path, the
  6504. # global toggle plus the filament map, short-circuits here.
  6505. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6506. logger.info(
  6507. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6508. "target, so there is nothing to soak for (override=%s model=%s)",
  6509. item.id,
  6510. override,
  6511. printer.model or "",
  6512. )
  6513. self._preheat_flap_to_cooling(item.id, printer)
  6514. return True
  6515. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6516. if bed_target <= 0:
  6517. # No bed temperature in the slicer metadata. When the print needs a
  6518. # hot chamber the bed is simply how we heat it, so fall back to the
  6519. # configured chamber-heating bed temperature rather than skipping
  6520. # the whole stage — otherwise the print starts with a cold chamber,
  6521. # which is exactly what preheat exists to prevent. Without a chamber
  6522. # requirement there is nothing to preheat *for*, so skip as before
  6523. # rather than guess a bed temperature for the print itself.
  6524. if chamber_target <= 0:
  6525. logger.info(
  6526. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6527. item.id,
  6528. )
  6529. return True
  6530. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6531. logger.info(
  6532. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6533. "%d°C to drive the chamber to %d°C",
  6534. item.id,
  6535. bed_target,
  6536. chamber_target,
  6537. )
  6538. client = printer_manager.get_client(printer.id)
  6539. if client is None:
  6540. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6541. return True
  6542. model = printer.model or ""
  6543. has_heater = supports_chamber_heater(model)
  6544. has_sensor = supports_chamber_temp(model)
  6545. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6546. # Fast path: if the chamber has been continuously above target for at
  6547. # least soak_seconds and the bed is already at temperature, skip the
  6548. # entire preheat stage. Typical case: keep-warm held the bed between
  6549. # consecutive same-material prints and the chamber never dropped.
  6550. if do_chamber and has_sensor and soak_seconds > 0:
  6551. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6552. if remaining == 0:
  6553. cur = printer_manager.get_status(printer.id)
  6554. if cur:
  6555. cur_temps = cur.temperatures or {}
  6556. if (
  6557. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6558. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6559. ):
  6560. logger.info(
  6561. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6562. "and bed is already at temperature (chamber history fast-path)",
  6563. item.id,
  6564. chamber_target,
  6565. soak_seconds,
  6566. )
  6567. # Still set targets to prevent cooling during the 3MF upload window.
  6568. # Register each successful set in the preheat pin so `_dispatch_one`
  6569. # unwinds them on any non-success exit.
  6570. pin = self._preheat_pin.setdefault(printer.id, set())
  6571. try:
  6572. client.set_bed_temperature(bed_target)
  6573. pin.add("bed")
  6574. self._preheat_pin_bed[printer.id] = bed_target
  6575. except Exception as exc:
  6576. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6577. if supports_airduct(model):
  6578. cur_airduct = getattr(cur, "airduct_mode", None)
  6579. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6580. try:
  6581. client.set_airduct_mode("heating")
  6582. # Only undo what we can see we replaced. `None`
  6583. # means no mode has been observed yet, and
  6584. # rolling that back to cooling would assert a
  6585. # state the printer never reported.
  6586. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6587. pin.add("airduct")
  6588. except Exception as exc:
  6589. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6590. if has_heater:
  6591. try:
  6592. client.set_chamber_temperature(chamber_target)
  6593. pin.add("chamber")
  6594. except Exception as exc:
  6595. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6596. return True
  6597. logger.info(
  6598. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6599. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6600. item.id,
  6601. bed_target,
  6602. chamber_target if do_chamber else 0,
  6603. chamber_source,
  6604. override,
  6605. model,
  6606. has_heater,
  6607. has_sensor,
  6608. max_wait,
  6609. soak_seconds,
  6610. )
  6611. # Preheat rollback registry: everything we set below is recorded here so
  6612. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6613. # (bed off, chamber off, airduct back to cooling) on any non-success
  6614. # exit. Populated as each command succeeds; consumed and cleared by
  6615. # `_dispatch_one`.
  6616. pin = self._preheat_pin.setdefault(printer.id, set())
  6617. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6618. # cache the target locally so the polling reads below see consistent
  6619. # state (firmware MQTT echoes lag by ~1s).
  6620. try:
  6621. client.set_bed_temperature(bed_target)
  6622. pin.add("bed")
  6623. self._preheat_pin_bed[printer.id] = bed_target
  6624. except Exception as exc:
  6625. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6626. return True
  6627. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6628. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6629. # left it on, regardless of M141. Default cooling actively vents the
  6630. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6631. # cooling never converges — the heater fights the open exhaust. We
  6632. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6633. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6634. # on an H2D that was previously running ABS would otherwise stay in
  6635. # heating mode and overheat PLA). The current-state read keeps the
  6636. # command idempotent — no MQTT chatter when the flap is already where
  6637. # we want it.
  6638. if supports_airduct(model):
  6639. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6640. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6641. current_state = printer_manager.get_status(printer.id)
  6642. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6643. if current_airduct != desired_id:
  6644. try:
  6645. client.set_airduct_mode(desired_airduct)
  6646. # As in the fast path: only pin a rollback for a flap we
  6647. # saw in cooling. `current_airduct` of None means no mode
  6648. # has been observed, so there is nothing to restore to.
  6649. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6650. pin.add("airduct")
  6651. except Exception as exc:
  6652. logger.warning(
  6653. "Queue item %s: preheat airduct %s mode failed: %s",
  6654. item.id,
  6655. desired_airduct,
  6656. exc,
  6657. )
  6658. if do_chamber and has_heater:
  6659. try:
  6660. client.set_chamber_temperature(chamber_target)
  6661. pin.add("chamber")
  6662. except Exception as exc:
  6663. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6664. # Release the pooled DB connection before the (potentially many-minute)
  6665. # heat-soak wait below (#2572). Every setting this method needs is read
  6666. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6667. # it never touches the DB. Without this the caller's transaction sat
  6668. # "idle in transaction" for the whole soak, pinning one pooled connection
  6669. # per preheating printer. expire_on_commit=False keeps item/printer
  6670. # readable afterwards; there are no pending writes to lose here.
  6671. await db.commit()
  6672. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6673. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6674. # Poll every 3s — frequent enough for responsive logging without
  6675. # spamming the MQTT state stream. The "converged" predicate is:
  6676. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6677. # AND
  6678. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6679. BED_TOLERANCE = 2.0
  6680. CHAMBER_TOLERANCE = 2.0
  6681. POLL_INTERVAL = 3.0
  6682. deadline = asyncio.get_event_loop().time() + max_wait
  6683. while True:
  6684. state = printer_manager.get_status(printer.id)
  6685. if state is None:
  6686. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6687. break
  6688. temps = state.temperatures or {}
  6689. bed_now = float(temps.get("bed", 0) or 0)
  6690. chamber_now = float(temps.get("chamber", 0) or 0)
  6691. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6692. if not do_chamber:
  6693. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6694. elif not has_sensor:
  6695. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6696. else:
  6697. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6698. if bed_ok and chamber_ok:
  6699. logger.info(
  6700. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6701. item.id,
  6702. bed_now,
  6703. chamber_now,
  6704. )
  6705. break
  6706. if asyncio.get_event_loop().time() >= deadline:
  6707. logger.info(
  6708. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6709. item.id,
  6710. bed_now,
  6711. bed_target,
  6712. chamber_now,
  6713. chamber_target if do_chamber else 0,
  6714. )
  6715. break
  6716. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6717. logger.info(
  6718. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6719. item.id,
  6720. )
  6721. return False
  6722. if soak_seconds > 0:
  6723. if do_chamber and has_sensor:
  6724. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6725. else:
  6726. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6727. if remaining > 0:
  6728. logger.info(
  6729. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6730. "has been above target for ~%ds already)",
  6731. item.id,
  6732. remaining,
  6733. soak_seconds,
  6734. soak_seconds - remaining,
  6735. )
  6736. if not await self._preheat_sleep(item.id, remaining):
  6737. logger.info(
  6738. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6739. item.id,
  6740. )
  6741. return False
  6742. else:
  6743. logger.info(
  6744. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6745. item.id,
  6746. chamber_target,
  6747. soak_seconds,
  6748. )
  6749. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6750. return True
  6751. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6752. """Turn on smart plug and wait for printer to connect.
  6753. Returns True if printer connected successfully within timeout.
  6754. """
  6755. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6756. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6757. # Check current plug state
  6758. status = await service.get_status(plug)
  6759. if not status.get("reachable"):
  6760. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6761. return False
  6762. # Turn on if not already on
  6763. if status.get("state") != "ON":
  6764. success = await service.turn_on(plug)
  6765. if not success:
  6766. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6767. return False
  6768. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  6769. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6770. # Get printer from database for connection
  6771. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6772. printer = result.scalar_one_or_none()
  6773. if not printer:
  6774. logger.error("Printer %s not found in database", printer_id)
  6775. return False
  6776. # Wait for printer to boot (give it some time before trying to connect)
  6777. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6778. await asyncio.sleep(30)
  6779. # Try to connect to the printer periodically
  6780. elapsed = 30 # Already waited 30s
  6781. while elapsed < self._power_on_wait_time:
  6782. # Try to connect
  6783. logger.info("Attempting to connect to printer %s...", printer_id)
  6784. try:
  6785. connected = await printer_manager.connect_printer(printer)
  6786. if connected:
  6787. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6788. # Give it a moment to stabilize and get status
  6789. await asyncio.sleep(5)
  6790. return True
  6791. except Exception as e:
  6792. logger.debug("Connection attempt failed: %s", e)
  6793. await asyncio.sleep(self._power_on_check_interval)
  6794. elapsed += self._power_on_check_interval
  6795. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6796. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6797. return False
  6798. async def _check_previous_success(
  6799. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  6800. ) -> bool:
  6801. """Check if the previous print on this printer succeeded.
  6802. ``printer_id`` names the printer to look at when the item has none yet
  6803. (a job for any printer of a model, checked against the one offered).
  6804. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6805. deliberate action, not a failure, so subsequent items should still
  6806. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6807. a skip isn't an actual print attempt, so it must not gate downstream
  6808. items — counting it as a failed predecessor was the cascade bug that
  6809. let a single cancellation block 18 items over 3 days for the reporter.
  6810. Only `failed` and `aborted` — real print-attempt failures — block.
  6811. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6812. action — #1818) are also excluded from the lookback so the user can
  6813. clear the gate after fixing the physical issue without having to
  6814. re-queue every downstream job.
  6815. """
  6816. result = await db.execute(
  6817. select(PrintQueueItem)
  6818. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  6819. .where(PrintQueueItem.id != item.id)
  6820. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6821. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6822. # A row ended without a completion time must not count as the
  6823. # latest: PostgreSQL sorts NULL first in a descending order.
  6824. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  6825. .limit(1)
  6826. )
  6827. prev_item = result.scalar_one_or_none()
  6828. # If no previous item, assume success (first in queue)
  6829. if not prev_item:
  6830. return True
  6831. return prev_item.status in ("completed", "cancelled")
  6832. async def _repoint_siblings_at_archive(
  6833. self,
  6834. db: AsyncSession,
  6835. *,
  6836. consumed_library_file_id: int,
  6837. archive_id: int,
  6838. dispatched_item_id: int,
  6839. ) -> int:
  6840. """Move the other queue items off a library row that is about to be deleted (#2819).
  6841. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6842. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6843. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6844. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6845. clones, so the first dispatch could pull the file out from under rows that
  6846. had not run yet. What those rows did next depended on the database, and
  6847. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6848. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6849. they were left pointing at a row that no longer existed, failing with
  6850. "Library file not found" whenever someone started them -- or sitting
  6851. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6852. constraint, so there the rows were deleted outright and the queued copies
  6853. simply vanished, with no error and no history.
  6854. The archive holds its own copy of the 3MF, so the remaining copies can print
  6855. from it instead. Two things happen here, and both must happen *before* the
  6856. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6857. * every row still naming the file has ``library_file_id`` cleared, which is
  6858. what takes it out of the cascade's reach. That covers rows this cannot
  6859. re-point as well -- a copy already printing from its own archive, and the
  6860. finished ones, which are not spare parts but the record a batch order
  6861. counts its progress from.
  6862. * the rows that still need something to print are pointed at the archive.
  6863. Returns how many items were re-pointed.
  6864. """
  6865. variant_item_ids = (
  6866. (
  6867. await db.execute(
  6868. select(PrintQueueVariant.queue_item_id).where(
  6869. PrintQueueVariant.library_file_id == consumed_library_file_id
  6870. )
  6871. )
  6872. )
  6873. .scalars()
  6874. .all()
  6875. )
  6876. # Candidate rows naming the consumed file have to go rather than be
  6877. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  6878. # one out of the cascade. This is what PostgreSQL already does, and
  6879. # _candidates_for skips such a variant on SQLite anyway, so no selection
  6880. # outcome changes -- the two backends simply stop disagreeing about
  6881. # whether the row is still there.
  6882. #
  6883. # It also has to happen before the re-point below: a cross-model item
  6884. # (#671) picks a variant every pass and folds it onto the row, and
  6885. # _resolve_variant clears archive_id as it does so, which would undo the
  6886. # re-point on the very next lap.
  6887. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  6888. # An item left with other candidates still has somewhere to go, and those
  6889. # carry their own target model -- pointing it at this archive would print a
  6890. # file the matcher never chose. It is excluded from the re-point and simply
  6891. # re-resolves against what is left.
  6892. surviving_variant_item_ids = set(
  6893. (
  6894. await db.execute(
  6895. select(PrintQueueVariant.queue_item_id).where(
  6896. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  6897. )
  6898. )
  6899. )
  6900. .scalars()
  6901. .all()
  6902. )
  6903. repoint_ids = set(
  6904. (
  6905. await db.execute(
  6906. select(PrintQueueItem.id)
  6907. .where(PrintQueueItem.id != dispatched_item_id)
  6908. .where(PrintQueueItem.archive_id.is_(None))
  6909. # "skipped" belongs here with the two live states: it is not
  6910. # terminal. Clearing a printer's previous-success gate puts
  6911. # every item skipped by it back to "pending"
  6912. # (resume_after_failure), and one restored onto a deleted
  6913. # file is the same orphan by a slower route. "failed",
  6914. # "cancelled", "aborted" and "completed" never return.
  6915. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  6916. .where(
  6917. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  6918. )
  6919. .where(
  6920. or_(
  6921. PrintQueueItem.library_file_id == consumed_library_file_id,
  6922. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  6923. )
  6924. )
  6925. )
  6926. )
  6927. .scalars()
  6928. .all()
  6929. )
  6930. if repoint_ids:
  6931. await db.execute(
  6932. update(PrintQueueItem)
  6933. .where(PrintQueueItem.id.in_(repoint_ids))
  6934. .values(
  6935. archive_id=archive_id,
  6936. library_file_id=None,
  6937. # The file this flag named is already consumed. Leaving it set
  6938. # would arm every re-pointed copy to delete whatever library
  6939. # row it is next given.
  6940. cleanup_library_after_dispatch=False,
  6941. )
  6942. )
  6943. logger.info(
  6944. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  6945. sorted(repoint_ids),
  6946. archive_id,
  6947. consumed_library_file_id,
  6948. dispatched_item_id,
  6949. )
  6950. # Everything else that still names the file: taken out of the cascade's
  6951. # reach without touching what it prints. The file is gone either way; what
  6952. # this preserves is the row.
  6953. await db.execute(
  6954. update(PrintQueueItem)
  6955. .where(PrintQueueItem.id != dispatched_item_id)
  6956. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  6957. .values(library_file_id=None)
  6958. )
  6959. return len(repoint_ids)
  6960. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  6961. """Schedule power-off if the queue item enabled auto_off_after.
  6962. Delegates to the smart-plug manager so the off honours each plug's
  6963. configured strategy (time delay or temperature threshold), is cancelled
  6964. if the printer starts printing again, and never cuts power on a loaded
  6965. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  6966. powered off on the timeout regardless of print state.
  6967. """
  6968. if not item.auto_off_after:
  6969. return
  6970. try:
  6971. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  6972. except Exception as e:
  6973. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  6974. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  6975. """Get a human-readable name for a queue item."""
  6976. if item.archive_id:
  6977. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  6978. archive = result.scalar_one_or_none()
  6979. if archive:
  6980. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6981. if item.library_file_id:
  6982. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  6983. library_file = result.scalar_one_or_none()
  6984. if library_file:
  6985. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6986. # A cross-model item (#671) holds no file of its own until a printer is
  6987. # picked, so name it after its first candidate — otherwise every waiting
  6988. # notification for one reads "Job #12". Queried rather than read off
  6989. # item.variants because callers outside the selection loop have not
  6990. # eager-loaded them, and a lazy load raises in async.
  6991. first_variant_name = (
  6992. await db.execute(
  6993. select(LibraryFile.filename)
  6994. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  6995. .where(PrintQueueVariant.queue_item_id == item.id)
  6996. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  6997. .limit(1)
  6998. )
  6999. ).scalar_one_or_none()
  7000. if first_variant_name:
  7001. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7002. return f"Job #{item.id}"
  7003. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7004. """Get printer by ID."""
  7005. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7006. return result.scalar_one_or_none()
  7007. async def _notify_dispatch_gave_up(
  7008. self,
  7009. queue_item_id: int,
  7010. printer_id: int,
  7011. created_by_id: int | None,
  7012. reason: str = "Printer accepted the file but never started printing",
  7013. ) -> None:
  7014. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7015. Called from the watchdog, which is a background task with no session of
  7016. its own — hence the fresh one here. Best-effort throughout: the row is
  7017. already marked failed and that is the load-bearing part; a notification
  7018. provider being down must not resurrect the retry loop we just stopped.
  7019. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7020. path passes its own, because "accepted the file but never started" is the
  7021. opposite of what happened there — the printer refused it outright (#2732).
  7022. """
  7023. try:
  7024. async with async_session() as db:
  7025. item = await db.get(PrintQueueItem, queue_item_id)
  7026. if not item:
  7027. return
  7028. job_name = await self._get_job_name(db, item)
  7029. printer = await self._get_printer(db, printer_id)
  7030. await notification_service.on_queue_job_failed(
  7031. job_name=job_name,
  7032. printer_id=printer_id,
  7033. printer_name=printer.name if printer else "Unknown",
  7034. reason=reason,
  7035. db=db,
  7036. )
  7037. except Exception as e:
  7038. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7039. try:
  7040. await ws_manager.send_queue_item_failed(
  7041. user_id=created_by_id,
  7042. queue_item_id=queue_item_id,
  7043. printer_id=printer_id,
  7044. reason="never_started",
  7045. )
  7046. except Exception:
  7047. pass # toast is best-effort
  7048. async def _filament_short_on(
  7049. self,
  7050. db: AsyncSession,
  7051. item: PrintQueueItem,
  7052. printer_id: int,
  7053. *,
  7054. require_known: bool = False,
  7055. ) -> bool:
  7056. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7057. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7058. assigned there, with the mapping the item would get there, but changes
  7059. nothing. The model-based matcher uses it to prefer a printer whose
  7060. spools can finish the job.
  7061. False whenever the gate would let the item through: "Print Anyway",
  7062. no mapping, or a check that fails. With ``require_known`` all three of
  7063. those, and any printed slot whose remaining amount is unknown, count
  7064. as short instead: releasing a held job starts it with nobody asked, so
  7065. it needs the amount on record, not merely nothing against it.
  7066. """
  7067. if item.skip_filament_check:
  7068. return False
  7069. try:
  7070. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7071. if not mapping:
  7072. return require_known
  7073. deficit = await compute_deficit_for_queue_item(
  7074. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7075. )
  7076. except Exception as e:
  7077. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7078. return require_known
  7079. return bool(deficit)
  7080. async def _release_short_model_hold(
  7081. self,
  7082. db: AsyncSession,
  7083. item: PrintQueueItem,
  7084. unavailable: set[int],
  7085. require_plate_clear: bool,
  7086. printer_scope: PrinterScope,
  7087. ) -> bool:
  7088. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7089. The deficit gate holds a model-based job on the printer the matcher
  7090. gave it, because "Print Anyway" needs a printer to print on. When
  7091. another idle printer of the job's model has the filament, the job is
  7092. moved to that printer and its hold lifted, and the fixed-printer
  7093. branch dispatches it in this same pass, through the same checks a
  7094. held job meets when the user presses Start. It is moved rather than
  7095. put back in the pool because the model-based branch would pick again
  7096. without requiring the amounts on record (below), and could pick a
  7097. different printer. Only the deficit gate sets ``filament_short``, so a
  7098. job held for any other reason stays held.
  7099. The printer it is held on is left out: a spool loaded there is started
  7100. with Start, as before, rather than while someone may still be loading
  7101. the next one. Each job is checked at most every
  7102. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7103. on each idle printer again.
  7104. Cross-model jobs (#671) stay held: checking a variant writes its file
  7105. onto the item, which would leave a job that is not moved holding
  7106. another variant's file for the printer it waits on.
  7107. A printer qualifies only on a positive finding: every slot the plate
  7108. prints mapped to a spool whose remaining amount is on record and
  7109. enough. A printer whose spools Bambuddy does not track is not one.
  7110. Returns True when the job was moved. A check that fails keeps the hold
  7111. rather than stopping the queue pass.
  7112. """
  7113. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7114. return False
  7115. if not item.target_model or item.variants:
  7116. return False
  7117. now = time.monotonic()
  7118. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7119. return False
  7120. self._short_hold_checked_at[item.id] = now
  7121. try:
  7122. candidates = _candidates_for(item)
  7123. if not candidates:
  7124. return False
  7125. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7126. async def is_short(pid: int) -> bool:
  7127. return await self._filament_short_on(db, item, pid, require_known=True)
  7128. match_id, _ = await self._find_idle_printer_for_model(
  7129. db,
  7130. item.target_model,
  7131. unavailable | {item.printer_id},
  7132. effective_types,
  7133. item.target_location,
  7134. filament_overrides=filament_overrides,
  7135. require_plate_clear=require_plate_clear,
  7136. printer_scope=printer_scope,
  7137. is_short=is_short,
  7138. )
  7139. # Every idle printer short comes back as the first of them.
  7140. if match_id is None or await is_short(match_id):
  7141. return False
  7142. except Exception as e:
  7143. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7144. return False
  7145. logger.info(
  7146. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7147. item.id,
  7148. match_id,
  7149. item.printer_id,
  7150. )
  7151. self._short_hold_checked_at.pop(item.id, None)
  7152. item.printer_id = match_id
  7153. # Resolved against the printer it leaves (#3239): the tray mapping and
  7154. # the nozzle positions.
  7155. drop_printer_resolved(item)
  7156. item.manual_start = False
  7157. item.filament_short = False
  7158. item.waiting_reason = None
  7159. await db.commit()
  7160. try:
  7161. printer = await self._get_printer(db, match_id)
  7162. await notification_service.on_queue_job_assigned(
  7163. job_name=await self._get_job_name(db, item),
  7164. printer_id=match_id,
  7165. printer_name=printer.name if printer else "Unknown",
  7166. target_model=item.target_model,
  7167. db=db,
  7168. )
  7169. except Exception as e:
  7170. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7171. return True
  7172. async def _block_on_filament_deficit(
  7173. self,
  7174. db: AsyncSession,
  7175. item: PrintQueueItem,
  7176. ) -> bool:
  7177. """Promote the item to manual_start when the assigned spool is short (#1496).
  7178. Returns True when this dispatch attempt was blocked, False when the
  7179. item is clear to start. A previously-flagged item whose spool has
  7180. since been swapped to one with enough material clears the flag here
  7181. so the next scheduler tick dispatches it.
  7182. """
  7183. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7184. # don't re-flag, don't even compute. Without this short-circuit the
  7185. # scheduler bounces between "user said anyway" (route clears
  7186. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7187. # on identical spool state) (#1698-followup).
  7188. if item.skip_filament_check:
  7189. # #1762 diagnostic: surface the short-circuit at INFO so a
  7190. # future "Print Anyway didn't work" report (e.g. issue #1762
  7191. # comment 3) has actionable evidence in the support bundle
  7192. # without needing DEBUG enabled.
  7193. logger.info(
  7194. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7195. item.id,
  7196. )
  7197. return False
  7198. try:
  7199. deficit = await compute_deficit_for_queue_item(db, item)
  7200. except Exception as e:
  7201. # Never let a flaky deficit check wedge the queue — log and let
  7202. # dispatch proceed. The PrintModal-side check still runs on the
  7203. # manual paths.
  7204. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7205. return False
  7206. if deficit:
  7207. item.filament_short = True
  7208. item.manual_start = True
  7209. await db.commit()
  7210. job_name = await self._get_job_name(db, item)
  7211. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7212. logger.info(
  7213. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7214. item.id,
  7215. len(deficit),
  7216. )
  7217. try:
  7218. await notification_service.on_queue_job_waiting(
  7219. job_name=job_name,
  7220. target_model=(printer.model if printer else "") or "",
  7221. waiting_reason="filament_short",
  7222. db=db,
  7223. )
  7224. except Exception as e:
  7225. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7226. return True
  7227. # No deficit — clear any stale flag from a previous tick.
  7228. if item.filament_short:
  7229. item.filament_short = False
  7230. await db.commit()
  7231. return False
  7232. async def _block_on_unmatched_filament(
  7233. self,
  7234. db: AsyncSession,
  7235. item: PrintQueueItem,
  7236. release_assignment: bool = False,
  7237. ) -> bool:
  7238. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7239. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7240. goes ahead, letting the printer choose — which is how a job prints in the
  7241. wrong material without anyone being asked. Holding is the same answer the
  7242. deficit gate already gives for "the spool is too light", so it reuses the
  7243. same promote-and-notify machinery.
  7244. Keyed off unresolved slots in the *computed* mapping intersected with the
  7245. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7246. read: on its own it also pads slots this plate does not print, so the
  7247. array alone would hold perfectly good jobs. Reading the mapping rather
  7248. than the printer's loaded filament types also inherits the matcher's
  7249. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7250. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7251. type-only scan would wave that through.
  7252. A mapping that resolved *nothing* is the same finding arriving as an
  7253. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7254. could not replace, and dispatch then goes out as ``use_ams`` with no
  7255. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7256. That is held too, but only once live status positively reports loaded
  7257. trays: #2589's mapping is bogus precisely because the AMS was not known
  7258. yet, and its empty loaded list is that ignorance rather than a miss.
  7259. ``release_assignment`` is for the model-based path, which commits its
  7260. printer choice before the gates run. Holding an "any P2S" job would
  7261. otherwise pin it to the one P2S that could not run it.
  7262. Returns True when this dispatch attempt was blocked.
  7263. """
  7264. if item.skip_filament_check or not item.printer_id:
  7265. return False
  7266. if item.ams_mapping:
  7267. try:
  7268. mapping = json.loads(item.ams_mapping)
  7269. except (json.JSONDecodeError, TypeError):
  7270. return False
  7271. if not isinstance(mapping, list):
  7272. return False
  7273. else:
  7274. # Nothing resolved, or nothing survived revalidation. Only a printer
  7275. # that reported loaded trays makes that a finding — see the
  7276. # docstring on why an empty list is not one.
  7277. status = printer_manager.get_status(item.printer_id)
  7278. if status is None or not self._build_loaded_filaments(status):
  7279. return False
  7280. # Every required slot reads unresolved against an empty mapping.
  7281. mapping = []
  7282. required = await self._get_filament_requirements(db, item)
  7283. if not required:
  7284. return False
  7285. self._apply_filament_overrides(item, required)
  7286. unmatched = _unresolved_required(required, mapping)
  7287. if not unmatched:
  7288. # No cleanup needed here: once start is pressed the item is no
  7289. # longer staged, and whichever exit runs next overwrites the reason
  7290. # (`hold_item` on the fixed-printer branch, the assignment on the
  7291. # model-based one), as does dispatch.
  7292. return False
  7293. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7294. held_by = item.printer_id
  7295. item.manual_start = True
  7296. # Human-readable: this renders on the queue row.
  7297. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7298. if release_assignment:
  7299. # "Any P2S" means any, so the job returns to the pool rather than
  7300. # waiting on the printer that could not take it. The mapping goes
  7301. # with the assignment: its tray IDs were resolved against the
  7302. # printer being released and mean nothing on the next one (#2799),
  7303. # and keeping them would hold the job again even on a printer that
  7304. # has the filament, since an unresolved slot is deliberately not a
  7305. # conflict worth recomputing over.
  7306. item.printer_id = None
  7307. drop_printer_resolved(item)
  7308. await db.commit()
  7309. job_name = await self._get_job_name(db, item)
  7310. printer = await self._get_printer(db, held_by)
  7311. logger.info(
  7312. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7313. item.id,
  7314. held_by,
  7315. wanted,
  7316. )
  7317. try:
  7318. await notification_service.on_queue_job_waiting(
  7319. job_name=job_name,
  7320. target_model=(printer.model if printer else "") or "",
  7321. waiting_reason=f"needs {wanted}",
  7322. db=db,
  7323. )
  7324. except Exception as e:
  7325. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7326. return True
  7327. @staticmethod
  7328. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7329. """The queue item's owner as the row has it now.
  7330. item.created_by_id was read before preheat and upload, which can take
  7331. minutes; deleting the user clears the row, not this session's copy.
  7332. """
  7333. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7334. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7335. """Hand the queue item's owner to printer_manager so the
  7336. print-complete callback can credit the user in PrintLogEntry (#1670).
  7337. No-ops when the item has no `created_by_id` or the referenced user
  7338. row is missing (e.g. user deleted between queue-add and dispatch —
  7339. in that case the print log row falls back to the existing un-credited
  7340. behaviour rather than crashing the dispatch).
  7341. """
  7342. from backend.app.models.user import User
  7343. # Read from the row, not item.created_by_id or db.get: both can still
  7344. # hold a user deleted during the upload, after delete_user forgot them
  7345. # (on SQLite the id may be someone new's by the time the print ends).
  7346. # Joined with the printer too: one deleted during the upload was
  7347. # forgotten as well, and this would write the owner back under its id.
  7348. owner = (
  7349. await db.execute(
  7350. select(User.id, User.username)
  7351. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7352. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7353. .where(PrintQueueItem.id == item.id)
  7354. )
  7355. ).first()
  7356. if owner:
  7357. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7358. if item.printer_id is not None:
  7359. self._unconfirmed_print_user[item.id] = item.printer_id
  7360. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7361. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7362. A cancel lands in another session while the upload runs (the edit route
  7363. even tells users to cancel a job that is being sent). An unconditional
  7364. write here would turn that cancellation into a failure, with a failure
  7365. notification, and block the next job that needs the previous print to
  7366. have succeeded. Returns whether the item was marked failed.
  7367. """
  7368. result = cast(
  7369. CursorResult,
  7370. await db.execute(
  7371. update(PrintQueueItem)
  7372. .where(PrintQueueItem.id == item.id)
  7373. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7374. .values(status="failed", error_message=message, completed_at=datetime.now(timezone.utc))
  7375. .execution_options(synchronize_session=False)
  7376. ),
  7377. )
  7378. await db.commit()
  7379. if result.rowcount == 0:
  7380. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7381. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7382. return False
  7383. await db.refresh(item)
  7384. from backend.app.services.print_batch import refresh_batches_after
  7385. await refresh_batches_after([item.id])
  7386. return True
  7387. @staticmethod
  7388. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7389. """Put a job whose printer turned busy before the start back in the queue.
  7390. Only if it is still printing: a stop that landed meanwhile stands.
  7391. """
  7392. await db.execute(
  7393. update(PrintQueueItem)
  7394. .where(PrintQueueItem.id == item.id)
  7395. .where(PrintQueueItem.status == "printing")
  7396. .values(status="pending", started_at=None)
  7397. .execution_options(synchronize_session=False)
  7398. )
  7399. await db.commit()
  7400. @staticmethod
  7401. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7402. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7403. try:
  7404. await ws_manager.send_queue_item_failed(
  7405. user_id=toast_uid,
  7406. queue_item_id=item.id,
  7407. printer_id=item.printer_id,
  7408. reason="cancelled_mid_dispatch",
  7409. )
  7410. except Exception:
  7411. pass # toast is best-effort
  7412. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7413. """Upload file and start print for a queue item.
  7414. Supports two sources:
  7415. - archive_id: Print from an existing archive
  7416. - library_file_id: Print from a library file (file manager)
  7417. """
  7418. logger.info("Starting queue item %s", item.id)
  7419. # Also covers a reservation left active by a process interruption
  7420. # during an earlier attempt. `_dispatch_one` releases this marker on
  7421. # every exit unless start_print() confirms that the command was sent.
  7422. self._unconfirmed_budget_reservations.add(item.id)
  7423. try:
  7424. from backend.app.models.user import User
  7425. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7426. # Recompute at the final authorization boundary as well as enqueue
  7427. # time. This covers rows created before the server-side estimate
  7428. # migration and prevents any alternate write path from weakening
  7429. # the budget reservation.
  7430. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7431. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7432. item.estimated_cost = await estimate_queue_source_cost(
  7433. db,
  7434. archive=archive,
  7435. library_file=library_file,
  7436. plate_id=item.plate_id,
  7437. ams_mapping=item.ams_mapping,
  7438. printer_id=item.printer_id,
  7439. )
  7440. await validate_print_budget(
  7441. db,
  7442. cost_center_id=item.cost_center_id,
  7443. estimated_cost=item.estimated_cost,
  7444. current_user=queue_user,
  7445. exclude_queue_item_id=item.id,
  7446. exclude_reservation_source_type="print_queue",
  7447. exclude_reservation_source_id=item.id,
  7448. )
  7449. budget_reservation = await create_budget_reservation(
  7450. db,
  7451. cost_center_id=item.cost_center_id,
  7452. estimated_cost=item.estimated_cost,
  7453. current_user=queue_user,
  7454. source_type="print_queue",
  7455. source_id=item.id,
  7456. print_archive_id=item.archive_id,
  7457. exclude_queue_item_id=item.id,
  7458. )
  7459. await db.commit()
  7460. except HTTPException as exc:
  7461. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7462. return
  7463. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7464. await self._power_off_if_needed(db, item)
  7465. return
  7466. # Get printer first (needed for both paths)
  7467. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7468. printer = result.scalar_one_or_none()
  7469. if not printer:
  7470. if not await self._fail_dispatch(db, item, "Printer not found"):
  7471. return
  7472. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7473. await self._power_off_if_needed(db, item)
  7474. return
  7475. # Check printer is connected
  7476. if not printer_manager.is_connected(item.printer_id):
  7477. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7478. return
  7479. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7480. await self._power_off_if_needed(db, item)
  7481. return
  7482. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7483. # `items` was taken at the top of check_queue, but the user can /cancel
  7484. # any pending row in the gap before we reach this point. Re-read the
  7485. # row and bail out cleanly instead of starting an FTP upload for a row
  7486. # that's already cancelled. The atomic CAS at the pending→printing
  7487. # transition (below, before start_print) is the load-bearing guard;
  7488. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7489. await db.refresh(item)
  7490. if item.status != "pending":
  7491. logger.info(
  7492. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7493. item.id,
  7494. item.status,
  7495. )
  7496. return
  7497. # Busy-printer guard (#2598). check_queue gates dispatch on
  7498. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7499. # keep reporting FINISH for tens of seconds *after* it accepted a
  7500. # project_file (see the watchdog's phase-B note). A watchdog revert
  7501. # (#2555) also releases the dispatch hold, so a re-selected item can
  7502. # reach here while its printer has actually started printing. Uploading
  7503. # and dispatching then collides with the live job — the firmware answers
  7504. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7505. # live state right before the expensive FTP upload: if the printer is
  7506. # busy, leave the item pending and let a later tick dispatch it once the
  7507. # printer is genuinely idle. No wasted upload, no collision.
  7508. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7509. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7510. logger.info(
  7511. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7512. "leaving item pending for a later tick (#2598)",
  7513. item.id,
  7514. item.printer_id,
  7515. pre_dispatch_state,
  7516. )
  7517. return
  7518. # Determine source: archive or library file
  7519. archive = None
  7520. library_file = None
  7521. file_path = None
  7522. filename = None
  7523. cleanup_disk_paths: list[Path] = []
  7524. # Set when a dispatch consumes its library file, so the photos can be
  7525. # carried over after the commit that removes the row (#3077).
  7526. consumed_library_file_id: int | None = None
  7527. consumed_photos: list[str] = []
  7528. if item.archive_id:
  7529. # Print from archive
  7530. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7531. archive = result.scalar_one_or_none()
  7532. if not archive:
  7533. if not await self._fail_dispatch(db, item, "Archive not found"):
  7534. return
  7535. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7536. await self._power_off_if_needed(db, item)
  7537. return
  7538. # Persist the queue item's selected plate onto the archive so Print
  7539. # History can show the actual plate after cancel/fail/complete (#2603).
  7540. # Only when the archive doesn't already carry one, so a reprint of a
  7541. # plate-specific archive isn't relabelled by a differently-plated
  7542. # queue row.
  7543. if archive.plate_id is None and item.plate_id is not None:
  7544. archive.plate_id = item.plate_id
  7545. # Ask-for-outcome opt-in rides from the queue item to the archive
  7546. # the same way (#1898); never cleared here so a reprint of an
  7547. # archive that already asked keeps asking.
  7548. if item.confirm_outcome:
  7549. archive.confirm_requested = True
  7550. file_path = settings.base_dir / archive.file_path
  7551. filename = archive.filename
  7552. elif item.library_file_id:
  7553. # Print from library file (file manager)
  7554. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7555. library_file = result.scalar_one_or_none()
  7556. if not library_file:
  7557. # "Not found" covers two different situations and only one of
  7558. # them is recoverable, so say which. A trashed file is still
  7559. # there and restoring it makes a re-queued job work; a file that
  7560. # is really gone needs a different one. Neither is knowable from
  7561. # the queue, which is the whole complaint about this message.
  7562. trashed = (
  7563. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7564. ).scalar_one_or_none()
  7565. if not await self._fail_dispatch(
  7566. db,
  7567. item,
  7568. (
  7569. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7570. if trashed
  7571. else "Library file not found — it was deleted after this job was queued"
  7572. ),
  7573. ):
  7574. return
  7575. logger.error(
  7576. "Queue item %s: library file %s is %s",
  7577. item.id,
  7578. item.library_file_id,
  7579. "in the trash" if trashed else "gone",
  7580. )
  7581. await self._power_off_if_needed(db, item)
  7582. return
  7583. # Library files store absolute paths
  7584. lib_path = Path(library_file.file_path)
  7585. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7586. filename = library_file.filename
  7587. # Create archive from library file so usage tracking has access to the 3MF
  7588. queue_item_id = item.id
  7589. # Held separately: a cleanup dispatch clears item.library_file_id
  7590. # below, and the log line at the end of this block reported that
  7591. # cleared field -- so every consumed print logged "from library
  7592. # file None", which is the one case worth being able to trace.
  7593. source_library_file_id = item.library_file_id
  7594. try:
  7595. from backend.app.services.archive import ArchiveService
  7596. archive_service = ArchiveService(db)
  7597. archive = await archive_service.archive_print(
  7598. printer_id=item.printer_id,
  7599. source_file=file_path,
  7600. original_filename=filename,
  7601. created_by_id=item.created_by_id,
  7602. project_id=item.project_id,
  7603. cost_center_id=item.cost_center_id,
  7604. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7605. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7606. )
  7607. if archive:
  7608. item.archive_id = archive.id
  7609. if item.confirm_outcome:
  7610. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7611. if budget_reservation is not None:
  7612. budget_reservation.print_archive_id = archive.id
  7613. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7614. consumed_library_file_id = library_file.id
  7615. item.library_file_id = None
  7616. cleanup_disk_paths.append(file_path)
  7617. if library_file.thumbnail_path:
  7618. thumb_path = Path(library_file.thumbnail_path)
  7619. if not thumb_path.is_absolute():
  7620. thumb_path = settings.base_dir / library_file.thumbnail_path
  7621. cleanup_disk_paths.append(thumb_path)
  7622. # Before the delete, not after: on PostgreSQL the FK
  7623. # cascade would already have taken these rows (#2819).
  7624. await self._repoint_siblings_at_archive(
  7625. db,
  7626. consumed_library_file_id=consumed_library_file_id,
  7627. archive_id=archive.id,
  7628. dispatched_item_id=item.id,
  7629. )
  7630. # Read while the row is still here; the photos move
  7631. # below, once the delete has actually committed.
  7632. consumed_photos = list(library_file.photos or [])
  7633. # The delete clears the link on the earlier archives of
  7634. # this file (ON DELETE SET NULL; core/sqlite_fk on
  7635. # SQLite). This one is loaded, so set it here too, or it
  7636. # keeps the stale id in the session.
  7637. archive.library_file_id = None
  7638. await db.delete(library_file)
  7639. file_path = settings.base_dir / archive.file_path
  7640. filename = archive.filename
  7641. # Commit, not flush — flush opens the SQLite write
  7642. # transaction (item.archive_id update + library_file
  7643. # delete) and would hold the WAL writer lock through the
  7644. # FTP upload below, causing "database is locked" cascades
  7645. # for sensor history + concurrent cancels (#1853).
  7646. await db.commit()
  7647. logger.info(
  7648. "Queue item %s: Created archive %s from library file %s",
  7649. item.id,
  7650. archive.id,
  7651. source_library_file_id,
  7652. )
  7653. except Exception as e:
  7654. logger.warning(
  7655. "Queue item %s: Failed to create archive from library file: %s",
  7656. queue_item_id,
  7657. e,
  7658. exc_info=True,
  7659. )
  7660. await db.rollback()
  7661. item = await db.get(PrintQueueItem, queue_item_id)
  7662. if item:
  7663. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7664. return
  7665. await self._power_off_if_needed(db, item)
  7666. return
  7667. if not archive:
  7668. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7669. return
  7670. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7671. await self._power_off_if_needed(db, item)
  7672. return
  7673. # The photos follow the file into the archive that replaces it, for
  7674. # the same reason the siblings do (#3077). After the commit above,
  7675. # never before it: that commit can fail ("database is locked",
  7676. # #1853) and roll the library row back, and photos already moved
  7677. # would leave it naming a directory that no longer exists. The
  7678. # file and thumbnail unlinks are deferred for the same reason.
  7679. if consumed_library_file_id is not None and consumed_photos:
  7680. # Held as a plain int, read here while the session is still
  7681. # healthy, because the handler below may not touch an ORM
  7682. # instance at all. The commit it exists for fails inside the
  7683. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7684. # first DML statement, so a busy writer surfaces as "database
  7685. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7686. # internally through safe_reraise before re-raising, which
  7687. # expires every loaded instance and leaves the session in
  7688. # pending-rollback state -- so `archive.id` inside the except
  7689. # would itself raise PendingRollbackError and the rollback
  7690. # below would never be reached.
  7691. archive_id = archive.id
  7692. try:
  7693. carried_photos = move_library_photos(
  7694. consumed_library_file_id,
  7695. consumed_photos,
  7696. archive_photos_dir(archive),
  7697. )
  7698. if carried_photos:
  7699. archive.photos = list(archive.photos or []) + carried_photos
  7700. await db.commit()
  7701. except Exception as e:
  7702. # The archive and the delete are already committed; the
  7703. # print goes ahead either way. Worst case the pictures sit
  7704. # unnamed in the archive's own directory.
  7705. #
  7706. # Ints only until the rollback has run, per the note above,
  7707. # which is why this logs queue_item_id and not item.id --
  7708. # the sibling handler forty lines up does the same.
  7709. logger.warning(
  7710. "Queue item %s: failed to carry library photos into archive %s: %s",
  7711. queue_item_id,
  7712. archive_id,
  7713. e,
  7714. )
  7715. await db.rollback()
  7716. # rollback() expires every loaded instance, and in async
  7717. # SQLAlchemy the next plain attribute read is lazy IO
  7718. # outside the greenlet -- MissingGreenlet, which would turn
  7719. # this cosmetic failure into a dispatch crash in exactly the
  7720. # "database is locked" case the block exists for (#1853).
  7721. # The nozzle guard, the upload and the start all keep
  7722. # reading item, archive and printer, so all three go back
  7723. # into the session before falling through.
  7724. item = await db.get(PrintQueueItem, queue_item_id)
  7725. archive = await db.get(PrintArchive, archive_id)
  7726. printer = await db.get(Printer, item.printer_id) if item else None
  7727. if not item or not archive or not printer:
  7728. logger.error(
  7729. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7730. queue_item_id,
  7731. archive_id,
  7732. )
  7733. return
  7734. else:
  7735. # Neither archive nor library file specified
  7736. if not await self._fail_dispatch(db, item, "No source file specified"):
  7737. return
  7738. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7739. await self._power_off_if_needed(db, item)
  7740. return
  7741. # Check file exists on disk
  7742. if not file_path.exists():
  7743. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  7744. return
  7745. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7746. await self._power_off_if_needed(db, item)
  7747. return
  7748. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7749. # size dispatched to a printer with a different nozzle installed is
  7750. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7751. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7752. # gives the user no idea what went wrong. Catch it here, before we spend
  7753. # time preheating and uploading, and fail with an actionable message.
  7754. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7755. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7756. # the printer hasn't reported its nozzles yet, we fall through and let the
  7757. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7758. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7759. # as one of the two hotends is a 0.6.
  7760. #
  7761. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7762. # (#2885): the printer fetches one as part of starting the print, so the
  7763. # set to test against is "reachable", not "currently mounted". This runs
  7764. # well before the rack picker at the bottom of this method, so without
  7765. # the rack in scope here that picker never got the chance to run.
  7766. sliced_nozzle = archive.nozzle_diameter if archive else None
  7767. if sliced_nozzle:
  7768. nozzle_status = printer_manager.get_status(item.printer_id)
  7769. installed = _installed_nozzle_diameters(nozzle_status)
  7770. rack = _rack_nozzle_diameters(nozzle_status)
  7771. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7772. if mismatch_msg:
  7773. if not await self._fail_dispatch(db, item, mismatch_msg):
  7774. return
  7775. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7776. await notification_service.on_queue_job_failed(
  7777. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7778. printer_id=printer.id,
  7779. printer_name=printer.name,
  7780. reason=mismatch_msg,
  7781. db=db,
  7782. )
  7783. try:
  7784. await ws_manager.send_queue_item_failed(
  7785. user_id=item.created_by_id,
  7786. queue_item_id=item.id,
  7787. printer_id=item.printer_id,
  7788. reason="nozzle_mismatch",
  7789. )
  7790. except Exception:
  7791. pass
  7792. await self._power_off_if_needed(db, item)
  7793. return
  7794. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7795. # bed (and chamber, if applicable) is at temperature when the firmware
  7796. # starts the actual print routine. Best-effort: any failure logs and
  7797. # falls through to the normal upload+start path rather than turning a
  7798. # configuration issue into a failed queue item.
  7799. # Returns False only when the item was cancelled or deleted while the
  7800. # stage was holding at temperature. Uploading and starting it anyway
  7801. # would print a job the user has already called off, so abandon the
  7802. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7803. if not await self._preheat_and_soak(db, item, printer, archive):
  7804. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7805. return
  7806. # See `_effective_plate_id` for why this is resolved once here rather
  7807. # than each site below repeating `item.plate_id or 1`.
  7808. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7809. # G-code injection for auto-print systems (#422)
  7810. injected_path = None
  7811. # #2547: tracked separately from `injected_path`, which is also set when
  7812. # only a START snippet was injected. Only an END snippet changes what the
  7813. # camera sees at print completion.
  7814. end_gcode_injected = False
  7815. if item.gcode_injection:
  7816. try:
  7817. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7818. if snippets_raw:
  7819. snippets = json.loads(snippets_raw)
  7820. model_snippets = snippets.get(printer.model, {})
  7821. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7822. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7823. if start_gc or end_gc:
  7824. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7825. injected_path = inject_gcode_into_3mf(
  7826. file_path, effective_plate_id, start_gc or None, end_gc or None
  7827. )
  7828. if injected_path:
  7829. file_path = injected_path
  7830. end_gcode_injected = bool(end_gc)
  7831. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7832. else:
  7833. logger.warning(
  7834. "Queue item %s: G-code injection returned no result, using original", item.id
  7835. )
  7836. except Exception as e:
  7837. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7838. # #2547: the finish-photo path can't learn from telemetry that this print
  7839. # ends with user End G-code — which means the plate may be gone by the
  7840. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7841. # the print once the printer confirms it running.
  7842. if end_gcode_injected:
  7843. print_dispatch_context.mark_pending(printer.id)
  7844. # Upload to root directory (not /cache/) - the start_print command references
  7845. # files by name only (ftp://{filename}), so they must be in the root
  7846. remote_filename = derive_remote_filename(filename)
  7847. remote_path = f"/{remote_filename}"
  7848. # Get FTP retry settings
  7849. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7850. logger.info(
  7851. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7852. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7853. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7854. )
  7855. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7856. # Every read this method needs (printer, archive/library, preheat) is
  7857. # done, and the library-file branch already committed its archive
  7858. # creation. Without this the transaction opened by the first SELECT above
  7859. # stays "idle in transaction" for the entire upload — multiple seconds
  7860. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7861. # a farm dispatching many jobs at once then exhausts the pool. This was
  7862. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7863. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7864. # readable; the status writes below (upload-failure path and the
  7865. # pending->printing CAS) transparently open a fresh transaction.
  7866. # The owner is read here, after preheat, so the commit releases this read too.
  7867. toast_uid = await self._queue_owner_id(db, item)
  7868. await db.commit()
  7869. # Delete existing file if present (avoids 553 error on overwrite)
  7870. try:
  7871. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  7872. delete_result = await delete_file_async(
  7873. printer.ip_address,
  7874. printer.access_code,
  7875. remote_path,
  7876. socket_timeout=ftp_timeout,
  7877. printer_model=printer.model,
  7878. # This delete and the upload below are one bounded, user-initiated
  7879. # unit -- at most nine connections -- so neither skips on the
  7880. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  7881. # trace this delete took the TLS failure and armed the cool-off,
  7882. # and the upload's four attempts were then spent against it
  7883. # without a socket being opened.
  7884. respect_handshake_cooloff=False,
  7885. )
  7886. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  7887. except Exception as e:
  7888. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  7889. # Dispatch toast — announce the upload start with the total byte
  7890. # count so the frontend can render an honest progress bar.
  7891. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7892. try:
  7893. total_bytes = file_path.stat().st_size
  7894. except OSError:
  7895. total_bytes = 0
  7896. try:
  7897. await ws_manager.send_queue_item_uploading(
  7898. user_id=toast_uid,
  7899. queue_item_id=item.id,
  7900. printer_id=item.printer_id,
  7901. printer_name=printer.name,
  7902. file_name=toast_file_name,
  7903. total_bytes=total_bytes,
  7904. )
  7905. except Exception:
  7906. pass # toast is best-effort
  7907. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  7908. # A deadline expiry gets its own message: "check your SD card" is the
  7909. # wrong advice for a link that was simply too slow to finish (#2529).
  7910. upload_error: str | None = None
  7911. # Why the upload failed, straight from the client rather than inferred.
  7912. # Owned here, so a background fetch for another print cannot overwrite
  7913. # it between the failure and the sentence built from it (#2899).
  7914. upload_failure = FtpFailureReport()
  7915. try:
  7916. if ftp_retry_enabled:
  7917. uploaded = await with_ftp_retry(
  7918. upload_file_async,
  7919. printer.ip_address,
  7920. printer.access_code,
  7921. file_path,
  7922. remote_path,
  7923. socket_timeout=ftp_timeout,
  7924. printer_model=printer.model,
  7925. progress_callback=progress_bridge,
  7926. respect_handshake_cooloff=False,
  7927. failure=upload_failure,
  7928. max_retries=ftp_retry_count,
  7929. retry_delay=ftp_retry_delay,
  7930. operation_name=f"Upload print to {printer.name}",
  7931. )
  7932. else:
  7933. uploaded = await upload_file_async(
  7934. printer.ip_address,
  7935. printer.access_code,
  7936. file_path,
  7937. remote_path,
  7938. socket_timeout=ftp_timeout,
  7939. printer_model=printer.model,
  7940. progress_callback=progress_bridge,
  7941. respect_handshake_cooloff=False,
  7942. failure=upload_failure,
  7943. )
  7944. except UploadCancelled as e:
  7945. uploaded = False
  7946. upload_error = (
  7947. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  7948. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  7949. )
  7950. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  7951. except Exception as e:
  7952. uploaded = False
  7953. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  7954. # Clean up injected temp file after upload attempt
  7955. if injected_path and injected_path.exists():
  7956. injected_path.unlink(missing_ok=True)
  7957. # Again after the upload, which can take minutes: an owner deleted
  7958. # meanwhile gets no more toasts, and neither does whoever has their id.
  7959. toast_uid = await self._queue_owner_id(db, item)
  7960. if not uploaded:
  7961. # This used to be one string for every upload failure, telling
  7962. # everyone to check the SD card. The client knows which of seven
  7963. # things went wrong and logs each one differently; it just had no
  7964. # way to say so here, so the card got named even for a TLS
  7965. # handshake that never reached the printer's filesystem (#2899).
  7966. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  7967. failure = upload_failure.failure
  7968. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  7969. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  7970. return
  7971. if not await self._fail_dispatch(db, item, error_msg):
  7972. await self._close_cancelled_dispatch_toast(item, toast_uid)
  7973. return
  7974. logger.error(
  7975. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  7976. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  7977. )
  7978. # Send failure notification
  7979. await notification_service.on_queue_job_failed(
  7980. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7981. printer_id=printer.id,
  7982. printer_name=printer.name,
  7983. # The same sentence the queue shows. A push notification saying
  7984. # something different from the UI is its own small bug (#2899).
  7985. reason=error_msg,
  7986. db=db,
  7987. )
  7988. try:
  7989. await ws_manager.send_queue_item_failed(
  7990. user_id=toast_uid,
  7991. queue_item_id=item.id,
  7992. printer_id=item.printer_id,
  7993. reason="upload_failed",
  7994. )
  7995. except Exception:
  7996. pass
  7997. await self._power_off_if_needed(db, item)
  7998. return
  7999. # The printer took a file, so any run of refused uploads is over: the
  8000. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8001. self._upload_refusals.pop(printer.id, None)
  8002. self._upload_refusal_notified.discard(printer.id)
  8003. # Parse AMS mapping if stored
  8004. ams_mapping = None
  8005. if item.ams_mapping:
  8006. try:
  8007. ams_mapping = json.loads(item.ams_mapping)
  8008. except json.JSONDecodeError:
  8009. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8010. # Register as expected print so we don't create a duplicate archive
  8011. # Only applicable for archive-based prints
  8012. if archive:
  8013. from backend.app.main import register_expected_print
  8014. register_expected_print(
  8015. item.printer_id,
  8016. remote_filename,
  8017. archive.id,
  8018. ams_mapping=ams_mapping,
  8019. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8020. # no print-start email, and neither does whoever has their id.
  8021. created_by_id=toast_uid,
  8022. cost_center_id=item.cost_center_id,
  8023. # The plate actually dispatched, not the queue item's raw
  8024. # column: on None, `register_expected_print` stores nothing,
  8025. # and `extract_filament_usage_from_3mf` then books every
  8026. # filament in the file rather than the one plate that printed.
  8027. plate_id=effective_plate_id,
  8028. )
  8029. # Registration happens before the print command by necessity (the
  8030. # printer can report the print before the send returns), so record
  8031. # what to undo if we never get as far as sending. `_dispatch_one`
  8032. # rolls back anything still pending here on every exit — exception,
  8033. # early return, or cancel winning the CAS below.
  8034. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8035. # Propagate the queue item's owner into printer_manager so the
  8036. # print-complete callback can credit the user in the PrintLogEntry
  8037. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8038. # items) or when the user clicks the manual-start button.
  8039. await self._propagate_owner_to_printer_manager(db, item)
  8040. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8041. # This prevents phantom reprints if the backend crashes/restarts after the
  8042. # print command is sent but before the status update is committed.
  8043. # If we crash after this commit but before start_print(), the item will be
  8044. # in "printing" status without actually printing - but that's safer than
  8045. # accidentally reprinting the same file hours later.
  8046. #
  8047. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8048. # initial pending read at the top of check_queue and this point) flips
  8049. # the row to "cancelled" in a separate session. Without the WHERE
  8050. # status='pending' clause, the unconditional update here would silently
  8051. # overwrite that cancellation and we'd ship the MQTT start_print below
  8052. # — printer obeys, user sees "I pressed cancel and the print started".
  8053. # rowcount==0 means the user won the race; bail out, best-effort delete
  8054. # the file we just uploaded, do NOT send start_print.
  8055. now_utc = datetime.now(timezone.utc)
  8056. billing_run_id = str(uuid.uuid4())
  8057. cas = await db.execute(
  8058. update(PrintQueueItem)
  8059. .where(PrintQueueItem.id == item.id)
  8060. .where(PrintQueueItem.status == "pending")
  8061. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  8062. )
  8063. await db.commit()
  8064. if cas.rowcount == 0:
  8065. logger.info(
  8066. "Queue item %s no longer pending at print-command time "
  8067. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8068. item.id,
  8069. )
  8070. try:
  8071. await delete_file_async(
  8072. printer.ip_address,
  8073. printer.access_code,
  8074. remote_path,
  8075. socket_timeout=ftp_timeout,
  8076. printer_model=printer.model,
  8077. )
  8078. except Exception as cleanup_err:
  8079. logger.debug(
  8080. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8081. item.id,
  8082. cleanup_err,
  8083. )
  8084. try:
  8085. await ws_manager.send_queue_item_failed(
  8086. user_id=toast_uid,
  8087. queue_item_id=item.id,
  8088. printer_id=item.printer_id,
  8089. reason="cancelled_mid_dispatch",
  8090. )
  8091. except Exception:
  8092. pass
  8093. return
  8094. # Sync the in-memory item so subsequent code that reads item.status /
  8095. # item.started_at sees the values we just persisted.
  8096. item.status = "printing"
  8097. item.started_at = now_utc
  8098. item.billing_run_id = billing_run_id
  8099. if archive is not None:
  8100. archive.billing_run_id = billing_run_id
  8101. # Legacy transaction deletion used an archive-wide skip flag.
  8102. # A newly dispatched run has its own UUID/tombstone, so it must be
  8103. # billable independently of any older deleted run on this archive.
  8104. archive.wallet_charge_skipped = False
  8105. # Persist before MQTT send so completion and restart recovery can
  8106. # always recover the internal billing identity.
  8107. await db.commit()
  8108. for cleanup_path in cleanup_disk_paths:
  8109. try:
  8110. if cleanup_path.exists():
  8111. cleanup_path.unlink()
  8112. except OSError as cleanup_err:
  8113. logger.warning(
  8114. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8115. json.dumps(
  8116. {
  8117. "queue_item_id": item.id,
  8118. "path": str(cleanup_path),
  8119. "error": str(cleanup_err),
  8120. },
  8121. sort_keys=True,
  8122. ),
  8123. )
  8124. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8125. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8126. # #1898: with the opt-in default-good setting, moving on to the next
  8127. # print resolves the previous print's unanswered outcome prompt as
  8128. # "good" — this path also covers the camera-based plate detection,
  8129. # which releases the gate by allowing dispatch rather than by an
  8130. # explicit acknowledgment. Rides on the dispatch transaction.
  8131. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8132. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8133. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8134. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8135. # Capture state before dispatch so the watchdog can detect whether the
  8136. # printer actually transitioned (#967). Also capture subtask_id so the
  8137. # watchdog can recognise "command landed but state hasn't flipped yet"
  8138. # on slow H2D transitions (#1078).
  8139. pre_status = printer_manager.get_status(item.printer_id)
  8140. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8141. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8142. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8143. # #1721: respect the user's explicit timelapse choice. The #1397
  8144. # force-on at dispatch was removed because it caused per-layer nozzle
  8145. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8146. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8147. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8148. # FINISH-state fallback — no need to force a video.
  8149. effective_timelapse = bool(item.timelapse)
  8150. # Nozzle-rack fallback (#2800). A job that never passed through the
  8151. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8152. # dispatches with no nozzle field at all and chooses for itself — which
  8153. # is how a print levelled on one hotend and then printed on another,
  8154. # millimetres above the plate. Derive the per-slot extruder assignment
  8155. # from the file being dispatched.
  8156. #
  8157. # Done here rather than at queue time because this is the first point
  8158. # that knows both the actual printer and the actual file: an item can
  8159. # be created without a printer (model-based assignment), reassigned
  8160. # afterwards, or have its file swapped for a G-code-injected copy just
  8161. # above. Every queue-creation path — the print dialog, a bulk library
  8162. # add, the webhook, a pipeline run — is covered by the one call.
  8163. # Skipped when the item already carries a Bambu Studio capture: that
  8164. # one wins downstream anyway, so reading the 3MF again would be work
  8165. # thrown away on every dispatch.
  8166. # Rack position resolution (#1784), tried before the #2800 fallback
  8167. # below because it can express what that one cannot: a plate wanting a
  8168. # *different* hotend off the rack per filament group. The position per
  8169. # group is the operator's pick — the 3MF states it nowhere, proven by
  8170. # sending one plate twice with different picks and finding the two
  8171. # files identical bar float noise — so it is resolved here against the
  8172. # rack as it stands right now, after the upload, not at queue time.
  8173. resolved_nozzle_mapping = None
  8174. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8175. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8176. if rack_plan is not None:
  8177. try:
  8178. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8179. except (json.JSONDecodeError, TypeError):
  8180. stored_choice = {}
  8181. logger.warning(
  8182. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8183. item.id,
  8184. item.nozzle_rack_choice,
  8185. )
  8186. # JSON object keys are strings; the groups are ints.
  8187. choice: dict[int, int] = {}
  8188. for key, value in (stored_choice or {}).items():
  8189. try:
  8190. choice[int(key)] = int(value)
  8191. except (TypeError, ValueError):
  8192. continue
  8193. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8194. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8195. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8196. )
  8197. if resolved_nozzle_mapping is None and choice:
  8198. # An explicit pick that no longer holds stops the print. The
  8199. # operator named a hotend; printing from a different one is
  8200. # how a plate gets levelled on one nozzle and drawn with
  8201. # another, millimetres above the bed. Nothing has been sent
  8202. # to the printer yet, so failing here costs only the upload.
  8203. # The file is already on the SD card by this point, and a
  8204. # 3MF left there is a phantom print waiting to be started
  8205. # from the touchscreen. Same cleanup the start_print
  8206. # failure path below does, for the same reason.
  8207. try:
  8208. await delete_file_async(
  8209. printer.ip_address,
  8210. printer.access_code,
  8211. remote_path,
  8212. printer_model=printer.model,
  8213. )
  8214. except Exception:
  8215. pass # Best-effort — don't fail the error handler
  8216. if not await self._fail_dispatch(
  8217. db,
  8218. item,
  8219. (
  8220. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8221. "Edit the item to choose another position."
  8222. ),
  8223. ):
  8224. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8225. return
  8226. logger.warning(
  8227. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8228. item.id,
  8229. printer.name,
  8230. rack_error,
  8231. choice,
  8232. [slot.get("id") for slot in live_rack],
  8233. )
  8234. await notification_service.on_queue_job_failed(
  8235. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8236. printer_id=printer.id,
  8237. printer_name=printer.name,
  8238. reason=item.error_message,
  8239. db=db,
  8240. )
  8241. try:
  8242. await ws_manager.send_queue_item_failed(
  8243. user_id=toast_uid,
  8244. queue_item_id=item.id,
  8245. printer_id=item.printer_id,
  8246. reason="nozzle_rack_pick_stale",
  8247. )
  8248. except Exception:
  8249. pass # Best-effort — don't fail the error handler
  8250. return
  8251. if resolved_nozzle_mapping is None:
  8252. # Nothing was picked and nothing could be assigned. Falls
  8253. # through to the #2800 path, which is what ran before this
  8254. # existed — strictly not worse than today.
  8255. logger.info(
  8256. "Queue item %s: no rack positions assignable (%s); falling back",
  8257. item.id,
  8258. rack_error,
  8259. )
  8260. else:
  8261. logger.info(
  8262. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8263. item.id,
  8264. resolved_nozzle_mapping,
  8265. rack_plan.slot_groups,
  8266. choice or "auto",
  8267. )
  8268. nozzle_slot_extruders = None
  8269. if (
  8270. not item.nozzle_mapping
  8271. and resolved_nozzle_mapping is None
  8272. and file_path is not None
  8273. and is_nozzle_rack_model(printer.model)
  8274. ):
  8275. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8276. if slot_extruders:
  8277. nozzle_slot_extruders = json.dumps(slot_extruders)
  8278. # Every filament this plate prints is on the external spool -> the print
  8279. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8280. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8281. # table", which is what held the reporter's P1S at Heatbed preheating
  8282. # for ten minutes before it gave up (#3087). The MQTT command builder
  8283. # already downgrades a mapping that is *only* external ([254]), but a
  8284. # multi-filament project pads the slots this plate does not print with
  8285. # -1 — BambuStudio's own convention — and down there a -1 is
  8286. # indistinguishable from a slot that never resolved, which must never be
  8287. # sent to the spool holder (#2589). Here the plate's filament list says
  8288. # which is which, so the answer is exact rather than a guess.
  8289. #
  8290. # Deliberately narrow: this fires only when every consumed slot is an
  8291. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8292. # alone and the firmware still rejects the print, exactly as today. And
  8293. # only for single-nozzle printers, mirroring the builder's own reconcile
  8294. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8295. # whether to use the AMS, so it is not ours to rewrite.
  8296. effective_use_ams = item.use_ams
  8297. if (
  8298. effective_use_ams
  8299. and ams_mapping
  8300. and file_path is not None
  8301. # Cheap gate before opening the file: with nothing on the spool
  8302. # holder anywhere in the mapping, no subset of it can be all
  8303. # external, so most dispatches never pay for the parse. The
  8304. # isinstance also keeps a malformed stored mapping (a bare number
  8305. # from a hand-edited row) failing where it always failed, in the
  8306. # command builder, rather than here.
  8307. and isinstance(ams_mapping, list)
  8308. and any(_is_external_tray(t) for t in ams_mapping)
  8309. and not _might_be_dual_nozzle(printer.model, pre_status)
  8310. ):
  8311. from backend.app.services.filament_requirements import extract_filament_requirements
  8312. consumed = _consumed_mapping_entries(
  8313. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8314. )
  8315. if consumed and all(_is_external_tray(t) for t in consumed):
  8316. effective_use_ams = False
  8317. logger.info(
  8318. "Queue item %s: every filament plate %s prints is on the external spool "
  8319. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8320. item.id,
  8321. effective_plate_id,
  8322. ams_mapping,
  8323. )
  8324. # A slot that lost its K-profile selection (a power cycle resets every
  8325. # slot to the default K) would print on the default. The idle check in
  8326. # the status handler normally restores it first, but nothing guarantees
  8327. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8328. # Never allowed to stop the print it is protecting.
  8329. try:
  8330. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8331. except Exception:
  8332. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8333. # Start the print with AMS mapping, plate_id and print options.
  8334. # nozzle_mapping rides through verbatim — JSON string captured from
  8335. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8336. # parses + injects it only for dual-nozzle models so a null on every
  8337. # other model is a transparent pass-through. The rack fallback is
  8338. # resolved down there too, where the live rack position is known.
  8339. started = printer_manager.start_print(
  8340. item.printer_id,
  8341. remote_filename,
  8342. plate_id=effective_plate_id,
  8343. ams_mapping=ams_mapping,
  8344. bed_levelling=item.bed_levelling,
  8345. flow_cali=item.flow_cali,
  8346. vibration_cali=item.vibration_cali,
  8347. layer_inspect=item.layer_inspect,
  8348. timelapse=effective_timelapse,
  8349. use_ams=effective_use_ams,
  8350. nozzle_offset_cali=item.nozzle_offset_cali,
  8351. nozzle_mapping=item.nozzle_mapping
  8352. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8353. nozzle_slot_extruders=nozzle_slot_extruders,
  8354. )
  8355. if started:
  8356. # The command is away, so the expectation is now legitimate and must
  8357. # survive. Anything still in this dict when _dispatch_one exits gets
  8358. # rolled back.
  8359. self._unconfirmed_expected_print.pop(item.id, None)
  8360. self._unconfirmed_budget_reservations.discard(item.id)
  8361. self._unconfirmed_print_user.pop(item.id, None)
  8362. if item.printer_id is not None:
  8363. self._sent_unstarted_print[item.id] = (
  8364. item.printer_id,
  8365. remote_filename if archive else None,
  8366. archive.id if archive else None,
  8367. )
  8368. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8369. # target, chamber target, airduct heating) — the gcode owns
  8370. # heater/flap control from here. Clearing the pin prevents
  8371. # `_dispatch_one`'s finally from unwinding a live print.
  8372. self._preheat_pin.pop(item.printer_id, None)
  8373. self._preheat_pin_bed.pop(item.printer_id, None)
  8374. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8375. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8376. # status='processing' from upload start until the printer acked
  8377. # (or timed out). The frontend derives "Awaiting printer…" purely
  8378. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8379. # event would push the status chip out of 'PROCESSING' prematurely
  8380. # — which is exactly what the screenshot at #1625-followup
  8381. # complained about.
  8382. # Register the local 3MF in the cover-cache so /cover skips FTP
  8383. # (#1166 follow-up). file_path was resolved earlier from either the
  8384. # archive or the library file row.
  8385. if file_path is not None:
  8386. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8387. # Hold the printer against further dispatches until the watchdog
  8388. # confirms the printer transitioned (or until the hard timeout).
  8389. # Prevents multi-plate batches from triple-dispatching onto the
  8390. # same H2D Pro while it digests the first project_file (#1157).
  8391. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8392. # Watchdog: if the printer never transitions out of pre_state AND
  8393. # never advances subtask_id, the MQTT publish was accepted locally but
  8394. # didn't reach the printer (half-broken session — same shape as
  8395. # #887/#936). Revert the queue item so the next dispatch can pick it
  8396. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8397. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8398. # that would otherwise cause the item to re-dispatch as a reprint
  8399. # of the just-finished job (#1078).
  8400. if pre_state:
  8401. spawn_background_task(
  8402. self._watchdog_print_start(
  8403. item.id,
  8404. item.printer_id,
  8405. pre_state,
  8406. pre_subtask_id,
  8407. pre_gcode_file,
  8408. created_by_id=toast_uid,
  8409. ),
  8410. name=f"watchdog-print-start-{item.id}",
  8411. )
  8412. # Get estimated time for notification.
  8413. #
  8414. # This used to fall back to `library_file.print_time_seconds`, a column
  8415. # LibraryFile does not have — the print time it knows about lives in
  8416. # `file_metadata`. So a library print whose archive carried no parseable
  8417. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8418. # AttributeError right here, *after* the printer had already been sent
  8419. # the job: the started-notification never fired, and the exception
  8420. # unwound the whole queue pass, so every other printer still waiting to
  8421. # be dispatched on that tick silently missed its turn.
  8422. #
  8423. # The queue item caches the print time at creation ("Cached from
  8424. # archive/library"), which is the value this was reaching for.
  8425. estimated_time = None
  8426. if archive and archive.print_time_seconds:
  8427. estimated_time = archive.print_time_seconds
  8428. elif item.print_time_seconds:
  8429. estimated_time = item.print_time_seconds
  8430. # Send job started notification
  8431. await notification_service.on_queue_job_started(
  8432. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8433. printer_id=printer.id,
  8434. printer_name=printer.name,
  8435. db=db,
  8436. estimated_time=estimated_time,
  8437. )
  8438. # MQTT relay - publish queue job started
  8439. try:
  8440. await mqtt_relay.on_queue_job_started(
  8441. job_id=item.id,
  8442. filename=filename,
  8443. printer_id=printer.id,
  8444. printer_name=printer.name,
  8445. printer_serial=printer.serial_number,
  8446. )
  8447. except Exception:
  8448. pass # Don't fail if MQTT fails
  8449. else:
  8450. # Clean up uploaded file from SD card to prevent phantom prints
  8451. try:
  8452. await delete_file_async(
  8453. printer.ip_address,
  8454. printer.access_code,
  8455. remote_path,
  8456. printer_model=printer.model,
  8457. )
  8458. except Exception:
  8459. pass # Best-effort — don't fail the error handler
  8460. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8461. # state can flip from idle to active in the window between the
  8462. # pre-dispatch check above and this publish (the FTP upload takes
  8463. # seconds); start_print() then refuses to send project_file to the
  8464. # now-busy printer and returns False. Failing the item here would be
  8465. # wrong — the printer is fine, it is simply busy — so revert to
  8466. # pending and let a later tick dispatch it once the printer is idle,
  8467. # exactly like the pre-dispatch guard. Only a start_print() False on
  8468. # an idle/unknown printer is a genuine command failure.
  8469. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8470. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8471. logger.info(
  8472. "Queue item %s: printer %s became busy (state=%s) before the start "
  8473. "command was sent — deferring, reverting item to pending (#2598)",
  8474. item.id,
  8475. item.printer_id,
  8476. post_dispatch_state,
  8477. )
  8478. await self._defer_until_printer_idle(db, item)
  8479. return
  8480. # Print command failed - revert status
  8481. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8482. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8483. return
  8484. logger.error(
  8485. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8486. f"printer_manager.start_print() returned False. "
  8487. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8488. f"Check printer status and backend logs for details."
  8489. )
  8490. # Send failure notification
  8491. await notification_service.on_queue_job_failed(
  8492. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8493. printer_id=printer.id,
  8494. printer_name=printer.name,
  8495. reason="Failed to send print command to printer - check printer connection and status",
  8496. db=db,
  8497. )
  8498. try:
  8499. await ws_manager.send_queue_item_failed(
  8500. user_id=toast_uid,
  8501. queue_item_id=item.id,
  8502. printer_id=item.printer_id,
  8503. reason="start_command_failed",
  8504. )
  8505. except Exception:
  8506. pass
  8507. await self._power_off_if_needed(db, item)
  8508. @staticmethod
  8509. async def _watchdog_print_start(
  8510. queue_item_id: int,
  8511. printer_id: int,
  8512. pre_state: str,
  8513. pre_subtask_id: str | None = None,
  8514. pre_gcode_file: str | None = None,
  8515. timeout: float = 90.0,
  8516. phase_b_timeout: float = 180.0,
  8517. poll_interval: float = 3.0,
  8518. created_by_id: int | None = None,
  8519. ) -> None:
  8520. """Revert a queue item if the printer never acknowledges the start command.
  8521. Bambuddy optimistically marks the queue item as "printing" right after the
  8522. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8523. Phase A (up to ``timeout``): wait for either an active-state transition
  8524. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8525. primary signal; subtask_id advance handles the H2D case where state can
  8526. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8527. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8528. was lost on a half-broken session (#887/#936) — revert and force
  8529. reconnect (the #967 recovery path).
  8530. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8531. alone): keep watching for the active-state transition. subtask_id alone
  8532. proves the file landed but not that the printer started — and a printer
  8533. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8534. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8535. used to leave the queue item stuck in 'printing' forever because the
  8536. old watchdog returned success as soon as subtask_id advanced. If Phase
  8537. B times out, revert the queue item so the user can retry without
  8538. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8539. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8540. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8541. transitions that also don't emit an early subtask_id tick.
  8542. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8543. refuses to verify our commands will never start this job or any other,
  8544. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8545. burns an upload slot the rest of the farm is queued behind — that path
  8546. is for a printer that might still come good, which this one cannot
  8547. (#2732). It fails the item on the spot with the actual reason instead.
  8548. """
  8549. last_status = None
  8550. landed_on_subtask = False
  8551. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8552. # every push carrying an `hms` key, so the fault can come and go between
  8553. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8554. command_rejected = False
  8555. # Latched for the same reason as command_rejected: drying can finish, or
  8556. # be stopped by the user, part-way through the dispatch window. Seeing it
  8557. # once is what matters — it is the state the printer was in when it
  8558. # declined to start (#2758).
  8559. drying_ams_ids: list[int] = []
  8560. deadline = time.monotonic() + timeout
  8561. while time.monotonic() < deadline:
  8562. await asyncio.sleep(poll_interval)
  8563. status = printer_manager.get_status(printer_id)
  8564. if not status:
  8565. # Printer disconnected — don't mess with the DB. Drop the
  8566. # in-memory dispatch hold too so a fresh dispatch can retry
  8567. # once the printer comes back; the hard timeout would
  8568. # otherwise hold the printer unnecessarily.
  8569. scheduler._release_dispatch_hold(printer_id)
  8570. return
  8571. last_status = status
  8572. if status.state in _ACTIVE_PRINT_STATES:
  8573. # Printer is actively processing the job — release the
  8574. # post-dispatch hold so the next pending item for this printer
  8575. # can be evaluated normally. We do NOT accept arbitrary state
  8576. # transitions: a printer going FINISH -> IDLE (user dismissed
  8577. # the post-print prompt without accepting our project_file)
  8578. # would otherwise look like "command landed" and leave the
  8579. # queue item stuck in 'printing' forever (#1370).
  8580. scheduler._release_dispatch_hold(printer_id)
  8581. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8582. try:
  8583. await ws_manager.send_queue_item_acked(
  8584. user_id=created_by_id,
  8585. queue_item_id=queue_item_id,
  8586. printer_id=printer_id,
  8587. )
  8588. except Exception:
  8589. pass
  8590. return
  8591. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8592. # Checked only after the active-state exit above: a stale HMS left
  8593. # over from an earlier job must never abort a print that is visibly
  8594. # running. An actually-refused command leaves the printer idle, so
  8595. # this ordering costs the detection nothing.
  8596. if _mqtt_commands_rejected(status):
  8597. command_rejected = True
  8598. break
  8599. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8600. # Phase A exit — printer accepted the file (subtask_id flipped
  8601. # to our submission id). Don't return yet: the printer may
  8602. # have accepted the command but never actually start (e.g.
  8603. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8604. # B watches for the active-state transition.
  8605. landed_on_subtask = True
  8606. break
  8607. if landed_on_subtask and not command_rejected:
  8608. phase_b_deadline = time.monotonic() + phase_b_timeout
  8609. while time.monotonic() < phase_b_deadline:
  8610. await asyncio.sleep(poll_interval)
  8611. status = printer_manager.get_status(printer_id)
  8612. if not status:
  8613. scheduler._release_dispatch_hold(printer_id)
  8614. return
  8615. last_status = status
  8616. if status.state in _ACTIVE_PRINT_STATES:
  8617. scheduler._release_dispatch_hold(printer_id)
  8618. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8619. try:
  8620. await ws_manager.send_queue_item_acked(
  8621. user_id=created_by_id,
  8622. queue_item_id=queue_item_id,
  8623. printer_id=printer_id,
  8624. )
  8625. except Exception:
  8626. pass
  8627. return
  8628. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8629. # Same ordering rule as Phase A: a running print wins over a
  8630. # lingering HMS.
  8631. if _mqtt_commands_rejected(status):
  8632. command_rejected = True
  8633. break
  8634. # No active-state transition. Revert the item so the scheduler can retry.
  8635. # Drop the in-memory hold so the retry isn't blocked by it.
  8636. scheduler._release_dispatch_hold(printer_id)
  8637. # Logged on every failed dispatch window, not just the last one, so a
  8638. # support bundle shows the correlation from the first attempt rather than
  8639. # only after the retry budget is spent (#2758).
  8640. if drying_ams_ids:
  8641. logger.info(
  8642. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8643. queue_item_id,
  8644. printer_id,
  8645. ", ".join(str(i) for i in drying_ams_ids),
  8646. )
  8647. # Four outcomes from the revert attempt, each routed differently:
  8648. # "reverted": row flipped from printing -> pending, run recovery
  8649. # "gave_up": same, but the retry budget is spent — row failed
  8650. # rather than pending, so it stops going round again
  8651. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8652. # on_print_complete or user). Skip recovery entirely
  8653. # — the print clearly landed somewhere even if the
  8654. # watchdog didn't see the active-state transition.
  8655. # "revert_failed": SQLite contention exhausted retries. Still run
  8656. # recovery so the MQTT session gets a fresh client_id
  8657. # on the half-broken-session path.
  8658. #
  8659. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8660. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8661. # the watchdog again. For a printer that is genuinely wedged that loop never
  8662. # ends — the reporter had one printer "since this morning still not launch"
  8663. # — and each lap also consumes an upload slot that the other printers in the
  8664. # farm are waiting on. Retrying is right; retrying forever is not.
  8665. async def _do_revert(db):
  8666. item = await db.get(PrintQueueItem, queue_item_id)
  8667. if not item or item.status != "printing":
  8668. return "already_moved_on"
  8669. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8670. item.started_at = None
  8671. # Charge the attempt to the candidate that was actually dispatched, so
  8672. # a cross-model item (#671) reaches for its other file next lap instead
  8673. # of retrying the printer that just failed to start. Matched by file
  8674. # because that is what the resolver copied onto the row.
  8675. if item.library_file_id is not None:
  8676. await db.execute(
  8677. update(PrintQueueVariant)
  8678. .where(PrintQueueVariant.queue_item_id == item.id)
  8679. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8680. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8681. )
  8682. if command_rejected:
  8683. # No retry budget for this one: the printer refused to verify the
  8684. # command, and re-uploading the same 3MF to the same printer will
  8685. # be refused the same way. Fail now with the fix rather than after
  8686. # three laps of a message about SD cards (#2732).
  8687. item.status = "failed"
  8688. item.error_message = (
  8689. "The printer rejected the print command: MQTT command verification failed "
  8690. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8691. "then start the job again."
  8692. )
  8693. item.completed_at = datetime.now(timezone.utc)
  8694. await db.commit()
  8695. return "command_rejected"
  8696. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8697. item.status = "failed"
  8698. if drying_ams_ids:
  8699. # #2758: the generic message below sent the reporter looking
  8700. # at the SD card while the actual obstacle — AMS units in a
  8701. # drying cycle — was on screen the whole time. Name what we
  8702. # observed and let the user judge it; Bambuddy does not stop
  8703. # the cycle itself, because on this hardware drying can run
  8704. # alongside a print and stopping it may not be the fix.
  8705. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8706. item.error_message = (
  8707. f"The printer accepted the file but never started printing, after "
  8708. f"{item.dispatch_attempts} attempts. {units} "
  8709. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8710. f"some printers refuse to begin a print while an AMS is in a drying "
  8711. f"cycle, and an AMS drying without its external power supply can also "
  8712. f"leave too little power for the start-of-print calibration. Stop the "
  8713. f"drying, or connect the AMS power supply, and start the job again."
  8714. )
  8715. else:
  8716. item.error_message = (
  8717. f"The printer accepted the file but never started printing, after "
  8718. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8719. f"prompt or error, confirm its SD card is readable, and start the job again."
  8720. )
  8721. item.completed_at = datetime.now(timezone.utc)
  8722. await release_budget_reservation(
  8723. db,
  8724. source_type="print_queue",
  8725. source_id=item.id,
  8726. status="released",
  8727. )
  8728. await db.commit()
  8729. return "gave_up"
  8730. item.status = "pending"
  8731. await db.commit()
  8732. return "reverted"
  8733. try:
  8734. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8735. except Exception as e:
  8736. logger.warning(
  8737. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8738. "scheduler may keep treating this item as in-flight",
  8739. queue_item_id,
  8740. printer_id,
  8741. e,
  8742. )
  8743. revert_outcome = "revert_failed"
  8744. if revert_outcome in ("command_rejected", "gave_up"):
  8745. # The item is failed: its print user and expected print must not
  8746. # pass the printer's next print off as Bambuddy's.
  8747. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  8748. from backend.app.services.print_batch import refresh_batches_after
  8749. await refresh_batches_after([queue_item_id])
  8750. elif revert_outcome == "reverted":
  8751. # Another try claims the printer again. Until then no print on it
  8752. # is vouched for as this item's, except a late start of its file.
  8753. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  8754. elif revert_outcome == "already_moved_on":
  8755. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8756. if revert_outcome == "already_moved_on":
  8757. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8758. # other path) already moved the item past 'printing', don't run the
  8759. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8760. # session breaks ongoing prints on the same printer.
  8761. return
  8762. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8763. if revert_outcome == "command_rejected":
  8764. logger.error(
  8765. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8766. "failed) — the print command was rejected, not lost. Failing the item "
  8767. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8768. queue_item_id,
  8769. printer_id,
  8770. HMS_MQTT_VERIFY_FAILED,
  8771. )
  8772. await scheduler._notify_dispatch_gave_up(
  8773. queue_item_id,
  8774. printer_id,
  8775. created_by_id,
  8776. reason="Printer rejected the print command (MQTT command verification failed)",
  8777. )
  8778. # Same reasoning as the landed_on_subtask path below: the file is on
  8779. # the printer and a forced reconnect would only add 0500_4003 to a
  8780. # problem that has nothing to do with the MQTT session (#1150).
  8781. return
  8782. if revert_outcome == "gave_up":
  8783. logger.error(
  8784. "Queue item %s: printer %d never started the print after %d dispatch "
  8785. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8786. "re-uploading it again (#2555)",
  8787. queue_item_id,
  8788. printer_id,
  8789. DISPATCH_MAX_ATTEMPTS,
  8790. total_timeout,
  8791. )
  8792. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8793. elif revert_outcome == "reverted":
  8794. if landed_on_subtask:
  8795. logger.warning(
  8796. "Queue item %s: printer %d accepted project_file (subtask_id "
  8797. "advanced) but never transitioned to an active state within "
  8798. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8799. "for retry (#1678)",
  8800. queue_item_id,
  8801. printer_id,
  8802. total_timeout,
  8803. )
  8804. else:
  8805. logger.warning(
  8806. "Queue item %s: printer %d did not respond to print command within "
  8807. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8808. "for retry (#967)",
  8809. queue_item_id,
  8810. printer_id,
  8811. timeout,
  8812. pre_state,
  8813. pre_subtask_id,
  8814. )
  8815. # Phase B was entered iff subtask_id advanced, which means the
  8816. # project_file landed on the printer. A forced reconnect at this point
  8817. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8818. # skip the recovery entirely.
  8819. if landed_on_subtask:
  8820. return
  8821. # Phase A timeout path: if the printer's gcode_file changed since
  8822. # pre-dispatch, the project_file command landed and the printer is
  8823. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8824. # If gcode_file is unchanged, the publish was silently swallowed
  8825. # (#887/#936) and force_reconnect recovery is what we want.
  8826. client = printer_manager.get_client(printer_id)
  8827. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8828. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8829. if publish_landed:
  8830. logger.warning(
  8831. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8832. "received the command and is parsing slowly. Skipping forced "
  8833. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8834. queue_item_id,
  8835. current_gcode_file,
  8836. pre_gcode_file,
  8837. )
  8838. elif client and hasattr(client, "force_reconnect_stale_session"):
  8839. client.force_reconnect_stale_session(
  8840. f"queue print command unacknowledged after {timeout:.0f}s "
  8841. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8842. )
  8843. # Global scheduler instance
  8844. scheduler = PrintScheduler()