print_scheduler.py 496 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786
  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.smart_plug_manager import publish_plug_state, smart_plug_manager
  65. from backend.app.services.spool_assignment_notifications import (
  66. _global_tray_from_assignment,
  67. _slot_label_from_global_tray,
  68. )
  69. from backend.app.utils.ams_drying import is_countdown_parked
  70. from backend.app.utils.ams_humidity import ams_humidity_percent
  71. from backend.app.utils.archive_paths import archive_photos_dir
  72. from backend.app.utils.color_utils import perceptual_color_distance
  73. from backend.app.utils.filament_types import canonical_filament_type
  74. from backend.app.utils.filename import derive_remote_filename
  75. from backend.app.utils.library_paths import move_library_photos
  76. from backend.app.utils.local_time import utcnow_naive
  77. from backend.app.utils.printer_models import (
  78. is_dual_nozzle_model,
  79. is_gcode_compatible,
  80. is_nozzle_rack_model,
  81. normalize_printer_model,
  82. )
  83. from backend.app.utils.threemf_tools import (
  84. default_plate_number,
  85. extract_rack_plan_from_3mf,
  86. extract_slot_extruders_from_3mf,
  87. select_plate_gcode_name,
  88. )
  89. logger = logging.getLogger(__name__)
  90. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  91. """Human slot name for an assignment tuple, in the spelling already in use.
  92. Composed from the notification side's own pair rather than spelled out again
  93. here. The hand-rolled version this replaces got three real slot kinds wrong:
  94. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  95. ``chr(191)``; both externals collapsed to one label, because an external
  96. assignment stores ams_id 255 with tray_id picking left or right
  97. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  98. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  99. Naming the same slot two ways is its own defect once an alert and the
  100. Inventory page are meant to be talking about the same tray, so this defers
  101. rather than adding a fifth spelling.
  102. """
  103. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  104. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  105. # interval: the fast path runs every 3 s while an upload is in flight, and a
  106. # low spool does not need answering at that resolution (#2913).
  107. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  108. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  109. # days, so a finer check would only repeat the same answer.
  110. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  111. # The settings row that holds which stock alerts have already been sent (#2955).
  112. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  113. # The Inventory page asks for this many usage records and the forecast panel
  114. # builds its rates from them; the alert reads the same window so the two agree.
  115. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  116. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  117. """Remaining filament as a percentage of the label weight.
  118. The same arithmetic the Inventory page's Low Stock count uses, and it works
  119. unchanged in both inventory modes: internal spools store ``weight_used``
  120. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  121. ``remaining_weight`` so the shape matches. Returns None when there is no
  122. label weight to be a percentage of -- a spool that cannot say how full it
  123. started cannot say how empty it is.
  124. """
  125. if not label_weight or label_weight <= 0:
  126. return None
  127. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  128. return remaining / float(label_weight) * 100.0
  129. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  130. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  131. # byte gate) from before the scheduler unification. Time gate keeps small
  132. # files from going silent (a single 8 KB chunk fires once and that's it);
  133. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  134. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  135. # sub-200 ms files.
  136. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  137. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  138. # How far back chamber temperature samples are retained. 2h comfortably spans
  139. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  140. # before the next print.
  141. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  142. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  143. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  144. # who clear plates promptly will want far less than this; it is deliberately
  145. # the cautious end, since the cost of it being too short is only a re-soak.
  146. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  147. # Max acceptable gap between two consecutive chamber samples before we treat
  148. # the older one as belonging to a separate observation run (printer went
  149. # offline and came back). Above ~30s cadence with a safety margin.
  150. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  151. # How long the chamber must read below target before we accept that it really
  152. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  153. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  154. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  155. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  156. # sub-target readings are therefore a door opening or noise, not lost soak,
  157. # and a plate swap (exactly when keep-warm is running) produces one. Six
  158. # minutes clears the longest such artifact observed (~5 min once bracketed by
  159. # its neighbouring samples) and still sits far below the 23-minute floor for
  160. # real cooling.
  161. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  162. # How often the preheat stage re-checks that the item it is heating for still
  163. # wants to be printed. Cancelling only writes `status` to the database — it
  164. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  165. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  166. # and the printer stays in `busy_printers`, blocking every other queued item
  167. # behind a print that is not happening.
  168. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  169. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  170. _AIRDUCT_MODE_COOLING = 0
  171. _AIRDUCT_MODE_HEATING = 1
  172. # How long a queue row may stay 'printing' while its printer sits in a terminal
  173. # state before the scheduler closes it itself (#2829).
  174. #
  175. # A real completion arrives within seconds of the printer going terminal, so
  176. # five minutes is far outside the normal path — this only ever sees a row whose
  177. # completion was refused or never delivered. It is the whole cost of the
  178. # failure to the user, though: a stranded row blocks every later job for that
  179. # printer, so it should not be raised without reason.
  180. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  181. # gcode_state values that mean the print is over, mapped to the queue status
  182. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  183. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  184. # which the queue calls cancelled) so a recovered row cannot disagree with one
  185. # closed by the normal path.
  186. _TERMINAL_STATE_QUEUE_STATUS = {
  187. "FINISH": "completed",
  188. "FAILED": "failed",
  189. "IDLE": "cancelled",
  190. }
  191. def _terminal_queue_status(state) -> str | None:
  192. """Queue status implied by *state*, or None if the print is not over.
  193. None for a disconnected printer as well as a busy one: a printer we are not
  194. talking to has a stale ``state`` field that proves nothing about what it is
  195. doing now.
  196. """
  197. if state is None or not getattr(state, "connected", False):
  198. return None
  199. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  200. @dataclass
  201. class _KeepWarmEntry:
  202. """Per-printer keep-warm state.
  203. - ``started``: monotonic time when keep-warm first fired for this printer.
  204. Used by the max-duration timeout.
  205. - ``held_target``: last bed target we successfully published. On release
  206. we only send bed-off when firmware still reports this value, so a user
  207. or subsequent print that changed the target isn't clobbered.
  208. - ``expired``: latched True when the max-duration timeout fires. Prevents
  209. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  210. release sweep drops the entry entirely once the printer leaves the
  211. candidate set.
  212. """
  213. started: float
  214. held_target: int
  215. expired: bool = False
  216. # Auto-drying re-arm guards (#2770).
  217. #
  218. # An AMS reports HIGHER relative humidity while it is warm than once it has
  219. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  220. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  221. # threshold set inside that band therefore cannot be satisfied while the box is
  222. # hot, and the firmware is free to end a cycle whenever it decides the filament
  223. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  224. # the threshold and arms another cycle. The reporter's log has five 12-hour
  225. # cycles armed inside four hours, one of them six seconds after the previous
  226. # ended.
  227. #
  228. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  229. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  230. # manual or firmware-run dry is untouched.
  231. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  232. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  233. # Sustained-humidity wait (#2518): an above-threshold streak is only
  234. # "continuous" if some pass observed it within the gap ceiling. A unit that
  235. # goes unobserved longer (print running, printer disconnected, sensor silent)
  236. # restarts its streak rather than inheriting a stale one. The ceiling is
  237. # derived from the scheduler cadence — four missed passes — with this floor so
  238. # a fast-polling configuration does not void streaks on a single hiccup.
  239. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  240. # How long a finished scheduled drying row is kept before it is pruned.
  241. SCHEDULED_DRYING_RETENTION_DAYS = 7
  242. # How often that prune actually runs. The check itself is called on every queue
  243. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  244. # write transaction, which SQLite serialises against every other writer. Rows
  245. # only become prunable a week after they finish, so anything short of hourly is
  246. # paying that cost for nothing.
  247. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  248. class _UploadProgressBridge:
  249. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  250. ``upload_file_async`` runs the FTP transfer in an executor thread and
  251. invokes its ``progress_callback`` from that thread, so the callback
  252. body cannot ``await`` directly. This bridge captures the asyncio loop
  253. at construction (on the scheduler thread) and uses
  254. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  255. matches the legacy background_dispatch.py path 1:1 so the toast feels
  256. identical to the pre-#1625 experience.
  257. Failures inside the emit are swallowed — progress is a UX nicety, the
  258. upload itself must not fail because of a WS hiccup.
  259. """
  260. def __init__(self, user_id: int | None, queue_item_id: int):
  261. self._user_id = user_id
  262. self._queue_item_id = queue_item_id
  263. try:
  264. self._loop = asyncio.get_running_loop()
  265. except RuntimeError:
  266. self._loop = None
  267. self._last_emit_bytes = 0
  268. self._last_emit_monotonic = 0.0
  269. self._has_emitted = False
  270. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  271. if self._loop is None or total_bytes <= 0:
  272. return
  273. now = time.monotonic()
  274. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  275. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  276. # the four matter most: first-call so the user sees something even
  277. # for sub-chunk-size files; uploaded >= total so the bar locks at
  278. # 100% even when the throttle would otherwise eat it.
  279. should_emit = (
  280. not self._has_emitted
  281. or bytes_transferred >= total_bytes
  282. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  283. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  284. )
  285. if not should_emit:
  286. return
  287. self._has_emitted = True
  288. self._last_emit_bytes = bytes_transferred
  289. self._last_emit_monotonic = now
  290. try:
  291. asyncio.run_coroutine_threadsafe(
  292. ws_manager.send_queue_item_upload_progress(
  293. user_id=self._user_id,
  294. queue_item_id=self._queue_item_id,
  295. bytes_transferred=bytes_transferred,
  296. total_bytes=total_bytes,
  297. ),
  298. self._loop,
  299. )
  300. except Exception:
  301. pass # progress is best-effort, never block the upload
  302. # Bambu firmware states that mean the project_file has actually been accepted
  303. # and the printer is now processing / running / paused mid-print. Used by the
  304. # dispatch watchdog (#1370): a transition into one of these states means the
  305. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  306. # a post-print prompt) is NOT a valid "command landed" signal even though the
  307. # state value did change. SLICING is included because some firmwares park
  308. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  309. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  310. # How many times the start-watchdog may revert an item to 'pending' before it
  311. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  312. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  313. # both never recovers and starves the other printers of dispatch slots. Three
  314. # is chosen to clear the transient causes the watchdog already recovers from —
  315. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  316. # force-reconnect on the very next attempt — while still bounding the loop.
  317. DISPATCH_MAX_ATTEMPTS = 3
  318. # Upload failures that mean the file never reached the printer's storage: the
  319. # file service refused or never answered (#3210). These put the item back in
  320. # the queue instead of failing it, because nothing about the job is wrong --
  321. # and failing it left the printer idle, so the next pass handed it the next
  322. # item, which failed the same way. One P2S whose file service was out of
  323. # connection slots ate 43 queued jobs in ten minutes that way.
  324. #
  325. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  326. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  327. # and an upload that overran its deadline -- each of those would fail the same
  328. # way on every retry.
  329. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  330. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  331. )
  332. # How long a printer whose upload was put back stays out of dispatch (#3210).
  333. # The first window matches the FTP client's own handshake cool-off, so the
  334. # retry lands after the client would talk to the printer again anyway. Each
  335. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  336. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  337. # five connection attempts and a page of log. A successful upload resets it.
  338. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  339. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  340. def _upload_backoff_seconds(refusals: int) -> int:
  341. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  342. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  343. @dataclass(slots=True)
  344. class _ModelCandidate:
  345. """One (file, printer model) pair the model-based matcher may try.
  346. Model-based assignment used to have exactly one of these per item, held
  347. directly in the item's own columns. Cross-model queue items (#671) have
  348. several, held in ``print_queue_variants``. Both shapes are normalised into
  349. this so the matching, the cross-model gate and the waiting-reason handling
  350. are written once and an item without variants provably takes the same path
  351. it took before variants existed.
  352. ``variant`` is None for the item's own columns and set for a real variant
  353. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  354. item once that candidate wins.
  355. """
  356. target_model: str | None
  357. sliced_for: str | None
  358. required_filament_types: str | None
  359. filament_overrides: str | None
  360. variant: "PrintQueueVariant | None" = None
  361. def _sliced_for_model(archive, library_file) -> str | None:
  362. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  363. if archive is not None:
  364. return archive.sliced_for_model
  365. if library_file is not None and library_file.file_metadata:
  366. return library_file.file_metadata.get("sliced_for_model")
  367. return None
  368. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  369. """The filament a candidate needs, as ``(types, overrides)``.
  370. Both columns are JSON text written by the slicer step. Malformed content is
  371. treated as no constraint rather than as an error: a job whose overrides
  372. cannot be parsed still prints, it just gets no filament-based narrowing.
  373. Overrides carry their own types, so the returned type list is the union of
  374. the two — an override on one slot must not drop the requirements of the
  375. slots it says nothing about.
  376. Shared by the matcher and by the smart-plug wake step so both ask a printer
  377. for the same filament (#2876). Waking a printer the matcher would then
  378. reject on colour is the bug this exists to prevent.
  379. """
  380. required_types = None
  381. if candidate.required_filament_types:
  382. try:
  383. required_types = json.loads(candidate.required_filament_types)
  384. except json.JSONDecodeError:
  385. pass
  386. filament_overrides = None
  387. if candidate.filament_overrides:
  388. try:
  389. filament_overrides = json.loads(candidate.filament_overrides)
  390. except json.JSONDecodeError:
  391. pass
  392. effective_types = required_types
  393. if filament_overrides:
  394. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  395. if override_types:
  396. effective_types = sorted(set(required_types or []) | set(override_types))
  397. return effective_types, filament_overrides
  398. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  399. """Whether ``item`` was competing for the printer another item just took.
  400. The SJF starvation guard marks a job as jumped when a shorter one lower in
  401. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  402. compete for the same printer, so the guard has to look across both lanes
  403. (#3200); looking only inside the dispatched item's own lane let a stream of
  404. short model-based jobs hold a longer pinned job back indefinitely.
  405. Location filters are not checked: over-marking only lifts an item that was
  406. going to wait anyway, while under-marking is the starvation this prevents.
  407. """
  408. if item.printer_id is not None:
  409. return item.printer_id == printer_id
  410. if not printer_model:
  411. return False
  412. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  413. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  414. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  415. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  416. """Candidate files for ``item``, best first.
  417. An item with no variant rows yields exactly one candidate built from its own
  418. columns — the pre-#671 behaviour, unchanged.
  419. Variants come back least-attempted first, ties broken by the user's
  420. ``position``. On the first pass every count is zero, so this is purely the
  421. user's priority order. After a start-watchdog bounce the printer that failed
  422. drops behind, so the next lap tries the other machine rather than spending the
  423. item's whole retry budget on the one that is wedged. Once every candidate has
  424. been tried equally often they cycle again, which keeps the item-level
  425. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  426. still gives up, it just does not give up without trying them.
  427. """
  428. if not item.variants:
  429. if not item.archive_id and not item.library_file_id:
  430. # Nothing to print at all. Dispatching would fail deep in the upload
  431. # on "No archive_id or library_file_id"; the caller holds the item
  432. # with an explanation instead.
  433. return []
  434. return [
  435. _ModelCandidate(
  436. target_model=item.target_model,
  437. sliced_for=_sliced_for_model(item.archive, item.library_file),
  438. required_filament_types=item.required_filament_types,
  439. filament_overrides=item.filament_overrides,
  440. )
  441. ]
  442. # Drop candidates whose file is gone or in the trash. Both are reachable and
  443. # neither is covered by the schema: library deletes are soft (the row lives
  444. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  445. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  446. # fires there and a hard delete leaves the variant row pointing at nothing.
  447. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  448. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  449. return [
  450. _ModelCandidate(
  451. target_model=v.target_model,
  452. sliced_for=_sliced_for_model(None, v.library_file),
  453. required_filament_types=v.required_filament_types,
  454. filament_overrides=v.filament_overrides,
  455. variant=v,
  456. )
  457. for v in ordered
  458. ]
  459. # Why a job for any printer of a model waits when every free one's last print
  460. # failed. The queue page matches it to offer Resume for the model.
  461. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  462. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  463. """Fold one waiting reason per candidate into a single line for the item.
  464. A cross-model item produces a reason per candidate, and pasting them
  465. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  466. — on which machine?). Each reason is prefixed with its model, except in the
  467. single-candidate case where the item already displays its target model and
  468. the prefix would be noise.
  469. Identical reasons collapse rather than repeat, so three idle-less models
  470. read as one clause.
  471. When *every* candidate is merely busy the parts are joined with the ``" | "``
  472. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  473. unprefixed. That case must keep testing busy-only: a fleet that is simply
  474. printing needs no user action, and labelling the clauses would turn each pass
  475. over a two-model item into a "job waiting" notification.
  476. """
  477. reasons = [(model, reason) for model, reason in per_model if reason]
  478. if not reasons:
  479. return None
  480. if len(reasons) == 1:
  481. return reasons[0][1]
  482. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  483. if len(distinct) == 1:
  484. return distinct[0]
  485. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  486. return " | ".join(distinct)
  487. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  488. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  489. """Human label for the models an item is waiting on ("H2S or H2C").
  490. Notifications take a single target model. For a cross-model item the item's
  491. own ``target_model`` is whichever variant happens to be first, which reads as
  492. a lie once it is the H2C that actually runs — so name all of them.
  493. """
  494. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  495. if not models:
  496. return None
  497. return " or ".join(models)
  498. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  499. """True if ``mapping`` is a non-empty list whose every entry is the
  500. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  501. Such a mapping is a bug artifact: a frontend status-load race can serialize
  502. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  503. recomputed from live status at dispatch rather than trusted, otherwise it
  504. reaches the print command and is silently downgraded to external-spool mode.
  505. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  506. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  507. explicit external selection (``>= 254``) is NOT unresolved either — those
  508. keep their meaning.
  509. """
  510. if not isinstance(mapping, list) or not mapping:
  511. return False
  512. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  513. def _is_tray_id(value: object) -> bool:
  514. """True when ``value`` can be read as a global tray ID.
  515. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  516. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  517. against whatever happens to be loaded there.
  518. """
  519. return isinstance(value, int) and not isinstance(value, bool)
  520. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  521. # stages an item (#2799). The manual_start branch clears every other reason on
  522. # a staged item (#3074); this one is the reason it was staged, so it stays.
  523. _UNMATCHED_HOLD_PREFIX = "Needs "
  524. # How often an "any model" job held for low filament looks for another printer
  525. # of its model that has enough (#3137). Each look matches its filament on every
  526. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  527. _SHORT_HOLD_RECHECK_SECONDS = 120
  528. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  529. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  530. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  531. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  532. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  533. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  534. for a filament this plate does not use. A slot past the end of the mapping
  535. is unresolved too.
  536. """
  537. unresolved = []
  538. for req in required:
  539. slot_id = req.get("slot_id") or 0
  540. if slot_id <= 0:
  541. continue
  542. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  543. if not _is_tray_id(tray) or tray < 0:
  544. unresolved.append(req)
  545. return unresolved
  546. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  547. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  548. # on `_mapping_is_all_unresolved`.
  549. _EXTERNAL_TRAY_ID_MIN = 254
  550. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  551. """The ``mapping`` entries for the slots this plate actually prints.
  552. ``required`` comes from ``extract_filament_requirements``, which drops any
  553. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  554. consumes, and one absent from it is padding. That distinction is why this
  555. decision lives here and not in the MQTT command builder: a ``-1`` in the
  556. mapping means either "this plate does not print filament N" or "we never
  557. worked out which tray", and only the plate's own filament list separates
  558. them. The builder sees both as the same byte, which is how a plate whose one
  559. printed filament sat on the external spool went out as `use_ams=true` with a
  560. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  561. with 07FF_8012 (#3087).
  562. Returns None whenever the two cannot be lined up — no mapping, no parsed
  563. requirements, or a requirement the mapping is too short to cover — so every
  564. caller falls back to existing behaviour rather than acting on a guess.
  565. """
  566. if not isinstance(mapping, list) or not mapping or not required:
  567. return None
  568. entries = []
  569. for filament in required:
  570. slot_id = filament.get("slot_id")
  571. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  572. # The mapping and the requirements disagree about how many filaments
  573. # the file has. They came from different reads, so judge nothing.
  574. return None
  575. entries.append(mapping[slot_id - 1])
  576. return entries or None
  577. def _is_external_tray(tray_id) -> bool:
  578. """True for an explicit external-spool selection (254/255), not for an
  579. unresolved slot and not for an AMS tray."""
  580. if tray_id is None:
  581. return False
  582. try:
  583. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  584. except (TypeError, ValueError):
  585. return False
  586. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  587. """Whether this printer could have two extruders, judged generously.
  588. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  589. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  590. why the MQTT command builder skips its own use_ams reconcile there. Anything
  591. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  592. with, external spools or not.
  593. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  594. behaviour it has always had, while a wrong "no" would rewrite a field that
  595. steers which nozzle prints. The model name is the first answer (it is what
  596. the command builder falls back to as well), then the same live evidence the
  597. dispatcher's extruder annotation uses — a second nozzle reporting a
  598. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  599. since a single-nozzle printer has exactly one.
  600. """
  601. if is_dual_nozzle_model(printer_model):
  602. return True
  603. nozzles = getattr(status, "nozzles", None) or []
  604. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  605. return True
  606. raw = getattr(status, "raw_data", None) or {}
  607. if raw.get("ams_extruder_map"):
  608. return True
  609. vt_trays = raw.get("vt_tray") or []
  610. return isinstance(vt_trays, list) and len(vt_trays) > 1
  611. def _int_or(value, default: int) -> int:
  612. """``int(value)``, or ``default`` when the field is missing or junk.
  613. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  614. the next — and a tray id that fails to parse must not take the whole
  615. derivation down with it.
  616. """
  617. try:
  618. return int(value)
  619. except (TypeError, ValueError):
  620. return default
  621. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  622. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  623. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  624. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  625. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  626. agree or a mapping cannot be read back against live tray telemetry.
  627. """
  628. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  629. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  630. """The global tray ids ``item`` actually prints from, or None if unknown.
  631. ``ams_mapping`` is the array the print command carries: position = filament
  632. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  633. not use. None means "no usable statement" — no mapping, unparseable JSON,
  634. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  635. documents), or one that resolves to no tray at all. Callers must treat None
  636. as "consider every loaded tray" rather than "consider none": narrowing on
  637. an absent mapping would silently drop requirements the print really has.
  638. """
  639. raw = getattr(item, "ams_mapping", None)
  640. if not raw:
  641. return None
  642. if isinstance(raw, str):
  643. try:
  644. mapping = json.loads(raw)
  645. except (json.JSONDecodeError, TypeError):
  646. return None
  647. else:
  648. mapping = raw
  649. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  650. return None
  651. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  652. return used or None
  653. def _mqtt_commands_rejected(status) -> bool:
  654. """True when the printer is currently reporting that it refused a command.
  655. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  656. a control command it could not verify. Queries still answer, so the printer
  657. looks connected and idle while project_file, gcode_line and
  658. ams_change_filament are all dropped — no amount of waiting or re-uploading
  659. changes that (#2732).
  660. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  661. ``print_error`` path builds HMSError differently), so this is safe to call on
  662. every watchdog poll.
  663. """
  664. for err in getattr(status, "hms_errors", None) or []:
  665. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  666. return True
  667. return False
  668. def _drying_ams_ids(status) -> list[int]:
  669. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  670. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  671. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  672. started (#2758) — it is a diagnostic, not a gate.
  673. Deliberately not used to block or stop drying before dispatch. This printer
  674. class supports drying concurrently with an active print
  675. (``supports_drying_while_printing``), so drying is not incompatible with
  676. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  677. while two AMS units were drying, one of them without its external PSU. Until
  678. it is known whether the blocker is drying itself or the power budget
  679. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  680. hardware is perfectly happy to continue.
  681. """
  682. ids: list[int] = []
  683. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  684. if not isinstance(unit, dict):
  685. continue
  686. try:
  687. if int(unit.get("dry_time") or 0) > 0:
  688. ids.append(int(unit.get("id", 0)))
  689. except (TypeError, ValueError):
  690. continue
  691. return ids
  692. def _parse_diameter(raw) -> float | None:
  693. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  694. try:
  695. value = float(raw)
  696. except (TypeError, ValueError):
  697. return None
  698. return value if value > 0 else None
  699. def _nozzle_info_by_id(status) -> dict[int, dict]:
  700. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  701. The field name is historical: on the H2 series ``nozzle_info`` carries an
  702. entry for *every* nozzle the printer knows about — the L/R hotends under
  703. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  704. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  705. :func:`_installed_nozzle_diameters` each take the half they need.
  706. """
  707. by_id: dict[int, dict] = {}
  708. for entry in getattr(status, "nozzle_rack", None) or []:
  709. if not isinstance(entry, dict):
  710. continue
  711. try:
  712. by_id[int(entry.get("id"))] = entry
  713. except (TypeError, ValueError):
  714. continue
  715. return by_id
  716. # What the firmware puts in a nozzle's serial number when the carriage or dock
  717. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  718. # its nozzle back in the rack (#2885).
  719. _EMPTY_NOZZLE_SERIAL = "N/A"
  720. def _nozzle_is_mounted(entry: dict | None) -> bool:
  721. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  722. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  723. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  724. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  725. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  726. the dock. So the diameter is not a presence signal (#2885).
  727. Emptiness has to be stated, not merely unstated. The serial must be the
  728. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  729. absent — an empty serial only means the printer didn't say, and a firmware
  730. that reports neither field normalises to exactly that. Treating "didn't
  731. say" as "empty" would silently switch the #1899 guard off on any such
  732. machine, so everything we cannot positively call empty counts as mounted.
  733. """
  734. if entry is None:
  735. return True
  736. serial = str(entry.get("serial_number") or "").strip().upper()
  737. if serial != _EMPTY_NOZZLE_SERIAL:
  738. return True
  739. try:
  740. max_temp = float(entry.get("max_temp") or 0)
  741. except (TypeError, ValueError):
  742. return True
  743. return max_temp > 0
  744. def _installed_nozzle_diameters(status) -> list[float]:
  745. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  746. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  747. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  748. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  749. told us its nozzle hardware" — callers must treat that as unknown, not as a
  750. mismatch, so we never block a print on missing data.
  751. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  752. though ``nozzles`` still carries a diameter for it: that value is stale, and
  753. counting it would let a slice match a nozzle the machine does not have
  754. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  755. """
  756. info = _nozzle_info_by_id(status)
  757. diameters: list[float] = []
  758. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  759. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  760. try:
  761. value = float(raw)
  762. except (TypeError, ValueError):
  763. continue
  764. if value > 0 and _nozzle_is_mounted(info.get(index)):
  765. diameters.append(value)
  766. return diameters
  767. def _rack_nozzle_diameters(status) -> list[float]:
  768. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  769. Keyed off the nozzle ids themselves rather than the printer model: only a
  770. rack machine ever reports ids 16-21, so there is no model registry to keep
  771. in sync. An empty dock is simply absent from the payload — measured on an
  772. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  773. present — so appearing here already means "a nozzle is in that dock".
  774. ``stat`` is deliberately not interpreted: its values aren't known, and
  775. reading it wrongly could hide a nozzle the printer would happily fetch.
  776. """
  777. diameters: list[float] = []
  778. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  779. if nozzle_id not in _RACK_NOZZLE_IDS:
  780. continue
  781. # PrinterState spells it "diameter"; the REST schema renames it to
  782. # "nozzle_diameter". Accept either so a caller holding the serialised
  783. # shape gets the same answer.
  784. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  785. if value is not None:
  786. diameters.append(value)
  787. return diameters
  788. def _format_diameters(diameters: list[float]) -> str:
  789. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  790. Deduplicated because a loaded rack holds several nozzles of the same size,
  791. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  792. short form doesn't. Matching still runs over the full list.
  793. """
  794. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  795. def _nozzle_mismatch_message(
  796. sliced_nozzle: float | None,
  797. installed: list[float],
  798. rack: list[float] | None = None,
  799. ) -> str | None:
  800. """Return an actionable error message when the sliced nozzle can't be
  801. printed on any nozzle the machine can reach, else None (#1899).
  802. Fail-safe: returns None whenever we lack the data to judge — no sliced
  803. diameter, or the printer reported no nozzles — so a print is only ever
  804. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  805. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  806. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  807. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  808. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  809. as reachable: the printer fetches one as part of starting the print, so a
  810. slice that matches a docked nozzle is not a mismatch. Without this the
  811. guard blocked every job whose nozzle happened not to be on a hotend at
  812. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  813. diameter already mounted could ever print, and the user had to fetch the
  814. nozzle by hand on the printer's own UI first (#2885).
  815. """
  816. reachable = [*installed, *(rack or [])]
  817. if not sliced_nozzle or not reachable:
  818. return None
  819. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  820. return None
  821. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  822. if rack:
  823. where += f" and {_format_diameters(rack)} in the nozzle rack"
  824. return (
  825. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  826. f"{where}. Re-slice for an available nozzle, or fit the matching "
  827. f"nozzle before printing."
  828. )
  829. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  830. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  831. Shared by the required and loaded sides, which name their extruder
  832. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  833. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  834. 1 the left/deputy — and both are absent on single-nozzle printers, where
  835. naming a nozzle would be noise.
  836. """
  837. parts = [(entry.get("type") or "filament").upper()]
  838. if entry.get("color"):
  839. parts.append(str(entry["color"]))
  840. nozzle = entry.get(nozzle_key)
  841. if nozzle == 0:
  842. parts.append("(right nozzle)")
  843. elif nozzle == 1:
  844. parts.append("(left nozzle)")
  845. return " ".join(parts)
  846. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  847. """Explain that nothing loaded matches what the file needs (#2771).
  848. Only ever built for a printer with no AMS, where the loaded list is short
  849. enough to quote in full and there is no "load another spool and hit Resume"
  850. recovery — the external spool holder is all there is, so the user needs to
  851. be told which filament to put on it.
  852. """
  853. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  854. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  855. return (
  856. f"No filament loaded on this printer matches the file. It needs {want}; "
  857. f"the printer has {have} and no AMS. Load the required filament on the "
  858. f"external spool holder, or send this job to a printer that has it."
  859. )
  860. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  861. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  862. every call site below it: G-code injection, usage registration, rack-plan
  863. lookup, slot-extruder lookup, the external-spool check, and the actual
  864. print command.
  865. A positive explicit ``plate_id`` on the queue item always wins. A
  866. non-positive one is treated as "not set" and resolved from the archive,
  867. the way the rest of the queue code already reads it (``if item.plate_id:``
  868. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  869. field, and passing a 0 straight through would build a print command for
  870. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  871. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  872. Falling back to a bare ``1`` instead of reading the archive assumes a
  873. single-plate file's one G-code is numbered 1, which only holds for a
  874. plate exported on its own: one cut out of a larger project keeps its
  875. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  876. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  877. the file, throws an HMS error, and sits wedged in IDLE until
  878. power-cycled (#2947).
  879. The call sites agreed on a fallback only by accident before this:
  880. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  881. the archive's own default plate internally whenever the plate id it's
  882. handed isn't in the file, so it could silently inject into a different
  883. plate than the one the print command itself asked for.
  884. Falls back to 1 when the archive can't be read, holds no G-code member at
  885. all, or its default member doesn't follow the ``plate_N`` naming
  886. convention (a slicer that doesn't use it has no number to dispatch).
  887. An explicit plate the archive doesn't hold is logged and then sent
  888. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  889. to a plate that is in the file would print a model nobody asked for,
  890. which is the worse of the two.
  891. """
  892. try:
  893. with zipfile.ZipFile(file_path, "r") as zf:
  894. names = zf.namelist()
  895. except (OSError, zipfile.BadZipFile) as exc:
  896. logger.warning(
  897. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  898. "is unavailable; dispatching plate %s",
  899. file_path,
  900. exc,
  901. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  902. )
  903. names = None
  904. if explicit_plate_id is not None and explicit_plate_id > 0:
  905. if (
  906. names is not None
  907. and default_plate_number(names) is not None
  908. and select_plate_gcode_name(names, explicit_plate_id) is None
  909. ):
  910. logger.warning(
  911. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  912. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  913. "file, since printing a different plate would print the wrong model (#2947)",
  914. file_path,
  915. explicit_plate_id,
  916. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  917. explicit_plate_id,
  918. )
  919. return explicit_plate_id
  920. resolved = default_plate_number(names) if names is not None else None
  921. return resolved if resolved is not None else 1
  922. class PrintScheduler:
  923. """Background scheduler that processes the print queue."""
  924. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  925. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  926. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  927. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  928. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  929. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  930. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  931. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  932. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  933. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  934. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  935. }
  936. def __init__(self):
  937. self._running = False
  938. self._check_interval = 30 # seconds
  939. # After a pass that actually dispatched something, loop again almost
  940. # immediately instead of sleeping the full interval (#2555). A dispatch
  941. # changes printer state — a batch launch fans out over several passes as
  942. # printers free up, a wedged head-of-line job reverts to pending, an
  943. # upload slot opens — and the next batch of ready work should not have to
  944. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  945. # pending items are behind printers that are genuinely busy printing),
  946. # there is nothing to react to, so we fall back to the normal interval;
  947. # that also means this can never tight-loop, since fast ticks only
  948. # continue while dispatches keep happening and the queue is draining.
  949. self._fast_check_interval = 3 # seconds
  950. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  951. self._power_on_check_interval = 10 # seconds between connection checks
  952. # Printers whose class-target power-on failed, mapped to the monotonic
  953. # time their cool-off expires (#2786).
  954. #
  955. # Without this, one printer with an unreachable plug starves every
  956. # sibling of its model forever: the wake step walks candidates in id
  957. # order, spends the pass's single attempt on the same broken printer
  958. # every time, and the healthy one two slots down is never reached. It
  959. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  960. # which delays the whole queue, not just this job.
  961. #
  962. # Entries expire on read rather than being cleared on success: a printer
  963. # inside its cool-off is skipped before the power-on is reached, so a
  964. # live entry can never be overwritten by a success anyway. A printer
  965. # that comes back by any other route stops being a wake candidate the
  966. # moment it connects.
  967. self._wake_failures: dict[int, float] = {}
  968. self._wake_failure_cooloff = 600 # seconds
  969. # Printers whose last upload never reached them, mapped to the monotonic
  970. # time they may be dispatched to again (#3210). Same expire-on-read shape
  971. # as `_wake_failures`. Without it, a printer that cannot take files is
  972. # idle on every pass, so it is picked on every pass.
  973. self._upload_backoff: dict[int, float] = {}
  974. # Refused uploads in a row per printer, which sets the next backoff
  975. # window. Cleared by a successful upload to that printer.
  976. self._upload_refusals: dict[int, int] = {}
  977. # Printers whose current run of refusals has already sent its one
  978. # "job waiting" notification. Each retry clears the item's waiting
  979. # reason and the next refusal sets it again, which `hold_item` reads as
  980. # a new reason; without this, every retry would notify. Cleared with
  981. # `_upload_refusals`.
  982. self._upload_refusal_notified: set[int] = set()
  983. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  984. self._drying_in_progress: dict[int, float] = {}
  985. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  986. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  987. # cycle and the humidity finally coming down, so the normal steady
  988. # state is an empty dict. Fields:
  989. # running — a cycle we armed is (or should be) on the firmware
  990. # ended_at — monotonic when we observed that cycle end
  991. # unproductive — consecutive armed cycles that ended with the reading
  992. # still above the threshold
  993. # suspended — we have stopped arming this unit and said so
  994. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  995. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  996. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  997. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  998. # print-takes-priority stop, the manual-cycle adoption guard, and the
  999. # arming setdefault all act on that meaning -- a unit that is merely
  1000. # waiting out its streak must not become stoppable or judgeable.
  1001. # since -- monotonic stamp when the current continuous above-threshold
  1002. # streak began
  1003. # last -- monotonic stamp of the last pass that observed the streak
  1004. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1005. # Slots already notified as low on filament:
  1006. # {(printer_id, ams_id, tray_id, spool_id)}.
  1007. # Cleared when the slot goes back above its threshold rather than on a
  1008. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1009. # boundary must not produce an alert on every pass, and a slot that has
  1010. # been refilled has to be able to alert again. See #2913.
  1011. #
  1012. # The spool id is part of the key because the slot alone cannot clear
  1013. # itself. Pull a low spool and put a different part-used one in the same
  1014. # slot: the key survives the pass where the slot resolves to nothing --
  1015. # deliberately, so a brief Spoolman outage does not re-alert everything
  1016. # when it returns -- and the replacement never goes above the threshold,
  1017. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1018. # different key and the stale one is inert.
  1019. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1020. # The same, for the MQTT relay's filament/low event: its own record, so
  1021. # one channel having been told never silences the other.
  1022. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1023. # Earliest monotonic time the next low-filament check may run (#2913).
  1024. self._filament_low_next_check: float = 0.0
  1025. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1026. # condition is "reorder" or "break", the events are those that had a
  1027. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1028. # condition clears, so it can alert again, and when nobody wants either
  1029. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1030. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1031. # re-send one message per SKU that is still low.
  1032. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1033. # The JSON last read from or written to that row; None until it has been read.
  1034. self._stock_alerts_persisted: str | None = None
  1035. # Earliest monotonic time the next stock forecast check may run (#2955).
  1036. self._stock_forecast_next_check: float = 0.0
  1037. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1038. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1039. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1040. # both features share _drying_in_progress.
  1041. self._scheduled_drying_printer_ids: set[int] = set()
  1042. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1043. # the first pass after a restart reaps anything left behind.
  1044. self._last_scheduled_drying_prune: float | None = None
  1045. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1046. # a project_file command must not get a second dispatch until either it
  1047. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1048. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1049. # during that window the DB busy_printers seed is empirically unreliable
  1050. # (multi-plate batches double-/triple-dispatched onto the same printer
  1051. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1052. # or revert.
  1053. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1054. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1055. # Minimum cooldown between dispatches to the same printer (covers the
  1056. # H2D's project_file digestion window).
  1057. self._dispatch_min_cooldown = 60.0
  1058. # Hard timeout — drop the hold even if we never observed a transition,
  1059. # so a lost MQTT session can't lock a printer out of the queue forever.
  1060. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1061. # watchdog runs first on the unhappy path.
  1062. self._dispatch_max_hold = 180.0
  1063. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1064. # an earlier pass and is still running. `_start_print` flips the row
  1065. # pending -> printing only *after* the upload completes, so until then
  1066. # the row stays `pending`: each tick, check_queue excludes these
  1067. # item_ids from re-selection and their printers from new dispatch /
  1068. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1069. # freed slots refill on the next fast tick. check_queue is the sole,
  1070. # sequential caller and the prune done-callbacks run in the same
  1071. # event-loop thread, so this dict needs no lock.
  1072. # item_id -> (task, printer_id)
  1073. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1074. # Expected prints registered by `_start_print` that have not yet had a
  1075. # print command sent. Populated at registration, dropped once
  1076. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1077. # other exit. Same threading argument as `_inflight` above: one
  1078. # sequential caller, callbacks on the same loop, so no lock.
  1079. # item_id -> (printer_id, remote_filename, archive_id)
  1080. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1081. # Budget reservations created for a dispatch whose print command has
  1082. # not been confirmed yet. `_dispatch_one` releases these on every
  1083. # unsuccessful exit; a successful start removes the item id and leaves
  1084. # the reservation for finance_billing to consume with the archive.
  1085. self._unconfirmed_budget_reservations: set[int] = set()
  1086. # The print user `_start_print` handed to printer_manager for an item
  1087. # whose print command has not been sent yet (item_id -> printer_id).
  1088. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1089. # expected print above: it marks the printer's next print as Bambuddy's.
  1090. self._unconfirmed_print_user: dict[int, int] = {}
  1091. # Prints whose command went out but which the printer has not been
  1092. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1093. # the file and archive None for a library print. The watchdog drops the
  1094. # entry once the print runs, and withdraws what it stands for when the
  1095. # print never starts (see `_forget_unstarted_print`).
  1096. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1097. # Chamber temperature history for smart soak-time reduction.
  1098. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1099. # Entries older than _chamber_history_ttl are pruned on write.
  1100. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1101. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1102. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1103. # Populated on engagement in `_apply_keep_warm`, cleared by
  1104. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1105. # when a gate setting toggles off mid-hold — the release publishes
  1106. # bed → 0 first).
  1107. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1108. # Preheat rollback registry: printer_id -> subset of
  1109. # {"bed", "chamber", "airduct"} listing which preheat commands
  1110. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1111. # every entry still present at exit unless the print successfully
  1112. # started, so a failed upload / cancel / exception never leaves the
  1113. # printer heating for a job that isn't happening.
  1114. self._preheat_pin: dict[int, set[str]] = {}
  1115. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1116. # rollback can tell its own target from one someone else has since
  1117. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1118. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1119. self._preheat_pin_bed: dict[int, int] = {}
  1120. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1121. # its preheat was still holding at temperature. Set by
  1122. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1123. # `_preheat_sleep`, and cleared when the dispatch exits.
  1124. self._cancelled_dispatches: set[int] = set()
  1125. # printer_id -> monotonic time it was first seen terminal while one of
  1126. # its queue rows was still 'printing'. Reset by any non-terminal
  1127. # observation, so it measures an unbroken run rather than a total.
  1128. # In-memory on purpose: a restart re-arms the grace period, which only
  1129. # delays a recovery that is already the exceptional path (#2829).
  1130. self._terminal_since: dict[int, float] = {}
  1131. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1132. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1133. # across idle printers repeats that for every one of them in a single
  1134. # pass. Cleared at the top of each pass so a re-sliced file is never
  1135. # served from a previous tick.
  1136. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1137. # When each "any model" job held for low filament last looked for
  1138. # another printer (#3137), by queue item id.
  1139. self._short_hold_checked_at: dict[int, float] = {}
  1140. async def run(self):
  1141. """Main loop - check queue every interval."""
  1142. self._running = True
  1143. logger.info("Print scheduler started")
  1144. await self._clear_stale_dispatch_claims(at_startup=True)
  1145. while self._running:
  1146. dispatched = False
  1147. try:
  1148. self._sample_chamber_temps()
  1149. # No-op while any upload is in flight; on a quiet tick it releases
  1150. # a claim whose best-effort clear failed (e.g. the database was
  1151. # briefly unreachable), instead of leaving the row wedged until
  1152. # the next restart.
  1153. await self._clear_stale_dispatch_claims()
  1154. await self._close_stranded_printing_items()
  1155. dispatched = await self.check_queue()
  1156. except Exception as e:
  1157. logger.error("Scheduler error: %s", e)
  1158. # Re-check quickly after a productive pass so a draining batch does
  1159. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1160. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1161. async def _close_stranded_printing_items(self) -> None:
  1162. """Close a ``printing`` row the completion event never closed (#2829).
  1163. ``on_print_complete`` refuses to close a row when the completion's
  1164. subtask name disagrees with the file the row was dispatched with, so a
  1165. completion meant for something else (the printer's own
  1166. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1167. The refusal has no way back, though: nothing else ever closes the row,
  1168. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1169. one bad comparison wedges that printer's queue until a human presses
  1170. cancel. That is what #2829's reporters hit, and the guard's own
  1171. docstring already called stranding the worse of the two failures.
  1172. This is the way back. When a row has been ``printing`` while its
  1173. printer sat in a terminal state for the whole grace period, the print
  1174. is over however the event was read, and the row is closed with the
  1175. status the printer's own state implies.
  1176. Deliberately conservative:
  1177. * Only a connected printer counts. A disconnected one has a stale
  1178. ``state`` and proves nothing.
  1179. * The clock is reset by any non-terminal observation, so this cannot
  1180. fire on a printer that is merely between stages.
  1181. * The grace period is far longer than the gap between a printer
  1182. finishing and its completion arriving, so the normal path always
  1183. wins the race and this only ever sees genuine strandings.
  1184. What it does *not* do is replay the completion's side effects --
  1185. notifications, billing, auto-off. It restores the queue, which is the
  1186. harm being undone; the archive was updated by the normal path
  1187. regardless, since only the queue block refuses. A recovery that
  1188. silently re-fired notifications minutes late would be its own bug.
  1189. """
  1190. try:
  1191. async with async_session() as db:
  1192. result = await db.execute(
  1193. select(PrintQueueItem)
  1194. .where(PrintQueueItem.status == "printing")
  1195. .where(PrintQueueItem.printer_id.is_not(None))
  1196. )
  1197. items = list(result.scalars().all())
  1198. if not items:
  1199. self._terminal_since.clear()
  1200. return
  1201. now = time.monotonic()
  1202. seen_printers: set[int] = set()
  1203. closed = False
  1204. for item in items:
  1205. printer_id = item.printer_id
  1206. seen_printers.add(printer_id)
  1207. state = printer_manager.get_status(printer_id)
  1208. status = _terminal_queue_status(state)
  1209. if status is None:
  1210. self._terminal_since.pop(printer_id, None)
  1211. continue
  1212. since = self._terminal_since.setdefault(printer_id, now)
  1213. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1214. continue
  1215. item.status = status
  1216. item.completed_at = datetime.now(timezone.utc)
  1217. closed = True
  1218. # The printer is idle: nothing it prints next is this item's.
  1219. self._forget_unstarted_print(item.id, unless_printing=True)
  1220. logger.warning(
  1221. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1222. "closing it as %s. Its completion event was never matched to it, which blocks "
  1223. "every later job for this printer (#2829).",
  1224. item.id,
  1225. printer_id,
  1226. getattr(state, "state", None),
  1227. now - since,
  1228. status,
  1229. )
  1230. if closed:
  1231. await db.commit()
  1232. from backend.app.services.print_batch import refresh_batches_after
  1233. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1234. for printer_id in list(self._terminal_since):
  1235. if printer_id not in seen_printers:
  1236. del self._terminal_since[printer_id]
  1237. except Exception as e:
  1238. # Best-effort, same as the claim sweep beside it: a recovery path
  1239. # that can itself break the scheduler loop is worse than the strand.
  1240. logger.error("Stranded-item sweep failed: %s", e)
  1241. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1242. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1243. A claim is only ever held by a live dispatch coroutine, so when this
  1244. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1245. is stale. At startup that is trivially true — no coroutine survives a
  1246. restart. It is equally true on any later tick where no upload is running,
  1247. which is what makes this safe to repeat rather than only run once.
  1248. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1249. the database is briefly unreachable at exactly the moment dispatch ends,
  1250. the claim survives and the row is wedged out of the selection query. That
  1251. used to last until the next restart (#2702 follow-up, seen when
  1252. PostgreSQL refused a connection mid-dispatch).
  1253. ``_inflight`` is populated when the task is spawned, before the coroutine
  1254. claims its row, and pruned by a done-callback that cannot run before the
  1255. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1256. race window and needs no age threshold. A size-derived upload deadline
  1257. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1258. """
  1259. if self._inflight:
  1260. return
  1261. try:
  1262. async with async_session() as db:
  1263. res = await db.execute(
  1264. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1265. )
  1266. await db.commit()
  1267. if res.rowcount:
  1268. logger.info(
  1269. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1270. res.rowcount,
  1271. " at startup" if at_startup else "",
  1272. )
  1273. except Exception as exc:
  1274. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1275. def stop(self):
  1276. """Stop the scheduler."""
  1277. self._running = False
  1278. logger.info("Print scheduler stopped")
  1279. def forget_printer(self, printer_id: int) -> None:
  1280. """Drop what is kept for a deleted printer, so the next printer given its
  1281. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1282. would keep it out of dispatch for up to an hour.
  1283. A dispatch already in flight keeps its own state (_inflight, the preheat
  1284. pins, unconfirmed prints): it unwinds that when it ends.
  1285. """
  1286. for keyed in (
  1287. self._upload_backoff,
  1288. self._upload_refusals,
  1289. self._wake_failures,
  1290. self._drying_in_progress,
  1291. self._dispatch_holds,
  1292. self._chamber_history,
  1293. self._keep_warm,
  1294. self._terminal_since,
  1295. ):
  1296. keyed.pop(printer_id, None)
  1297. self._upload_refusal_notified.discard(printer_id)
  1298. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1299. for key in [key for key in keyed if key[0] == printer_id]:
  1300. del keyed[key]
  1301. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1302. del self._sent_unstarted_print[item_id]
  1303. async def check_queue(self) -> bool:
  1304. """Check for prints ready to start.
  1305. Returns True if this pass dispatched at least one item, so the caller
  1306. can loop again quickly instead of sleeping the full interval (#2555).
  1307. """
  1308. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1309. self._filament_req_memo.clear()
  1310. async with async_session() as db:
  1311. # Check if shortest-job-first scheduling is enabled
  1312. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1313. # Get all pending items in the one order the queue page shows them
  1314. # in (#3200). The first eligible item takes a printer, so this order
  1315. # decides who wins a printer that a pinned job and an "Any <model>"
  1316. # job both want. It used to start with ``printer_id``, which made the
  1317. # lane outrank the position: SQLite sorts NULL first, so model-based
  1318. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1319. # Neither is what the user dragged into place.
  1320. if sjf_enabled:
  1321. # SJF: items already jumped get top priority (starvation guard),
  1322. # then sort by print_time ascending. Items with no print time go
  1323. # last, and position breaks ties.
  1324. result = await db.execute(
  1325. select(PrintQueueItem)
  1326. .where(PrintQueueItem.status == "pending")
  1327. # Never re-select a row a dispatch worker has already claimed
  1328. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1329. # below, and the guard that lets an orphaned claim be ignored
  1330. # until startup reconciliation clears it.
  1331. .where(PrintQueueItem.dispatching_at.is_(None))
  1332. # archive/library_file are read by the cross-model gate
  1333. # (#2578); eager-load once per pass instead of a lazy-load
  1334. # (which would raise in async) per item.
  1335. .options(
  1336. selectinload(PrintQueueItem.archive),
  1337. selectinload(PrintQueueItem.library_file),
  1338. # Cross-model candidates (#671), plus each candidate's file
  1339. # for the same cross-model gate. Lazy-loading either would
  1340. # raise in async.
  1341. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1342. )
  1343. .order_by(
  1344. PrintQueueItem.been_jumped.desc(),
  1345. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1346. PrintQueueItem.position,
  1347. PrintQueueItem.id,
  1348. )
  1349. )
  1350. else:
  1351. result = await db.execute(
  1352. select(PrintQueueItem)
  1353. .where(PrintQueueItem.status == "pending")
  1354. # Skip rows already claimed by a dispatch worker (#2615).
  1355. .where(PrintQueueItem.dispatching_at.is_(None))
  1356. .options(
  1357. selectinload(PrintQueueItem.archive),
  1358. selectinload(PrintQueueItem.library_file),
  1359. # Cross-model candidates (#671), plus each candidate's file
  1360. # for the same cross-model gate. Lazy-loading either would
  1361. # raise in async.
  1362. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1363. )
  1364. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1365. )
  1366. items = list(result.scalars().all())
  1367. # Drop rows whose upload is still in flight from an earlier pass
  1368. # (#2602). They stay `pending` until the upload finishes, so without
  1369. # this a fast tick would re-select and re-dispatch the same row.
  1370. # Belt-and-suspenders with the printer exclusion below.
  1371. if self._inflight:
  1372. inflight_ids = set(self._inflight)
  1373. items = [it for it in items if it.id not in inflight_ids]
  1374. # Read plate-clear setting once per queue check. Default MUST be
  1375. # False to match the schema (SettingsSchema.require_plate_clear
  1376. # defaults False) and the frontend (toggle + card badge both treat a
  1377. # missing value as off). When no settings row exists, a True default
  1378. # here re-enabled the plate-clear gate the UI showed as disabled,
  1379. # blocking dispatch to FINISH-state printers forever with no UI path
  1380. # to clear it (#1865).
  1381. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1382. # Dispatch and track scheduled drying runs (#2638)
  1383. await self._check_scheduled_dryings(db)
  1384. if not items:
  1385. # No dispatchable pending items — still check auto-drying on idle
  1386. # printers, but keep any printer with an upload still in flight
  1387. # from an earlier pass out of it (#2602): its print is imminent,
  1388. # so it must not be auto-dried in the gap before the row flips to
  1389. # printing. Report the pass as productive while uploads run so the
  1390. # loop stays on the fast interval.
  1391. #
  1392. # Also release any keep-warm holds that got orphaned by the queue
  1393. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1394. # this early return, so call it directly with an empty candidate
  1395. # set. Without this, a printer whose queued item was cancelled or
  1396. # deleted would keep its bed at target until the max-duration
  1397. # timeout expired.
  1398. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1399. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1400. await self._check_auto_drying(db, [], inflight_printers)
  1401. await self._check_filament_low(db)
  1402. await self._check_stock_forecast(db)
  1403. return bool(self._inflight)
  1404. logger.info(
  1405. "Queue check: found %d pending items: %s",
  1406. len(items),
  1407. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1408. )
  1409. # Forget jobs that left the queue since they were last checked.
  1410. pending_ids = {i.id for i in items}
  1411. self._short_hold_checked_at = {
  1412. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1413. }
  1414. # Seed busy_printers with printers that already have an item in 'printing'
  1415. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1416. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1417. # lag several seconds behind the print command, so the next check_queue
  1418. # tick still sees IDLE and would double-dispatch onto the same printer.
  1419. # Without this guard, two pending items targeting the same printer
  1420. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1421. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1422. busy_result = await db.execute(
  1423. select(PrintQueueItem.printer_id)
  1424. .where(PrintQueueItem.status == "printing")
  1425. .where(PrintQueueItem.printer_id.is_not(None))
  1426. )
  1427. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1428. # Why each printer left this pass, recorded where the decision is
  1429. # made rather than re-derived when the summary is logged. #3018's
  1430. # bundle shows what the old summary produced: "printer 1 not
  1431. # available -- connected=True, state=IDLE" immediately followed by a
  1432. # dispatch to printer 1. Two things went wrong at once. The line read
  1433. # live state at log time, which by then no longer matched the state
  1434. # the decision was made on; and `busy_printers` holds both printers
  1435. # that cannot take work and printers this pass has claimed for it,
  1436. # which are opposite facts. It is the first line anyone greps for
  1437. # "why did my item not go out", so it has to say which.
  1438. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1439. # Printers this pass is dispatching to. They are in busy_printers so
  1440. # nothing else in the pass targets them -- that is a reservation, not
  1441. # an obstruction, and the summary says so.
  1442. claimed_printers: set[int] = set()
  1443. def mark_busy(printer_id: int, reason: str) -> None:
  1444. """Take ``printer_id`` out of this pass, recording why.
  1445. First reason wins: a printer already excluded by a stronger fact
  1446. -- a print running on it -- must not be relabelled by a weaker
  1447. check that ran later and would have excluded it anyway.
  1448. """
  1449. busy_printers.add(printer_id)
  1450. busy_reasons.setdefault(printer_id, reason)
  1451. def claim_printer(printer_id: int) -> None:
  1452. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1453. claimed_printers.add(printer_id)
  1454. mark_busy(printer_id, "selected for dispatch in this pass")
  1455. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1456. # worded for a different audience: the log wants "still inside its
  1457. # post-dispatch hold window", the queue row wants to know the printer
  1458. # is taken and nothing is broken. Only the cases that would read wrong
  1459. # as a plain "Busy" are recorded here; the rest fall back to it.
  1460. item_hold_reasons: dict[int, str] = {}
  1461. # Names and models for the printers this pass may have to write a
  1462. # waiting reason about, read once rather than per skip per tick. The
  1463. # model-based branch already has its names from `_printers_for_model`.
  1464. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1465. pinned_printers: dict[int, tuple[str, str]] = {}
  1466. if pinned_printer_ids:
  1467. pinned_rows = await db.execute(
  1468. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1469. )
  1470. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1471. def printer_label(printer_id: int) -> str:
  1472. """What to call this printer in a queue row."""
  1473. entry = pinned_printers.get(printer_id)
  1474. return (entry[0] if entry else "") or f"printer {printer_id}"
  1475. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1476. """Record why *item* is not going out, in the words the queue row shows.
  1477. The fixed-printer branch's single writer for ``waiting_reason``
  1478. (#3074). Before this, the sensor interlock was the only thing that
  1479. wrote the field there, so an item pinned to a printer that was
  1480. merely printing sat at `pending` with nothing to show for it —
  1481. indistinguishable from a queue that had stopped working — while
  1482. the same job queued as "Any <model>" explained itself.
  1483. Every exit from that branch now calls this, which is also what
  1484. replaced the interlock's old habit of clearing the field up front:
  1485. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1486. because whichever exit runs next overwrites it and the dispatch
  1487. path clears it.
  1488. A notification goes out when this item starts asking for
  1489. something, and only then: the new reason needs the user, and what
  1490. it replaced did not. "What it replaced did not" has to include a
  1491. busy-only reason, not just an empty one. The sequence this branch
  1492. actually produces is a print running (``Busy: X1C-01``) and then
  1493. the plate it left behind (``Waiting for plate confirmation``), and
  1494. testing "was the field empty" would call that no transition at all
  1495. and stay quiet through the one case worth saying out loud.
  1496. The cost is that a printer dropping offline, coming back busy and
  1497. dropping again asks twice rather than once. That is the honest
  1498. reading — it went wrong twice — and the alternative was a rule
  1499. that never fired for the case this was built for.
  1500. *notify* is how a caller opts out. The sensor interlock does: it
  1501. has never sent this notification, and a change about what the
  1502. queue *displays* is not the place to start (#1148).
  1503. """
  1504. if item.waiting_reason == reason:
  1505. return
  1506. # Busy-only and empty are the same thing here: neither is the
  1507. # queue asking the user for anything.
  1508. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1509. item.waiting_reason = reason
  1510. await db.commit()
  1511. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1512. return
  1513. try:
  1514. job_name = await self._get_job_name(db, item)
  1515. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1516. await notification_service.on_queue_job_waiting(
  1517. job_name=job_name,
  1518. target_model=(entry[1] if entry else "") or "",
  1519. waiting_reason=reason,
  1520. db=db,
  1521. )
  1522. except Exception as e:
  1523. # A queue that cannot say why it is waiting is the bug being
  1524. # fixed here; a queue that stops dispatching because a
  1525. # notification provider is down would be a worse one.
  1526. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1527. async def hold_for_printer(
  1528. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1529. ) -> None:
  1530. """Take *printer_id* out of this pass and tell the item's owner why."""
  1531. mark_busy(printer_id, log_reason)
  1532. item_hold_reasons.setdefault(printer_id, item_reason)
  1533. await hold_item(item, item_reason)
  1534. # Defense-in-depth (#1157): augment busy_printers with any printer
  1535. # still in its post-dispatch hold window. Empirically, the DB seed
  1536. # above can miss in-flight items in a multi-plate batch — same-file
  1537. # plates were being dispatched 30 s apart while the H2D was still
  1538. # digesting the first project_file. The hold is keyed in-memory and
  1539. # released by the watchdog on the success path, so it adds a layer
  1540. # that doesn't depend on DB row visibility or completion-callback
  1541. # timing.
  1542. for held_printer_id in list(self._dispatch_holds.keys()):
  1543. if self._printer_in_dispatch_hold(held_printer_id):
  1544. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1545. # Exclude printers whose upload is still in flight from an earlier
  1546. # pass (#2602). The row is `pending` until the upload finishes and
  1547. # the printing-state seed / dispatch hold above only arm once the
  1548. # upload completes, so this is what holds the printer (and, via
  1549. # busy_printers, its auto-drying) out of the pass during the upload.
  1550. for _task, inflight_pid in self._inflight.values():
  1551. if inflight_pid is not None:
  1552. mark_busy(inflight_pid, "an upload to it is still in flight")
  1553. # Snapshot taken here, before the item loop adds anything (#2801).
  1554. #
  1555. # The three sources above all mean the same thing: a print on this
  1556. # printer is running or imminent. Everything the loop adds below
  1557. # means only "the queue could not dispatch to it this pass", which
  1558. # is a different statement -- a printer waiting on a plate-clear
  1559. # acknowledgment, an offline printer, one with no matching file.
  1560. #
  1561. # Auto-drying must only see the first kind. Reading the whole set
  1562. # as "is currently printing" is what put a plate-held printer down
  1563. # the mid-print path: it capped the drying temperature, logged the
  1564. # cycle as (mid-print), and skipped the very gate that was supposed
  1565. # to hold it. The interlock block below already documents the same
  1566. # hazard and works around it by staying out of busy_printers; this
  1567. # generalises that workaround instead of repeating it per case.
  1568. dispatching_printers: set[int] = set(busy_printers)
  1569. # Printers whose last upload never reached them (#3210). After the
  1570. # snapshot above on purpose: such a printer is idle, not about to
  1571. # print, and auto-drying must keep treating it as idle.
  1572. now_mono = time.monotonic()
  1573. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1574. # can leave them out: there is no print to keep a bed warm for.
  1575. backoff_printers: set[int] = set()
  1576. # In backoff, and the "job waiting" notification for this run of
  1577. # refusals has gone out already. Their holds are written silently.
  1578. silent_hold_printers: set[int] = set()
  1579. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1580. if now_mono >= retry_at:
  1581. del self._upload_backoff[backoff_pid]
  1582. continue
  1583. backoff_printers.add(backoff_pid)
  1584. if backoff_pid in self._upload_refusal_notified:
  1585. silent_hold_printers.add(backoff_pid)
  1586. else:
  1587. self._upload_refusal_notified.add(backoff_pid)
  1588. mark_busy(
  1589. backoff_pid,
  1590. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1591. )
  1592. item_hold_reasons.setdefault(
  1593. backoff_pid,
  1594. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1595. )
  1596. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1597. # enclosure door left open, say. The fixed-printer branch turns
  1598. # this into a waiting_reason the user can act on; the model-based
  1599. # branch hides these printers from the matcher so an "Any <model>"
  1600. # job runs on a sibling instead of queueing behind the held one.
  1601. #
  1602. # Deliberately NOT merged into busy_printers, even though that set
  1603. # already means "unavailable this pass". _check_auto_drying reads
  1604. # it as "is currently printing" and would put an idle-but-held
  1605. # printer down the mid-print drying path, which caps the drying
  1606. # temperature and skips the queue-only gating. A held printer is
  1607. # idle; it should dry exactly as it did before.
  1608. #
  1609. # Only sensors we actually read and found alerting appear here; see
  1610. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1611. # holds nothing.
  1612. interlocked: dict[int, str] = {}
  1613. try:
  1614. interlocked = await ha_sensor_manager.blocked_printers(db)
  1615. except Exception as e:
  1616. # Never let the interlock stop the queue running. A broken
  1617. # lookup means no holds, not no dispatches.
  1618. logger.warning("Home Assistant interlock check failed: %s", e)
  1619. interlocked = {}
  1620. # Printers a smart plug can bring back, read once for the whole pass
  1621. # (#2786). Used by the model-based branch both to word "Offline" in
  1622. # the waiting reason and to decide what the wake step may switch on.
  1623. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1624. # At most one power-on per queue check. Each one blocks this loop
  1625. # for the boot wait, so a queue of ten class-targeted jobs must not
  1626. # switch on ten printers inside a single pass — the next pass wakes
  1627. # the next one (#2786).
  1628. power_on_attempted = False
  1629. # Log skip reasons once per queue check (not per item)
  1630. skip_reasons: dict[str, int] = {}
  1631. # Items selected for dispatch in this pass, one per printer. The
  1632. # loop below only *decides* — the uploads happen afterwards, in
  1633. # parallel (#2555). See _dispatch_selected().
  1634. dispatch_ids: list[int] = []
  1635. # Library rows queued with `cleanup_library_after_dispatch` (the
  1636. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1637. # that prints them: the row is deleted and the 3MF is unlinked from
  1638. # disk. That was safe only because dispatch was serial. Run two of
  1639. # them against the same row at once and the second DELETE matches no
  1640. # row (StaleDataError), and the winner's unlink can pull the file out
  1641. # from under the loser's in-flight upload.
  1642. #
  1643. # Only the cleanup flag mutates the row. An ordinary library print
  1644. # just reads it, so the common fan-out — one file, many printers,
  1645. # which is exactly the reporter's workload — still goes out fully in
  1646. # parallel. Narrow the guard to the mutating case; do not serialise
  1647. # the case the whole fix exists for.
  1648. dispatch_libs: set[int] = set()
  1649. consumed_libs: set[int] = set()
  1650. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1651. """True if dispatching `candidate` now would race another item's cleanup."""
  1652. lib_id = candidate.library_file_id
  1653. if lib_id is None:
  1654. return False
  1655. if candidate.cleanup_library_after_dispatch:
  1656. # We would delete a row someone else in this pass is reading.
  1657. return lib_id in dispatch_libs
  1658. # Someone else in this pass will delete the row out from under us.
  1659. return lib_id in consumed_libs
  1660. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1661. lib_id = candidate.library_file_id
  1662. if lib_id is None:
  1663. return
  1664. dispatch_libs.add(lib_id)
  1665. if candidate.cleanup_library_after_dispatch:
  1666. consumed_libs.add(lib_id)
  1667. # Printer scope of each job's creator (#1727), so an "any <model>"
  1668. # job only lands on a printer its creator may use. Loaded lazily,
  1669. # once per creator per pass.
  1670. from backend.app.core.auth import is_auth_enabled
  1671. scope_auth_enabled = await is_auth_enabled(db)
  1672. creator_scopes: dict[int, PrinterScope] = {}
  1673. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1674. if not scope_auth_enabled or user_id is None:
  1675. return ALL_PRINTERS
  1676. if user_id not in creator_scopes:
  1677. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1678. return creator_scopes[user_id]
  1679. for item in items:
  1680. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1681. if item.scheduled_time:
  1682. sched = item.scheduled_time
  1683. if sched.tzinfo is None:
  1684. sched = sched.replace(tzinfo=timezone.utc)
  1685. if sched > datetime.now(timezone.utc):
  1686. # Waiting on the clock, not on a printer.
  1687. await hold_item(item, None)
  1688. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1689. continue
  1690. # Skip items that require manual start, except an "any model"
  1691. # job held for low filament that another idle printer can now
  1692. # run: that one is moved there and carries on below (#3137).
  1693. if item.manual_start and not (
  1694. item.filament_short
  1695. and await self._release_short_model_hold(
  1696. db,
  1697. item,
  1698. busy_printers | interlocked.keys(),
  1699. require_plate_clear,
  1700. await _creator_scope(item.created_by_id),
  1701. )
  1702. ):
  1703. # Waiting on the user, not on a printer. Cleared here because
  1704. # this is the last pass that will look at the row: a staged
  1705. # item never reaches the branches below again, so a reason
  1706. # left from before it was staged would stand forever (#3074).
  1707. # The one exception is the unmatched-filament hold, whose
  1708. # reason was written at staging and is why the item waits:
  1709. # it names the filament to load (#2799). Pressing start
  1710. # clears manual_start, and the branches below overwrite it.
  1711. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1712. await hold_item(item, keep)
  1713. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1714. continue
  1715. if item.printer_id and item.printer_id not in pinned_printers:
  1716. # Moved by the release above to a printer no row named when
  1717. # the labels were read.
  1718. moved_to = await self._get_printer(db, item.printer_id)
  1719. if moved_to is not None:
  1720. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1721. if item.printer_id:
  1722. # Its creator may no longer use this printer (#1727): an
  1723. # admin took it away from their group after the job was
  1724. # queued, say to keep it free for a training session. Held,
  1725. # not failed, so it starts if access comes back or the user
  1726. # moves it to a printer they still have.
  1727. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1728. await hold_item(
  1729. item,
  1730. "Its owner no longer has access to this printer — move it to another printer",
  1731. notify=False,
  1732. )
  1733. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1734. continue
  1735. # Held by a sensor interlock (#1148). Checked before the
  1736. # busy_printers test that would otherwise swallow it
  1737. # silently — "waiting for a printer" and "waiting for you
  1738. # to shut the enclosure" need to read differently, and only
  1739. # one of them is something the user can fix.
  1740. #
  1741. # It used to be the only thing that wrote a waiting_reason on
  1742. # this branch, and it cleared the field up front so a lifted
  1743. # hold could not leave a shut door reading "Waiting on
  1744. # Enclosure Door". `hold_item` carries that guarantee now —
  1745. # every exit below writes — so the clear is gone and the
  1746. # interlock is an ordinary hold like the rest (#3074).
  1747. interlock_reason = interlocked.get(item.printer_id)
  1748. if interlock_reason:
  1749. # Silent, exactly as it has always been. #1148 built this
  1750. # as a hold that shows on the row, never as an alert, and
  1751. # routing it through the shared writer must not quietly
  1752. # turn every open door into a notification.
  1753. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1754. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1755. continue
  1756. # Specific printer assignment (existing behavior)
  1757. if item.printer_id in busy_printers:
  1758. # Whatever took the printer out of this pass — a print
  1759. # already running on it, a post-dispatch hold, an upload
  1760. # still in flight, an item ahead of this one in the same
  1761. # pass — reads the same way from the queue: the printer is
  1762. # taken and this item is in line for it. The exceptions
  1763. # that do not (an offline printer, say) recorded their own
  1764. # wording in `item_hold_reasons` when they held it.
  1765. await hold_item(
  1766. item,
  1767. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1768. notify=item.printer_id not in silent_hold_printers,
  1769. )
  1770. continue
  1771. # Check if printer is idle
  1772. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1773. printer_connected = printer_manager.is_connected(item.printer_id)
  1774. # If printer not connected, try to power on via smart plug
  1775. if not printer_connected:
  1776. plugs = await self._get_smart_plugs(db, item.printer_id)
  1777. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1778. if auto_on_plugs:
  1779. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1780. # Power on using the plug that actually feeds the printer, and
  1781. # wait for it to boot on that one only (#2629).
  1782. primary_plug = self._pick_power_plug(auto_on_plugs)
  1783. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1784. if powered_on:
  1785. # Also turn on any remaining auto_on plugs (e.g., filter)
  1786. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1787. try:
  1788. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1789. if await service.turn_on(extra_plug):
  1790. await publish_plug_state(
  1791. extra_plug.id,
  1792. extra_plug.name,
  1793. extra_plug.printer_id,
  1794. on=True,
  1795. ha_entity_id=extra_plug.ha_entity_id,
  1796. )
  1797. logger.info(
  1798. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1799. )
  1800. except Exception as e:
  1801. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1802. printer_connected = True
  1803. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1804. else:
  1805. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1806. await hold_for_printer(
  1807. item,
  1808. item.printer_id,
  1809. "smart-plug power-on failed",
  1810. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1811. )
  1812. continue
  1813. else:
  1814. # No plug or auto_on disabled. Worded exactly as the
  1815. # model-based branch words it (#2786): this is the one
  1816. # entry on that list the user has to act on, because
  1817. # Bambuddy will never switch this printer on itself.
  1818. await hold_for_printer(
  1819. item,
  1820. item.printer_id,
  1821. "offline, with no smart plug to power it on",
  1822. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1823. )
  1824. continue
  1825. # Check if printer is idle (busy with another print)
  1826. if not printer_idle:
  1827. await hold_for_printer(
  1828. item,
  1829. item.printer_id,
  1830. "not idle",
  1831. self._pinned_hold_reason(
  1832. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1833. ),
  1834. )
  1835. continue
  1836. # Drying blocks the queue, if the user asked it to. A hold
  1837. # is a skip like any other, so it belongs here with the
  1838. # rest of the availability checks.
  1839. # A parked timer (#2896) never ends, so it must not hold the
  1840. # queue; it stays tracked so the stop paths still reach it.
  1841. if (
  1842. self._drying_in_progress.get(item.printer_id)
  1843. and not self._drying_is_only_parked(item.printer_id)
  1844. and await self._get_bool_setting(db, "queue_drying_block")
  1845. ):
  1846. # Busy-shaped on purpose: the cycle ends on its own and
  1847. # the job goes out, so there is nothing to alert about.
  1848. await hold_for_printer(
  1849. item,
  1850. item.printer_id,
  1851. "drying, and drying is set to block the queue",
  1852. f"Busy: {printer_label(item.printer_id)} (drying)",
  1853. )
  1854. continue
  1855. # Check condition (previous print success)
  1856. if item.require_previous_success:
  1857. if not await self._check_previous_success(db, item):
  1858. item.status = "skipped"
  1859. item.error_message = "Previous print failed or was aborted"
  1860. item.completed_at = datetime.now(timezone.utc)
  1861. # Not pending any more, so not waiting for anything.
  1862. item.waiting_reason = None
  1863. await db.commit()
  1864. logger.info("Skipped queue item %s - previous print failed", item.id)
  1865. # Send notification
  1866. job_name = await self._get_job_name(db, item)
  1867. printer = await self._get_printer(db, item.printer_id)
  1868. await notification_service.on_queue_job_skipped(
  1869. job_name=job_name,
  1870. printer_id=item.printer_id,
  1871. printer_name=printer.name if printer else "Unknown",
  1872. reason="Previous print failed or was aborted",
  1873. db=db,
  1874. )
  1875. continue
  1876. # Resolve the AMS mapping when it's missing OR unresolved
  1877. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1878. # frontend status-load race can persist [-1] (#2589) — and
  1879. # must be recomputed from live trays rather than trusted.
  1880. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1881. if unmappable:
  1882. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1883. continue
  1884. # Filament-deficit pre-dispatch check (#1496). If the
  1885. # assigned spool can't satisfy any required slot grams,
  1886. # promote the item to manual_start so the user must
  1887. # acknowledge via the ▶ button (which re-checks live).
  1888. if await self._block_on_filament_deficit(db, item):
  1889. # Now staged for the user to start by hand, and the row
  1890. # shows the filament-short badge instead. Cleared because
  1891. # a staged item never reaches this branch again.
  1892. await hold_item(item, None)
  1893. continue
  1894. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1895. # than let the printer pick a substitute for a slot the
  1896. # matcher could not resolve on this printer.
  1897. if await self._block_on_unmatched_filament(db, item):
  1898. continue
  1899. # Hold this item back for the next pass rather than racing
  1900. # another dispatch over the same transient library row. The
  1901. # printer is still marked busy so a later item does not jump
  1902. # its place in this printer's queue.
  1903. if _library_row_conflict(item):
  1904. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1905. await hold_for_printer(
  1906. item,
  1907. item.printer_id,
  1908. "holding its place while another item releases a library row",
  1909. f"Busy: {printer_label(item.printer_id)}",
  1910. )
  1911. continue
  1912. # Print takes priority: stop a cycle Bambuddy armed, now
  1913. # that this item is definitely going out.
  1914. #
  1915. # Placement is the whole point (#2801). This used to sit up
  1916. # with the availability checks, inside the not-idle branch
  1917. # -- so it fired only on the passes where the print was NOT
  1918. # going to start, and never on the ones where it was.
  1919. # Drying is not one of the things `_is_printer_idle` looks
  1920. # at, so a stop could never have unblocked that printer
  1921. # anyway; the cycle was spent for nothing, auto-drying
  1922. # re-armed on the next tick, and a plate left
  1923. # unacknowledged turned that into a loop on the scheduler
  1924. # interval. Every skip between there and here -- a failed
  1925. # previous print, an unmappable item, a filament deficit, a
  1926. # contested library row -- is another way to lose a cycle
  1927. # for a print that never happens, which is why this waits
  1928. # until the decision is actually made.
  1929. if self._drying_in_progress.get(
  1930. item.printer_id
  1931. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1932. await self._stop_drying(item.printer_id)
  1933. # Queue the dispatch instead of running it here — see
  1934. # _dispatch_selected(). busy_printers still gets the printer
  1935. # immediately, so nothing else in this pass can target it.
  1936. #
  1937. # The reason goes first: this item is not waiting for anything
  1938. # any more, and the model-based branch clears its own at the
  1939. # equivalent moment (#3074).
  1940. await hold_item(item, None)
  1941. _claim_library_row(item)
  1942. dispatch_ids.append(item.id)
  1943. claim_printer(item.printer_id)
  1944. # SJF starvation guard: mark items that were jumped
  1945. if sjf_enabled and item.print_time_seconds is not None:
  1946. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1947. for other in items:
  1948. if (
  1949. other.id != item.id
  1950. and other.id not in dispatch_ids
  1951. and other.status == "pending"
  1952. and _could_take_printer(other, item.printer_id, pinned_model)
  1953. and not other.been_jumped
  1954. and other.position < item.position
  1955. and (
  1956. other.print_time_seconds is None
  1957. or other.print_time_seconds > item.print_time_seconds
  1958. )
  1959. ):
  1960. other.been_jumped = True
  1961. await db.commit()
  1962. elif item.target_model or item.variants:
  1963. # Model-based assignment - find any idle printer of matching model.
  1964. # A plain model-based item has exactly one candidate, built from
  1965. # its own columns. A cross-model item (#671) has one per sliced
  1966. # variant and takes the first that matches, walking them in the
  1967. # user's priority order so the pick is reproducible when more
  1968. # than one printer is free in the same pass.
  1969. candidates = _candidates_for(item)
  1970. item_scope = await _creator_scope(item.created_by_id)
  1971. printer_id = None
  1972. chosen: _ModelCandidate | None = None
  1973. per_model_reasons: list[tuple[str | None, str]] = []
  1974. # Candidates that cleared the cross-model gate below. The
  1975. # smart-plug wake step may only consider these — waking a
  1976. # printer for a file that can never legally run on it is
  1977. # worse than not waking at all (#2786).
  1978. wakeable_candidates: list[_ModelCandidate] = []
  1979. # Printers passed over because their last print failed.
  1980. gate_blocked: set[int] = set()
  1981. if not candidates:
  1982. # Every candidate file has been deleted or trashed out from
  1983. # under this item. Hold it with something the user can act
  1984. # on rather than letting it look dispatchable forever.
  1985. per_model_reasons.append(
  1986. (
  1987. item.target_model,
  1988. "Every file for this job has been deleted — add a file back or remove the item",
  1989. )
  1990. )
  1991. for candidate in candidates:
  1992. effective_types, filament_overrides = _filament_constraints(candidate)
  1993. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1994. # for an incompatible model to a printer, no matter how the
  1995. # row got into the DB (old rows, direct API writes). Held
  1996. # as pending with an actionable waiting_reason — the user
  1997. # fixes it by editing the item's target model.
  1998. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1999. per_model_reasons.append(
  2000. (
  2001. candidate.target_model,
  2002. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2003. f"{candidate.target_model} — edit the item and fix its target model",
  2004. )
  2005. )
  2006. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2007. continue
  2008. wakeable_candidates.append(candidate)
  2009. async def is_short(
  2010. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2011. ) -> bool:
  2012. # The check reads the file and plate off the item,
  2013. # so it must hold this candidate's. Resolving is
  2014. # safe to repeat, and the winner is resolved again
  2015. # below.
  2016. self._resolve_variant(item, candidate)
  2017. return await self._filament_short_on(db, item, pid)
  2018. while True:
  2019. match_id, match_reason = await self._find_idle_printer_for_model(
  2020. db,
  2021. candidate.target_model,
  2022. # Sensor-held printers are unavailable to the
  2023. # matcher but stay out of busy_printers itself
  2024. # (#1148) — see where `interlocked` is built.
  2025. busy_printers | interlocked.keys() | gate_blocked,
  2026. effective_types,
  2027. item.target_location,
  2028. filament_overrides=filament_overrides,
  2029. require_plate_clear=require_plate_clear,
  2030. wakeable_ids=wakeable_printer_ids,
  2031. printer_scope=item_scope,
  2032. is_short=is_short,
  2033. )
  2034. # "Only if the previous print succeeded" is about the
  2035. # printer the job lands on: one whose last print failed
  2036. # is passed over for another of the model.
  2037. if (
  2038. match_id
  2039. and item.require_previous_success
  2040. and not await self._check_previous_success(db, item, printer_id=match_id)
  2041. ):
  2042. gate_blocked.add(match_id)
  2043. continue
  2044. break
  2045. if match_id:
  2046. printer_id = match_id
  2047. chosen = candidate
  2048. break
  2049. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2050. # Nothing is available and nothing has been woken this pass:
  2051. # switch one matching printer on. Assignment is left to the
  2052. # next pass, which sees the booted printer's live state
  2053. # instead of guessing at it seconds after connect (#2786).
  2054. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2055. woken_id, attempted_id = await self._wake_printer_for_model(
  2056. db,
  2057. wakeable_candidates,
  2058. item.target_location,
  2059. busy_printers | interlocked.keys(),
  2060. wakeable_printer_ids,
  2061. require_plate_clear,
  2062. printer_scope=item_scope,
  2063. )
  2064. # An attempt spends the pass's one wake whether or not
  2065. # it worked: it has already blocked the queue loop for
  2066. # the boot wait. A failed printer is held out of later
  2067. # passes by its own cool-off, deliberately NOT by
  2068. # busy_printers — it is off, not busy, and labelling it
  2069. # busy would both misdescribe it in every later item's
  2070. # waiting reason and suppress the notification, since
  2071. # an all-busy reason is treated as needing no action.
  2072. power_on_attempted = attempted_id is not None
  2073. if woken_id is not None:
  2074. # Hold this item back rather than dispatching onto a
  2075. # printer whose AMS has not reported yet.
  2076. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2077. continue
  2078. if printer_id is None and gate_blocked:
  2079. # The matcher reports the printers passed over as busy;
  2080. # what holds the job is their failed last print.
  2081. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2082. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2083. # Fold the winning variant's file and settings onto the item
  2084. # before anything else looks at them — the guards below and
  2085. # every step of the dispatch read the item's own columns.
  2086. if chosen is not None:
  2087. self._resolve_variant(item, chosen)
  2088. # Update waiting_reason if changed and send notification when first waiting
  2089. if item.waiting_reason != waiting_reason:
  2090. was_waiting = item.waiting_reason is not None
  2091. previous_reason = item.waiting_reason
  2092. item.waiting_reason = waiting_reason
  2093. await db.commit()
  2094. # Send waiting notification only when transitioning to waiting state
  2095. # and the reason requires user action (not just "all printers busy")
  2096. # Also when a job that only waited for a busy printer
  2097. # now waits on something the user has to do.
  2098. if (
  2099. waiting_reason
  2100. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2101. and not self._is_busy_only(waiting_reason)
  2102. ):
  2103. job_name = await self._get_job_name(db, item)
  2104. await notification_service.on_queue_job_waiting(
  2105. job_name=job_name,
  2106. target_model=_candidate_model_label(candidates) or item.target_model,
  2107. waiting_reason=waiting_reason,
  2108. db=db,
  2109. )
  2110. if printer_id:
  2111. # Before claiming the printer: hold back rather than race
  2112. # another dispatch over the same transient library row.
  2113. # Checked here so a held item does not get a printer
  2114. # assigned and then sit on it. See _library_row_conflict().
  2115. #
  2116. # No busy_printers.add() here, unlike the fixed-printer
  2117. # branch above: that one protects its printer's own queue
  2118. # ordering, but this item was never assigned to `printer_id`
  2119. # — the matcher merely offered it. Marking it busy would
  2120. # strand an idle printer for the rest of the pass.
  2121. if _library_row_conflict(item):
  2122. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2123. continue
  2124. # Assign printer and start - clear waiting reason
  2125. item.printer_id = printer_id
  2126. item.waiting_reason = None
  2127. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2128. # Send assignment notification
  2129. job_name = await self._get_job_name(db, item)
  2130. printer = await self._get_printer(db, printer_id)
  2131. await notification_service.on_queue_job_assigned(
  2132. job_name=job_name,
  2133. printer_id=printer_id,
  2134. printer_name=printer.name if printer else "Unknown",
  2135. target_model=item.target_model,
  2136. db=db,
  2137. )
  2138. # A mapping on this item was not made for the printer just
  2139. # picked: it came with a job moved here from a fixed
  2140. # printer, or from a variant. Its tray IDs can name a
  2141. # tray of the right type in another colour here, which
  2142. # the fit check lets through (#3239). Match afresh, by
  2143. # type and colour.
  2144. if item.ams_mapping:
  2145. logger.info(
  2146. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2147. item.id,
  2148. item.ams_mapping,
  2149. printer_id,
  2150. )
  2151. item.ams_mapping = None
  2152. # Resolve the AMS mapping for the assigned printer. It is
  2153. # always missing here, so this computes it, and it also
  2154. # self-heals a bogus stored [-1] (#2589).
  2155. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2156. if unmappable:
  2157. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2158. continue
  2159. # Filament-deficit pre-dispatch check (#1496).
  2160. if await self._block_on_filament_deficit(db, item):
  2161. continue
  2162. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2163. # selection already filters on filament type, so this is a
  2164. # backstop for an AMS that changed between assignment and
  2165. # dispatch, and for a type loaded on the wrong nozzle.
  2166. # The assignment made above is released with the hold —
  2167. # this item asked for a model, not this printer.
  2168. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2169. continue
  2170. _claim_library_row(item)
  2171. dispatch_ids.append(item.id)
  2172. claim_printer(printer_id)
  2173. # SJF starvation guard: mark items that were jumped
  2174. if sjf_enabled and item.print_time_seconds is not None:
  2175. for other in items:
  2176. if (
  2177. other.id != item.id
  2178. and other.id not in dispatch_ids
  2179. and other.status == "pending"
  2180. and _could_take_printer(other, printer_id, item.target_model)
  2181. and not other.been_jumped
  2182. and other.position < item.position
  2183. and (
  2184. other.print_time_seconds is None
  2185. or other.print_time_seconds > item.print_time_seconds
  2186. )
  2187. ):
  2188. other.been_jumped = True
  2189. await db.commit()
  2190. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2191. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2192. # skip summary that only lands after the transfers have finished is
  2193. # useless for working out why an item did not go out.
  2194. if skip_reasons:
  2195. logger.info("Queue skip summary: %s", skip_reasons)
  2196. for pid in sorted(busy_printers):
  2197. reason = busy_reasons.get(pid, "no reason recorded")
  2198. if pid in claimed_printers:
  2199. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2200. continue
  2201. # The three live fields stay, because they are what someone
  2202. # reading a bundle wants next -- but they are labelled as read
  2203. # now, not as the state the decision was made on, which is what
  2204. # made the old line contradict itself.
  2205. state = printer_manager.get_status(pid)
  2206. logger.info(
  2207. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2208. pid,
  2209. reason,
  2210. printer_manager.is_connected(pid),
  2211. state.state if state else "NO_STATUS",
  2212. printer_manager.is_awaiting_plate_clear(pid),
  2213. )
  2214. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2215. # selection and `_launch_uploads`, so anything raising here would
  2216. # discard this tick's selections — computed AMS mappings and all —
  2217. # and, on a persistent fault, stop the queue dispatching entirely.
  2218. # Same reasoning as the deficit check's guard below: never let an
  2219. # auxiliary check wedge the queue. The bed simply stays wherever it
  2220. # was, and the next tick tries again.
  2221. try:
  2222. await self._apply_keep_warm(
  2223. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2224. )
  2225. except Exception as e:
  2226. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2227. # Read the concurrency limit BEFORE the commit below, not inside
  2228. # _dispatch_selected(). A SELECT on this session after the commit
  2229. # implicitly opens a fresh transaction that nothing then closes, and
  2230. # it would stay open for the whole dispatch — minutes of "idle in
  2231. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2232. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2233. # checkpointed while every dispatch is writing to it.
  2234. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2235. # Selection is done; every decision above is recorded on `db`
  2236. # (model-based printer assignment, computed ams_mapping). Flush it
  2237. # before the dispatch tasks open their own sessions, or they will
  2238. # read a row that still says printer_id=None. This also releases the
  2239. # connection back to the pool for the duration of the dispatch.
  2240. await db.commit()
  2241. if dispatch_ids:
  2242. item_printers = {it.id: it.printer_id for it in items}
  2243. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2244. # Auto-drying: start drying on idle printers that have no pending queue items
  2245. await self._check_auto_drying(db, items, dispatching_printers)
  2246. # Low filament: alert on assigned spools that have crossed their
  2247. # low-stock threshold (#2913). Runs on both paths out of this method
  2248. # for the same reason auto-drying does — an empty queue does not mean
  2249. # the spools in the printers stopped mattering.
  2250. await self._check_filament_low(db)
  2251. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2252. # is about to run out before a replenishment could arrive (#2955).
  2253. await self._check_stock_forecast(db)
  2254. # Keep the loop on the fast interval while any upload is in flight so
  2255. # a slot freed mid-tick refills within seconds rather than after the
  2256. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2257. # deferred because the pool was full) also counts as productive.
  2258. return bool(dispatch_ids) or bool(self._inflight)
  2259. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2260. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2261. Dispatch used to happen inline in the selection loop: ``await
  2262. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2263. performs the FTP upload, that serialized every printer behind every
  2264. other printer's transfer even though the printers are independent
  2265. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2266. gather was awaited before ``check_queue`` returned, so the run loop
  2267. stayed blocked until the *slowest* upload in the batch finished — a
  2268. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2269. 93-printer farm even as other printers came free (#2602).
  2270. Each upload now runs as an independent background task tracked in
  2271. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2272. `pending` until their upload completes) and their printers from the
  2273. next pass's selection, and this method launches at most
  2274. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2275. the next fast tick instead of waiting out the whole batch. The bound
  2276. exists because the printers are independent but the host is not: each
  2277. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2278. file handle.
  2279. The no-overlapping-dispatch invariant the batch-await used to provide
  2280. is now carried by the in-flight exclusion in check_queue. Everything
  2281. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2282. per-printer hold, and each item's independent failure handling — still
  2283. lives in ``_start_print`` and runs per task exactly as before.
  2284. Synchronous on purpose: it registers every launched task into
  2285. ``self._inflight`` before returning, so the next (sequential) tick sees
  2286. an accurate in-flight count with no interleaving await.
  2287. """
  2288. free = limit - len(self._inflight)
  2289. if free <= 0:
  2290. logger.info(
  2291. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2292. len(self._inflight),
  2293. limit,
  2294. len(item_ids),
  2295. item_ids,
  2296. )
  2297. return
  2298. to_launch = item_ids[:free]
  2299. deferred = item_ids[free:]
  2300. logger.info(
  2301. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2302. len(to_launch),
  2303. len(self._inflight),
  2304. limit,
  2305. f" — deferring {deferred} to a later tick" if deferred else "",
  2306. )
  2307. for item_id in to_launch:
  2308. task = spawn_background_task(
  2309. self._dispatch_one(item_id, item_printers.get(item_id)),
  2310. name=f"queue-upload-{item_id}",
  2311. )
  2312. self._inflight[item_id] = (task, item_printers.get(item_id))
  2313. # Prune on completion so the freed slot is refillable next tick.
  2314. # spawn_background_task already logs any uncaught exception; this
  2315. # only reclaims the pool slot (fires on success, failure, or cancel).
  2316. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2317. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2318. """Upload + start one queue item in its own session (pool worker, #2602).
  2319. Its own session: pool workers run concurrently and an AsyncSession is
  2320. not safe to share across tasks; it also keeps a slow upload from pinning
  2321. the scheduler's session (and, on SQLite, its transaction) open for the
  2322. transfer's duration.
  2323. ``selected_printer_id`` is the printer this item was selected for, taken
  2324. from the same snapshot the caller used. It exists so the preheat pin can
  2325. be unwound on the paths that never reach the ``finally`` below — see the
  2326. claim failure a few lines down. Optional so the direct-call tests keep
  2327. working; when it is absent those paths simply behave as they did before.
  2328. """
  2329. async with async_session() as item_db:
  2330. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2331. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2332. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2333. # routes reject reassignment (409), so printer_id can't change out from
  2334. # under the in-flight upload and split the queue row from the
  2335. # archive/expected-print/physical command.
  2336. if not await self._claim_for_dispatch(item_db, item_id):
  2337. logger.info(
  2338. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2339. item_id,
  2340. )
  2341. # This return is outside the try/finally below, so the rollback
  2342. # has to happen here. Selecting this item already handed any
  2343. # keep-warm hold on its printer over to the preheat pin
  2344. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2345. # unwind it. Bailing without doing so leaves the bed hot with
  2346. # nothing tracking it: the keep-warm entry is gone, so the
  2347. # max-duration cap no longer applies, and if this was the
  2348. # printer's last pending item nothing else will ever turn it
  2349. # off. Reachable whenever a cancel or delete lands between
  2350. # selection and the claim.
  2351. if selected_printer_id is not None:
  2352. self._rollback_preheat_pin(item_id, selected_printer_id)
  2353. return
  2354. # Seeded from the caller's snapshot so the `item vanished` return
  2355. # below still unwinds the pin; overwritten with the row's own
  2356. # printer_id as soon as we have it.
  2357. item_printer_id: int | None = selected_printer_id
  2358. try:
  2359. item = await item_db.get(PrintQueueItem, item_id)
  2360. if not item:
  2361. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2362. return
  2363. item_printer_id = item.printer_id
  2364. await self._start_print(item_db, item)
  2365. finally:
  2366. # Undo an expected-print registration whose print command never
  2367. # went out. One choke point covers every way `_start_print` can
  2368. # end without sending: a raised exception (a DB failure mid-
  2369. # dispatch is the reported case), an early return, a cancel
  2370. # winning the #1853 CAS, or `start_print()` returning False.
  2371. # A confirmed send removes the entry itself, so this is a no-op
  2372. # on the happy path.
  2373. self._rollback_unconfirmed_expected_print(item_id)
  2374. # Likewise the print user it set: the printer's next print is
  2375. # not this item's.
  2376. self._rollback_unconfirmed_print_user(item_id)
  2377. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2378. # reservation survives only after start_print() accepted the
  2379. # command. Failure, cancellation, deferral, and exceptions all
  2380. # release it here.
  2381. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2382. # Unwind preheat state (bed/chamber/airduct) if the
  2383. # dispatch aborted before the print's own gcode took over.
  2384. # `_start_print` clears the pin on successful `start_print()`;
  2385. # anything still present here is by definition an aborted
  2386. # dispatch and gets rolled back so the printer isn't left
  2387. # heating for a job that isn't happening.
  2388. if item_printer_id is not None:
  2389. self._rollback_preheat_pin(item_id, item_printer_id)
  2390. # The cancellation flag only has meaning while this dispatch is
  2391. # running; drop it so the set cannot grow without bound and a
  2392. # re-queued item never inherits a stale cancellation.
  2393. self._cancelled_dispatches.discard(item_id)
  2394. # Release the claim on every exit. Once dispatch has finished the
  2395. # row's status carries the lock (printing/failed/cancelled are all
  2396. # != pending), so the token is only needed for the duration of the
  2397. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2398. # dispatchable again on the next tick.
  2399. await self._clear_dispatch_claim(item_db, item_id)
  2400. async def _requeue_after_upload_refused(
  2401. self,
  2402. db: AsyncSession,
  2403. item: PrintQueueItem,
  2404. printer: Printer,
  2405. error_msg: str,
  2406. toast_uid: int | None,
  2407. ) -> None:
  2408. """Put an item back in the queue after its file never reached the printer (#3210).
  2409. The item keeps its printer. Its AMS mapping was computed against that
  2410. printer's trays, and nothing on the row says whether a mapping was
  2411. computed or set by the user, so moving it to a sibling could print from
  2412. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2413. keeps every other item away from it; this one waits there and is the
  2414. only thing that knocks again, once per backoff window. The window
  2415. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2416. `dispatch_attempts` is not charged: that budget bounds a printer that
  2417. takes the file and then never starts, which this is not.
  2418. """
  2419. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2420. self._upload_refusals[printer.id] = refusals
  2421. backoff = _upload_backoff_seconds(refusals)
  2422. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2423. # The row is still `pending` -- it only moves to `printing` after a
  2424. # successful upload -- so there is no status to write back. Writing one
  2425. # anyway would undo a cancel that landed during the upload.
  2426. if item.error_message:
  2427. item.error_message = None
  2428. await db.commit()
  2429. logger.warning(
  2430. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2431. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2432. item.id,
  2433. printer.id,
  2434. printer.name,
  2435. error_msg,
  2436. refusals,
  2437. backoff,
  2438. )
  2439. try:
  2440. # Closes the dispatch toast for this attempt. Without it the toast
  2441. # keeps spinning on an upload that has ended.
  2442. await ws_manager.send_queue_item_failed(
  2443. user_id=toast_uid,
  2444. queue_item_id=item.id,
  2445. printer_id=item.printer_id,
  2446. reason="upload_failed",
  2447. )
  2448. except Exception:
  2449. pass # toast is best-effort
  2450. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2451. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2452. if printer_id is not None:
  2453. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2454. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2455. """Withdraw the expected print and print user of a sent print that never started.
  2456. Both tell the rest of Bambuddy that the printer's next print is this
  2457. item's: left behind, a print started by hand later is taken for it.
  2458. With ``unless_printing``, a printer that is printing after all keeps
  2459. them, as that print is most likely this one starting late.
  2460. ``keep_expected`` withdraws only the print user, which vouches for any
  2461. print on the printer. The expected print names this item's file, so a
  2462. late start of it is still matched to its archive.
  2463. """
  2464. sent = self._sent_unstarted_print.get(item_id)
  2465. if sent is None:
  2466. return
  2467. printer_id, remote_filename, archive_id = sent
  2468. if unless_printing:
  2469. status = printer_manager.get_status(printer_id)
  2470. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2471. return
  2472. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2473. if keep_expected:
  2474. return
  2475. del self._sent_unstarted_print[item_id]
  2476. if remote_filename is not None and archive_id is not None:
  2477. try:
  2478. from backend.app.main import unregister_expected_print
  2479. unregister_expected_print(printer_id, remote_filename, archive_id)
  2480. except Exception:
  2481. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2482. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2483. """Drop an expectation for a print command that was never sent.
  2484. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2485. where the interesting exception is usually the one already propagating.
  2486. """
  2487. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2488. if pending is None:
  2489. return
  2490. printer_id, remote_filename, archive_id = pending
  2491. try:
  2492. from backend.app.main import unregister_expected_print
  2493. unregister_expected_print(printer_id, remote_filename, archive_id)
  2494. except Exception:
  2495. logger.warning(
  2496. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2497. item_id,
  2498. printer_id,
  2499. remote_filename,
  2500. archive_id,
  2501. exc_info=True,
  2502. )
  2503. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2504. """Release a queue reservation without touching the dispatch session."""
  2505. if item_id not in self._unconfirmed_budget_reservations:
  2506. return
  2507. for attempt in range(1, 4):
  2508. async with async_session() as cleanup_db:
  2509. try:
  2510. await release_budget_reservation(
  2511. cleanup_db,
  2512. source_type="print_queue",
  2513. source_id=item_id,
  2514. status="released",
  2515. )
  2516. await cleanup_db.commit()
  2517. self._unconfirmed_budget_reservations.discard(item_id)
  2518. return
  2519. except Exception as exc:
  2520. try:
  2521. await cleanup_db.rollback()
  2522. except Exception:
  2523. pass
  2524. if attempt == 3:
  2525. logger.error(
  2526. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2527. item_id,
  2528. attempt,
  2529. exc,
  2530. )
  2531. return
  2532. await asyncio.sleep(0.5 * attempt)
  2533. @staticmethod
  2534. def _reported_bed_target(printer_id: int) -> int | None:
  2535. """The bed target firmware currently reports, or None if it can't be read.
  2536. None means "no evidence", not "zero" — callers must not treat it as a
  2537. temperature. Deliberately total: this feeds cleanup paths that run in a
  2538. ``finally``, where a malformed status must not become the exception the
  2539. caller sees.
  2540. """
  2541. try:
  2542. state = printer_manager.get_status(printer_id)
  2543. if state is None:
  2544. return None
  2545. temps = state.temperatures
  2546. if not isinstance(temps, dict):
  2547. return None
  2548. return int(float(temps.get("bed_target", 0) or 0))
  2549. except (TypeError, ValueError, AttributeError):
  2550. return None
  2551. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2552. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2553. Turns the bed heater off, the chamber heater off, and opens the
  2554. airduct flap back to cooling — for whichever of those preheat
  2555. actually applied. `_start_print` clears the pin on successful
  2556. `start_print()`; anything still present when `_dispatch_one` exits
  2557. is by definition an aborted dispatch and gets rolled back here.
  2558. The bed is the one action that can be declined: if firmware has since
  2559. been given a target other than the one we pinned, it belongs to someone
  2560. else and is left alone. See the comment at that branch.
  2561. Also called directly from `_dispatch_one`'s claim-failure return, which
  2562. never reaches the ``finally``.
  2563. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2564. """
  2565. pin = self._preheat_pin.pop(printer_id, set())
  2566. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2567. if not pin:
  2568. return
  2569. client = printer_manager.get_client(printer_id)
  2570. if client is None:
  2571. logger.info(
  2572. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2573. item_id,
  2574. printer_id,
  2575. )
  2576. return
  2577. if "bed" in pin:
  2578. # Only undo our own target. If firmware reports something else, the
  2579. # user or another writer owns the bed now and zeroing it would
  2580. # clobber their choice -- the same guard `_release_keep_warm`
  2581. # applies to a keep-warm hold.
  2582. #
  2583. # Every uncertain case switches the bed off rather than leaving it:
  2584. # no recorded target (a pin written before this bookkeeping, or a
  2585. # setter that raised after pinning) and an unreadable status both
  2586. # fall through. A bed left hot with no owner is the worse failure,
  2587. # and this runs in a `finally` where raising would mask the real
  2588. # exception.
  2589. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2590. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2591. logger.info(
  2592. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2593. item_id,
  2594. printer_id,
  2595. cur_bed_target,
  2596. pinned_bed,
  2597. )
  2598. else:
  2599. try:
  2600. client.set_bed_temperature(0)
  2601. except Exception as exc:
  2602. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2603. if "chamber" in pin:
  2604. try:
  2605. client.set_chamber_temperature(0)
  2606. except Exception as exc:
  2607. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2608. if "airduct" in pin:
  2609. try:
  2610. client.set_airduct_mode("cooling")
  2611. except Exception as exc:
  2612. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2613. logger.info(
  2614. "Dispatch item %s (printer %d): preheat rollback → %s",
  2615. item_id,
  2616. printer_id,
  2617. sorted(pin),
  2618. )
  2619. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  2620. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2621. Returns True if this call won the claim, False if the row was already
  2622. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2623. the load-bearing guard against reassign-during-dispatch (#2615)."""
  2624. res = await db.execute(
  2625. update(PrintQueueItem)
  2626. .where(PrintQueueItem.id == item_id)
  2627. .where(PrintQueueItem.status == "pending")
  2628. .where(PrintQueueItem.dispatching_at.is_(None))
  2629. .values(dispatching_at=datetime.now(timezone.utc))
  2630. )
  2631. await db.commit()
  2632. return res.rowcount > 0
  2633. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2634. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2635. mask the dispatch outcome.
  2636. Retried, because the failure mode in practice is transient and narrow: a
  2637. database that is momentarily unreachable — PostgreSQL out of connection
  2638. slots is the observed case — refuses this write for a second or two while
  2639. the dispatch that just ended is still holding the row out of the selection
  2640. query. One attempt was enough to wedge the item; a couple of spaced
  2641. attempts clear it. Each attempt rolls back first, since a failed write
  2642. leaves the session needing it before it can be reused.
  2643. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2644. on the next quiet tick.
  2645. """
  2646. for attempt in range(1, 4):
  2647. try:
  2648. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2649. await db.commit()
  2650. return
  2651. except Exception as exc:
  2652. try:
  2653. await db.rollback()
  2654. except Exception:
  2655. pass
  2656. if attempt == 3:
  2657. logger.warning(
  2658. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2659. "— a later quiet tick will release it",
  2660. item_id,
  2661. attempt,
  2662. exc,
  2663. )
  2664. return
  2665. await asyncio.sleep(0.5 * attempt)
  2666. async def _printers_for_model(
  2667. self,
  2668. db: AsyncSession,
  2669. model: str,
  2670. target_location: str | None = None,
  2671. printer_scope: PrinterScope = ALL_PRINTERS,
  2672. ) -> list[Printer]:
  2673. """Active printers of *model*, optionally narrowed to one location.
  2674. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2675. answer "which printers can this job run on" from one query — a job can
  2676. only be woken onto a printer the matcher would also have considered.
  2677. ``printer_scope`` is the job creator's (#1727).
  2678. """
  2679. normalized_model = normalize_printer_model(model) or model
  2680. query = (
  2681. select(Printer)
  2682. .where(func.lower(Printer.model) == normalized_model.lower())
  2683. .where(Printer.is_active == True) # noqa: E712
  2684. )
  2685. if target_location:
  2686. query = query.where(Printer.location == target_location)
  2687. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2688. query = query.where(clause)
  2689. result = await db.execute(query)
  2690. return list(result.scalars().all())
  2691. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2692. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2693. Read once per queue check rather than per printer: it decides both
  2694. whether the wake step has anything to do and how an offline printer is
  2695. worded in the waiting reason — "Offline" and "offline with no Auto On
  2696. plug" are different problems, and the second is the one the user has to
  2697. fix themselves (#2786).
  2698. """
  2699. result = await db.execute(
  2700. select(SmartPlug.printer_id)
  2701. .where(SmartPlug.printer_id.is_not(None))
  2702. .where(SmartPlug.enabled == True) # noqa: E712
  2703. .where(SmartPlug.auto_on == True) # noqa: E712
  2704. )
  2705. return {pid for (pid,) in result.all() if pid is not None}
  2706. def _wake_recently_failed(self, printer_id: int) -> bool:
  2707. """True while this printer's failed power-on is still cooling off (#2786)."""
  2708. deadline = self._wake_failures.get(printer_id)
  2709. if deadline is None:
  2710. return False
  2711. if time.monotonic() >= deadline:
  2712. del self._wake_failures[printer_id]
  2713. return False
  2714. return True
  2715. async def _wake_printer_for_model(
  2716. self,
  2717. db: AsyncSession,
  2718. candidates: list[_ModelCandidate],
  2719. target_location: str | None,
  2720. exclude_ids: set[int],
  2721. wakeable_ids: set[int],
  2722. require_plate_clear: bool,
  2723. printer_scope: PrinterScope = ALL_PRINTERS,
  2724. ) -> tuple[int | None, int | None]:
  2725. """Power on one offline printer a model-based item could run on (#2786).
  2726. The fixed-printer branch has powered a printer on since smart plugs
  2727. existed. The model-based branch never could: its matcher drops an
  2728. offline printer into the "Offline:" waiting reason and nothing looks at
  2729. its plugs, so a class-targeted job with every matching printer switched
  2730. off sat pending forever. The reporter's log is the controlled
  2731. experiment — the same item, same plug, same Auto On setting, dispatched
  2732. the moment they edited it onto a specific printer.
  2733. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2734. power-on was actually tried, so the caller can tell "nothing here was
  2735. wakeable" (both None — cheap, other items may still find something)
  2736. from "we tried and it did not come up" (only ``attempted_id`` — the
  2737. boot timeout has already been spent).
  2738. A printer whose last known trays cannot satisfy the job is passed over
  2739. rather than woken (#2876): the colours are readable while it is off, so
  2740. switching a farm on one machine at a time to discover them wakes
  2741. printers that could never have taken the job.
  2742. Deliberately does NOT go on to match the job once a printer is up: AMS
  2743. trays arrive with the first status push after connect, so a filament
  2744. check against a printer that booted seconds ago can reject the printer
  2745. we just woke. The next queue pass matches it with live state.
  2746. At most one printer per pass. Each wake blocks the queue loop for the
  2747. boot wait, and a queue of ten class-targeted jobs must not switch on
  2748. ten printers inside one check.
  2749. """
  2750. for candidate in candidates:
  2751. if not candidate.target_model:
  2752. continue
  2753. required_types, filament_overrides = _filament_constraints(candidate)
  2754. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2755. for printer in sorted(printers, key=lambda p: p.id):
  2756. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2757. continue
  2758. if printer_manager.is_connected(printer.id):
  2759. continue
  2760. if self._wake_recently_failed(printer.id):
  2761. # Its plug did not bring it back a moment ago. Move on to a
  2762. # sibling instead of spending this pass — and every pass —
  2763. # on the same printer.
  2764. continue
  2765. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2766. # Waking this one buys nothing: it would boot into IDLE and
  2767. # then be held by the plate-clear gate, which is exactly
  2768. # what the reporter's log shows happening for 80 minutes
  2769. # after a fixed-printer wake. The flag is Bambuddy-side and
  2770. # persisted, so it is readable while the printer is off.
  2771. logger.info(
  2772. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2773. printer.id,
  2774. candidate.target_model,
  2775. )
  2776. continue
  2777. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2778. if shortfall:
  2779. logger.info(
  2780. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2781. printer.id,
  2782. candidate.target_model,
  2783. ", ".join(shortfall),
  2784. )
  2785. continue
  2786. plugs = await self._get_smart_plugs(db, printer.id)
  2787. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2788. if not auto_on_plugs:
  2789. # wakeable_ids said otherwise — the plug changed under us
  2790. # mid-pass. Nothing to do but move on.
  2791. continue
  2792. logger.info(
  2793. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2794. candidate.target_model,
  2795. printer.id,
  2796. )
  2797. primary_plug = self._pick_power_plug(auto_on_plugs)
  2798. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2799. logger.warning(
  2800. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2801. printer.id,
  2802. self._wake_failure_cooloff,
  2803. )
  2804. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2805. return None, printer.id
  2806. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2807. try:
  2808. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2809. if await service.turn_on(extra_plug):
  2810. await publish_plug_state(
  2811. extra_plug.id,
  2812. extra_plug.name,
  2813. extra_plug.printer_id,
  2814. on=True,
  2815. ha_entity_id=extra_plug.ha_entity_id,
  2816. )
  2817. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2818. except Exception as e:
  2819. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2820. return printer.id, printer.id
  2821. return None, None
  2822. async def _find_idle_printer_for_model(
  2823. self,
  2824. db: AsyncSession,
  2825. model: str,
  2826. exclude_ids: set[int],
  2827. required_filament_types: list[str] | None = None,
  2828. target_location: str | None = None,
  2829. filament_overrides: list[dict] | None = None,
  2830. require_plate_clear: bool = True,
  2831. wakeable_ids: set[int] | None = None,
  2832. printer_scope: PrinterScope = ALL_PRINTERS,
  2833. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2834. ) -> tuple[int | None, str | None]:
  2835. """Find an idle, connected printer matching the model with compatible filaments.
  2836. Args:
  2837. db: Database session
  2838. model: Printer model to match (e.g., "X1C", "P1S")
  2839. exclude_ids: Printer IDs to exclude (already busy)
  2840. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2841. If provided, only printers with all required types loaded will match.
  2842. target_location: Optional location filter. If provided, only printers in this location are considered.
  2843. filament_overrides: Optional list of override dicts. Each entry may include
  2844. ``force_color_match: true`` to require an exact type+color match
  2845. on the printer for that slot. Without the flag the existing
  2846. colour-preference logic applies.
  2847. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2848. offline printer is worded: one Bambuddy will switch on reads
  2849. differently from one the user has to go and switch on themselves.
  2850. is_short: Says whether a printer's spools are too light for the job (#3137).
  2851. A printer it flags is passed over while another eligible one
  2852. is not. When every eligible printer is short, the first is
  2853. returned all the same, so the deficit gate holds the job there
  2854. and "Print Anyway" still has a printer to print on.
  2855. Returns:
  2856. Tuple of (printer_id, waiting_reason):
  2857. - (printer_id, None) if a matching printer was found
  2858. - (None, reason) if no printer is available, with explanation
  2859. """
  2860. normalized_model = normalize_printer_model(model) or model
  2861. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2862. location_suffix = f" in {target_location}" if target_location else ""
  2863. if not printers:
  2864. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2865. # Separate force-matched overrides from preference-only overrides
  2866. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2867. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2868. # Track reasons for skipping printers
  2869. printers_busy = []
  2870. printers_offline = []
  2871. printers_offline_no_plug = []
  2872. printers_missing_filament: list[tuple[str, list[str]]] = []
  2873. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2874. # The first eligible printer that is short on filament, kept in case
  2875. # every eligible printer is (#3137).
  2876. short_fallback: int | None = None
  2877. for printer in printers:
  2878. if printer.id in exclude_ids:
  2879. # Printer is already claimed by another job in this scheduling run.
  2880. # For force-color jobs, still check if the color would match — if not,
  2881. # report it as a color mismatch rather than plain "Busy" so the user
  2882. # knows the job needs a filament change, not just to wait for availability.
  2883. if force_overrides and not pref_overrides:
  2884. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2885. if missing_colors:
  2886. printers_missing_filament.append((printer.name, missing_colors))
  2887. continue
  2888. printers_busy.append(printer.name)
  2889. continue
  2890. is_connected = printer_manager.is_connected(printer.id)
  2891. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2892. if not is_connected:
  2893. # An offline printer whose last known filament cannot run this
  2894. # job is reported as needing filament rather than as offline
  2895. # (#2876). It is also the printer the smart-plug step will now
  2896. # decline to switch on, and "Offline:" on its own would leave
  2897. # that decision looking like nothing happening at all.
  2898. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2899. if shortfall:
  2900. printers_missing_filament.append((printer.name, shortfall))
  2901. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2902. printers_offline_no_plug.append(printer.name)
  2903. else:
  2904. printers_offline.append(printer.name)
  2905. continue
  2906. if not is_idle:
  2907. # Printer is currently printing. For force-color jobs, check whether the
  2908. # loaded color would satisfy the requirement — if not, surface it as a
  2909. # color-mismatch reason rather than plain "Busy" so the user understands
  2910. # that the job is waiting for a filament change, not just printer availability.
  2911. if force_overrides and not pref_overrides:
  2912. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2913. if missing_colors:
  2914. printers_missing_filament.append((printer.name, missing_colors))
  2915. logger.debug(
  2916. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2917. printer.id,
  2918. printer.name,
  2919. missing_colors,
  2920. )
  2921. continue
  2922. printers_busy.append(printer.name)
  2923. continue
  2924. # Validate filament compatibility if required types are specified
  2925. if required_filament_types:
  2926. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2927. if missing:
  2928. # When force_overrides are present, enrich missing entries with color info
  2929. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2930. if force_overrides:
  2931. force_color_map = {
  2932. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2933. for o in force_overrides
  2934. }
  2935. missing_enriched = [
  2936. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2937. for t in missing
  2938. ]
  2939. printers_missing_filament.append((printer.name, missing_enriched))
  2940. else:
  2941. printers_missing_filament.append((printer.name, missing))
  2942. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2943. continue
  2944. # Force color match: ALL flagged slots must have an exact type+color match
  2945. if force_overrides:
  2946. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2947. if missing_colors:
  2948. printers_missing_filament.append((printer.name, missing_colors))
  2949. logger.debug(
  2950. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2951. printer.id,
  2952. printer.name,
  2953. missing_colors,
  2954. )
  2955. continue
  2956. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2957. if pref_overrides:
  2958. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2959. if color_matches > 0:
  2960. candidates.append((printer.id, color_matches))
  2961. else:
  2962. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2963. printers_missing_filament.append((printer.name, override_colors))
  2964. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2965. continue
  2966. else:
  2967. # No preference ordering needed: the first eligible printer
  2968. # wins, unless its spools are too light for the job (#3137).
  2969. if is_short is not None and await is_short(printer.id):
  2970. if short_fallback is None:
  2971. short_fallback = printer.id
  2972. logger.info(
  2973. "Model-based assignment: passing over printer %s (%s), not enough filament",
  2974. printer.id,
  2975. printer.name,
  2976. )
  2977. continue
  2978. return printer.id, None
  2979. # If we have candidates from preference override matching, pick the one with most color matches
  2980. if candidates:
  2981. candidates.sort(key=lambda c: c[1], reverse=True)
  2982. if is_short is not None:
  2983. for candidate_id, _ in candidates:
  2984. if not await is_short(candidate_id):
  2985. return candidate_id, None
  2986. logger.info(
  2987. "Model-based assignment: passing over printer %s, not enough filament",
  2988. candidate_id,
  2989. )
  2990. return candidates[0][0], None
  2991. if short_fallback is not None:
  2992. return short_fallback, None
  2993. # Build waiting reason from what we found
  2994. reasons = []
  2995. if printers_missing_filament:
  2996. # Filament/color mismatch is most actionable - show first
  2997. if force_overrides and not pref_overrides:
  2998. # All mismatches are force-color failures — use descriptive message only;
  2999. # but only if there are no busy printers that DO have the matching color.
  3000. # If a printer has the right color but is busy, surface "Busy" instead so
  3001. # the user knows the job will start automatically once that printer is free.
  3002. # Same for a printer that is merely offline: Bambuddy switches that one on
  3003. # by itself, so the job is not actually waiting on anybody to change a
  3004. # spool (#2876 — offline printers reach this list now that a switched-off
  3005. # printer's own filament is read).
  3006. if not printers_busy and not printers_offline:
  3007. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3008. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3009. # else: fall through — the self-resolving entries are appended below
  3010. else:
  3011. names_and_missing = [
  3012. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3013. ]
  3014. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3015. if printers_busy:
  3016. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3017. if printers_offline:
  3018. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3019. if printers_offline_no_plug:
  3020. # Named separately because it is the one entry on this list the
  3021. # user has to act on: no enabled Auto On plug means Bambuddy will
  3022. # never power this printer on for the queue (#2786).
  3023. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3024. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3025. @staticmethod
  3026. def _is_busy_only(waiting_reason: str) -> bool:
  3027. """Check if the waiting reason only contains 'Busy' entries.
  3028. When all matching printers are simply busy printing, the queued job
  3029. will start automatically once a printer finishes — no user action
  3030. is required, so we skip the notification.
  3031. """
  3032. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3033. return all(p.startswith("Busy:") for p in parts)
  3034. def _get_missing_force_color_slots(
  3035. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3036. ) -> list[str]:
  3037. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3038. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3039. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3040. with an exact type+color match.
  3041. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3042. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3043. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3044. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3045. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3046. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3047. setups are unaffected.
  3048. Returns:
  3049. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3050. """
  3051. if raw_data is None:
  3052. status = printer_manager.get_status(printer_id)
  3053. if not status:
  3054. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3055. raw_data = status.raw_data
  3056. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3057. loaded: list[tuple[str, str, str]] = []
  3058. for ams_unit in raw_data.get("ams", []):
  3059. for tray in ams_unit.get("tray", []):
  3060. tray_type = tray.get("tray_type")
  3061. if tray_type:
  3062. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3063. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3064. for vt in raw_data.get("vt_tray") or []:
  3065. vt_type = vt.get("tray_type")
  3066. if vt_type:
  3067. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3068. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3069. missing = []
  3070. for o in force_overrides:
  3071. o_type = canonical_filament_type(o.get("type") or "")
  3072. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3073. o_idx = o.get("tray_info_idx") or ""
  3074. satisfied = any(
  3075. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  3076. for t_type, t_color, t_idx in loaded
  3077. )
  3078. if not satisfied:
  3079. color_label = o.get("color_name") or o.get("color", "?")
  3080. missing.append(f"{o_type} ({color_label})")
  3081. return missing
  3082. def _get_missing_filament_types(
  3083. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3084. ) -> list[str]:
  3085. """Get the list of required filament types that are not loaded on the printer.
  3086. Args:
  3087. printer_id: The printer ID
  3088. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3089. Returns:
  3090. List of missing filament types (empty if all are loaded)
  3091. """
  3092. if raw_data is None:
  3093. status = printer_manager.get_status(printer_id)
  3094. if not status:
  3095. return required_types # Can't determine, assume all missing
  3096. raw_data = status.raw_data
  3097. # Collect all filament types loaded on this printer (AMS units + external spool)
  3098. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3099. loaded_types: set[str] = set()
  3100. # Check AMS units (stored in raw_data["ams"])
  3101. ams_data = raw_data.get("ams", [])
  3102. if ams_data:
  3103. for ams_unit in ams_data:
  3104. for tray in ams_unit.get("tray", []):
  3105. tray_type = tray.get("tray_type")
  3106. if tray_type:
  3107. loaded_types.add(canonical_filament_type(tray_type))
  3108. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3109. for vt in raw_data.get("vt_tray") or []:
  3110. vt_type = vt.get("tray_type")
  3111. if vt_type:
  3112. loaded_types.add(canonical_filament_type(vt_type))
  3113. # Find which required types are missing (using canonical type for equivalence)
  3114. missing = []
  3115. for req_type in required_types:
  3116. if canonical_filament_type(req_type) not in loaded_types:
  3117. missing.append(req_type)
  3118. return missing
  3119. def _count_override_color_matches(
  3120. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3121. ) -> int:
  3122. """Count how many filament overrides have an exact color match on the printer.
  3123. Used to prefer printers that already have the desired override colors loaded.
  3124. """
  3125. if raw_data is None:
  3126. status = printer_manager.get_status(printer_id)
  3127. if not status:
  3128. return 0
  3129. raw_data = status.raw_data
  3130. # Collect loaded filaments' type+color pairs
  3131. loaded: set[tuple[str, str]] = set()
  3132. for ams_unit in raw_data.get("ams", []):
  3133. for tray in ams_unit.get("tray", []):
  3134. tray_type = tray.get("tray_type")
  3135. # `or ""`, not a dict default: a slot can carry the key with a
  3136. # null value, and this now runs against switched-off printers
  3137. # too, where nobody is watching for the AttributeError.
  3138. tray_color = tray.get("tray_color") or ""
  3139. if tray_type:
  3140. color_norm = tray_color.replace("#", "").lower()[:6]
  3141. loaded.add((tray_type.upper(), color_norm))
  3142. for vt in raw_data.get("vt_tray") or []:
  3143. vt_type = vt.get("tray_type")
  3144. if vt_type:
  3145. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3146. loaded.add((vt_type.upper(), color_norm))
  3147. matches = 0
  3148. for o in overrides:
  3149. o_type = (o.get("type") or "").upper()
  3150. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3151. if (o_type, o_color) in loaded:
  3152. matches += 1
  3153. return matches
  3154. @staticmethod
  3155. def _tray_reading(printer_id: int) -> dict:
  3156. """The best tray reading available for a printer that is not printing.
  3157. Live status first: a printer keeps its last status after the power
  3158. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3159. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3160. for when the client itself has been dropped and taken its status with
  3161. it — which is what every power-on attempt does.
  3162. An empty result means "we have never heard", not "nothing is loaded":
  3163. the two are indistinguishable from here, and only the second would be
  3164. safe to act on.
  3165. """
  3166. status = printer_manager.get_status(printer_id)
  3167. raw = (status.raw_data if status else None) or {}
  3168. for ams_unit in raw.get("ams") or []:
  3169. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3170. return raw
  3171. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3172. return raw
  3173. return printer_manager.last_known_trays(printer_id)
  3174. def _cached_filament_shortfall(
  3175. self,
  3176. printer_id: int,
  3177. required_types: list[str] | None,
  3178. filament_overrides: list[dict] | None,
  3179. ) -> list[str]:
  3180. """What a switched-off printer's last known filament cannot provide (#2876).
  3181. The smart-plug wake step used to consider only the model, so a job for a
  3182. colour loaded on the last printer in ID order switched on every earlier
  3183. one in turn, evaluated it, rejected it on colour and left it running.
  3184. Bambuddy knew those colours the whole time. This asks the same three
  3185. questions the matcher asks a live printer — required types, forced
  3186. colours, preferred colours — of the trays it last reported, and returns
  3187. the answers in the same shape the "Waiting for filament" reason uses.
  3188. Empty means the printer may still be able to take the job.
  3189. Fails open, and deliberately: with no tray reading (never connected
  3190. since Bambuddy started, or the cache dropped by a reconnect) this
  3191. returns nothing to report and the printer is treated as it was before.
  3192. A farm restarted while its printers were off must not conclude that
  3193. none of them can print.
  3194. """
  3195. if not required_types and not filament_overrides:
  3196. return []
  3197. raw_data = self._tray_reading(printer_id)
  3198. if not raw_data:
  3199. return []
  3200. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3201. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3202. if required_types:
  3203. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3204. if missing:
  3205. # Same enrichment the live path applies: a bare "PLA" is not
  3206. # much help when what is missing is a particular PLA.
  3207. force_color_map = {
  3208. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3209. }
  3210. return [
  3211. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3212. for t in missing
  3213. ]
  3214. if force_overrides:
  3215. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3216. if missing_colors:
  3217. return missing_colors
  3218. # Preference overrides read as a preference but the matcher treats zero
  3219. # matches as a skip, so a printer with none of the wanted colours is
  3220. # rejected there too. Waking it would only produce that same rejection.
  3221. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3222. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3223. return []
  3224. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3225. """Fold the winning candidate's file and settings onto the queue row (#671).
  3226. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3227. never escapes the selection loop. By the time the pass commits, the row
  3228. looks exactly like an ordinary single-file model-based item, so the upload,
  3229. archive creation, expected-print registration, print history and reprint
  3230. paths need no knowledge that variants exist.
  3231. No-ops for a non-variant candidate, which is already the item's own columns.
  3232. Safe to run and re-run: the item's file columns are only ever *read* when it
  3233. has no variants, so an item that gets resolved and then skipped (library-row
  3234. conflict, previous-print gate) is simply resolved again on the next pass.
  3235. """
  3236. variant = candidate.variant
  3237. if variant is None:
  3238. return
  3239. item.library_file_id = variant.library_file_id
  3240. item.library_file = variant.library_file
  3241. # The dispatcher checks archive_id first and would print that instead of
  3242. # the file we just picked. Creation refuses to combine the two, so this
  3243. # only ever fires on a hand-written row — clear it rather than silently
  3244. # dispatch something the matcher never considered.
  3245. item.archive_id = None
  3246. item.archive = None
  3247. item.target_model = variant.target_model
  3248. item.plate_id = variant.plate_id
  3249. item.ams_mapping = variant.ams_mapping
  3250. item.nozzle_mapping = variant.nozzle_mapping
  3251. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3252. item.filament_overrides = variant.filament_overrides
  3253. item.required_filament_types = variant.required_filament_types
  3254. if variant.print_time_seconds is not None:
  3255. # The row carried the shortest candidate's estimate so SJF could order
  3256. # it before a printer was known; now that one is chosen, record what is
  3257. # actually going to run so history and the ETA agree with reality.
  3258. item.print_time_seconds = variant.print_time_seconds
  3259. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3260. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3261. Recomputes from live printer status when the stored mapping is missing OR
  3262. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3263. frontend status-load race can serialize [-1] before the printer's AMS
  3264. trays are known (#2589) — and must not be trusted: downstream it would be
  3265. silently downgraded to external-spool mode and print against an empty
  3266. feed. A resolved mapping is re-checked against the target printer's
  3267. live trays before it is trusted (#2799) and recomputed when it does not
  3268. fit. When it does fit, its resolved slots are kept as they are and only
  3269. the slots the plate prints that are still unresolved are matched again;
  3270. all of it is left alone when the user has acknowledged it with "Print
  3271. Anyway".
  3272. When recompute cannot resolve it either (no compatible tray loaded), the
  3273. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3274. external selection. On a printer that reported loaded trays,
  3275. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3276. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3277. and the firmware surfaces a clear AMS-mapping error instead of silently
  3278. printing to the empty external feed.
  3279. Returns an actionable message when that firmware error is the only
  3280. possible outcome — the matcher ran, matched nothing, and the printer has
  3281. no AMS to load a different spool into (#2771). The caller fails the item
  3282. on it instead of spending an upload on a print that cannot start.
  3283. Returns None everywhere else, including every case where we simply lack
  3284. the data to judge, so dispatch is only ever blocked on a positive
  3285. finding.
  3286. """
  3287. stored_mapping: list | None = None
  3288. if item.ams_mapping:
  3289. try:
  3290. stored_mapping = json.loads(item.ams_mapping)
  3291. except (json.JSONDecodeError, TypeError):
  3292. stored_mapping = None
  3293. # Present and resolved. Global tray IDs only mean something relative to
  3294. # the printer they were resolved against, so "resolved" is not the same
  3295. # as "resolved *here*" — check the mapping still fits the printer that
  3296. # is about to run this item before trusting it (#2799). "Print anyway"
  3297. # is the user overriding exactly this judgement, so it short-circuits.
  3298. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3299. if item.skip_filament_check:
  3300. return None
  3301. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3302. if conflict is None:
  3303. # It fits, but a slot the plate prints may still be empty: the
  3304. # spool was missing when it was mapped, and has perhaps been
  3305. # loaded since. Nothing else would ever look at that slot again,
  3306. # so a job held for it would be held again on every Start.
  3307. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3308. if filled is not None:
  3309. item.ams_mapping = json.dumps(filled)
  3310. logger.info(
  3311. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3312. item.id,
  3313. stored_mapping,
  3314. printer_id,
  3315. filled,
  3316. )
  3317. await db.commit()
  3318. return None
  3319. logger.warning(
  3320. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3321. item.id,
  3322. stored_mapping,
  3323. printer_id,
  3324. conflict,
  3325. )
  3326. # Drop it before recomputing so a failed recompute cannot fall back
  3327. # to the mapping we just rejected.
  3328. item.ams_mapping = None
  3329. stored_mapping = None
  3330. await db.commit()
  3331. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3332. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3333. item.ams_mapping = json.dumps(computed_mapping)
  3334. logger.info(
  3335. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3336. item.id,
  3337. printer_id,
  3338. computed_mapping,
  3339. )
  3340. await db.commit()
  3341. return None
  3342. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3343. if external_only is not None:
  3344. item.ams_mapping = json.dumps(external_only)
  3345. logger.info(
  3346. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3347. "mapping every filament to it: %s",
  3348. item.id,
  3349. printer_id,
  3350. external_only,
  3351. )
  3352. await db.commit()
  3353. return None
  3354. if _mapping_is_all_unresolved(stored_mapping):
  3355. logger.warning(
  3356. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3357. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3358. item.id,
  3359. stored_mapping,
  3360. printer_id,
  3361. )
  3362. item.ams_mapping = None
  3363. await db.commit()
  3364. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3365. async def _external_spool_only_mapping(
  3366. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3367. ) -> list[int] | None:
  3368. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3369. A printer without an AMS prints from its external spool, and an external
  3370. spool whose filament was never set reports no type, so the matcher has
  3371. nothing to match. Sent without a mapping, the print goes out with the AMS
  3372. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3373. to carry such a job through; a job placed by model or location no longer
  3374. keeps one, and one queued that way never had one.
  3375. Only on a positive report: the printer has said it has no AMS, it has a
  3376. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3377. is not ours to pick), and no feed has a filament set — with one set, the
  3378. matcher has already given its answer. Not for a job that asked for its
  3379. colours to be matched strictly: a spool without a filament set has no
  3380. colour to check. Returns None otherwise.
  3381. """
  3382. if item.filament_overrides:
  3383. try:
  3384. overrides = json.loads(item.filament_overrides)
  3385. except (json.JSONDecodeError, TypeError):
  3386. return None
  3387. if not isinstance(overrides, list) or any(
  3388. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3389. ):
  3390. return None
  3391. status = printer_manager.get_status(printer_id)
  3392. if status is None or not isinstance(status.raw_data, dict):
  3393. return None
  3394. ams_units = status.raw_data.get("ams")
  3395. if not isinstance(ams_units, list) or ams_units:
  3396. return None
  3397. vt_trays = status.raw_data.get("vt_tray")
  3398. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3399. return None
  3400. if self._build_loaded_filaments(status):
  3401. return None
  3402. printer = await self._get_printer(db, printer_id)
  3403. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3404. return None
  3405. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3406. if external < _EXTERNAL_TRAY_ID_MIN:
  3407. return None
  3408. required = await self._get_filament_requirements(db, item)
  3409. slot_ids = [r.get("slot_id") for r in required or []]
  3410. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3411. if not slot_ids:
  3412. return None
  3413. mapping = [-1] * max(slot_ids)
  3414. for slot_id in slot_ids:
  3415. mapping[slot_id - 1] = external
  3416. return mapping
  3417. async def _fill_unresolved_slots(
  3418. self,
  3419. db: AsyncSession,
  3420. printer_id: int,
  3421. item: PrintQueueItem,
  3422. stored_mapping: list | None,
  3423. ) -> list | None:
  3424. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3425. Every resolved entry is kept, so a tray the user picked by hand stays
  3426. picked. Only the plate's unresolved slots are matched, and only against
  3427. trays the mapping does not already use: the matcher never gives two
  3428. slots one tray, and filling a gap with a tray the user assigned to
  3429. another slot would print that slot's filament twice.
  3430. Returns None when there is nothing to fill or nothing could be filled.
  3431. """
  3432. if not isinstance(stored_mapping, list) or not stored_mapping:
  3433. return None
  3434. required = await self._get_filament_requirements(db, item)
  3435. if not required:
  3436. return None
  3437. self._apply_filament_overrides(item, required)
  3438. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3439. if not gaps:
  3440. return None
  3441. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3442. computed = await self._compute_ams_mapping_for_printer(
  3443. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3444. )
  3445. if not computed:
  3446. return None
  3447. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3448. filled = False
  3449. for slot_id in gaps:
  3450. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3451. if _is_tray_id(tray) and tray >= 0:
  3452. merged[slot_id - 1] = tray
  3453. filled = True
  3454. return merged if filled else None
  3455. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3456. """What a staged item would be held for if it were started now (#2799).
  3457. The Start button asks this before releasing an item, so that a job whose
  3458. filament is still not loaded offers "Print Anyway" instead of being
  3459. released, held again by the scheduler and leaving no way past the hold.
  3460. It reaches the same answer the dispatch path would: a stored mapping
  3461. that fits is kept and only its gaps are matched again, and one that
  3462. does not fit (or is missing) is replaced by a fresh match.
  3463. Returns the missing filaments, described the way the queue row
  3464. describes them, or None when nothing is missing or there is not enough
  3465. evidence to say: no printer yet (a model-based item picks one at
  3466. dispatch), no status, no trays reported, or no readable 3MF.
  3467. """
  3468. if item.skip_filament_check or not item.printer_id:
  3469. return None
  3470. status = printer_manager.get_status(item.printer_id)
  3471. if status is None or not self._build_loaded_filaments(status):
  3472. return None
  3473. # Called from a request, not from a pass: drop whatever the last pass
  3474. # memoised so this reads the file as it is now. A pass running at the
  3475. # same time only loses its cache.
  3476. self._filament_req_memo.clear()
  3477. mapping: list | None = None
  3478. if item.ams_mapping:
  3479. try:
  3480. mapping = json.loads(item.ams_mapping)
  3481. except (json.JSONDecodeError, TypeError):
  3482. mapping = None
  3483. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3484. mapping = None
  3485. if mapping is not None:
  3486. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3487. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3488. else:
  3489. mapping = None
  3490. if mapping is None:
  3491. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3492. required = await self._get_filament_requirements(db, item)
  3493. if not required:
  3494. return None
  3495. self._apply_filament_overrides(item, required)
  3496. missing = _unresolved_required(required, mapping)
  3497. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3498. async def _stored_mapping_conflict(
  3499. self,
  3500. db: AsyncSession,
  3501. printer_id: int,
  3502. item: PrintQueueItem,
  3503. stored_mapping: list | None,
  3504. ) -> str | None:
  3505. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3506. A mapping is a list of global tray IDs, and those are only meaningful
  3507. relative to the printer they were resolved against — the same rule
  3508. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3509. arrives at a printer it was not resolved for:
  3510. * the print dialog stamps one mapping onto every selected printer, so a
  3511. mapping computed against the first printer is dispatched verbatim to
  3512. the rest, whose AMS slot order differs;
  3513. * a spool is moved between queueing and dispatch.
  3514. Both end the same way: the slot index still resolves, so nothing looks
  3515. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3516. the firmware's own type check, so a PETG slot happily prints in ASA.
  3517. Returns a short reason when the mapping names a tray this printer does
  3518. not have loaded, points a slot at a tray holding a different filament
  3519. type, or points it at an external spool this printer reports empty while
  3520. its AMS holds that slot's filament (#3239). Returns None when the
  3521. mapping fits, and — deliberately — whenever we lack the evidence to
  3522. judge, so a recompute only ever follows a positive finding.
  3523. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3524. matcher had nothing, not that the mapping belongs to another printer,
  3525. and destroying a partially hand-resolved mapping over it would lose the
  3526. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3527. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3528. item when that finds nothing.
  3529. """
  3530. if not isinstance(stored_mapping, list) or not stored_mapping:
  3531. return None
  3532. status = printer_manager.get_status(printer_id)
  3533. if status is None:
  3534. return None
  3535. loaded = self._build_loaded_filaments(status)
  3536. if not loaded:
  3537. # Nothing reported yet (reconnect, first push pending). Saying
  3538. # "tray not loaded" here would recompute against an AMS we cannot
  3539. # see, which is how #2589 produced a bogus all-[-1] in the first
  3540. # place.
  3541. return None
  3542. by_tray = {f["global_tray_id"]: f for f in loaded}
  3543. # Cheap pass first, on live status alone: every tray the mapping names
  3544. # has to exist here. This catches a foreign mapping without opening the
  3545. # 3MF, which is worth doing because the parse below is neither cached
  3546. # nor free.
  3547. for index, tray in enumerate(stored_mapping):
  3548. if not _is_tray_id(tray) or tray < 0:
  3549. continue
  3550. if tray in by_tray:
  3551. continue
  3552. if tray >= 254:
  3553. # An external feed we have not heard about is absence of
  3554. # evidence about *that slot* — the rest of the mapping is still
  3555. # worth judging, so skip it rather than abandoning the pass.
  3556. continue
  3557. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3558. # Only now is the 3MF worth opening: the type check needs to know what
  3559. # each slot actually asked for. The external spool is checked the same
  3560. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3561. # two printers with different filament in the external feed is the same
  3562. # failure this method exists to catch.
  3563. required = await self._get_filament_requirements(db, item)
  3564. if not required:
  3565. return None
  3566. self._apply_filament_overrides(item, required)
  3567. # External feeds the printer reports and reports as empty. That is
  3568. # evidence, unlike an external feed it says nothing about (#3239).
  3569. empty_external: set[int] = set()
  3570. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3571. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3572. if isinstance(vt, dict) and not vt.get("tray_type"):
  3573. try:
  3574. empty_external.add(int(vt.get("id", 254)))
  3575. except (TypeError, ValueError):
  3576. continue
  3577. for req in required:
  3578. slot_id = req.get("slot_id") or 0
  3579. if slot_id <= 0:
  3580. continue
  3581. if slot_id > len(stored_mapping):
  3582. return f"slot {slot_id} is not covered by the mapping"
  3583. tray = stored_mapping[slot_id - 1]
  3584. if not _is_tray_id(tray) or tray < 0:
  3585. continue
  3586. loaded_tray = by_tray.get(tray)
  3587. if loaded_tray is None:
  3588. # A mapping made for a printer that feeds this slot from its
  3589. # external spool, sent to one whose external spool is empty and
  3590. # whose AMS holds the filament (#3239). Only then: an external
  3591. # spool can be loaded without its filament set, and on a printer
  3592. # with nothing else to offer that job printed before. The colour
  3593. # has to match too: with only another colour in the AMS, the
  3594. # printer asking for the spool beats printing in that colour.
  3595. want = canonical_filament_type(req.get("type"))
  3596. if tray >= 254 and tray in empty_external and want:
  3597. ams_tray = next(
  3598. (
  3599. f
  3600. for f in loaded
  3601. if not f.get("is_external")
  3602. and canonical_filament_type(f.get("type")) == want
  3603. and self._colors_are_similar(f.get("color"), req.get("color"))
  3604. ),
  3605. None,
  3606. )
  3607. if ams_tray is not None:
  3608. return (
  3609. f"slot {slot_id} points at the external spool, which is empty, "
  3610. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3611. )
  3612. continue
  3613. want = canonical_filament_type(req.get("type"))
  3614. have = canonical_filament_type(loaded_tray.get("type"))
  3615. if want and have and want != have:
  3616. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3617. return None
  3618. async def _unmappable_without_ams_message(
  3619. self,
  3620. db: AsyncSession,
  3621. printer_id: int,
  3622. item: PrintQueueItem,
  3623. computed_mapping: list[int] | None,
  3624. ) -> str | None:
  3625. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3626. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3627. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3628. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3629. uploaded several megabytes and burned its dispatch retries. This method
  3630. speaks only for the AMS-less case: there is nothing to resume into — the
  3631. external spool holder is the whole inventory — so the useful answer is to
  3632. say which filament is missing and stop. With an AMS attached it returns
  3633. None: where live status reported loaded trays,
  3634. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3635. reported none the print goes out and the firmware error is the answer —
  3636. the user can load the right spool and press Resume.
  3637. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3638. every branch that lacks the evidence to be sure returns None.
  3639. """
  3640. # None means the matcher never ran (no requirements parsed from the 3MF,
  3641. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3642. # dispatch as they always have.
  3643. if not _mapping_is_all_unresolved(computed_mapping):
  3644. return None
  3645. status = printer_manager.get_status(printer_id)
  3646. if status is None:
  3647. return None
  3648. # "No AMS" has to be a fact the printer stated, not the absence of a
  3649. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3650. # handled and is preserved across partial pushes thereafter, so a missing
  3651. # key means we have not heard yet — most likely a reconnect, where the
  3652. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3653. # empty list is the positive report of a printer with no AMS.
  3654. ams_units = status.raw_data.get("ams")
  3655. if not isinstance(ams_units, list) or ams_units:
  3656. return None
  3657. required = await self._get_filament_requirements(db, item)
  3658. loaded = self._build_loaded_filaments(status)
  3659. if not required or not loaded:
  3660. # Both were non-empty moments ago or the matcher could not have run.
  3661. # If the picture changed under us, say nothing rather than fail an
  3662. # item on stale evidence.
  3663. return None
  3664. self._apply_filament_overrides(item, required)
  3665. return _unmatched_filament_message(required, loaded)
  3666. async def _fail_unmappable_item(
  3667. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3668. ) -> None:
  3669. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3670. This replaces a failure, not a success: without it the item is uploaded,
  3671. rejected by the firmware with 0700_8012, retried twice more and failed
  3672. anyway with "never started the print after N dispatch attempts". So this
  3673. applies on the model-based path too, even though it means an "Any <model>"
  3674. job stops at the first printer offered rather than trying its siblings —
  3675. deferring instead would need the check to move inside
  3676. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3677. re-assigns the same printer on the next tick.
  3678. """
  3679. item.status = "failed"
  3680. item.error_message = message
  3681. item.completed_at = datetime.now(timezone.utc)
  3682. item.waiting_reason = None
  3683. await db.commit()
  3684. from backend.app.services.print_batch import refresh_batches_after
  3685. await refresh_batches_after([item.id])
  3686. logger.warning(
  3687. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3688. item.id,
  3689. printer_id,
  3690. message,
  3691. )
  3692. job_name = await self._get_job_name(db, item)
  3693. printer = await self._get_printer(db, printer_id)
  3694. await notification_service.on_queue_job_failed(
  3695. job_name=job_name,
  3696. printer_id=printer_id,
  3697. printer_name=printer.name if printer else "Unknown",
  3698. reason=message,
  3699. db=db,
  3700. )
  3701. try:
  3702. await ws_manager.send_queue_item_failed(
  3703. user_id=item.created_by_id,
  3704. queue_item_id=item.id,
  3705. printer_id=printer_id,
  3706. reason="filament_unmappable",
  3707. )
  3708. except Exception:
  3709. pass
  3710. async def _compute_ams_mapping_for_printer(
  3711. self,
  3712. db: AsyncSession,
  3713. printer_id: int,
  3714. item: PrintQueueItem,
  3715. *,
  3716. only_slots: set[int] | None = None,
  3717. reserved_trays: set[int] | None = None,
  3718. ) -> list[int] | None:
  3719. """Compute AMS mapping for a printer based on filament requirements.
  3720. Called when a queue item has no ams_mapping set — either for model-based
  3721. items after printer assignment, or printer-specific items (e.g. from VP).
  3722. Args:
  3723. db: Database session
  3724. printer_id: The assigned printer ID
  3725. item: The queue item (contains archive_id or library_file_id)
  3726. only_slots: Match only these filament slots; every other slot comes
  3727. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3728. reserved_trays: Global tray IDs to leave out of the match, because
  3729. the stored mapping already gives them to another slot.
  3730. Returns:
  3731. AMS mapping array or None if no mapping needed/possible
  3732. """
  3733. # Get printer status
  3734. status = printer_manager.get_status(printer_id)
  3735. if not status:
  3736. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3737. return None
  3738. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3739. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3740. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3741. # an AMS on the *other* nozzle, and the matcher falls through to a
  3742. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3743. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3744. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3745. # Get filament requirements from source file
  3746. filament_reqs = await self._get_filament_requirements(db, item)
  3747. if not filament_reqs:
  3748. # When the 3MF can't be read but force-color overrides are present, build a
  3749. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3750. if item.filament_overrides:
  3751. try:
  3752. overrides = json.loads(item.filament_overrides)
  3753. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3754. if force_overrides:
  3755. logger.info(
  3756. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3757. "force-color override(s)",
  3758. item.id,
  3759. len(force_overrides),
  3760. )
  3761. return self._build_override_direct_mapping(force_overrides, status)
  3762. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3763. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3764. logger.debug("No filament requirements found for queue item %s", item.id)
  3765. return None
  3766. self._apply_filament_overrides(item, filament_reqs)
  3767. if only_slots is not None:
  3768. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3769. if not filament_reqs:
  3770. return None
  3771. # Build loaded filaments from printer status
  3772. loaded_filaments = self._build_loaded_filaments(status)
  3773. if reserved_trays:
  3774. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3775. if not loaded_filaments:
  3776. logger.debug("No filaments loaded on printer %s", printer_id)
  3777. return None
  3778. # Check if user prefers lowest remaining filament when multiple spools match
  3779. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3780. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3781. # Without backup, the printer will not switch to a second spool when the
  3782. # picked one runs out — so sorting toward the lowest leaves the print
  3783. # at risk of running dry mid-job. None (unknown: no status report with
  3784. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3785. if prefer_lowest and status.ams_filament_backup is False:
  3786. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3787. prefer_lowest = False
  3788. # When the preference is on, surface Bambuddy's inventory-side
  3789. # remaining for each slot that's bound to a tracked spool, so the
  3790. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3791. # entirely when the preference is off — no behaviour change for
  3792. # users who haven't opted in.
  3793. inventory_remain_overrides: dict[int, float] | None = None
  3794. if prefer_lowest:
  3795. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3796. # Compute mapping: match required filaments to available slots
  3797. return self._match_filaments_to_slots(
  3798. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3799. )
  3800. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3801. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3802. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3803. diagnosis (#2771) describes the filament the matcher actually looked
  3804. for, not the one the 3MF was sliced with — naming the pre-override
  3805. filament in a user-facing error would send the user to load the wrong
  3806. spool.
  3807. """
  3808. if not item.filament_overrides:
  3809. return
  3810. try:
  3811. overrides = json.loads(item.filament_overrides)
  3812. override_map = {o["slot_id"]: o for o in overrides}
  3813. for req in filament_reqs:
  3814. if req["slot_id"] in override_map:
  3815. override = override_map[req["slot_id"]]
  3816. req["type"] = override["type"]
  3817. req["color"] = override["color"]
  3818. # A manual/preference override SWAPS the slot's filament, so the
  3819. # 3MF's original tray_info_idx now points at the old spool and must
  3820. # be cleared — matching then falls back to type+colour. A
  3821. # force_color_match override is not a swap: it carries the 3MF's
  3822. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3823. # it here too, letting the matcher pin the correct variant slot on a
  3824. # printer holding two same-colour spools of different variants (#2650).
  3825. # If that variant isn't loaded the matcher falls back to type+colour,
  3826. # so an eligible printer never fails to map.
  3827. req["tray_info_idx"] = (
  3828. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3829. )
  3830. logger.debug(
  3831. "Queue item %s: Override slot %d -> %s %s",
  3832. item.id,
  3833. req["slot_id"],
  3834. override["type"],
  3835. override["color"],
  3836. )
  3837. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3838. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3839. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3840. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3841. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3842. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3843. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3844. treated as the filament requirement for that slot and matched against the
  3845. current AMS state of the printer.
  3846. Returns the same format as ``_match_filaments_to_slots``, or None when
  3847. the AMS has no loaded filaments.
  3848. """
  3849. loaded = self._build_loaded_filaments(status)
  3850. if not loaded:
  3851. return None
  3852. reqs = [
  3853. {
  3854. "slot_id": o["slot_id"],
  3855. "type": o.get("type", ""),
  3856. "color": o.get("color", ""),
  3857. # These are all force_color_match overrides, so the idx (when the
  3858. # 3MF carried one) is the intended variant, not a stale swap —
  3859. # keep it so the matcher pins the right variant slot, falling back
  3860. # to type+colour when it isn't loaded (#2650).
  3861. "tray_info_idx": o.get("tray_info_idx", ""),
  3862. }
  3863. for o in force_overrides
  3864. ]
  3865. return self._match_filaments_to_slots(reqs, loaded)
  3866. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3867. """Resolve the queue item's source 3MF and parse the per-slot
  3868. filament requirements out of it. Thin DB-resolver wrapper around
  3869. ``filament_requirements.extract_filament_requirements`` so the VP
  3870. queue-mode write path (#1188) can reuse the same parser at upload
  3871. time.
  3872. """
  3873. from backend.app.services.filament_requirements import extract_filament_requirements
  3874. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3875. # so every caller gets its own copy — a shared list would leak one
  3876. # item's overrides into the next item that happens to print the same
  3877. # plate.
  3878. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3879. if memo_key in self._filament_req_memo:
  3880. cached = self._filament_req_memo[memo_key]
  3881. return [dict(r) for r in cached] if cached else None
  3882. file_path: Path | None = None
  3883. if item.archive_id:
  3884. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3885. archive = result.scalar_one_or_none()
  3886. if archive:
  3887. file_path = settings.base_dir / archive.file_path
  3888. elif item.library_file_id:
  3889. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3890. library_file = result.scalar_one_or_none()
  3891. if library_file:
  3892. lib_path = Path(library_file.file_path)
  3893. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3894. if not file_path or not file_path.exists():
  3895. self._filament_req_memo[memo_key] = None
  3896. return None
  3897. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3898. self._filament_req_memo[memo_key] = filaments or None
  3899. return [dict(r) for r in filaments] if filaments else None
  3900. def _build_loaded_filaments(self, status) -> list[dict]:
  3901. """Build list of loaded filaments from printer status.
  3902. Args:
  3903. status: PrinterState from printer_manager
  3904. Returns:
  3905. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3906. """
  3907. filaments = []
  3908. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3909. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3910. # Dual-nozzle detection, used below to route external spools to an
  3911. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  3912. # which was corrected for #1257 while this copy kept the old signal.
  3913. #
  3914. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  3915. # printer with zero AMS units reports an empty map — and every external
  3916. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  3917. # `_match_filaments_to_slots` rejects outright because `None` equals
  3918. # neither 0 nor 1. On an X2D feeding from external spools only that left
  3919. # nothing to match, the mapping came back all -1, and the print went out
  3920. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  3921. # "Failed to get AMS mapping table".
  3922. #
  3923. # `nozzles` is always a two-entry list (the state seeds it with two empty
  3924. # NozzleInfo stubs), so its length proves nothing; only a populated
  3925. # diameter on the second entry means real hardware. The other two signals
  3926. # are fallbacks for firmware revisions that surface one but not the
  3927. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  3928. # and so is more than one `vt_tray` entry, since single-nozzle printers
  3929. # expose exactly one external feed.
  3930. nozzles = getattr(status, "nozzles", None) or []
  3931. vt_trays = status.raw_data.get("vt_tray") or []
  3932. is_dual_nozzle = bool(
  3933. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  3934. or ams_extruder_map
  3935. # isinstance, because a dict here would count its ~30 keys as trays.
  3936. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  3937. # so this is unreachable — but the loop below would raise on a dict
  3938. # and that is the pre-existing behaviour to keep, not to paper over.
  3939. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  3940. )
  3941. # Parse AMS units from raw_data
  3942. ams_data = status.raw_data.get("ams", [])
  3943. for ams_unit in ams_data:
  3944. ams_id = int(ams_unit.get("id", 0))
  3945. trays = ams_unit.get("tray", [])
  3946. is_ht = len(trays) == 1 # AMS-HT has single tray
  3947. for tray in trays:
  3948. tray_type = tray.get("tray_type")
  3949. if tray_type:
  3950. tray_id = int(tray.get("id", 0))
  3951. tray_color = tray.get("tray_color", "")
  3952. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  3953. tray_info_idx = tray.get("tray_info_idx", "")
  3954. # Normalize color: remove alpha, add hash
  3955. color = self._normalize_color(tray_color)
  3956. # Calculate global tray ID
  3957. # AMS-HT units have IDs starting at 128 with a single tray
  3958. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  3959. filaments.append(
  3960. {
  3961. "type": tray_type,
  3962. "color": color,
  3963. "tray_info_idx": tray_info_idx,
  3964. "ams_id": ams_id,
  3965. "tray_id": tray_id,
  3966. "is_ht": is_ht,
  3967. "is_external": False,
  3968. "global_tray_id": global_tray_id,
  3969. "extruder_id": ams_extruder_map.get(str(ams_id)),
  3970. "remain": tray.get("remain", -1),
  3971. }
  3972. )
  3973. # Check external spool(s) (vt_tray is a list)
  3974. for idx, vt in enumerate(vt_trays):
  3975. if vt.get("tray_type"):
  3976. color = self._normalize_color(vt.get("tray_color", ""))
  3977. tray_id = int(vt.get("id", 254))
  3978. filaments.append(
  3979. {
  3980. "type": vt["tray_type"],
  3981. "color": color,
  3982. "tray_info_idx": vt.get("tray_info_idx", ""),
  3983. "ams_id": -1,
  3984. "tray_id": idx,
  3985. "is_ht": False,
  3986. "is_external": True,
  3987. "global_tray_id": tray_id,
  3988. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  3989. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  3990. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  3991. "remain": vt.get("remain", -1),
  3992. }
  3993. )
  3994. return filaments
  3995. def _normalize_color(self, color: str | None) -> str:
  3996. """Normalize color to #RRGGBB format."""
  3997. if not color:
  3998. return "#808080"
  3999. hex_color = color.replace("#", "")[:6]
  4000. return f"#{hex_color}"
  4001. def _normalize_color_for_compare(self, color: str | None) -> str:
  4002. """Normalize color for comparison (lowercase, no hash)."""
  4003. if not color:
  4004. return ""
  4005. return color.replace("#", "").lower()[:6]
  4006. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4007. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4008. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4009. stays the per-channel box that shipped — this only decides which of
  4010. several eligible spools is closest, so nothing becomes usable or
  4011. unusable because of it.
  4012. It ranks by how far apart the colours *look*, not how far apart their
  4013. numbers are. RGB distance overweights blue badly enough to invert the
  4014. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4015. the nearer of two eligible spools by RGB and the further by a factor of
  4016. four once measured perceptually.
  4017. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4018. transparent filament is not a colour the user chose, and counting it
  4019. would stop a transparent filament matching itself.
  4020. """
  4021. return perceptual_color_distance(color1, color2)
  4022. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4023. """Check if two colors are visually similar within a threshold."""
  4024. hex1 = self._normalize_color_for_compare(color1)
  4025. hex2 = self._normalize_color_for_compare(color2)
  4026. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4027. return False
  4028. try:
  4029. r1 = int(hex1[0:2], 16)
  4030. g1 = int(hex1[2:4], 16)
  4031. b1 = int(hex1[4:6], 16)
  4032. r2 = int(hex2[0:2], 16)
  4033. g2 = int(hex2[2:4], 16)
  4034. b2 = int(hex2[4:6], 16)
  4035. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4036. except ValueError:
  4037. return False
  4038. async def _build_inventory_remain_overrides(
  4039. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4040. ) -> dict[int, float]:
  4041. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4042. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4043. The MQTT ``remain`` field on a tray is the printer firmware's
  4044. RFID-decremented value, which has two limitations the "Prefer Lowest
  4045. Remaining Filament" feature has been ignoring (#1508):
  4046. - it's only meaningful for Bambu RFID spools; everything else reports
  4047. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4048. compare equal and the sort collapses to AMS-slot order — the user
  4049. who's curating inventory weights gets the lower-slot pick instead
  4050. of the lower-remaining pick;
  4051. - even when set, it's the *printer's* counter, not Bambuddy's
  4052. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4053. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4054. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4055. When the user has bound a spool to a slot, their own inventory
  4056. tracking is authoritative; this helper surfaces that value so the
  4057. sort can prefer it. Slots without a binding are absent from the
  4058. returned map — the caller then falls back to MQTT ``remain`` for
  4059. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4060. Returns an empty map on any failure (no inventory bindings, DB
  4061. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4062. is a preference, not a guarantee.
  4063. """
  4064. if not loaded:
  4065. return {}
  4066. # External / virtual-tray slots are tracked separately from AMS — skip
  4067. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4068. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4069. # match is fiddly and out of scope for this fix).
  4070. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4071. if not tracked_slots:
  4072. return {}
  4073. is_spoolman = await self._is_spoolman_mode(db)
  4074. overrides: dict[int, float] = {}
  4075. if is_spoolman:
  4076. result = await db.execute(
  4077. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4078. )
  4079. assignments = list(result.scalars().all())
  4080. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4081. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4082. for ams_id, tray_id, gtid in tracked_slots:
  4083. spoolman_id = by_slot.get((ams_id, tray_id))
  4084. if spoolman_id is None:
  4085. continue
  4086. grams = await _spoolman_remaining_grams(spoolman_id)
  4087. if grams is not None:
  4088. overrides[gtid] = grams
  4089. return overrides
  4090. # Internal inventory mode (default). selectinload matches the pattern
  4091. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4092. # plus an eager-loaded relationship rather than an explicit join, so
  4093. # the row-attribute shape is exactly what those routes already rely on.
  4094. result = await db.execute(
  4095. select(SpoolAssignment)
  4096. .options(selectinload(SpoolAssignment.spool))
  4097. .where(SpoolAssignment.printer_id == printer_id)
  4098. )
  4099. assignments = list(result.scalars().all())
  4100. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4101. for ams_id, tray_id, gtid in tracked_slots:
  4102. spool = by_slot.get((ams_id, tray_id))
  4103. if spool is None:
  4104. continue
  4105. label = float(spool.label_weight or 0)
  4106. used = float(spool.weight_used or 0)
  4107. overrides[gtid] = max(0.0, label - used)
  4108. return overrides
  4109. @staticmethod
  4110. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4111. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4112. here to avoid making this module import-dependent on that private
  4113. helper's signature."""
  4114. try:
  4115. from backend.app.api.routes.settings import get_setting
  4116. v = await get_setting(db, "spoolman_enabled")
  4117. return bool(v) and v.lower() == "true"
  4118. except Exception:
  4119. return False
  4120. @staticmethod
  4121. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4122. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4123. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4124. so a tied sort produces the same physical-position order the pre-#1508
  4125. stable sort did (preserves the regression-free baseline):
  4126. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4127. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4128. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4129. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4130. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4131. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4132. """
  4133. if ams_id is None or ams_id < 0:
  4134. return 10_000
  4135. if ams_id >= 128:
  4136. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4137. return ams_id * 4 + (tray_id or 0)
  4138. @staticmethod
  4139. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4140. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4141. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4142. non-tracked spools (the user has told us they care about these
  4143. specifically), then ascending by remaining within each tier, then
  4144. ascending by AMS slot position as the deterministic tie-breaker.
  4145. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4146. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4147. because the tier flag dominates — which is what lets us mix grams
  4148. (inventory) and percent (MQTT) without a unit conversion.
  4149. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4150. spools the printer DOES know something about sort ahead of those
  4151. it knows nothing about — preserves pre-#1508 behaviour for the
  4152. no-inventory-binding case.
  4153. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4154. external on ties, matching the legacy emission-order stable sort.
  4155. """
  4156. gtid = f.get("global_tray_id")
  4157. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4158. if overrides and gtid in overrides:
  4159. return (0, overrides[gtid], slot_order)
  4160. remain = f.get("remain", -1)
  4161. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4162. def _match_filaments_to_slots(
  4163. self,
  4164. required: list[dict],
  4165. loaded: list[dict],
  4166. prefer_lowest: bool = False,
  4167. inventory_remain_overrides: dict[int, float] | None = None,
  4168. fts_installed: bool = False,
  4169. ) -> list[int] | None:
  4170. """Match required filaments to loaded filaments and build AMS mapping.
  4171. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4172. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4173. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4174. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4175. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4176. matching among those trays.
  4177. Args:
  4178. required: List of required filaments with slot_id, type, color, tray_info_idx
  4179. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4180. Returns:
  4181. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4182. """
  4183. if not required:
  4184. return None
  4185. # Track used trays to avoid duplicate assignment
  4186. used_tray_ids: set[int] = set()
  4187. comparisons = []
  4188. for req in required:
  4189. req_type = (req.get("type") or "").upper()
  4190. req_color = req.get("color", "")
  4191. req_tray_info_idx = req.get("tray_info_idx", "")
  4192. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4193. idx_match = None
  4194. exact_match = None
  4195. similar_match = None
  4196. similar_distance = float("inf")
  4197. type_only_match = None
  4198. # Get available trays (not already used)
  4199. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4200. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4201. # Hard filter — cross-nozzle assignment causes print failures
  4202. # ("position of left hotend is abnormal"), so never fall back.
  4203. # Skipped when an FTS is installed: it routes any AMS slot to either
  4204. # extruder, so restricting to one nozzle would wrongly exclude the
  4205. # correct spool sitting in the other nozzle's AMS (#2186).
  4206. req_nozzle_id = req.get("nozzle_id")
  4207. if req_nozzle_id is not None and not fts_installed:
  4208. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4209. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4210. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4211. # _prefer_lowest_sort_key for the full rationale.
  4212. if prefer_lowest:
  4213. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4214. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4215. # One line per filament req so a bug report can be diagnosed
  4216. # without enabling debug logging: shows what the matcher saw
  4217. # (req shape + sorted candidate trays with their remain values
  4218. # and any inventory override that was applied). Mirrored by
  4219. # the picked-match log at the bottom of the loop.
  4220. logger.info(
  4221. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4222. req.get("slot_id"),
  4223. req_type,
  4224. req_color,
  4225. req_tray_info_idx,
  4226. req_nozzle_id,
  4227. [
  4228. {
  4229. "gtid": f.get("global_tray_id"),
  4230. "type": f.get("type"),
  4231. "color": f.get("color"),
  4232. "tii": f.get("tray_info_idx"),
  4233. "remain": f.get("remain"),
  4234. "inv_g": (
  4235. inventory_remain_overrides.get(f.get("global_tray_id"))
  4236. if inventory_remain_overrides
  4237. else None
  4238. ),
  4239. }
  4240. for f in available
  4241. ],
  4242. )
  4243. # Check if tray_info_idx is unique among available trays
  4244. if req_tray_info_idx:
  4245. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4246. if len(idx_matches) == 1:
  4247. # Unique tray_info_idx - use it as definitive match
  4248. idx_match = idx_matches[0]
  4249. logger.debug(
  4250. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4251. f"-> tray {idx_match['global_tray_id']}"
  4252. )
  4253. elif len(idx_matches) > 1:
  4254. # Multiple trays with same tray_info_idx - use color matching among them
  4255. logger.debug(
  4256. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4257. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4258. )
  4259. if prefer_lowest:
  4260. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4261. # Use color matching within this subset
  4262. for f in idx_matches:
  4263. f_color = f.get("color", "")
  4264. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4265. if not exact_match:
  4266. exact_match = f
  4267. elif self._colors_are_similar(f_color, req_color):
  4268. distance = self._color_distance(f_color, req_color)
  4269. if distance is not None and distance < similar_distance:
  4270. similar_match = f
  4271. similar_distance = distance
  4272. elif not type_only_match:
  4273. type_only_match = f
  4274. # If no idx_match yet, do standard type/color matching on all available trays
  4275. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4276. for f in available:
  4277. f_type = (f.get("type") or "").upper()
  4278. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4279. continue
  4280. # Type matches - check color
  4281. f_color = f.get("color", "")
  4282. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4283. if not exact_match:
  4284. exact_match = f
  4285. elif self._colors_are_similar(f_color, req_color):
  4286. # Nearest wins, not first-in-tray-order. `available` is
  4287. # already in the caller's order (slot order, or the
  4288. # prefer-lowest sort), and `<` keeps the earliest of
  4289. # equally close spools — so that order survives as the
  4290. # tie-break (#2804).
  4291. distance = self._color_distance(f_color, req_color)
  4292. if distance is not None and distance < similar_distance:
  4293. similar_match = f
  4294. similar_distance = distance
  4295. elif not type_only_match:
  4296. type_only_match = f
  4297. match = idx_match or exact_match or similar_match or type_only_match
  4298. if match:
  4299. used_tray_ids.add(match["global_tray_id"])
  4300. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4301. else:
  4302. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4303. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4304. # "Why did it pick that spool" is the question every wrong-filament
  4305. # report starts with, and a `similar_color` win is now a ranked
  4306. # choice among several eligible spools rather than whichever tray
  4307. # came first, so it is worth being able to see after the fact.
  4308. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4309. # is on (#1766).
  4310. if match:
  4311. bucket = (
  4312. "idx"
  4313. if idx_match is not None
  4314. else "exact_color"
  4315. if exact_match is not None
  4316. else "similar_color"
  4317. if similar_match is not None
  4318. else "type_only"
  4319. )
  4320. logger.info(
  4321. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4322. match["global_tray_id"],
  4323. bucket,
  4324. req.get("slot_id"),
  4325. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4326. )
  4327. else:
  4328. logger.info(
  4329. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4330. req.get("slot_id"),
  4331. req_type,
  4332. req_color,
  4333. req_tray_info_idx,
  4334. )
  4335. # Build mapping array
  4336. if not comparisons:
  4337. return None
  4338. max_slot_id = max(c["slot_id"] for c in comparisons)
  4339. if max_slot_id <= 0:
  4340. return None
  4341. mapping = [-1] * max_slot_id
  4342. for c in comparisons:
  4343. slot_id = c["slot_id"]
  4344. if slot_id and slot_id > 0:
  4345. mapping[slot_id - 1] = c["global_tray_id"]
  4346. return mapping
  4347. def _mark_printer_dispatched(
  4348. self,
  4349. printer_id: int,
  4350. pre_state: str | None,
  4351. pre_subtask_id: str | None,
  4352. ) -> None:
  4353. """Record that a print command was just sent to ``printer_id``.
  4354. Held until either the watchdog observes a state/subtask transition
  4355. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4356. """
  4357. if not pre_state:
  4358. # No pre_state means we can't detect a transition — fall back to a
  4359. # pure time-based hold using empty string as a sentinel that won't
  4360. # match any real printer state.
  4361. pre_state = ""
  4362. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4363. def _release_dispatch_hold(self, printer_id: int) -> None:
  4364. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4365. self._dispatch_holds.pop(printer_id, None)
  4366. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4367. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4368. Returns False (and clears the hold) once any of these are true:
  4369. - hard timeout (``_dispatch_max_hold``) has elapsed
  4370. - the printer has transitioned out of pre_state and we're past the
  4371. minimum cooldown
  4372. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4373. past the minimum cooldown
  4374. Otherwise the printer is held — caller should treat it as busy.
  4375. """
  4376. entry = self._dispatch_holds.get(printer_id)
  4377. if not entry:
  4378. return False
  4379. started_at, pre_state, pre_subtask_id = entry
  4380. elapsed = time.monotonic() - started_at
  4381. if elapsed >= self._dispatch_max_hold:
  4382. self._dispatch_holds.pop(printer_id, None)
  4383. return False
  4384. # Without a pre_state we can't detect a transition — fall back to the
  4385. # min cooldown alone, then drop the hold.
  4386. if not pre_state:
  4387. if elapsed >= self._dispatch_min_cooldown:
  4388. self._dispatch_holds.pop(printer_id, None)
  4389. return False
  4390. return True
  4391. status = printer_manager.get_status(printer_id)
  4392. current_state = getattr(status, "state", None) if status else None
  4393. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4394. transitioned = (current_state is not None and current_state != pre_state) or (
  4395. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4396. )
  4397. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4398. self._dispatch_holds.pop(printer_id, None)
  4399. return False
  4400. return True
  4401. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4402. """Check if a printer is connected and idle."""
  4403. if not printer_manager.is_connected(printer_id):
  4404. logger.debug("Printer %d: not connected", printer_id)
  4405. return False
  4406. state = printer_manager.get_status(printer_id)
  4407. if not state:
  4408. logger.debug("Printer %d: no status available", printer_id)
  4409. return False
  4410. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4411. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4412. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4413. # printer, it boots back into IDLE with no memory of the previous finish; without
  4414. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4415. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4416. logger.debug(
  4417. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4418. printer_id,
  4419. state.state,
  4420. )
  4421. return False
  4422. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4423. if not idle:
  4424. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4425. return idle
  4426. @staticmethod
  4427. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4428. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4429. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4430. and that the fixed-printer branch has already found connected, so the two
  4431. offline cases answer at their own exits and never arrive here.
  4432. The default is the model-based branch's ``Busy:`` wording, which
  4433. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4434. the right answer for the connected-but-no-telemetry second or two after a
  4435. reconnect: the model-based branch has always reported it that way, and it
  4436. is not something to wake anybody up for.
  4437. A plate nobody has confirmed is the one case here that does not resolve
  4438. itself — somebody has to walk over to the printer — so it is worded as
  4439. itself and allowed to notify.
  4440. """
  4441. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4442. return f"Waiting for plate confirmation: {printer_name}"
  4443. return f"Busy: {printer_name}"
  4444. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4445. """Read a setting value from the database."""
  4446. result = await db.execute(select(Settings).where(Settings.key == key))
  4447. setting = result.scalar_one_or_none()
  4448. return setting.value if setting else None
  4449. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4450. """Read a boolean setting from the database."""
  4451. result = await db.execute(select(Settings).where(Settings.key == key))
  4452. setting = result.scalar_one_or_none()
  4453. if setting:
  4454. return setting.value.lower() == "true"
  4455. return default
  4456. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4457. """Read an int setting; falls back to default on missing/unparseable rows."""
  4458. result = await db.execute(select(Settings).where(Settings.key == key))
  4459. setting = result.scalar_one_or_none()
  4460. if setting and setting.value:
  4461. try:
  4462. return int(setting.value)
  4463. except ValueError:
  4464. pass
  4465. return default
  4466. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4467. """Get drying presets (user-configured or built-in defaults)."""
  4468. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4469. setting = result.scalar_one_or_none()
  4470. if setting and setting.value:
  4471. try:
  4472. presets = json.loads(setting.value)
  4473. if isinstance(presets, dict) and presets:
  4474. return presets
  4475. except json.JSONDecodeError:
  4476. pass
  4477. return self.DEFAULT_DRYING_PRESETS
  4478. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4479. """Per-filament humidity thresholds (#1605).
  4480. Returns the user-configured overrides map keyed by normalized filament
  4481. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4482. unknown / unmapped types. Empty / unset → empty dict, in which case
  4483. callers fall back to ``ams_humidity_fair``.
  4484. """
  4485. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4486. setting = result.scalar_one_or_none()
  4487. if not setting or not setting.value:
  4488. return {}
  4489. try:
  4490. data = json.loads(setting.value)
  4491. except json.JSONDecodeError:
  4492. return {}
  4493. if not isinstance(data, dict):
  4494. return {}
  4495. out: dict[str, int] = {}
  4496. for key, value in data.items():
  4497. try:
  4498. out[str(key).upper() if key != "default" else "default"] = int(value)
  4499. except (TypeError, ValueError):
  4500. continue
  4501. return out
  4502. # Materials whose AMS spelling differs from the key the tables above use.
  4503. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4504. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4505. # good PA row (#3067).
  4506. #
  4507. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4508. # The drying popover has resolved these correctly since #2774 and the
  4509. # scheduler never did, which is exactly why #3067's reporter could dry a
  4510. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4511. #
  4512. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4513. # of nylon, so it is the one entry that is a judgement rather than a
  4514. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4515. # way, and PA's row is the hottest the table has. Drying it there is closer
  4516. # to right than not drying it at all, which is what it got before.
  4517. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4518. "NYLON": "PA",
  4519. "PA6": "PA",
  4520. "PA11": "PA",
  4521. "PA12": "PA",
  4522. "PAHT": "PA",
  4523. "PPA": "PA",
  4524. }
  4525. @classmethod
  4526. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4527. """The key in *table* that answers for this tray's material, or None.
  4528. The printer reports the material in ``tray_type``, and it spells filled
  4529. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4530. tables here are keyed by base material, so matching the raw string alone
  4531. found a row for 8 of the 41 types a printer can report and skipped the
  4532. rest -- silently, because every caller reads "no row" as "nothing to do
  4533. for this tray". Auto-drying therefore ignored every composite spool on
  4534. the install (#3067).
  4535. Exact match first, so a table the user has extended with a row of its
  4536. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4537. base material's. Then the suffix is dropped, then the alias map above
  4538. answers for the polyamide spellings.
  4539. Returns None rather than a default: what to do with an unrecognised
  4540. material differs per caller, and only the caller knows whether "no row"
  4541. means skip the tray or fall back to a catch-all. Nothing here invents a
  4542. temperature for a material the table does not list.
  4543. """
  4544. raw = cls._normalize_filament_type(tray_type or "")
  4545. if not raw:
  4546. return None
  4547. for candidate in (raw, raw.split("-")[0]):
  4548. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4549. if key in table:
  4550. return key
  4551. return None
  4552. @staticmethod
  4553. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4554. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4555. For mixed filament types loaded into one AMS, returns the most
  4556. restrictive (lowest) threshold across all loaded tray types — matches
  4557. the conservative-params strategy already used for drying temp/hours.
  4558. Empty / unloaded trays contribute no constraint. Unknown types use the
  4559. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4560. when no per-type map is configured at all.
  4561. """
  4562. default = thresholds.get("default", fallback)
  4563. if not thresholds:
  4564. return fallback
  4565. candidates: list[int] = []
  4566. for tray in trays:
  4567. tray_type = str(tray.get("tray_type") or "").strip()
  4568. if not tray_type:
  4569. continue
  4570. # A composite carries its base material's threshold when it has no
  4571. # row of its own, the same way it takes its drying preset (#3067).
  4572. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4573. candidates.append(thresholds[key] if key is not None else default)
  4574. if not candidates:
  4575. return default
  4576. return min(candidates)
  4577. def _get_conservative_drying_params(
  4578. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4579. ) -> tuple[int, int, str] | None:
  4580. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4581. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4582. """
  4583. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4584. hours_key = f"{temp_key}_hours"
  4585. min_temp = None
  4586. max_hours = None
  4587. filament_type = ""
  4588. for tray in trays:
  4589. tray_type = tray.get("tray_type", "")
  4590. if not tray_type:
  4591. continue
  4592. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4593. # which is what stopped auto-drying on every composite spool (#3067).
  4594. base_type = self._resolve_filament_key(tray_type, presets)
  4595. if base_type is None:
  4596. continue
  4597. # The table is user-editable JSON with no per-row validation, so a
  4598. # row can be present and empty. That has always meant "skip this
  4599. # material", and it has to keep meaning it: the reads below fall
  4600. # back to 55C/12h per missing field, which is a temperature nobody
  4601. # chose and would deform a PLA spool.
  4602. preset = presets[base_type]
  4603. if not preset:
  4604. continue
  4605. temp = preset.get(temp_key, 55)
  4606. hours = preset.get(hours_key, 12)
  4607. # Conservative: lowest temp, longest duration
  4608. if min_temp is None or temp < min_temp:
  4609. min_temp = temp
  4610. if max_hours is None or hours > max_hours:
  4611. max_hours = hours
  4612. if not filament_type:
  4613. filament_type = base_type
  4614. if min_temp is None:
  4615. return None
  4616. return (min_temp, max_hours or 12, filament_type)
  4617. async def _check_filament_low(self, db: AsyncSession) -> None:
  4618. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4619. ``on_filament_low`` has had a column, a schema field, a route, a template
  4620. and a UI toggle since the notification system was built, and no caller --
  4621. so the toggle could be switched on and could never fire. This is the
  4622. producer.
  4623. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4624. ``low_stock_threshold_pct`` override is already exactly this decision:
  4625. already configurable, already surfaced, already driving the Inventory
  4626. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4627. consulted -- it has been measured up to 56 points out against a scale,
  4628. which is not a number to page someone on.
  4629. Only slots with an assigned spool produce an event. A slot Bambuddy
  4630. cannot resolve to a spool has no remaining weight it can stand behind,
  4631. and guessing one is how the remain percentage would have got in.
  4632. """
  4633. from backend.app.models.spool import Spool
  4634. # Time-gated rather than run on every pass. run() sleeps
  4635. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4636. # early-return path counts as productive while an upload is in flight
  4637. # (#2602), so an unthrottled check would re-read the whole spool
  4638. # collection every 3 seconds for the length of a batch drain. In
  4639. # Spoolman mode that is a request storm against a third-party service,
  4640. # which is the thing this producer's design note argues against; and
  4641. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4642. # check_queue holding the scheduler's session, so the outage would
  4643. # throttle the print queue itself. A low spool is not a 3-second
  4644. # concern -- the idle interval is the natural resolution.
  4645. now = time.monotonic()
  4646. if now < self._filament_low_next_check:
  4647. return
  4648. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4649. try:
  4650. # on_filament_low defaults to off on every provider, so on most
  4651. # installs nobody wants this alert. Without this the check would
  4652. # still read every assigned spool each interval -- the whole
  4653. # collection over HTTP in Spoolman mode -- for an event that is
  4654. # switched off. One query against the provider table settles it
  4655. # before any spool work, the same guard the bed-cooled waiter uses.
  4656. # No printer_id: this asks whether any provider wants the event at
  4657. # all; per-printer scoping is applied when the event is sent.
  4658. #
  4659. # While nobody wants it, no pass sees a slot go back above its
  4660. # threshold, so nothing can re-arm; a spool refilled under the same
  4661. # id in that time would stay silenced until a restart. Forgetting
  4662. # what was sent is right anyway: whoever switches the event back on
  4663. # is told about the spools that are low now.
  4664. #
  4665. # The MQTT relay publishes the same event, so a connected relay is
  4666. # reason enough to run the check. Its record is forgotten when the
  4667. # relay is switched off, not when the broker drops: a reconnect must
  4668. # not re-send every low slot.
  4669. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low"))
  4670. relay = mqtt_relay.enabled and mqtt_relay.connected
  4671. if not notify:
  4672. self._notified_filament_low.clear()
  4673. if not mqtt_relay.enabled:
  4674. self._relayed_filament_low.clear()
  4675. if not notify and not relay:
  4676. return
  4677. global_threshold = await self._get_low_stock_threshold(db)
  4678. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4679. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4680. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4681. if spoolman_on:
  4682. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4683. else:
  4684. rows = (
  4685. await db.execute(
  4686. select(SpoolAssignment, Spool)
  4687. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4688. # An archived spool is not stock. The Inventory page's
  4689. # Low Stock count skips them (InventoryPage.tsx:1089)
  4690. # and get_all_spools without allow_archived already
  4691. # excludes them in Spoolman mode, so without this the
  4692. # internal path is the only one that alerts on them.
  4693. .where(Spool.archived_at.is_(None))
  4694. )
  4695. ).all()
  4696. for assignment, spool in rows:
  4697. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4698. if pct is None:
  4699. continue
  4700. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4701. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4702. pct,
  4703. threshold,
  4704. spool.color_name,
  4705. )
  4706. if not slots:
  4707. # Nothing resolvable this pass. Deliberately not clearing the
  4708. # notified set: a Spoolman that is briefly unreachable would
  4709. # otherwise re-alert on every spool as soon as it came back.
  4710. return
  4711. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4712. except Exception as e:
  4713. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4714. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4715. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4716. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4717. if raw is None or raw.value is None:
  4718. return 20.0
  4719. try:
  4720. value = float(raw.value)
  4721. except (TypeError, ValueError):
  4722. return 20.0
  4723. return value if 0 < value <= 100 else 20.0
  4724. async def _filament_low_slots_spoolman(
  4725. self, db: AsyncSession, global_threshold: float
  4726. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4727. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4728. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4729. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4730. so the global threshold is the only one that applies here. That matches
  4731. what the Inventory page already does in this mode.
  4732. One ``get_all_spools`` call covers every slot rather than a request per
  4733. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4734. without ``allow_archived`` -- which is the behaviour the internal path
  4735. has to ask for explicitly.
  4736. An unreachable Spoolman returns no slots rather than raising. It is an
  4737. ordinary state for a third-party service, not an error in this pass: the
  4738. caller's "nothing resolvable" branch already leaves the notified set
  4739. alone, which is exactly right here, whereas letting it reach the broad
  4740. ``except`` would write a full traceback every time the check runs.
  4741. """
  4742. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4743. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4744. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4745. if not assignments:
  4746. return {}
  4747. client = await get_spoolman_client()
  4748. if client is None:
  4749. return {}
  4750. try:
  4751. all_spools = await client.get_all_spools()
  4752. except SpoolmanUnavailableError as e:
  4753. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4754. return {}
  4755. by_id: dict[int, dict] = {}
  4756. for raw in all_spools:
  4757. raw_id = raw.get("id")
  4758. if isinstance(raw_id, int):
  4759. by_id[raw_id] = raw
  4760. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4761. for assignment in assignments:
  4762. raw = by_id.get(assignment.spoolman_spool_id)
  4763. if raw is None:
  4764. continue
  4765. try:
  4766. mapped = _map_spoolman_spool(raw)
  4767. except ValueError:
  4768. continue
  4769. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4770. if pct is None:
  4771. continue
  4772. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4773. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4774. return slots
  4775. async def _emit_filament_low(
  4776. self,
  4777. db: AsyncSession,
  4778. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4779. *,
  4780. notify: bool = True,
  4781. relay: bool = False,
  4782. ) -> None:
  4783. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4784. printers: dict[int, Printer] = {}
  4785. for key, (pct, threshold, color) in slots.items():
  4786. printer_id, ams_id, tray_id, spool_id = key
  4787. if pct >= threshold:
  4788. # Back above the line: re-arm rather than expire on a timer, so a
  4789. # refilled slot can alert again and a spool sitting just under the
  4790. # threshold stays quiet.
  4791. self._notified_filament_low.discard(key)
  4792. self._relayed_filament_low.discard(key)
  4793. continue
  4794. send_notification = notify and key not in self._notified_filament_low
  4795. # Only while connected, so a crossing the relay missed reaches it
  4796. # after the reconnect.
  4797. send_relay = relay and key not in self._relayed_filament_low
  4798. if not send_notification and not send_relay:
  4799. continue
  4800. # Marked before sending, which is a choice rather than the only
  4801. # option, and it is the opposite failure mode from the one the
  4802. # debounce argues against: one transient provider failure loses this
  4803. # alert until the spool goes back above the threshold and crosses it
  4804. # again. Marking after a successful send would trade that for
  4805. # re-alerting on every pass while a provider is down -- which is the
  4806. # repetition the whole debounce exists to prevent, and the louder of
  4807. # the two failures. A spool that is low stays low, so the next real
  4808. # signal is not far away; a provider stuck retrying is a signal that
  4809. # never stops.
  4810. if send_notification:
  4811. self._notified_filament_low.add(key)
  4812. if send_relay:
  4813. self._relayed_filament_low.add(key)
  4814. if printer_id not in printers:
  4815. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4816. if printer is None:
  4817. continue
  4818. printers[printer_id] = printer
  4819. printer = printers[printer_id]
  4820. slot = _ams_slot_label(ams_id, tray_id)
  4821. if send_notification:
  4822. try:
  4823. await notification_service.on_filament_low(
  4824. printer_id,
  4825. printer.name,
  4826. slot,
  4827. int(pct),
  4828. db,
  4829. color=color,
  4830. )
  4831. except Exception as e:
  4832. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4833. if send_relay:
  4834. try:
  4835. await mqtt_relay.on_filament_low(
  4836. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  4837. )
  4838. except Exception as e:
  4839. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  4840. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4841. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4842. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4843. a schema field, a template and a UI toggle, and nothing that computes the
  4844. condition -- the Forecast panel does it in the browser, so with no page
  4845. open nothing could ever alert. This runs the same arithmetic
  4846. (``stock_forecast``) from the scheduler loop.
  4847. An alert is sent when a SKU *moves into* a condition, once, and again
  4848. after the condition has cleared. A SKU that worsens from reorder to break
  4849. alerts again as a break, because the panel treats the two as exclusive; one
  4850. that eases from break back to reorder does not alert again.
  4851. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4852. while it is still low tells you.
  4853. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4854. loop runs every 3 s while an upload is in flight, and the whole spool
  4855. collection is read over HTTP in Spoolman mode. Both events default to off
  4856. on every provider, so nothing is read unless a provider wants one.
  4857. """
  4858. now = time.monotonic()
  4859. if now < self._stock_forecast_next_check:
  4860. return
  4861. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4862. try:
  4863. if self._stock_alerts_persisted is None:
  4864. await self._load_stock_alerts(db)
  4865. wanted = {
  4866. "reorder": bool(await notification_service._get_providers_for_event(db, "on_stock_reorder_alert")),
  4867. "break": bool(await notification_service._get_providers_for_event(db, "on_stock_break_alert")),
  4868. }
  4869. if not any(wanted.values()):
  4870. # Nobody wants either event. Forget what was sent, so whoever
  4871. # switches one on is told about the SKUs that are low now.
  4872. self._notified_stock_alerts.clear()
  4873. await self._save_stock_alerts(db)
  4874. return
  4875. forecasts = await self._stock_forecasts(db)
  4876. if forecasts is None:
  4877. # Spoolman unreachable. Deliberately not clearing the notified
  4878. # set: a brief outage would otherwise re-alert every SKU when it
  4879. # came back.
  4880. return
  4881. await self._emit_stock_alerts(db, forecasts, wanted)
  4882. await self._save_stock_alerts(db)
  4883. except Exception as e:
  4884. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4885. def _serialize_stock_alerts(self) -> str:
  4886. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4887. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4888. return json.dumps(rows)
  4889. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4890. """Read the notified set saved by the last run, once per process.
  4891. A missing or unreadable row is an empty set: the worst that does is one
  4892. repeat of what a restart used to cause every time.
  4893. """
  4894. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4895. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4896. if raw and raw.value:
  4897. try:
  4898. for key, kind, events in json.loads(raw.value):
  4899. if len(key) == 4 and kind in ("reorder", "break"):
  4900. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4901. except (ValueError, TypeError):
  4902. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4903. loaded = {}
  4904. self._notified_stock_alerts = loaded
  4905. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4906. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4907. """Write the notified set to its settings row if it changed since it was last read or written."""
  4908. serialized = self._serialize_stock_alerts()
  4909. if serialized == self._stock_alerts_persisted:
  4910. return
  4911. from backend.app.core.db_dialect import upsert_setting
  4912. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4913. await db.commit()
  4914. self._stock_alerts_persisted = serialized
  4915. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4916. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4917. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4918. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4919. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4920. sku_settings = {
  4921. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4922. lead_time_days=row.lead_time_days,
  4923. safety_margin_value=row.safety_margin_value,
  4924. safety_margin_unit=row.safety_margin_unit,
  4925. alerts_snoozed=bool(row.alerts_snoozed),
  4926. )
  4927. for row in sku_rows
  4928. }
  4929. if await self._get_bool_setting(db, "spoolman_enabled"):
  4930. spools = await self._stock_spools_spoolman()
  4931. if spools is None:
  4932. return None
  4933. # Spoolman owns the usage in this mode and Bambuddy's own history
  4934. # table holds nothing for those spools, so the rate is always the
  4935. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4936. # are local spool ids, and a Spoolman id that happens to match one
  4937. # (left over from before Spoolman was switched on) would borrow an
  4938. # unrelated spool's history.
  4939. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4940. else:
  4941. spools = await self._stock_spools_internal(db)
  4942. history = await self._stock_usage_history(db)
  4943. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4944. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4945. from backend.app.models.spool import Spool
  4946. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4947. return [
  4948. stock_forecast.StockSpool(
  4949. id=spool.id,
  4950. material=spool.material,
  4951. subtype=spool.subtype,
  4952. brand=spool.brand,
  4953. color_name=spool.color_name,
  4954. label_weight=float(spool.label_weight or 0),
  4955. weight_used=float(spool.weight_used or 0),
  4956. weight_used_baseline=float(spool.weight_used_baseline or 0),
  4957. created_at=spool.created_at,
  4958. )
  4959. for spool in rows
  4960. ]
  4961. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  4962. from backend.app.models.spool_usage_history import SpoolUsageHistory
  4963. rows = (
  4964. await db.execute(
  4965. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  4966. .order_by(SpoolUsageHistory.created_at.desc())
  4967. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  4968. )
  4969. ).all()
  4970. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4971. for spool_id, created_at, weight_used in rows:
  4972. # A deleted spool's usage forecasts no stock. Skipped here rather than
  4973. # filtered before the limit, so the window matches the forecast panel's.
  4974. if created_at is None or spool_id is None:
  4975. continue
  4976. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  4977. return history
  4978. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  4979. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  4980. ``get_all_spools`` leaves archived spools out unless asked, which is the
  4981. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  4982. is the same mapping the Inventory page (and so the panel) reads.
  4983. """
  4984. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4985. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4986. client = await get_spoolman_client()
  4987. if client is None:
  4988. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  4989. return None
  4990. try:
  4991. raw_spools = await client.get_all_spools()
  4992. except SpoolmanUnavailableError as e:
  4993. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  4994. return None
  4995. spools: list[stock_forecast.StockSpool] = []
  4996. for raw in raw_spools:
  4997. try:
  4998. mapped = _map_spoolman_spool(raw)
  4999. except ValueError:
  5000. continue
  5001. created_at = None
  5002. if mapped.get("created_at"):
  5003. try:
  5004. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  5005. except ValueError:
  5006. created_at = None
  5007. spools.append(
  5008. stock_forecast.StockSpool(
  5009. id=mapped["id"],
  5010. material=mapped["material"],
  5011. subtype=mapped.get("subtype"),
  5012. brand=mapped.get("brand"),
  5013. color_name=mapped.get("color_name"),
  5014. label_weight=float(mapped.get("label_weight") or 0),
  5015. weight_used=float(mapped.get("weight_used") or 0),
  5016. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5017. created_at=created_at,
  5018. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5019. )
  5020. )
  5021. return spools
  5022. async def _emit_stock_alerts(
  5023. self,
  5024. db: AsyncSession,
  5025. forecasts: stock_forecast.ForecastMap,
  5026. wanted: dict[str, bool],
  5027. ) -> None:
  5028. """Send the notifications for each SKU that has moved into a stock alert condition.
  5029. A SKU in break has also reached its reorder point, so both events apply to
  5030. it: the break event goes to providers that have it on, and the reorder event
  5031. to the providers that have only that one on. A provider with both on gets the
  5032. break and no second message.
  5033. What is remembered per SKU is the condition and which events had a
  5034. subscriber when it was sent. An event with no subscriber is forgotten, so
  5035. switching it on later reports the SKUs already in that condition.
  5036. """
  5037. active_events = {event for event, on in wanted.items() if on}
  5038. for key, (forecast, spool) in forecasts.items():
  5039. kind: str | None = None
  5040. if not forecast.snoozed:
  5041. if forecast.stock_break_alert:
  5042. kind = "break"
  5043. elif forecast.reorder_alert:
  5044. kind = "reorder"
  5045. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5046. events = applicable & active_events
  5047. if not events:
  5048. self._notified_stock_alerts.pop(key, None)
  5049. continue
  5050. previous = self._notified_stock_alerts.get(key)
  5051. told = (previous[1] & active_events) if previous else frozenset()
  5052. # Trimmed to the events this condition can send. That is what makes easing from
  5053. # break back to reorder silent (the reorder event was told with the break) and
  5054. # worsening again news again (the break event is no longer remembered).
  5055. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5056. # Recorded before sending, for the reason _emit_filament_low gives: a
  5057. # provider that is down should lose this alert, not repeat it every hour.
  5058. to_send = events - told
  5059. # Both flags imply a positive rate and so a day count.
  5060. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5061. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5062. color = None if spool.color_name_is_synthesized else spool.color_name
  5063. try:
  5064. if "break" in to_send:
  5065. await notification_service.on_stock_break_alert(
  5066. spool.material,
  5067. spool.brand,
  5068. forecast.remaining_g,
  5069. rate,
  5070. days_left,
  5071. forecast.effective_lead_time_days,
  5072. db,
  5073. subtype=spool.subtype,
  5074. color=color,
  5075. )
  5076. if "reorder" in to_send:
  5077. await notification_service.on_stock_reorder_alert(
  5078. spool.material,
  5079. spool.brand,
  5080. forecast.remaining_g,
  5081. rate,
  5082. days_left,
  5083. db,
  5084. subtype=spool.subtype,
  5085. color=color,
  5086. skip_break_subscribers=kind == "break",
  5087. )
  5088. except Exception as e:
  5089. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5090. # A SKU with no spools left is no longer alerting.
  5091. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5092. del self._notified_stock_alerts[key]
  5093. async def _check_auto_drying(
  5094. self,
  5095. db: AsyncSession,
  5096. queue_items: list[PrintQueueItem],
  5097. dispatching_printers: set[int],
  5098. ):
  5099. """Start drying on idle printers based on humidity.
  5100. Three modes (can all be enabled independently):
  5101. - queue_drying_enabled: Dry between scheduled queue prints
  5102. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5103. - print_drying_enabled: Also evaluate printers that are currently printing,
  5104. when model+firmware supports "Print While Drying" (gated by
  5105. supports_drying_while_printing). Drying temperature is capped at
  5106. max(40, preset_temp - 5) to protect spools mid-print.
  5107. """
  5108. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5109. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5110. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5111. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5112. # The wait belongs to ambient drying: the settings UI only shows it while
  5113. # ambient drying is on, so a value left behind when ambient is turned off
  5114. # must not keep delaying the one path that still reaches the wait gate
  5115. # without it (a mid-print start under print_drying).
  5116. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5117. # Clear every streak as soon as the wait is inactive. An early return (or
  5118. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5119. # a quick toggle-on inherit an old streak.
  5120. if not sustained_wait_active:
  5121. self._auto_dry_above.clear()
  5122. if not queue_drying_enabled and not ambient_drying_enabled:
  5123. # Stop active drying on all printers if both features disabled
  5124. if self._drying_in_progress:
  5125. for pid in list(self._drying_in_progress):
  5126. if pid in self._scheduled_drying_printer_ids:
  5127. continue
  5128. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5129. await self._stop_drying(pid)
  5130. return
  5131. # Update drying state from printer status (handles backend restart)
  5132. self._sync_drying_state()
  5133. # Find printers with scheduled items (for queue drying mode)
  5134. printers_with_scheduled: set[int] = set()
  5135. printers_with_items: set[int] = set()
  5136. for item in queue_items:
  5137. if item.printer_id:
  5138. printers_with_items.add(item.printer_id)
  5139. if item.scheduled_time and not item.manual_start:
  5140. printers_with_scheduled.add(item.printer_id)
  5141. # If only queue mode is on and no printers have scheduled items, stop drying
  5142. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5143. # may still be eligible for mid-print drying regardless of queue state).
  5144. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5145. for pid in list(self._drying_in_progress):
  5146. if pid in self._scheduled_drying_printer_ids:
  5147. continue
  5148. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5149. await self._stop_drying(pid)
  5150. return
  5151. # Get humidity threshold (global fallback)
  5152. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5153. setting = result.scalar_one_or_none()
  5154. global_humidity_threshold = int(setting.value) if setting else 60
  5155. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5156. # to the global threshold for every AMS unit.
  5157. per_type_thresholds = await self._get_humidity_thresholds(db)
  5158. # Get drying presets
  5159. presets = await self._get_drying_presets(db)
  5160. # Determine if drying should be skipped for printers with pending items
  5161. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5162. # Get all active printers
  5163. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5164. for printer in all_printers.scalars():
  5165. pid = printer.id
  5166. # Resolve model+firmware up front — needed to decide whether this printer
  5167. # qualifies for mid-print drying (busy printer on capable hardware).
  5168. state = printer_manager.get_status(pid)
  5169. if not state:
  5170. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5171. continue
  5172. model = printer_manager.get_model(pid)
  5173. firmware = state.firmware_version
  5174. # "Mid-print" has to mean the printer is actually printing (#2801).
  5175. # It used to be inferred from the dispatch set, which also holds
  5176. # printers that merely could not be dispatched to -- so a printer
  5177. # sitting in FINISH behind an unacknowledged plate was treated as
  5178. # printing, had its drying temperature capped by the mid-print
  5179. # spool protection, and was logged as (mid-print) while idle.
  5180. is_printing = state.state in _ACTIVE_PRINT_STATES
  5181. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5182. # A printer whose print is running or imminent is left alone unless
  5183. # it can dry through it. `dispatching_printers` is deliberately the
  5184. # narrow set: running, held post-dispatch, or mid-upload.
  5185. if (is_printing or pid in dispatching_printers) and not mid_print:
  5186. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5187. continue
  5188. if not mid_print:
  5189. # In queue-only mode, only dry printers that have scheduled prints
  5190. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5191. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5192. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5193. await self._stop_drying(pid)
  5194. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5195. continue
  5196. # When block mode is on, don't START new drying on printers with pending items.
  5197. # But allow already-drying printers through so humidity auto-stop logic still runs.
  5198. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  5199. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  5200. continue
  5201. if not printer_manager.is_connected(pid):
  5202. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5203. continue
  5204. # Plate-clear is deliberately ignored here (#2801). It answers
  5205. # "is the bed ready for the next job", which says nothing about
  5206. # whether the AMS may heat -- and the gap between a finished print
  5207. # and the acknowledgment is exactly when drying is most useful,
  5208. # because the printer is free and nobody is waiting on it. Leaving
  5209. # the plate unacknowledged is also how people hold the queue by
  5210. # hand, and that hold should not cost them their drying.
  5211. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5212. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5213. continue
  5214. # Check drying capability. For mid-print path, supports_drying_while_printing
  5215. # was already verified when computing mid_print above.
  5216. if not mid_print and not supports_drying(model, firmware):
  5217. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5218. continue
  5219. # Check each AMS unit from raw_data
  5220. ams_list = state.raw_data.get("ams", [])
  5221. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5222. for ams_data in ams_list:
  5223. module_type = str(ams_data.get("module_type") or "")
  5224. ams_id = int(ams_data.get("id", 0))
  5225. # Only n3f/n3s support drying
  5226. if module_type not in ("n3f", "n3s"):
  5227. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5228. continue
  5229. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5230. # Most-restrictive of all loaded tray types; falls back to the
  5231. # global threshold when no overrides are configured.
  5232. trays = ams_data.get("tray", []) or []
  5233. humidity_threshold = self.resolve_humidity_threshold(
  5234. trays, per_type_thresholds, global_humidity_threshold
  5235. )
  5236. dry_time = int(ams_data.get("dry_time") or 0)
  5237. # Read humidity as a percentage. The 1-5 index is never
  5238. # substituted: it is inverted, and being unable to exceed any
  5239. # threshold it would read as "dry" forever (#3140). ``None``
  5240. # already means "skip this unit" everywhere below.
  5241. humidity_pct = ams_humidity_percent(ams_data)
  5242. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5243. unit_key = (pid, ams_id)
  5244. unit_state = self._auto_dry_units.get(unit_key)
  5245. # Already drying — let it run to its configured duration (#1892).
  5246. #
  5247. # We deliberately do NOT stop drying from a humidity re-check here.
  5248. # Relative humidity drops steeply in heated air, so the AMS sensor
  5249. # reads ~15-20% within minutes of the dryer starting even while the
  5250. # filament is still saturated. A humidity-based early-stop therefore
  5251. # always fires at the minimum-time floor, truncating both user-started
  5252. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5253. # The firmware stops when the configured duration elapses; scheduling
  5254. # stops (print takes priority, queue no longer needs drying) are
  5255. # handled separately via _stop_drying().
  5256. if dry_time > 0:
  5257. if pid not in self._drying_in_progress:
  5258. # Drying we didn't start (manual or from before restart) —
  5259. # track it so scheduling stops still apply; never auto-stop it.
  5260. self._drying_in_progress[pid] = time.monotonic()
  5261. if unit_state is not None:
  5262. unit_state["running"] = True
  5263. logger.debug(
  5264. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5265. pid,
  5266. ams_id,
  5267. dry_time,
  5268. humidity,
  5269. )
  5270. continue
  5271. # Nothing is drying. Close out a cycle we armed ourselves and
  5272. # judge whether it achieved anything (#2770).
  5273. #
  5274. # "Achieved anything" is measured against the LOWEST reading any
  5275. # cycle on this unit has ended at, not against the threshold and
  5276. # not against the previous cycle. A spool that is genuinely wet
  5277. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5278. # allowed to keep going for as long as it is still coming down,
  5279. # however far it still is from the threshold. What must not
  5280. # continue is a cycle that ends exactly where the last one did,
  5281. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5282. # Comparing against the running minimum rather than the previous
  5283. # end is what stops a sensor oscillating by one point between two
  5284. # values from reading as progress every other cycle.
  5285. if unit_state is not None and unit_state.pop("running", False):
  5286. unit_state["ended_at"] = time.monotonic()
  5287. # The streak that armed this cycle is spent; the next one
  5288. # starts fresh (and accumulates through the re-arm cooldown
  5289. # below, so the wait overlaps the cooldown, never stacks on
  5290. # top of it).
  5291. self._auto_dry_above.pop(unit_key, None)
  5292. if humidity is not None and humidity > humidity_threshold:
  5293. best = unit_state.get("best_end_humidity")
  5294. if isinstance(best, int) and humidity < best:
  5295. # Still coming down. Keep going, however far the
  5296. # threshold still is.
  5297. unproductive = 0
  5298. else:
  5299. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5300. if not isinstance(best, int) or humidity < best:
  5301. unit_state["best_end_humidity"] = humidity
  5302. unit_state["unproductive"] = unproductive
  5303. logger.info(
  5304. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5305. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5306. pid,
  5307. ams_id,
  5308. humidity,
  5309. humidity_threshold,
  5310. unit_state.get("best_end_humidity"),
  5311. unproductive,
  5312. )
  5313. # A cycle that ended at or below the threshold needs no
  5314. # counter reset here: the branch below drops the whole entry.
  5315. # Humidity below threshold — no need to start drying. This is
  5316. # also the only thing that lifts a suspension: the reading we
  5317. # gave up on has come down, so auto-drying works again and the
  5318. # unit goes back to having no history at all.
  5319. if humidity is None or humidity <= humidity_threshold:
  5320. if unit_state is not None and unit_state.get("suspended"):
  5321. logger.info(
  5322. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5323. "threshold, resuming automatic drying",
  5324. pid,
  5325. ams_id,
  5326. humidity,
  5327. humidity_threshold,
  5328. )
  5329. # Clear the judgement, keep the clock (#2801). Dropping the
  5330. # whole entry also dropped `ended_at`, and with it the
  5331. # 30-minute cooldown -- so a reading that dips to the
  5332. # threshold as the AMS cools and comes back above it once
  5333. # warm wiped its own history and re-armed immediately. That
  5334. # oscillation is the very thing #2770's cooldown exists to
  5335. # ride out, and it is worst at exactly the margin that makes
  5336. # a unit dry repeatedly: a point or two above the threshold.
  5337. if unit_state is not None:
  5338. unit_state.pop("suspended", None)
  5339. unit_state.pop("unproductive", None)
  5340. unit_state.pop("best_end_humidity", None)
  5341. # A real below-threshold reading ends any sustained-wait
  5342. # streak (#2518) -- "continuously above" means exactly that.
  5343. # An absent reading (humidity is None) is no-information and
  5344. # leaves the streak alone; the observation-gap guard handles
  5345. # a prolonged sensor silence.
  5346. if humidity is not None:
  5347. _above = self._auto_dry_above.pop(unit_key, None)
  5348. if _above is not None and sustained_wait_active:
  5349. logger.info(
  5350. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5351. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5352. pid,
  5353. ams_id,
  5354. humidity,
  5355. time.monotonic() - _above["since"],
  5356. sustained_minutes,
  5357. humidity_threshold,
  5358. )
  5359. logger.debug(
  5360. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5361. pid,
  5362. ams_id,
  5363. humidity,
  5364. humidity_threshold,
  5365. )
  5366. continue
  5367. # Sustained-humidity streak (#2518): updated on every pass that
  5368. # observes the reading above the threshold, BEFORE the
  5369. # suspension/cooldown gates below -- a suspended or cooling-down
  5370. # unit still accumulates streak time, so the wait overlaps those
  5371. # gates instead of stacking after them. Inert when the feature
  5372. # is off: no entries are written, and an entry left over from a
  5373. # toggle-off is dropped so it cannot seed a stale streak later.
  5374. if sustained_wait_active:
  5375. _now = time.monotonic()
  5376. # Four missed scheduler passes, floored: a single slow pass
  5377. # must not void a streak, but the ceiling has to scale with
  5378. # the cadence or a slow loop silently restarts every streak.
  5379. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5380. _above = self._auto_dry_above.get(unit_key)
  5381. if _above is None:
  5382. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5383. elif _now - _above["last"] > _gap_ceiling:
  5384. # Restart, and say so at the same level as the dip
  5385. # reset: a silent restart voids the streak invisibly,
  5386. # and a user who set a long wait and never gets a dry
  5387. # has no way to see why.
  5388. logger.info(
  5389. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5390. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5391. pid,
  5392. ams_id,
  5393. _now - _above["last"],
  5394. _gap_ceiling,
  5395. sustained_minutes,
  5396. )
  5397. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5398. else:
  5399. _above["last"] = _now
  5400. else:
  5401. self._auto_dry_above.pop(unit_key, None)
  5402. if unit_state is not None:
  5403. if unit_state.get("suspended"):
  5404. logger.debug(
  5405. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5406. "above the %d%% threshold",
  5407. pid,
  5408. ams_id,
  5409. int(unit_state.get("unproductive", 0)),
  5410. humidity_threshold,
  5411. )
  5412. continue
  5413. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5414. unit_state["suspended"] = True
  5415. logger.warning(
  5416. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5417. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5418. "higher while it is warm, so a threshold in that range can never be reached and "
  5419. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5420. pid,
  5421. ams_id,
  5422. int(unit_state.get("unproductive", 0)),
  5423. humidity,
  5424. humidity_threshold,
  5425. )
  5426. await self._notify_auto_drying_suspended(
  5427. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5428. )
  5429. continue
  5430. ended_at = unit_state.get("ended_at")
  5431. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5432. logger.debug(
  5433. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5434. "cycle before the humidity reading is worth acting on",
  5435. pid,
  5436. ams_id,
  5437. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5438. )
  5439. continue
  5440. # Check cannot-dry reasons (power constraints etc.). Sits
  5441. # ahead of the sustained wait so a unit the firmware refuses
  5442. # to dry never logs a wait it was never going to cash in.
  5443. sf_reasons = ams_data.get("dry_sf_reason", [])
  5444. if sf_reasons:
  5445. logger.debug(
  5446. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5447. pid,
  5448. ams_id,
  5449. sf_reasons,
  5450. )
  5451. continue
  5452. # Sustained-humidity wait (#2518): ambient-triggered starts
  5453. # wait; only a printer with a scheduled queue item pending
  5454. # keeps the instant behavior, because that drying has a real
  5455. # deadline. Mid-print is deliberately NOT exempt while ambient
  5456. # drying is on: a humidity start on a printer that happens to be
  5457. # printing is as vulnerable to a lid-open spike as one on an idle
  5458. # printer (proven live: a 2-point threshold crossing mid-print
  5459. # bought a parked 12h command). Inactive when ambient drying is
  5460. # off: print_drying then still starts mid-print cycles on its own
  5461. # (#1816, "regardless of queue state"), and those stay instant.
  5462. if sustained_wait_active and pid not in printers_with_scheduled:
  5463. _above = self._auto_dry_above.get(unit_key)
  5464. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5465. if _waited < sustained_minutes * 60:
  5466. logger.debug(
  5467. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5468. "threshold for %.0fs of the required %dm",
  5469. pid,
  5470. ams_id,
  5471. humidity,
  5472. humidity_threshold,
  5473. _waited,
  5474. sustained_minutes,
  5475. )
  5476. continue
  5477. # Get conservative drying params for mixed filaments
  5478. params = self._get_conservative_drying_params(trays, module_type, presets)
  5479. if not params:
  5480. logger.debug(
  5481. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5482. )
  5483. continue
  5484. temp, duration_hours, filament_type = params
  5485. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5486. # "drying temperature must not exceed the filament's softening temperature"
  5487. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5488. # ineffective and firmware will reject anyway.
  5489. if mid_print:
  5490. temp = max(40, temp - 5)
  5491. # Start drying
  5492. logger.info(
  5493. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5494. "starting %s drying at %d°C for %dh%s",
  5495. pid,
  5496. ams_id,
  5497. humidity,
  5498. humidity_threshold,
  5499. filament_type,
  5500. temp,
  5501. duration_hours,
  5502. " (mid-print)" if mid_print else "",
  5503. )
  5504. success = printer_manager.send_drying_command(
  5505. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5506. )
  5507. if success:
  5508. self._drying_in_progress[pid] = time.monotonic()
  5509. armed = self._auto_dry_units.setdefault(
  5510. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5511. )
  5512. armed["running"] = True
  5513. async def _notify_auto_drying_suspended(
  5514. self,
  5515. db: AsyncSession,
  5516. printer: Printer,
  5517. ams_id: int,
  5518. humidity: int,
  5519. threshold: int,
  5520. cycles: int,
  5521. ) -> None:
  5522. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5523. Fires once per suspension — the caller sets ``suspended`` before calling
  5524. and every later pass short-circuits on it — because the whole point is
  5525. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5526. building needs that to reach them, and the hourly humidity alarm they
  5527. are already getting says the opposite of what happened here.
  5528. Never raises: a notification provider being down must not stop the
  5529. suspension itself from taking effect.
  5530. """
  5531. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5532. try:
  5533. await notification_service.on_ams_drying_suspended(
  5534. printer.id,
  5535. printer.name,
  5536. ams_label,
  5537. float(humidity),
  5538. float(threshold),
  5539. cycles,
  5540. db,
  5541. )
  5542. except Exception as e:
  5543. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5544. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5545. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5546. The unproductive-cycle counter exists to notice that *drying* is not
  5547. moving the humidity reading. A cycle that ended because somebody sent a
  5548. stop says nothing about that — it was cut short before it had a chance —
  5549. so counting it would suspend auto-drying for a reason that has nothing to
  5550. do with the loop the counter is there to break.
  5551. Two callers, both of them a stop Bambuddy is responsible for: the
  5552. print-takes-priority stop below, and the manual Stop button. Left
  5553. uncalled, an install that dries between queue jobs would suspend its own
  5554. auto-drying after two prints interrupted a dry — exactly the install
  5555. queue-drying exists for.
  5556. The rest of the unit's history is kept: the cooldown before re-arming
  5557. still applies, and an earlier count still stands.
  5558. """
  5559. state = self._auto_dry_units.get((printer_id, ams_id))
  5560. if state is not None:
  5561. state.pop("running", None)
  5562. state["ended_at"] = time.monotonic()
  5563. # A stopped cycle spends the streak that armed it, same as a completed
  5564. # one (#2518).
  5565. self._auto_dry_above.pop((printer_id, ams_id), None)
  5566. def _sync_drying_state(self):
  5567. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5568. One direction only: it prunes, it never adds. A printer drying without an
  5569. entry here — because the user started the cycle from Studio, the printer's
  5570. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5571. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5572. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5573. That is deliberate for now rather than an oversight: populating this from
  5574. telemetry would hand the scheduler authority to stop drying a user started
  5575. by hand. It also means the backend-restart case this used to claim to
  5576. handle is not handled.
  5577. """
  5578. to_remove = []
  5579. for pid in self._drying_in_progress:
  5580. state = printer_manager.get_status(pid)
  5581. if not state:
  5582. to_remove.append(pid)
  5583. continue
  5584. # Check if any AMS unit is still drying
  5585. ams_list = state.raw_data.get("ams", [])
  5586. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5587. if not any_drying:
  5588. to_remove.append(pid)
  5589. for pid in to_remove:
  5590. self._drying_in_progress.pop(pid, None)
  5591. # A printer that has gone away entirely takes its per-AMS auto-drying
  5592. # history with it (#2770), so a printer deleted and re-added does not
  5593. # inherit a suspension it never earned.
  5594. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5595. self._auto_dry_units.pop(key, None)
  5596. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5597. # printer starts a fresh wait, and vanished printers do not leak
  5598. # entries.
  5599. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5600. self._auto_dry_above.pop(key, None)
  5601. @staticmethod
  5602. def _drying_is_only_parked(printer_id: int) -> bool:
  5603. """True when every AMS unit with a drying timer on this printer is parked.
  5604. A parked timer (#2896: the command was taken but the countdown never
  5605. runs) does not end on its own, so nothing may wait on it. False when no
  5606. unit reports a timer yet -- a command just sent that the firmware has not
  5607. reported back is real drying about to begin.
  5608. """
  5609. state = printer_manager.get_status(printer_id)
  5610. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5611. timed = []
  5612. for unit in units:
  5613. try:
  5614. if int(unit.get("dry_time") or 0) > 0:
  5615. timed.append(unit)
  5616. except (TypeError, ValueError):
  5617. continue
  5618. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5619. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5620. """True when a running cycle can be left alone while the next print runs.
  5621. Some hardware dries happily through a print and #2758 settled that we
  5622. should not tear those cycles down: the X2D there was refusing to
  5623. *start* a job, which is a different problem, and stopping drying before
  5624. every dispatch would throw away cycles the printer was content to run.
  5625. Where the model cannot do it, or the user has not enabled it, the print
  5626. takes priority and the cycle stops -- which is what the queue_drying_block
  5627. setting has always promised in its off position.
  5628. """
  5629. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5630. return False
  5631. status = printer_manager.get_status(printer_id)
  5632. return supports_drying_while_printing(
  5633. printer_manager.get_model(printer_id),
  5634. status.firmware_version if status else None,
  5635. )
  5636. async def _stop_drying(self, printer_id: int):
  5637. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5638. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5639. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5640. enough to kill a cycle the user had started by hand on a *different*
  5641. unit of the same printer (#2801). That contradicted the contract
  5642. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5643. only knows about cycles Bambuddy began, so the action must not reach
  5644. past them either.
  5645. """
  5646. state = printer_manager.get_status(printer_id)
  5647. if not state:
  5648. self._drying_in_progress.pop(printer_id, None)
  5649. return
  5650. ams_list = state.raw_data.get("ams", [])
  5651. for ams_data in ams_list:
  5652. dry_time = int(ams_data.get("dry_time") or 0)
  5653. if dry_time > 0:
  5654. ams_id = int(ams_data.get("id", 0))
  5655. if (printer_id, ams_id) not in self._auto_dry_units:
  5656. logger.debug(
  5657. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5658. printer_id,
  5659. ams_id,
  5660. )
  5661. continue
  5662. logger.info(
  5663. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5664. printer_id,
  5665. ams_id,
  5666. )
  5667. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5668. self.forget_auto_dry_cycle(printer_id, ams_id)
  5669. self._drying_in_progress.pop(printer_id, None)
  5670. # Scheduled manual drying (#2638) -----------------------------------
  5671. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5672. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5673. async def _check_scheduled_dryings(self, db: AsyncSession):
  5674. """Dispatch due scheduled drying runs and track running ones."""
  5675. now = utcnow_naive()
  5676. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5677. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5678. since_prune = time.monotonic()
  5679. if (
  5680. self._last_scheduled_drying_prune is None
  5681. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5682. ):
  5683. self._last_scheduled_drying_prune = since_prune
  5684. await db.execute(
  5685. delete(ScheduledDrying).where(
  5686. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5687. ScheduledDrying.completed_at.is_not(None),
  5688. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5689. )
  5690. )
  5691. # Same order as the list route: with two rows due on one printer the
  5692. # earliest scheduled wins rather than whatever the DB hands back first.
  5693. result = await db.execute(
  5694. select(ScheduledDrying)
  5695. .where(ScheduledDrying.status.in_(("pending", "running")))
  5696. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5697. )
  5698. rows = list(result.scalars().all())
  5699. # Rebuild from the DB every tick so route-side cancels and completions
  5700. # show up. Auto-drying's stop-all branches check this set before
  5701. # stopping anything (#2638).
  5702. # Kept from the previous pass so a run that ended between passes — a
  5703. # cancel through the route, say — can still be released below.
  5704. previously_running = self._scheduled_drying_printer_ids
  5705. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5706. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5707. # Model and firmware come from the printer row, not the live state.
  5708. printer_ids = {row.printer_id for row in rows}
  5709. printers_by_id: dict[int, Printer] = {}
  5710. if printer_ids:
  5711. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5712. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5713. for row in rows:
  5714. if row.status == "running":
  5715. self._update_running_scheduled_drying(row, now)
  5716. continue
  5717. if row.start_after is not None and row.start_after > now:
  5718. continue
  5719. state = printer_manager.get_status(row.printer_id)
  5720. if not state:
  5721. row.waiting_reason = "printer_offline"
  5722. continue
  5723. # Same preflight the immediate endpoint runs. Without it the publish
  5724. # succeeds, the row goes to running, the printer ignores the command
  5725. # and the run silently cancels itself after the grace window.
  5726. printer = printers_by_id.get(row.printer_id)
  5727. unsupported = drying_preflight.check_drying_supported(
  5728. printer.model if printer else None, state.firmware_version
  5729. )
  5730. if unsupported:
  5731. row.status = "failed"
  5732. row.error_message = unsupported
  5733. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5734. row.completed_at = now
  5735. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5736. continue
  5737. if (
  5738. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5739. ) or row.printer_id in running_printer_ids:
  5740. row.waiting_reason = "already_drying"
  5741. continue
  5742. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5743. row.waiting_reason = "printer_busy"
  5744. continue
  5745. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5746. if target is None:
  5747. row.waiting_reason = "ams_not_found"
  5748. continue
  5749. blocking = drying_preflight.blocking_reason_codes(target)
  5750. if blocking:
  5751. # Keep the power case distinct; it needs the user to act, so the
  5752. # card can say so instead of waiting silently.
  5753. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5754. continue
  5755. filament = drying_preflight.resolve_filament(target, row.filament)
  5756. logger.info(
  5757. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5758. row.id,
  5759. row.printer_id,
  5760. row.ams_id,
  5761. row.temp,
  5762. row.duration_hours,
  5763. )
  5764. success = printer_manager.send_drying_command(
  5765. row.printer_id,
  5766. row.ams_id,
  5767. row.temp,
  5768. row.duration_hours,
  5769. mode=1,
  5770. filament=filament,
  5771. rotate_tray=row.rotate_tray,
  5772. )
  5773. if success:
  5774. row.status = "running"
  5775. row.started_at = now
  5776. row.waiting_reason = None
  5777. row.filament = filament
  5778. self._drying_in_progress[row.printer_id] = time.monotonic()
  5779. self._scheduled_drying_printer_ids.add(row.printer_id)
  5780. running_printer_ids.add(row.printer_id)
  5781. else:
  5782. row.waiting_reason = "printer_offline"
  5783. # Release the printers whose run has ended. `_drying_in_progress` is
  5784. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5785. # but that call sits behind the auto-drying enabled check, and this
  5786. # method is the one writer that runs whether auto-drying is on or not.
  5787. # With it off, nothing would ever drop the entry short of a print being
  5788. # dispatched to the same printer, so the next scheduled run would wait
  5789. # on "already_drying" forever and `queue_drying_block` would hold the
  5790. # printer's prints too. Covers a run that ended during this pass and one
  5791. # cancelled through the route between passes.
  5792. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5793. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5794. self._drying_in_progress.pop(printer_id, None)
  5795. await db.commit()
  5796. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5797. """Detect completion or interruption of a running scheduled drying.
  5798. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5799. drying. Within the grace window after start we ignore dry_time==0
  5800. (the status lags the command). After that, dry_time==0 near the end
  5801. of the configured duration means completed. Much earlier means the
  5802. run was stopped: re-queue it if a print preempted the dryer, but a
  5803. stop while the printer is idle was deliberate, so cancel the row
  5804. rather than restart drying the user just stopped.
  5805. """
  5806. if row.started_at is None:
  5807. row.started_at = now
  5808. return
  5809. elapsed = (now - row.started_at).total_seconds()
  5810. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5811. return
  5812. state = printer_manager.get_status(row.printer_id)
  5813. if not state:
  5814. return # offline mid-dry; resolve when it reconnects
  5815. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5816. # throw on a malformed id would cost the whole pass including print
  5817. # dispatch, every tick.
  5818. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5819. try:
  5820. dry_time = int(target.get("dry_time") or 0) if target else 0
  5821. except (TypeError, ValueError):
  5822. dry_time = 0
  5823. if dry_time > 0 and is_countdown_parked(target):
  5824. # The printer took the command but the countdown is not running
  5825. # (#2896) and will never reach 0, so the run would stay "running"
  5826. # forever. A print in progress is the likely cause (the power budget
  5827. # is spent), so re-queue it like any interruption; the next start
  5828. # waits for the printer to be idle. Parked on an idle printer is a
  5829. # refusal, not something a retry fixes. The timer itself is left on
  5830. # the printer: it may yet start once power frees up.
  5831. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5832. logger.info(
  5833. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5834. row.id,
  5835. row.ams_id,
  5836. )
  5837. row.status = "pending"
  5838. row.started_at = None
  5839. row.waiting_reason = "interrupted"
  5840. else:
  5841. logger.warning(
  5842. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5843. row.id,
  5844. row.ams_id,
  5845. )
  5846. row.status = "failed"
  5847. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5848. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5849. row.completed_at = now
  5850. return
  5851. if dry_time > 0:
  5852. return
  5853. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5854. row.status = "completed"
  5855. row.completed_at = now
  5856. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5857. row.status = "pending"
  5858. row.started_at = None
  5859. row.waiting_reason = "interrupted"
  5860. else:
  5861. row.status = "cancelled"
  5862. row.completed_at = now
  5863. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5864. """Get all smart plugs associated with a printer."""
  5865. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5866. return list(result.scalars().all())
  5867. @staticmethod
  5868. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5869. """Pick the plug to power-cycle a printer back online with (#2629).
  5870. Only a plug flagged ``controls_printer_power`` can actually bring the
  5871. printer back; waiting for a boot on an accessory (filter fan, lights)
  5872. just burns the power-on timeout and fails the dispatch. Falls back to
  5873. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5874. Callers must pass a non-empty list.
  5875. """
  5876. for plug in auto_on_plugs:
  5877. if plug.controls_printer_power:
  5878. return plug
  5879. return auto_on_plugs[0]
  5880. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5881. # chamber-temperature recommendations BambuStudio ships for the matching
  5882. # filament profile; users can override via Settings → Workflow → Preheat
  5883. # card. "default" applies when a loaded tray's normalised type isn't in
  5884. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5885. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5886. "PLA": 0,
  5887. "PETG": 0,
  5888. "PETG-CF": 40,
  5889. "ABS": 45,
  5890. "ASA": 45,
  5891. "PA": 50,
  5892. "PA-CF": 55,
  5893. "PC": 50,
  5894. "PC-FR": 50,
  5895. "TPU": 0,
  5896. "PVA": 0,
  5897. "default": 0,
  5898. }
  5899. @classmethod
  5900. def _bundled_preheat_targets(cls) -> dict[str, int]:
  5901. """The bundled map under the same key casing a parsed one gets.
  5902. The constant is declared with a lowercase ``default`` because that is
  5903. the key the Settings editor writes and displays. Every read of the map
  5904. happens after ``str(key).upper()``, so handing the constant back as
  5905. declared broke the contract the parser documents: an install that had
  5906. never touched the setting returned a dict with no ``DEFAULT`` in it,
  5907. and the resolution loop's fallback silently found nothing. It read the
  5908. right number only because the bundled default happens to be 0 -- change
  5909. that constant and every unconfigured install would keep preheating to
  5910. zero with no way to tell why.
  5911. """
  5912. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  5913. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  5914. """Parse the user-configured filament→chamber-target map, falling back
  5915. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  5916. are uppercased and the 'default' fallback is always present in the
  5917. returned dict so the resolution loop can index it unconditionally."""
  5918. raw = await self._get_setting(db, "preheat_filament_targets")
  5919. if not raw:
  5920. return self._bundled_preheat_targets()
  5921. try:
  5922. parsed = json.loads(raw)
  5923. if not isinstance(parsed, dict):
  5924. raise ValueError("not an object")
  5925. except (json.JSONDecodeError, ValueError) as exc:
  5926. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  5927. return self._bundled_preheat_targets()
  5928. # Coerce values to int; drop unparseable rows so a stray string
  5929. # doesn't crash the loop.
  5930. out: dict[str, int] = {}
  5931. for key, value in parsed.items():
  5932. try:
  5933. out[str(key).upper()] = int(value)
  5934. except (TypeError, ValueError):
  5935. continue
  5936. if "DEFAULT" not in out:
  5937. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  5938. return out
  5939. @staticmethod
  5940. def _normalize_filament_type(tray_type: str) -> str:
  5941. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  5942. existing drying-preset normalisation (split-at-space, upper-case) so
  5943. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  5944. "PA-CF" (no space to split on).
  5945. This is the first stage of ``_resolve_filament_key``, which goes on to
  5946. drop the suffix and consult the alias map; on its own it only decides
  5947. what the tray is called, not which row answers for it.
  5948. Indexing the split rather than testing the input: a tray_type of spaces
  5949. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  5950. it through to an IndexError.
  5951. """
  5952. words = (tray_type or "").split()
  5953. return words[0].upper() if words else ""
  5954. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  5955. """Per-filament chamber target for one tray's reported type, or 0 when
  5956. the tray is empty / RFID-less and reports no type at all.
  5957. A filled or foamed variant wants its base material's chamber when the
  5958. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  5959. not the 0 an unknown type falls to. The specific type is still tried
  5960. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  5961. (#2902).
  5962. That lookup is now the shared one, which adds the polyamide aliases on
  5963. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  5964. too, rather than the catch-all it was landing on (#3067).
  5965. """
  5966. if not self._normalize_filament_type(tray_type or ""):
  5967. return 0
  5968. key = self._resolve_filament_key(tray_type, targets)
  5969. if key is not None:
  5970. return targets[key]
  5971. # A type the map does not list at all, which is not the same as a tray
  5972. # with nothing in it -- that already returned 0 above.
  5973. return targets.get("DEFAULT", 0)
  5974. def _derive_chamber_target(
  5975. self,
  5976. printer: Printer,
  5977. targets: dict[str, int],
  5978. item: PrintQueueItem | None = None,
  5979. ) -> int:
  5980. """Chamber target for the trays this print actually loads: the max of
  5981. their per-filament targets. Returns 0 when there is nothing to read (no
  5982. status, no AMS telemetry — e.g. external-spool prints) or when every
  5983. tray considered maps to 0, and the chamber phase then short-circuits in
  5984. the main loop.
  5985. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  5986. Scanning the whole unit instead meant one ASA spool parked in the AMS
  5987. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  5988. plus soak burned ahead of each upload, on a printer whose chamber never
  5989. reaches the target anyway (#2886). An item with no usable mapping falls
  5990. back to scanning every loaded tray: that is the only signal left, and
  5991. narrowing to nothing would skip preheat on prints that genuinely need
  5992. it.
  5993. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  5994. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  5995. less slots have empty `tray_type` and contribute nothing. The external
  5996. spool is consulted only when the mapping names it (>= 254); it stays
  5997. out of the unnarrowed scan, so an item without a mapping derives from
  5998. the AMS alone exactly as before.
  5999. """
  6000. state = printer_manager.get_status(printer.id)
  6001. if state is None:
  6002. return 0
  6003. raw_data = state.raw_data or {}
  6004. used = _used_global_tray_ids(item)
  6005. ams_list = raw_data.get("ams")
  6006. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6007. if isinstance(ams_list, dict):
  6008. ams_list = ams_list.get("ams") or []
  6009. if not isinstance(ams_list, list):
  6010. ams_list = []
  6011. best = 0
  6012. for ams in ams_list:
  6013. if not isinstance(ams, dict):
  6014. continue
  6015. ams_id = _int_or(ams.get("id"), 0)
  6016. for tray in ams.get("tray") or []:
  6017. # A non-dict entry has never been seen from real firmware, but
  6018. # `.get` on one raises, and nothing between here and
  6019. # `_dispatch_one`'s try/finally catches it — the item would be
  6020. # left holding its dispatch claim. Preheat is best-effort by
  6021. # contract, so step over it instead.
  6022. if not isinstance(tray, dict):
  6023. continue
  6024. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6025. continue
  6026. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6027. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6028. for vt in raw_data.get("vt_tray") or []:
  6029. if not isinstance(vt, dict):
  6030. continue
  6031. # `_build_loaded_filaments` addresses external feeds by the id
  6032. # the firmware reports — 255 main, 254 deputy — defaulting to
  6033. # 254 when the field is absent. Same expression here so the two
  6034. # agree on which entry a mapping's 254/255 refers to.
  6035. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6036. continue
  6037. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6038. return best
  6039. def _release_keep_warm(self, pid: int) -> None:
  6040. """Release keep-warm on a printer that left the candidate set.
  6041. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6042. reports the target we set (``entry.held_target``), so a user or
  6043. subsequent print that changed the bed target since is not clobbered.
  6044. Best-effort, never raises.
  6045. The entry is kept, not dropped, when the printer cannot be reached
  6046. right now: a printer that is briefly offline still has a hot bed, and
  6047. holding the entry is what keeps the max-duration timeout applying and
  6048. lets a later tick retry the release. Only a printer that has left the
  6049. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6050. """
  6051. entry = self._keep_warm.get(pid)
  6052. if entry is None:
  6053. return
  6054. state = printer_manager.get_status(pid)
  6055. client = printer_manager.get_client(pid)
  6056. if state is None or client is None:
  6057. logger.debug(
  6058. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6059. pid,
  6060. )
  6061. return
  6062. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6063. if int(cur_bed_target) != entry.held_target:
  6064. # Someone else owns the bed now, so there is nothing of ours to
  6065. # undo and nothing left to track.
  6066. logger.info(
  6067. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6068. pid,
  6069. int(cur_bed_target),
  6070. entry.held_target,
  6071. )
  6072. self._keep_warm.pop(pid, None)
  6073. return
  6074. try:
  6075. client.set_bed_temperature(0)
  6076. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6077. self._keep_warm.pop(pid, None)
  6078. except Exception as exc:
  6079. # Keep the entry so the next tick tries again rather than leaving
  6080. # the bed hot with nothing tracking it.
  6081. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6082. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6083. """Release printers that dropped out of the keep-warm candidate set.
  6084. Called from ``_apply_keep_warm`` on every tick (with the current
  6085. candidate set), and from ``check_queue``'s no-pending-items early
  6086. return (with an empty candidate set) so orphaned holds still get
  6087. released when the queue empties. Also called with an empty candidate
  6088. set when any of the three gate settings toggles off, so a printer
  6089. whose feature was disabled mid-hold gets its bed released.
  6090. Printers being dispatched this tick are excluded from the bed-off
  6091. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6092. transient 0 in between would just churn against preheat. Ownership of
  6093. the hot bed transfers to the preheat rollback pin instead — if the
  6094. dispatch aborts before the print starts (failed upload, cancelled
  6095. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6096. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6097. is the ONLY thing standing between an aborted dispatch and a bed
  6098. left hot with no owner. A successful print start clears the pin and
  6099. the print's own gcode takes over, as usual.
  6100. """
  6101. for _pid in list(self._keep_warm):
  6102. if _pid in active_candidates:
  6103. continue
  6104. if _pid in dispatched:
  6105. handed_over = self._keep_warm.pop(_pid, None)
  6106. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6107. if handed_over is not None:
  6108. self._preheat_pin_bed[_pid] = handed_over.held_target
  6109. continue
  6110. self._release_keep_warm(_pid)
  6111. async def _apply_keep_warm(
  6112. self,
  6113. db: AsyncSession,
  6114. items: list[PrintQueueItem],
  6115. dispatch_ids: list[int] | set[int],
  6116. busy_printers: set[int],
  6117. require_plate_clear: bool,
  6118. ) -> None:
  6119. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6120. When a printer just finished a job (FINISH state) and the next queued
  6121. item needs chamber heating, hold the bed hot so the chamber stays warm
  6122. during the bed-clearing window. The bed is the chamber's heating
  6123. element here, not a print surface — nothing is printing during the
  6124. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6125. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6126. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6127. aftermarket chamber heaters), raised to the item's own parsed
  6128. bed_temperature when that is higher. Items whose archive metadata has
  6129. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6130. get a hold — chamber need is what gates the feature, not metadata.
  6131. Skips entirely for filaments that map to a 0°C chamber target
  6132. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6133. names, so a hot-chamber spool it never touches does not hold the bed of
  6134. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6135. whole unit, as every item was before. Printers being dispatched this
  6136. cycle are excluded:
  6137. ``_preheat_and_soak`` already handles their bed temperature.
  6138. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6139. released to 0 and the entry is latched ``expired=True`` so
  6140. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6141. MQTT: publish is skipped when firmware already has the target.
  6142. The release sweep runs BEFORE the engagement gate so a printer that
  6143. was owned by keep-warm still gets its bed released when any of the
  6144. three gate settings is toggled off mid-hold. The
  6145. ``check_queue`` early-return-when-no-items path also calls
  6146. ``_sweep_keep_warm`` directly to release orphaned holds.
  6147. """
  6148. dispatch_set = set(dispatch_ids)
  6149. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6150. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6151. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6152. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6153. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6154. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6155. # Release sweep first — must run even when gate_open is False so a
  6156. # printer owned by keep-warm when a gate toggles off gets released.
  6157. self._sweep_keep_warm(
  6158. active_candidates=warm_candidates if gate_open else set(),
  6159. dispatched=dispatched_printers,
  6160. )
  6161. if not gate_open:
  6162. return
  6163. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6164. max_hold_seconds = (
  6165. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6166. )
  6167. now_mono = time.monotonic()
  6168. filament_targets: dict[str, int] | None = None
  6169. for pid in warm_candidates:
  6170. entry = self._keep_warm.get(pid)
  6171. # Latched-expired: max-duration timeout already fired for this
  6172. # printer. Skip until the release sweep drops the entry (i.e.
  6173. # until the printer leaves the candidate set).
  6174. if entry is not None and entry.expired:
  6175. continue
  6176. # These two guards sit ahead of the max-duration check below, so an
  6177. # engaged hold only ages out while its printer is still reachable
  6178. # and still in FINISH. That is deliberate rather than a hole: with
  6179. # no status or no client there is no M140 to send anyway, and the
  6180. # elapsed check runs off `entry.started` so it fires on the first
  6181. # tick after the printer comes back. Leaving FINISH means the plate
  6182. # was cleared, which drops the printer out of `warm_candidates` and
  6183. # hands it to `_release_keep_warm` instead. The invariant worth
  6184. # preserving if this is ever reordered: every path out of an
  6185. # engaged hold ends in a bed-off, whether by timeout or release.
  6186. state = printer_manager.get_status(pid)
  6187. if state is None or state.state != "FINISH":
  6188. continue
  6189. client = printer_manager.get_client(pid)
  6190. if client is None:
  6191. continue
  6192. next_item = next((it for it in items if it.printer_id == pid), None)
  6193. if next_item is None:
  6194. continue
  6195. # Hold temperature: the configured keep-warm temp, raised to the
  6196. # item's own bed temp when the metadata reports a higher one. A
  6197. # missing bed_temperature (Orca gcode.3mf exports parse without
  6198. # one) does NOT skip the hold — chamber need gates the feature.
  6199. archive = next_item.archive
  6200. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6201. bed_target = max(item_bed, hold_temp)
  6202. if bed_target <= 0:
  6203. continue
  6204. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6205. if explicit is not None:
  6206. chamber_needed = int(explicit) > 0
  6207. else:
  6208. if filament_targets is None:
  6209. filament_targets = await self._get_preheat_filament_targets(db)
  6210. printer_obj = await self._get_printer(db, pid)
  6211. chamber_needed = (
  6212. printer_obj is not None
  6213. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6214. )
  6215. if not chamber_needed:
  6216. continue
  6217. # Seed the timer on first engagement; keep it on subsequent ticks
  6218. # (never re-seed — that would defeat the max-duration cap).
  6219. if entry is None:
  6220. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6221. self._keep_warm[pid] = entry
  6222. elapsed = now_mono - entry.started
  6223. if elapsed > max_hold_seconds:
  6224. # Timeout: publish bed → 0 once (if firmware still holds our
  6225. # target) and latch expired. The entry stays until the release
  6226. # sweep drops it, preventing the next tick from re-seeding.
  6227. logger.warning(
  6228. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6229. pid,
  6230. elapsed,
  6231. )
  6232. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6233. if int(cur_bed_target) == entry.held_target:
  6234. try:
  6235. client.set_bed_temperature(0)
  6236. except Exception as exc:
  6237. logger.warning(
  6238. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6239. pid,
  6240. exc,
  6241. )
  6242. else:
  6243. logger.info(
  6244. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6245. pid,
  6246. int(cur_bed_target),
  6247. entry.held_target,
  6248. )
  6249. entry.expired = True
  6250. continue
  6251. # Idempotence: skip publish when firmware already has our target.
  6252. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6253. if int(cur_bed_target) == bed_target:
  6254. entry.held_target = bed_target
  6255. continue
  6256. try:
  6257. client.set_bed_temperature(bed_target)
  6258. entry.held_target = bed_target
  6259. logger.info(
  6260. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6261. bed_target,
  6262. pid,
  6263. )
  6264. except Exception as exc:
  6265. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6266. def _sample_chamber_temps(self) -> None:
  6267. """Record a chamber temperature sample for every connected printer.
  6268. Called once per scheduler tick (every 3–30 s). Entries older than
  6269. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6270. Also evicts per-printer state whose printer_id is no longer registered
  6271. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6272. """
  6273. now = time.monotonic()
  6274. cutoff = now - self._chamber_history_ttl
  6275. statuses = printer_manager.get_all_statuses()
  6276. known_pids = set(statuses.keys())
  6277. for pid, status in statuses.items():
  6278. if status is None or not status.connected:
  6279. continue
  6280. temps = status.temperatures or {}
  6281. chamber = temps.get("chamber")
  6282. if chamber is None:
  6283. continue
  6284. hist = self._chamber_history.setdefault(pid, deque())
  6285. hist.append((now, float(chamber)))
  6286. while hist and hist[0][0] < cutoff:
  6287. hist.popleft()
  6288. # Evict state for printers that are no longer registered with the manager.
  6289. # This is the one place a keep-warm entry is dropped without releasing
  6290. # the bed: the printer is gone from the manager, so there is no client
  6291. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6292. # for printers that are merely unreachable, which is what makes this
  6293. # the terminal case rather than a silent leak.
  6294. for pid in list(self._chamber_history):
  6295. if pid not in known_pids:
  6296. self._chamber_history.pop(pid, None)
  6297. for pid in list(self._keep_warm):
  6298. if pid not in known_pids:
  6299. logger.info(
  6300. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6301. pid,
  6302. )
  6303. self._keep_warm.pop(pid, None)
  6304. for pid in list(self._preheat_pin):
  6305. if pid not in known_pids:
  6306. self._preheat_pin.pop(pid, None)
  6307. self._preheat_pin_bed.pop(pid, None)
  6308. def _chamber_soak_remaining(
  6309. self,
  6310. printer_id: int,
  6311. chamber_target: float,
  6312. soak_seconds: int,
  6313. tolerance: float = 2.0,
  6314. ) -> int:
  6315. """Return how many seconds of soak time are still needed.
  6316. Credits the time the chamber has already spent at temperature against
  6317. the configured soak. The credit may not start earlier than any of:
  6318. * **The newest sample.** Nothing recent means the printer stopped
  6319. reporting mid-observation and the chamber may have cooled unseen, so
  6320. the full soak is required. (A 2 h history whose last reading is half
  6321. an hour old is not evidence of anything — the measured cooling rate
  6322. is fast enough to cross the threshold in that time.)
  6323. * **The most recent contiguous run of samples.** A gap wider than
  6324. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6325. far side is not evidence of temperature.
  6326. * **The end of the most recent real dip below the threshold.**
  6327. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6328. — see that constant for the thermal reasoning. A stray low reading is
  6329. an artifact, and treating it as cooling would discard a soak that
  6330. actually happened.
  6331. Returns ``soak_seconds`` when nothing can be credited (no history,
  6332. stale history, or the chamber is below the threshold right now) and 0
  6333. once the credited time covers the whole soak.
  6334. """
  6335. hist = self._chamber_history.get(printer_id)
  6336. if not hist:
  6337. return soak_seconds
  6338. now = time.monotonic()
  6339. newest_ts, newest_temp = hist[-1]
  6340. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6341. return soak_seconds # stale — no fresh evidence to credit
  6342. threshold = chamber_target - tolerance
  6343. if newest_temp < threshold:
  6344. return soak_seconds # below target right now; nothing is soaked
  6345. samples = list(hist)
  6346. # Earliest point we have unbroken observations for.
  6347. credit_from = samples[-1][0]
  6348. for i in range(len(samples) - 1, 0, -1):
  6349. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6350. break
  6351. credit_from = samples[i - 1][0]
  6352. # Pull the credit forward to the end of the last significant dip. Each
  6353. # excursion is measured between the in-range readings that bracket it,
  6354. # so a lone stray sample is charged one sampling interval rather than
  6355. # zero, and the comparison errs towards calling a dip real.
  6356. i = 0
  6357. while i < len(samples):
  6358. if samples[i][1] >= threshold:
  6359. i += 1
  6360. continue
  6361. j = i
  6362. while j < len(samples) and samples[j][1] < threshold:
  6363. j += 1
  6364. # `newest_temp >= threshold` was checked above, so j is in range.
  6365. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6366. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6367. # Credit resumes at the last below-threshold sample rather than
  6368. # the first good one after it, so a recovered dip over-credits
  6369. # by up to one sampling interval — the opposite lean to the
  6370. # bracketing above. Both are bounded by the sample cadence and
  6371. # dwarfed by the grace period, so neither is worth the extra
  6372. # arithmetic to remove.
  6373. credit_from = max(credit_from, samples[j - 1][0])
  6374. i = j
  6375. return max(0, soak_seconds - int(now - credit_from))
  6376. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6377. """Tell an in-flight dispatch that its item no longer wants to print.
  6378. Called by the queue's cancel and delete routes. Those only write to the
  6379. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6380. observe — so preheat would keep heating for the rest of max_wait + soak
  6381. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6382. blocking every other queued item behind a print that is not happening.
  6383. Signalling in memory rather than re-reading the row keeps this off the
  6384. database entirely: no second session, no transaction held across a long
  6385. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6386. Bambuddy serves from a single uvicorn process with one scheduler task,
  6387. so the route and the dispatch always share this object. The flag is
  6388. advisory — dropping it (e.g. after a restart) only costs a wasted
  6389. preheat, never a wrongly-abandoned print.
  6390. Only ids with a dispatch actually in flight are recorded, so the set
  6391. stays bounded by the upload pool rather than growing once per cancelled
  6392. item for the life of the process. Skipping the rest loses nothing: an
  6393. item that is not in flight cannot start heating later either, because
  6394. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6395. the caller has already committed a terminal status (or deleted the row)
  6396. before calling this.
  6397. """
  6398. if item_id in self._inflight:
  6399. self._cancelled_dispatches.add(item_id)
  6400. # A print sent for it earlier that never started is not one any more.
  6401. self._forget_unstarted_print(item_id, unless_printing=False)
  6402. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6403. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6404. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6405. while it is parked, so the wait is chopped into
  6406. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6407. """
  6408. remaining = float(seconds)
  6409. while remaining > 0:
  6410. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6411. await asyncio.sleep(slice_secs)
  6412. remaining -= slice_secs
  6413. if item_id in self._cancelled_dispatches:
  6414. return False
  6415. return True
  6416. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6417. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6418. The full preheat stage does this as part of its own dispatch: an H2D
  6419. left in heating mode by the ABS job before it would otherwise cook the
  6420. PLA that follows. The skip path never reaches that code, so it calls
  6421. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6422. add to the rollback pin, because a flap set to cooling for a print that
  6423. needs no heat is where it should have been either way.
  6424. Best-effort like everything else in the stage: a refused command logs
  6425. and the dispatch carries on.
  6426. """
  6427. model = printer.model or ""
  6428. if not supports_airduct(model):
  6429. return
  6430. state = printer_manager.get_status(printer.id)
  6431. current = getattr(state, "airduct_mode", None) if state else None
  6432. if current == _AIRDUCT_MODE_COOLING:
  6433. return
  6434. client = printer_manager.get_client(printer.id)
  6435. if client is None:
  6436. return
  6437. try:
  6438. client.set_airduct_mode("cooling")
  6439. except Exception as exc:
  6440. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6441. async def _preheat_and_soak(
  6442. self,
  6443. db: AsyncSession,
  6444. item: PrintQueueItem,
  6445. printer: Printer,
  6446. archive: PrintArchive | None,
  6447. ) -> bool:
  6448. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6449. Returns True when the dispatch should carry on to the upload — including
  6450. every case where preheat is skipped, since a skipped preheat is not a
  6451. reason to abandon the print. Returns False only when the item stopped
  6452. wanting to be printed while the stage was waiting (cancelled or
  6453. deleted); the caller must then abandon the dispatch, and
  6454. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6455. Resolution order:
  6456. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6457. to the global `preheat_enabled` setting; 'on' forces the stage on
  6458. even if the global is off.
  6459. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6460. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6461. across the trays `item.ams_mapping` names (every loaded slot when
  6462. it names none).
  6463. 3. A target of 0 off the filament map skips the whole stage: the
  6464. materials this print loads want no chamber, so there is nothing to
  6465. soak for and the bed phase would only delay the upload (#3041).
  6466. An explicit 0 typed into the per-item override, or a per-item
  6467. 'on', still runs the bed phase and the soak — both are the user
  6468. asking for a warm bed in so many words.
  6469. 4. Three hardware tiers branch the wait loop:
  6470. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6471. send M141 to the resolved target, then wait for the chamber sensor
  6472. to reach it (or the max-wait timeout to elapse).
  6473. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6474. no M141; the bed is the only heat source, so we wait for the chamber
  6475. sensor to rise via bed radiation OR fall through on timeout.
  6476. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6477. temperature; the function just heats the bed and holds for the
  6478. configured soak duration.
  6479. The bed target comes from the archive's parsed metadata
  6480. (`bed_temperature`); if missing the preheat stage logs and returns
  6481. without dispatching anything, rather than guessing at a default that
  6482. might wreck filament setup.
  6483. Failures are logged but never re-raised — preheat is best-effort. A
  6484. printer that goes offline mid-soak, a refused gcode command, or a
  6485. missing temperature reading must not turn into a failed queue item; the
  6486. normal upload + start path runs immediately after this method returns.
  6487. """
  6488. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6489. if override == "off":
  6490. return True
  6491. if override == "inherit":
  6492. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6493. if not enabled:
  6494. return True
  6495. # override == "on" forces the stage on regardless of the global setting.
  6496. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6497. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6498. # Chamber target resolution:
  6499. # 1. Explicit per-item override beats everything (user knows best).
  6500. # 2. Otherwise derive from the filament types this print loads, via
  6501. # the per-filament target map. A PLA-only print derives 0 and the
  6502. # block below skips the stage without the user touching anything,
  6503. # even when an ASA spool is sitting in another slot of the same
  6504. # AMS (#2886).
  6505. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6506. if explicit_target is not None and explicit_target > 0:
  6507. chamber_target = int(explicit_target)
  6508. chamber_source = "item-override"
  6509. elif explicit_target == 0:
  6510. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6511. chamber_source = "item-override-zero"
  6512. else:
  6513. targets = await self._get_preheat_filament_targets(db)
  6514. chamber_target = self._derive_chamber_target(printer, targets, item)
  6515. chamber_source = "filament-map"
  6516. # Nothing to preheat *for*. A zero that came out of the filament map is
  6517. # the map saying this print's materials want no chamber conditioning --
  6518. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6519. # anyway heated the bed and then held it for the full soak, which
  6520. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6521. # own G-code sets the bed the moment it starts, so preheating it here
  6522. # only moves that heating ahead of the upload instead of overlapping
  6523. # with it, and the soak has no chamber to condition (#3041).
  6524. #
  6525. # An explicit statement from the user still runs the stage. Forcing the
  6526. # per-item override to 'on', or typing a chamber target of exactly 0,
  6527. # both mean "preheat the bed for this print" -- the second is
  6528. # documented as doing precisely that. Only the automatic path, the
  6529. # global toggle plus the filament map, short-circuits here.
  6530. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6531. logger.info(
  6532. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6533. "target, so there is nothing to soak for (override=%s model=%s)",
  6534. item.id,
  6535. override,
  6536. printer.model or "",
  6537. )
  6538. self._preheat_flap_to_cooling(item.id, printer)
  6539. return True
  6540. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6541. if bed_target <= 0:
  6542. # No bed temperature in the slicer metadata. When the print needs a
  6543. # hot chamber the bed is simply how we heat it, so fall back to the
  6544. # configured chamber-heating bed temperature rather than skipping
  6545. # the whole stage — otherwise the print starts with a cold chamber,
  6546. # which is exactly what preheat exists to prevent. Without a chamber
  6547. # requirement there is nothing to preheat *for*, so skip as before
  6548. # rather than guess a bed temperature for the print itself.
  6549. if chamber_target <= 0:
  6550. logger.info(
  6551. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6552. item.id,
  6553. )
  6554. return True
  6555. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6556. logger.info(
  6557. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6558. "%d°C to drive the chamber to %d°C",
  6559. item.id,
  6560. bed_target,
  6561. chamber_target,
  6562. )
  6563. client = printer_manager.get_client(printer.id)
  6564. if client is None:
  6565. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6566. return True
  6567. model = printer.model or ""
  6568. has_heater = supports_chamber_heater(model)
  6569. has_sensor = supports_chamber_temp(model)
  6570. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6571. # Fast path: if the chamber has been continuously above target for at
  6572. # least soak_seconds and the bed is already at temperature, skip the
  6573. # entire preheat stage. Typical case: keep-warm held the bed between
  6574. # consecutive same-material prints and the chamber never dropped.
  6575. if do_chamber and has_sensor and soak_seconds > 0:
  6576. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6577. if remaining == 0:
  6578. cur = printer_manager.get_status(printer.id)
  6579. if cur:
  6580. cur_temps = cur.temperatures or {}
  6581. if (
  6582. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6583. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6584. ):
  6585. logger.info(
  6586. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6587. "and bed is already at temperature (chamber history fast-path)",
  6588. item.id,
  6589. chamber_target,
  6590. soak_seconds,
  6591. )
  6592. # Still set targets to prevent cooling during the 3MF upload window.
  6593. # Register each successful set in the preheat pin so `_dispatch_one`
  6594. # unwinds them on any non-success exit.
  6595. pin = self._preheat_pin.setdefault(printer.id, set())
  6596. try:
  6597. client.set_bed_temperature(bed_target)
  6598. pin.add("bed")
  6599. self._preheat_pin_bed[printer.id] = bed_target
  6600. except Exception as exc:
  6601. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6602. if supports_airduct(model):
  6603. cur_airduct = getattr(cur, "airduct_mode", None)
  6604. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6605. try:
  6606. client.set_airduct_mode("heating")
  6607. # Only undo what we can see we replaced. `None`
  6608. # means no mode has been observed yet, and
  6609. # rolling that back to cooling would assert a
  6610. # state the printer never reported.
  6611. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6612. pin.add("airduct")
  6613. except Exception as exc:
  6614. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6615. if has_heater:
  6616. try:
  6617. client.set_chamber_temperature(chamber_target)
  6618. pin.add("chamber")
  6619. except Exception as exc:
  6620. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6621. return True
  6622. logger.info(
  6623. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6624. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6625. item.id,
  6626. bed_target,
  6627. chamber_target if do_chamber else 0,
  6628. chamber_source,
  6629. override,
  6630. model,
  6631. has_heater,
  6632. has_sensor,
  6633. max_wait,
  6634. soak_seconds,
  6635. )
  6636. # Preheat rollback registry: everything we set below is recorded here so
  6637. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6638. # (bed off, chamber off, airduct back to cooling) on any non-success
  6639. # exit. Populated as each command succeeds; consumed and cleared by
  6640. # `_dispatch_one`.
  6641. pin = self._preheat_pin.setdefault(printer.id, set())
  6642. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6643. # cache the target locally so the polling reads below see consistent
  6644. # state (firmware MQTT echoes lag by ~1s).
  6645. try:
  6646. client.set_bed_temperature(bed_target)
  6647. pin.add("bed")
  6648. self._preheat_pin_bed[printer.id] = bed_target
  6649. except Exception as exc:
  6650. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6651. return True
  6652. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6653. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6654. # left it on, regardless of M141. Default cooling actively vents the
  6655. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6656. # cooling never converges — the heater fights the open exhaust. We
  6657. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6658. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6659. # on an H2D that was previously running ABS would otherwise stay in
  6660. # heating mode and overheat PLA). The current-state read keeps the
  6661. # command idempotent — no MQTT chatter when the flap is already where
  6662. # we want it.
  6663. if supports_airduct(model):
  6664. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6665. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6666. current_state = printer_manager.get_status(printer.id)
  6667. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6668. if current_airduct != desired_id:
  6669. try:
  6670. client.set_airduct_mode(desired_airduct)
  6671. # As in the fast path: only pin a rollback for a flap we
  6672. # saw in cooling. `current_airduct` of None means no mode
  6673. # has been observed, so there is nothing to restore to.
  6674. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6675. pin.add("airduct")
  6676. except Exception as exc:
  6677. logger.warning(
  6678. "Queue item %s: preheat airduct %s mode failed: %s",
  6679. item.id,
  6680. desired_airduct,
  6681. exc,
  6682. )
  6683. if do_chamber and has_heater:
  6684. try:
  6685. client.set_chamber_temperature(chamber_target)
  6686. pin.add("chamber")
  6687. except Exception as exc:
  6688. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6689. # Release the pooled DB connection before the (potentially many-minute)
  6690. # heat-soak wait below (#2572). Every setting this method needs is read
  6691. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6692. # it never touches the DB. Without this the caller's transaction sat
  6693. # "idle in transaction" for the whole soak, pinning one pooled connection
  6694. # per preheating printer. expire_on_commit=False keeps item/printer
  6695. # readable afterwards; there are no pending writes to lose here.
  6696. await db.commit()
  6697. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6698. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6699. # Poll every 3s — frequent enough for responsive logging without
  6700. # spamming the MQTT state stream. The "converged" predicate is:
  6701. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6702. # AND
  6703. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6704. BED_TOLERANCE = 2.0
  6705. CHAMBER_TOLERANCE = 2.0
  6706. POLL_INTERVAL = 3.0
  6707. deadline = asyncio.get_event_loop().time() + max_wait
  6708. while True:
  6709. state = printer_manager.get_status(printer.id)
  6710. if state is None:
  6711. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6712. break
  6713. temps = state.temperatures or {}
  6714. bed_now = float(temps.get("bed", 0) or 0)
  6715. chamber_now = float(temps.get("chamber", 0) or 0)
  6716. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6717. if not do_chamber:
  6718. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6719. elif not has_sensor:
  6720. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6721. else:
  6722. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6723. if bed_ok and chamber_ok:
  6724. logger.info(
  6725. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6726. item.id,
  6727. bed_now,
  6728. chamber_now,
  6729. )
  6730. break
  6731. if asyncio.get_event_loop().time() >= deadline:
  6732. logger.info(
  6733. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6734. item.id,
  6735. bed_now,
  6736. bed_target,
  6737. chamber_now,
  6738. chamber_target if do_chamber else 0,
  6739. )
  6740. break
  6741. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6742. logger.info(
  6743. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6744. item.id,
  6745. )
  6746. return False
  6747. if soak_seconds > 0:
  6748. if do_chamber and has_sensor:
  6749. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6750. else:
  6751. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6752. if remaining > 0:
  6753. logger.info(
  6754. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6755. "has been above target for ~%ds already)",
  6756. item.id,
  6757. remaining,
  6758. soak_seconds,
  6759. soak_seconds - remaining,
  6760. )
  6761. if not await self._preheat_sleep(item.id, remaining):
  6762. logger.info(
  6763. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6764. item.id,
  6765. )
  6766. return False
  6767. else:
  6768. logger.info(
  6769. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6770. item.id,
  6771. chamber_target,
  6772. soak_seconds,
  6773. )
  6774. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6775. return True
  6776. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6777. """Turn on smart plug and wait for printer to connect.
  6778. Returns True if printer connected successfully within timeout.
  6779. """
  6780. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6781. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6782. # Check current plug state
  6783. status = await service.get_status(plug)
  6784. if not status.get("reachable"):
  6785. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6786. return False
  6787. # Turn on if not already on
  6788. if status.get("state") != "ON":
  6789. success = await service.turn_on(plug)
  6790. if not success:
  6791. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6792. return False
  6793. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  6794. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6795. # Get printer from database for connection
  6796. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6797. printer = result.scalar_one_or_none()
  6798. if not printer:
  6799. logger.error("Printer %s not found in database", printer_id)
  6800. return False
  6801. # Wait for printer to boot (give it some time before trying to connect)
  6802. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6803. await asyncio.sleep(30)
  6804. # Try to connect to the printer periodically
  6805. elapsed = 30 # Already waited 30s
  6806. while elapsed < self._power_on_wait_time:
  6807. # Try to connect
  6808. logger.info("Attempting to connect to printer %s...", printer_id)
  6809. try:
  6810. connected = await printer_manager.connect_printer(printer)
  6811. if connected:
  6812. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6813. # Give it a moment to stabilize and get status
  6814. await asyncio.sleep(5)
  6815. return True
  6816. except Exception as e:
  6817. logger.debug("Connection attempt failed: %s", e)
  6818. await asyncio.sleep(self._power_on_check_interval)
  6819. elapsed += self._power_on_check_interval
  6820. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6821. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6822. return False
  6823. async def _check_previous_success(
  6824. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  6825. ) -> bool:
  6826. """Check if the previous print on this printer succeeded.
  6827. ``printer_id`` names the printer to look at when the item has none yet
  6828. (a job for any printer of a model, checked against the one offered).
  6829. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6830. deliberate action, not a failure, so subsequent items should still
  6831. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6832. a skip isn't an actual print attempt, so it must not gate downstream
  6833. items — counting it as a failed predecessor was the cascade bug that
  6834. let a single cancellation block 18 items over 3 days for the reporter.
  6835. Only `failed` and `aborted` — real print-attempt failures — block.
  6836. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6837. action — #1818) are also excluded from the lookback so the user can
  6838. clear the gate after fixing the physical issue without having to
  6839. re-queue every downstream job.
  6840. """
  6841. result = await db.execute(
  6842. select(PrintQueueItem)
  6843. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  6844. .where(PrintQueueItem.id != item.id)
  6845. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6846. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6847. # A row ended without a completion time must not count as the
  6848. # latest: PostgreSQL sorts NULL first in a descending order.
  6849. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  6850. .limit(1)
  6851. )
  6852. prev_item = result.scalar_one_or_none()
  6853. # If no previous item, assume success (first in queue)
  6854. if not prev_item:
  6855. return True
  6856. return prev_item.status in ("completed", "cancelled")
  6857. async def _repoint_siblings_at_archive(
  6858. self,
  6859. db: AsyncSession,
  6860. *,
  6861. consumed_library_file_id: int,
  6862. archive_id: int,
  6863. dispatched_item_id: int,
  6864. ) -> int:
  6865. """Move the other queue items off a library row that is about to be deleted (#2819).
  6866. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6867. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6868. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6869. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6870. clones, so the first dispatch could pull the file out from under rows that
  6871. had not run yet. What those rows did next depended on the database, and
  6872. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6873. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6874. they were left pointing at a row that no longer existed, failing with
  6875. "Library file not found" whenever someone started them -- or sitting
  6876. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6877. constraint, so there the rows were deleted outright and the queued copies
  6878. simply vanished, with no error and no history.
  6879. The archive holds its own copy of the 3MF, so the remaining copies can print
  6880. from it instead. Two things happen here, and both must happen *before* the
  6881. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6882. * every row still naming the file has ``library_file_id`` cleared, which is
  6883. what takes it out of the cascade's reach. That covers rows this cannot
  6884. re-point as well -- a copy already printing from its own archive, and the
  6885. finished ones, which are not spare parts but the record a batch order
  6886. counts its progress from.
  6887. * the rows that still need something to print are pointed at the archive.
  6888. Returns how many items were re-pointed.
  6889. """
  6890. variant_item_ids = (
  6891. (
  6892. await db.execute(
  6893. select(PrintQueueVariant.queue_item_id).where(
  6894. PrintQueueVariant.library_file_id == consumed_library_file_id
  6895. )
  6896. )
  6897. )
  6898. .scalars()
  6899. .all()
  6900. )
  6901. # Candidate rows naming the consumed file have to go rather than be
  6902. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  6903. # one out of the cascade. This is what PostgreSQL already does, and
  6904. # _candidates_for skips such a variant on SQLite anyway, so no selection
  6905. # outcome changes -- the two backends simply stop disagreeing about
  6906. # whether the row is still there.
  6907. #
  6908. # It also has to happen before the re-point below: a cross-model item
  6909. # (#671) picks a variant every pass and folds it onto the row, and
  6910. # _resolve_variant clears archive_id as it does so, which would undo the
  6911. # re-point on the very next lap.
  6912. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  6913. # An item left with other candidates still has somewhere to go, and those
  6914. # carry their own target model -- pointing it at this archive would print a
  6915. # file the matcher never chose. It is excluded from the re-point and simply
  6916. # re-resolves against what is left.
  6917. surviving_variant_item_ids = set(
  6918. (
  6919. await db.execute(
  6920. select(PrintQueueVariant.queue_item_id).where(
  6921. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  6922. )
  6923. )
  6924. )
  6925. .scalars()
  6926. .all()
  6927. )
  6928. repoint_ids = set(
  6929. (
  6930. await db.execute(
  6931. select(PrintQueueItem.id)
  6932. .where(PrintQueueItem.id != dispatched_item_id)
  6933. .where(PrintQueueItem.archive_id.is_(None))
  6934. # "skipped" belongs here with the two live states: it is not
  6935. # terminal. Clearing a printer's previous-success gate puts
  6936. # every item skipped by it back to "pending"
  6937. # (resume_after_failure), and one restored onto a deleted
  6938. # file is the same orphan by a slower route. "failed",
  6939. # "cancelled", "aborted" and "completed" never return.
  6940. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  6941. .where(
  6942. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  6943. )
  6944. .where(
  6945. or_(
  6946. PrintQueueItem.library_file_id == consumed_library_file_id,
  6947. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  6948. )
  6949. )
  6950. )
  6951. )
  6952. .scalars()
  6953. .all()
  6954. )
  6955. if repoint_ids:
  6956. await db.execute(
  6957. update(PrintQueueItem)
  6958. .where(PrintQueueItem.id.in_(repoint_ids))
  6959. .values(
  6960. archive_id=archive_id,
  6961. library_file_id=None,
  6962. # The file this flag named is already consumed. Leaving it set
  6963. # would arm every re-pointed copy to delete whatever library
  6964. # row it is next given.
  6965. cleanup_library_after_dispatch=False,
  6966. )
  6967. )
  6968. logger.info(
  6969. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  6970. sorted(repoint_ids),
  6971. archive_id,
  6972. consumed_library_file_id,
  6973. dispatched_item_id,
  6974. )
  6975. # Everything else that still names the file: taken out of the cascade's
  6976. # reach without touching what it prints. The file is gone either way; what
  6977. # this preserves is the row.
  6978. await db.execute(
  6979. update(PrintQueueItem)
  6980. .where(PrintQueueItem.id != dispatched_item_id)
  6981. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  6982. .values(library_file_id=None)
  6983. )
  6984. return len(repoint_ids)
  6985. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  6986. """Schedule power-off if the queue item enabled auto_off_after.
  6987. Delegates to the smart-plug manager so the off honours each plug's
  6988. configured strategy (time delay or temperature threshold), is cancelled
  6989. if the printer starts printing again, and never cuts power on a loaded
  6990. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  6991. powered off on the timeout regardless of print state.
  6992. """
  6993. if not item.auto_off_after:
  6994. return
  6995. try:
  6996. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  6997. except Exception as e:
  6998. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  6999. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7000. """Get a human-readable name for a queue item."""
  7001. if item.archive_id:
  7002. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7003. archive = result.scalar_one_or_none()
  7004. if archive:
  7005. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7006. if item.library_file_id:
  7007. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7008. library_file = result.scalar_one_or_none()
  7009. if library_file:
  7010. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7011. # A cross-model item (#671) holds no file of its own until a printer is
  7012. # picked, so name it after its first candidate — otherwise every waiting
  7013. # notification for one reads "Job #12". Queried rather than read off
  7014. # item.variants because callers outside the selection loop have not
  7015. # eager-loaded them, and a lazy load raises in async.
  7016. first_variant_name = (
  7017. await db.execute(
  7018. select(LibraryFile.filename)
  7019. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7020. .where(PrintQueueVariant.queue_item_id == item.id)
  7021. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7022. .limit(1)
  7023. )
  7024. ).scalar_one_or_none()
  7025. if first_variant_name:
  7026. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7027. return f"Job #{item.id}"
  7028. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7029. """Get printer by ID."""
  7030. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7031. return result.scalar_one_or_none()
  7032. async def _notify_dispatch_gave_up(
  7033. self,
  7034. queue_item_id: int,
  7035. printer_id: int,
  7036. created_by_id: int | None,
  7037. reason: str = "Printer accepted the file but never started printing",
  7038. ) -> None:
  7039. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7040. Called from the watchdog, which is a background task with no session of
  7041. its own — hence the fresh one here. Best-effort throughout: the row is
  7042. already marked failed and that is the load-bearing part; a notification
  7043. provider being down must not resurrect the retry loop we just stopped.
  7044. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7045. path passes its own, because "accepted the file but never started" is the
  7046. opposite of what happened there — the printer refused it outright (#2732).
  7047. """
  7048. try:
  7049. async with async_session() as db:
  7050. item = await db.get(PrintQueueItem, queue_item_id)
  7051. if not item:
  7052. return
  7053. job_name = await self._get_job_name(db, item)
  7054. printer = await self._get_printer(db, printer_id)
  7055. await notification_service.on_queue_job_failed(
  7056. job_name=job_name,
  7057. printer_id=printer_id,
  7058. printer_name=printer.name if printer else "Unknown",
  7059. reason=reason,
  7060. db=db,
  7061. )
  7062. except Exception as e:
  7063. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7064. try:
  7065. await ws_manager.send_queue_item_failed(
  7066. user_id=created_by_id,
  7067. queue_item_id=queue_item_id,
  7068. printer_id=printer_id,
  7069. reason="never_started",
  7070. )
  7071. except Exception:
  7072. pass # toast is best-effort
  7073. async def _filament_short_on(
  7074. self,
  7075. db: AsyncSession,
  7076. item: PrintQueueItem,
  7077. printer_id: int,
  7078. *,
  7079. require_known: bool = False,
  7080. ) -> bool:
  7081. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7082. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7083. assigned there, with the mapping the item would get there, but changes
  7084. nothing. The model-based matcher uses it to prefer a printer whose
  7085. spools can finish the job.
  7086. False whenever the gate would let the item through: "Print Anyway",
  7087. no mapping, or a check that fails. With ``require_known`` all three of
  7088. those, and any printed slot whose remaining amount is unknown, count
  7089. as short instead: releasing a held job starts it with nobody asked, so
  7090. it needs the amount on record, not merely nothing against it.
  7091. """
  7092. if item.skip_filament_check:
  7093. return False
  7094. try:
  7095. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7096. if not mapping:
  7097. return require_known
  7098. deficit = await compute_deficit_for_queue_item(
  7099. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7100. )
  7101. except Exception as e:
  7102. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7103. return require_known
  7104. return bool(deficit)
  7105. async def _release_short_model_hold(
  7106. self,
  7107. db: AsyncSession,
  7108. item: PrintQueueItem,
  7109. unavailable: set[int],
  7110. require_plate_clear: bool,
  7111. printer_scope: PrinterScope,
  7112. ) -> bool:
  7113. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7114. The deficit gate holds a model-based job on the printer the matcher
  7115. gave it, because "Print Anyway" needs a printer to print on. When
  7116. another idle printer of the job's model has the filament, the job is
  7117. moved to that printer and its hold lifted, and the fixed-printer
  7118. branch dispatches it in this same pass, through the same checks a
  7119. held job meets when the user presses Start. It is moved rather than
  7120. put back in the pool because the model-based branch would pick again
  7121. without requiring the amounts on record (below), and could pick a
  7122. different printer. Only the deficit gate sets ``filament_short``, so a
  7123. job held for any other reason stays held.
  7124. The printer it is held on is left out: a spool loaded there is started
  7125. with Start, as before, rather than while someone may still be loading
  7126. the next one. Each job is checked at most every
  7127. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7128. on each idle printer again.
  7129. Cross-model jobs (#671) stay held: checking a variant writes its file
  7130. onto the item, which would leave a job that is not moved holding
  7131. another variant's file for the printer it waits on.
  7132. A printer qualifies only on a positive finding: every slot the plate
  7133. prints mapped to a spool whose remaining amount is on record and
  7134. enough. A printer whose spools Bambuddy does not track is not one.
  7135. Returns True when the job was moved. A check that fails keeps the hold
  7136. rather than stopping the queue pass.
  7137. """
  7138. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7139. return False
  7140. if not item.target_model or item.variants:
  7141. return False
  7142. now = time.monotonic()
  7143. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7144. return False
  7145. self._short_hold_checked_at[item.id] = now
  7146. try:
  7147. candidates = _candidates_for(item)
  7148. if not candidates:
  7149. return False
  7150. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7151. async def is_short(pid: int) -> bool:
  7152. return await self._filament_short_on(db, item, pid, require_known=True)
  7153. match_id, _ = await self._find_idle_printer_for_model(
  7154. db,
  7155. item.target_model,
  7156. unavailable | {item.printer_id},
  7157. effective_types,
  7158. item.target_location,
  7159. filament_overrides=filament_overrides,
  7160. require_plate_clear=require_plate_clear,
  7161. printer_scope=printer_scope,
  7162. is_short=is_short,
  7163. )
  7164. # Every idle printer short comes back as the first of them.
  7165. if match_id is None or await is_short(match_id):
  7166. return False
  7167. except Exception as e:
  7168. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7169. return False
  7170. logger.info(
  7171. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7172. item.id,
  7173. match_id,
  7174. item.printer_id,
  7175. )
  7176. self._short_hold_checked_at.pop(item.id, None)
  7177. item.printer_id = match_id
  7178. # Resolved against the printer it leaves (#3239).
  7179. item.ams_mapping = None
  7180. item.manual_start = False
  7181. item.filament_short = False
  7182. item.waiting_reason = None
  7183. await db.commit()
  7184. try:
  7185. printer = await self._get_printer(db, match_id)
  7186. await notification_service.on_queue_job_assigned(
  7187. job_name=await self._get_job_name(db, item),
  7188. printer_id=match_id,
  7189. printer_name=printer.name if printer else "Unknown",
  7190. target_model=item.target_model,
  7191. db=db,
  7192. )
  7193. except Exception as e:
  7194. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7195. return True
  7196. async def _block_on_filament_deficit(
  7197. self,
  7198. db: AsyncSession,
  7199. item: PrintQueueItem,
  7200. ) -> bool:
  7201. """Promote the item to manual_start when the assigned spool is short (#1496).
  7202. Returns True when this dispatch attempt was blocked, False when the
  7203. item is clear to start. A previously-flagged item whose spool has
  7204. since been swapped to one with enough material clears the flag here
  7205. so the next scheduler tick dispatches it.
  7206. """
  7207. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7208. # don't re-flag, don't even compute. Without this short-circuit the
  7209. # scheduler bounces between "user said anyway" (route clears
  7210. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7211. # on identical spool state) (#1698-followup).
  7212. if item.skip_filament_check:
  7213. # #1762 diagnostic: surface the short-circuit at INFO so a
  7214. # future "Print Anyway didn't work" report (e.g. issue #1762
  7215. # comment 3) has actionable evidence in the support bundle
  7216. # without needing DEBUG enabled.
  7217. logger.info(
  7218. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7219. item.id,
  7220. )
  7221. return False
  7222. try:
  7223. deficit = await compute_deficit_for_queue_item(db, item)
  7224. except Exception as e:
  7225. # Never let a flaky deficit check wedge the queue — log and let
  7226. # dispatch proceed. The PrintModal-side check still runs on the
  7227. # manual paths.
  7228. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7229. return False
  7230. if deficit:
  7231. item.filament_short = True
  7232. item.manual_start = True
  7233. await db.commit()
  7234. job_name = await self._get_job_name(db, item)
  7235. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7236. logger.info(
  7237. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7238. item.id,
  7239. len(deficit),
  7240. )
  7241. try:
  7242. await notification_service.on_queue_job_waiting(
  7243. job_name=job_name,
  7244. target_model=(printer.model if printer else "") or "",
  7245. waiting_reason="filament_short",
  7246. db=db,
  7247. )
  7248. except Exception as e:
  7249. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7250. return True
  7251. # No deficit — clear any stale flag from a previous tick.
  7252. if item.filament_short:
  7253. item.filament_short = False
  7254. await db.commit()
  7255. return False
  7256. async def _block_on_unmatched_filament(
  7257. self,
  7258. db: AsyncSession,
  7259. item: PrintQueueItem,
  7260. release_assignment: bool = False,
  7261. ) -> bool:
  7262. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7263. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7264. goes ahead, letting the printer choose — which is how a job prints in the
  7265. wrong material without anyone being asked. Holding is the same answer the
  7266. deficit gate already gives for "the spool is too light", so it reuses the
  7267. same promote-and-notify machinery.
  7268. Keyed off unresolved slots in the *computed* mapping intersected with the
  7269. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7270. read: on its own it also pads slots this plate does not print, so the
  7271. array alone would hold perfectly good jobs. Reading the mapping rather
  7272. than the printer's loaded filament types also inherits the matcher's
  7273. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7274. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7275. type-only scan would wave that through.
  7276. A mapping that resolved *nothing* is the same finding arriving as an
  7277. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7278. could not replace, and dispatch then goes out as ``use_ams`` with no
  7279. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7280. That is held too, but only once live status positively reports loaded
  7281. trays: #2589's mapping is bogus precisely because the AMS was not known
  7282. yet, and its empty loaded list is that ignorance rather than a miss.
  7283. ``release_assignment`` is for the model-based path, which commits its
  7284. printer choice before the gates run. Holding an "any P2S" job would
  7285. otherwise pin it to the one P2S that could not run it.
  7286. Returns True when this dispatch attempt was blocked.
  7287. """
  7288. if item.skip_filament_check or not item.printer_id:
  7289. return False
  7290. if item.ams_mapping:
  7291. try:
  7292. mapping = json.loads(item.ams_mapping)
  7293. except (json.JSONDecodeError, TypeError):
  7294. return False
  7295. if not isinstance(mapping, list):
  7296. return False
  7297. else:
  7298. # Nothing resolved, or nothing survived revalidation. Only a printer
  7299. # that reported loaded trays makes that a finding — see the
  7300. # docstring on why an empty list is not one.
  7301. status = printer_manager.get_status(item.printer_id)
  7302. if status is None or not self._build_loaded_filaments(status):
  7303. return False
  7304. # Every required slot reads unresolved against an empty mapping.
  7305. mapping = []
  7306. required = await self._get_filament_requirements(db, item)
  7307. if not required:
  7308. return False
  7309. self._apply_filament_overrides(item, required)
  7310. unmatched = _unresolved_required(required, mapping)
  7311. if not unmatched:
  7312. # No cleanup needed here: once start is pressed the item is no
  7313. # longer staged, and whichever exit runs next overwrites the reason
  7314. # (`hold_item` on the fixed-printer branch, the assignment on the
  7315. # model-based one), as does dispatch.
  7316. return False
  7317. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7318. held_by = item.printer_id
  7319. item.manual_start = True
  7320. # Human-readable: this renders on the queue row.
  7321. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7322. if release_assignment:
  7323. # "Any P2S" means any, so the job returns to the pool rather than
  7324. # waiting on the printer that could not take it. The mapping goes
  7325. # with the assignment: its tray IDs were resolved against the
  7326. # printer being released and mean nothing on the next one (#2799),
  7327. # and keeping them would hold the job again even on a printer that
  7328. # has the filament, since an unresolved slot is deliberately not a
  7329. # conflict worth recomputing over.
  7330. item.printer_id = None
  7331. item.ams_mapping = None
  7332. await db.commit()
  7333. job_name = await self._get_job_name(db, item)
  7334. printer = await self._get_printer(db, held_by)
  7335. logger.info(
  7336. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7337. item.id,
  7338. held_by,
  7339. wanted,
  7340. )
  7341. try:
  7342. await notification_service.on_queue_job_waiting(
  7343. job_name=job_name,
  7344. target_model=(printer.model if printer else "") or "",
  7345. waiting_reason=f"needs {wanted}",
  7346. db=db,
  7347. )
  7348. except Exception as e:
  7349. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7350. return True
  7351. @staticmethod
  7352. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7353. """The queue item's owner as the row has it now.
  7354. item.created_by_id was read before preheat and upload, which can take
  7355. minutes; deleting the user clears the row, not this session's copy.
  7356. """
  7357. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7358. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7359. """Hand the queue item's owner to printer_manager so the
  7360. print-complete callback can credit the user in PrintLogEntry (#1670).
  7361. No-ops when the item has no `created_by_id` or the referenced user
  7362. row is missing (e.g. user deleted between queue-add and dispatch —
  7363. in that case the print log row falls back to the existing un-credited
  7364. behaviour rather than crashing the dispatch).
  7365. """
  7366. from backend.app.models.user import User
  7367. # Read from the row, not item.created_by_id or db.get: both can still
  7368. # hold a user deleted during the upload, after delete_user forgot them
  7369. # (on SQLite the id may be someone new's by the time the print ends).
  7370. # Joined with the printer too: one deleted during the upload was
  7371. # forgotten as well, and this would write the owner back under its id.
  7372. owner = (
  7373. await db.execute(
  7374. select(User.id, User.username)
  7375. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7376. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7377. .where(PrintQueueItem.id == item.id)
  7378. )
  7379. ).first()
  7380. if owner:
  7381. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7382. if item.printer_id is not None:
  7383. self._unconfirmed_print_user[item.id] = item.printer_id
  7384. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7385. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7386. A cancel lands in another session while the upload runs (the edit route
  7387. even tells users to cancel a job that is being sent). An unconditional
  7388. write here would turn that cancellation into a failure, with a failure
  7389. notification, and block the next job that needs the previous print to
  7390. have succeeded. Returns whether the item was marked failed.
  7391. """
  7392. result = cast(
  7393. CursorResult,
  7394. await db.execute(
  7395. update(PrintQueueItem)
  7396. .where(PrintQueueItem.id == item.id)
  7397. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7398. .values(status="failed", error_message=message, completed_at=datetime.now(timezone.utc))
  7399. .execution_options(synchronize_session=False)
  7400. ),
  7401. )
  7402. await db.commit()
  7403. if result.rowcount == 0:
  7404. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7405. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7406. return False
  7407. await db.refresh(item)
  7408. from backend.app.services.print_batch import refresh_batches_after
  7409. await refresh_batches_after([item.id])
  7410. return True
  7411. @staticmethod
  7412. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7413. """Put a job whose printer turned busy before the start back in the queue.
  7414. Only if it is still printing: a stop that landed meanwhile stands.
  7415. """
  7416. await db.execute(
  7417. update(PrintQueueItem)
  7418. .where(PrintQueueItem.id == item.id)
  7419. .where(PrintQueueItem.status == "printing")
  7420. .values(status="pending", started_at=None)
  7421. .execution_options(synchronize_session=False)
  7422. )
  7423. await db.commit()
  7424. @staticmethod
  7425. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7426. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7427. try:
  7428. await ws_manager.send_queue_item_failed(
  7429. user_id=toast_uid,
  7430. queue_item_id=item.id,
  7431. printer_id=item.printer_id,
  7432. reason="cancelled_mid_dispatch",
  7433. )
  7434. except Exception:
  7435. pass # toast is best-effort
  7436. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7437. """Upload file and start print for a queue item.
  7438. Supports two sources:
  7439. - archive_id: Print from an existing archive
  7440. - library_file_id: Print from a library file (file manager)
  7441. """
  7442. logger.info("Starting queue item %s", item.id)
  7443. # Also covers a reservation left active by a process interruption
  7444. # during an earlier attempt. `_dispatch_one` releases this marker on
  7445. # every exit unless start_print() confirms that the command was sent.
  7446. self._unconfirmed_budget_reservations.add(item.id)
  7447. try:
  7448. from backend.app.models.user import User
  7449. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7450. # Recompute at the final authorization boundary as well as enqueue
  7451. # time. This covers rows created before the server-side estimate
  7452. # migration and prevents any alternate write path from weakening
  7453. # the budget reservation.
  7454. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7455. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7456. item.estimated_cost = await estimate_queue_source_cost(
  7457. db,
  7458. archive=archive,
  7459. library_file=library_file,
  7460. plate_id=item.plate_id,
  7461. ams_mapping=item.ams_mapping,
  7462. printer_id=item.printer_id,
  7463. )
  7464. await validate_print_budget(
  7465. db,
  7466. cost_center_id=item.cost_center_id,
  7467. estimated_cost=item.estimated_cost,
  7468. current_user=queue_user,
  7469. exclude_queue_item_id=item.id,
  7470. exclude_reservation_source_type="print_queue",
  7471. exclude_reservation_source_id=item.id,
  7472. )
  7473. budget_reservation = await create_budget_reservation(
  7474. db,
  7475. cost_center_id=item.cost_center_id,
  7476. estimated_cost=item.estimated_cost,
  7477. current_user=queue_user,
  7478. source_type="print_queue",
  7479. source_id=item.id,
  7480. print_archive_id=item.archive_id,
  7481. exclude_queue_item_id=item.id,
  7482. )
  7483. await db.commit()
  7484. except HTTPException as exc:
  7485. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7486. return
  7487. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7488. await self._power_off_if_needed(db, item)
  7489. return
  7490. # Get printer first (needed for both paths)
  7491. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7492. printer = result.scalar_one_or_none()
  7493. if not printer:
  7494. if not await self._fail_dispatch(db, item, "Printer not found"):
  7495. return
  7496. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7497. await self._power_off_if_needed(db, item)
  7498. return
  7499. # Check printer is connected
  7500. if not printer_manager.is_connected(item.printer_id):
  7501. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7502. return
  7503. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7504. await self._power_off_if_needed(db, item)
  7505. return
  7506. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7507. # `items` was taken at the top of check_queue, but the user can /cancel
  7508. # any pending row in the gap before we reach this point. Re-read the
  7509. # row and bail out cleanly instead of starting an FTP upload for a row
  7510. # that's already cancelled. The atomic CAS at the pending→printing
  7511. # transition (below, before start_print) is the load-bearing guard;
  7512. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7513. await db.refresh(item)
  7514. if item.status != "pending":
  7515. logger.info(
  7516. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7517. item.id,
  7518. item.status,
  7519. )
  7520. return
  7521. # Busy-printer guard (#2598). check_queue gates dispatch on
  7522. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7523. # keep reporting FINISH for tens of seconds *after* it accepted a
  7524. # project_file (see the watchdog's phase-B note). A watchdog revert
  7525. # (#2555) also releases the dispatch hold, so a re-selected item can
  7526. # reach here while its printer has actually started printing. Uploading
  7527. # and dispatching then collides with the live job — the firmware answers
  7528. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7529. # live state right before the expensive FTP upload: if the printer is
  7530. # busy, leave the item pending and let a later tick dispatch it once the
  7531. # printer is genuinely idle. No wasted upload, no collision.
  7532. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7533. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7534. logger.info(
  7535. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7536. "leaving item pending for a later tick (#2598)",
  7537. item.id,
  7538. item.printer_id,
  7539. pre_dispatch_state,
  7540. )
  7541. return
  7542. # Determine source: archive or library file
  7543. archive = None
  7544. library_file = None
  7545. file_path = None
  7546. filename = None
  7547. cleanup_disk_paths: list[Path] = []
  7548. # Set when a dispatch consumes its library file, so the photos can be
  7549. # carried over after the commit that removes the row (#3077).
  7550. consumed_library_file_id: int | None = None
  7551. consumed_photos: list[str] = []
  7552. if item.archive_id:
  7553. # Print from archive
  7554. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7555. archive = result.scalar_one_or_none()
  7556. if not archive:
  7557. if not await self._fail_dispatch(db, item, "Archive not found"):
  7558. return
  7559. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7560. await self._power_off_if_needed(db, item)
  7561. return
  7562. # Persist the queue item's selected plate onto the archive so Print
  7563. # History can show the actual plate after cancel/fail/complete (#2603).
  7564. # Only when the archive doesn't already carry one, so a reprint of a
  7565. # plate-specific archive isn't relabelled by a differently-plated
  7566. # queue row.
  7567. if archive.plate_id is None and item.plate_id is not None:
  7568. archive.plate_id = item.plate_id
  7569. # Ask-for-outcome opt-in rides from the queue item to the archive
  7570. # the same way (#1898); never cleared here so a reprint of an
  7571. # archive that already asked keeps asking.
  7572. if item.confirm_outcome:
  7573. archive.confirm_requested = True
  7574. file_path = settings.base_dir / archive.file_path
  7575. filename = archive.filename
  7576. elif item.library_file_id:
  7577. # Print from library file (file manager)
  7578. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7579. library_file = result.scalar_one_or_none()
  7580. if not library_file:
  7581. # "Not found" covers two different situations and only one of
  7582. # them is recoverable, so say which. A trashed file is still
  7583. # there and restoring it makes a re-queued job work; a file that
  7584. # is really gone needs a different one. Neither is knowable from
  7585. # the queue, which is the whole complaint about this message.
  7586. trashed = (
  7587. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7588. ).scalar_one_or_none()
  7589. if not await self._fail_dispatch(
  7590. db,
  7591. item,
  7592. (
  7593. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7594. if trashed
  7595. else "Library file not found — it was deleted after this job was queued"
  7596. ),
  7597. ):
  7598. return
  7599. logger.error(
  7600. "Queue item %s: library file %s is %s",
  7601. item.id,
  7602. item.library_file_id,
  7603. "in the trash" if trashed else "gone",
  7604. )
  7605. await self._power_off_if_needed(db, item)
  7606. return
  7607. # Library files store absolute paths
  7608. lib_path = Path(library_file.file_path)
  7609. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7610. filename = library_file.filename
  7611. # Create archive from library file so usage tracking has access to the 3MF
  7612. queue_item_id = item.id
  7613. # Held separately: a cleanup dispatch clears item.library_file_id
  7614. # below, and the log line at the end of this block reported that
  7615. # cleared field -- so every consumed print logged "from library
  7616. # file None", which is the one case worth being able to trace.
  7617. source_library_file_id = item.library_file_id
  7618. try:
  7619. from backend.app.services.archive import ArchiveService
  7620. archive_service = ArchiveService(db)
  7621. archive = await archive_service.archive_print(
  7622. printer_id=item.printer_id,
  7623. source_file=file_path,
  7624. original_filename=filename,
  7625. created_by_id=item.created_by_id,
  7626. project_id=item.project_id,
  7627. cost_center_id=item.cost_center_id,
  7628. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7629. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7630. )
  7631. if archive:
  7632. item.archive_id = archive.id
  7633. if item.confirm_outcome:
  7634. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7635. if budget_reservation is not None:
  7636. budget_reservation.print_archive_id = archive.id
  7637. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7638. consumed_library_file_id = library_file.id
  7639. item.library_file_id = None
  7640. cleanup_disk_paths.append(file_path)
  7641. if library_file.thumbnail_path:
  7642. thumb_path = Path(library_file.thumbnail_path)
  7643. if not thumb_path.is_absolute():
  7644. thumb_path = settings.base_dir / library_file.thumbnail_path
  7645. cleanup_disk_paths.append(thumb_path)
  7646. # Before the delete, not after: on PostgreSQL the FK
  7647. # cascade would already have taken these rows (#2819).
  7648. await self._repoint_siblings_at_archive(
  7649. db,
  7650. consumed_library_file_id=consumed_library_file_id,
  7651. archive_id=archive.id,
  7652. dispatched_item_id=item.id,
  7653. )
  7654. # Read while the row is still here; the photos move
  7655. # below, once the delete has actually committed.
  7656. consumed_photos = list(library_file.photos or [])
  7657. # The delete clears the link on the earlier archives of
  7658. # this file (ON DELETE SET NULL; core/sqlite_fk on
  7659. # SQLite). This one is loaded, so set it here too, or it
  7660. # keeps the stale id in the session.
  7661. archive.library_file_id = None
  7662. await db.delete(library_file)
  7663. file_path = settings.base_dir / archive.file_path
  7664. filename = archive.filename
  7665. # Commit, not flush — flush opens the SQLite write
  7666. # transaction (item.archive_id update + library_file
  7667. # delete) and would hold the WAL writer lock through the
  7668. # FTP upload below, causing "database is locked" cascades
  7669. # for sensor history + concurrent cancels (#1853).
  7670. await db.commit()
  7671. logger.info(
  7672. "Queue item %s: Created archive %s from library file %s",
  7673. item.id,
  7674. archive.id,
  7675. source_library_file_id,
  7676. )
  7677. except Exception as e:
  7678. logger.warning(
  7679. "Queue item %s: Failed to create archive from library file: %s",
  7680. queue_item_id,
  7681. e,
  7682. exc_info=True,
  7683. )
  7684. await db.rollback()
  7685. item = await db.get(PrintQueueItem, queue_item_id)
  7686. if item:
  7687. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7688. return
  7689. await self._power_off_if_needed(db, item)
  7690. return
  7691. if not archive:
  7692. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7693. return
  7694. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7695. await self._power_off_if_needed(db, item)
  7696. return
  7697. # The photos follow the file into the archive that replaces it, for
  7698. # the same reason the siblings do (#3077). After the commit above,
  7699. # never before it: that commit can fail ("database is locked",
  7700. # #1853) and roll the library row back, and photos already moved
  7701. # would leave it naming a directory that no longer exists. The
  7702. # file and thumbnail unlinks are deferred for the same reason.
  7703. if consumed_library_file_id is not None and consumed_photos:
  7704. # Held as a plain int, read here while the session is still
  7705. # healthy, because the handler below may not touch an ORM
  7706. # instance at all. The commit it exists for fails inside the
  7707. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7708. # first DML statement, so a busy writer surfaces as "database
  7709. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7710. # internally through safe_reraise before re-raising, which
  7711. # expires every loaded instance and leaves the session in
  7712. # pending-rollback state -- so `archive.id` inside the except
  7713. # would itself raise PendingRollbackError and the rollback
  7714. # below would never be reached.
  7715. archive_id = archive.id
  7716. try:
  7717. carried_photos = move_library_photos(
  7718. consumed_library_file_id,
  7719. consumed_photos,
  7720. archive_photos_dir(archive),
  7721. )
  7722. if carried_photos:
  7723. archive.photos = list(archive.photos or []) + carried_photos
  7724. await db.commit()
  7725. except Exception as e:
  7726. # The archive and the delete are already committed; the
  7727. # print goes ahead either way. Worst case the pictures sit
  7728. # unnamed in the archive's own directory.
  7729. #
  7730. # Ints only until the rollback has run, per the note above,
  7731. # which is why this logs queue_item_id and not item.id --
  7732. # the sibling handler forty lines up does the same.
  7733. logger.warning(
  7734. "Queue item %s: failed to carry library photos into archive %s: %s",
  7735. queue_item_id,
  7736. archive_id,
  7737. e,
  7738. )
  7739. await db.rollback()
  7740. # rollback() expires every loaded instance, and in async
  7741. # SQLAlchemy the next plain attribute read is lazy IO
  7742. # outside the greenlet -- MissingGreenlet, which would turn
  7743. # this cosmetic failure into a dispatch crash in exactly the
  7744. # "database is locked" case the block exists for (#1853).
  7745. # The nozzle guard, the upload and the start all keep
  7746. # reading item, archive and printer, so all three go back
  7747. # into the session before falling through.
  7748. item = await db.get(PrintQueueItem, queue_item_id)
  7749. archive = await db.get(PrintArchive, archive_id)
  7750. printer = await db.get(Printer, item.printer_id) if item else None
  7751. if not item or not archive or not printer:
  7752. logger.error(
  7753. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7754. queue_item_id,
  7755. archive_id,
  7756. )
  7757. return
  7758. else:
  7759. # Neither archive nor library file specified
  7760. if not await self._fail_dispatch(db, item, "No source file specified"):
  7761. return
  7762. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7763. await self._power_off_if_needed(db, item)
  7764. return
  7765. # Check file exists on disk
  7766. if not file_path.exists():
  7767. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  7768. return
  7769. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7770. await self._power_off_if_needed(db, item)
  7771. return
  7772. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7773. # size dispatched to a printer with a different nozzle installed is
  7774. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7775. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7776. # gives the user no idea what went wrong. Catch it here, before we spend
  7777. # time preheating and uploading, and fail with an actionable message.
  7778. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7779. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7780. # the printer hasn't reported its nozzles yet, we fall through and let the
  7781. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7782. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7783. # as one of the two hotends is a 0.6.
  7784. #
  7785. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7786. # (#2885): the printer fetches one as part of starting the print, so the
  7787. # set to test against is "reachable", not "currently mounted". This runs
  7788. # well before the rack picker at the bottom of this method, so without
  7789. # the rack in scope here that picker never got the chance to run.
  7790. sliced_nozzle = archive.nozzle_diameter if archive else None
  7791. if sliced_nozzle:
  7792. nozzle_status = printer_manager.get_status(item.printer_id)
  7793. installed = _installed_nozzle_diameters(nozzle_status)
  7794. rack = _rack_nozzle_diameters(nozzle_status)
  7795. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7796. if mismatch_msg:
  7797. if not await self._fail_dispatch(db, item, mismatch_msg):
  7798. return
  7799. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7800. await notification_service.on_queue_job_failed(
  7801. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7802. printer_id=printer.id,
  7803. printer_name=printer.name,
  7804. reason=mismatch_msg,
  7805. db=db,
  7806. )
  7807. try:
  7808. await ws_manager.send_queue_item_failed(
  7809. user_id=item.created_by_id,
  7810. queue_item_id=item.id,
  7811. printer_id=item.printer_id,
  7812. reason="nozzle_mismatch",
  7813. )
  7814. except Exception:
  7815. pass
  7816. await self._power_off_if_needed(db, item)
  7817. return
  7818. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7819. # bed (and chamber, if applicable) is at temperature when the firmware
  7820. # starts the actual print routine. Best-effort: any failure logs and
  7821. # falls through to the normal upload+start path rather than turning a
  7822. # configuration issue into a failed queue item.
  7823. # Returns False only when the item was cancelled or deleted while the
  7824. # stage was holding at temperature. Uploading and starting it anyway
  7825. # would print a job the user has already called off, so abandon the
  7826. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7827. if not await self._preheat_and_soak(db, item, printer, archive):
  7828. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7829. return
  7830. # See `_effective_plate_id` for why this is resolved once here rather
  7831. # than each site below repeating `item.plate_id or 1`.
  7832. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7833. # G-code injection for auto-print systems (#422)
  7834. injected_path = None
  7835. # #2547: tracked separately from `injected_path`, which is also set when
  7836. # only a START snippet was injected. Only an END snippet changes what the
  7837. # camera sees at print completion.
  7838. end_gcode_injected = False
  7839. if item.gcode_injection:
  7840. try:
  7841. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7842. if snippets_raw:
  7843. snippets = json.loads(snippets_raw)
  7844. model_snippets = snippets.get(printer.model, {})
  7845. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7846. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7847. if start_gc or end_gc:
  7848. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7849. injected_path = inject_gcode_into_3mf(
  7850. file_path, effective_plate_id, start_gc or None, end_gc or None
  7851. )
  7852. if injected_path:
  7853. file_path = injected_path
  7854. end_gcode_injected = bool(end_gc)
  7855. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7856. else:
  7857. logger.warning(
  7858. "Queue item %s: G-code injection returned no result, using original", item.id
  7859. )
  7860. except Exception as e:
  7861. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7862. # #2547: the finish-photo path can't learn from telemetry that this print
  7863. # ends with user End G-code — which means the plate may be gone by the
  7864. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7865. # the print once the printer confirms it running.
  7866. if end_gcode_injected:
  7867. print_dispatch_context.mark_pending(printer.id)
  7868. # Upload to root directory (not /cache/) - the start_print command references
  7869. # files by name only (ftp://{filename}), so they must be in the root
  7870. remote_filename = derive_remote_filename(filename)
  7871. remote_path = f"/{remote_filename}"
  7872. # Get FTP retry settings
  7873. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7874. logger.info(
  7875. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7876. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7877. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7878. )
  7879. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7880. # Every read this method needs (printer, archive/library, preheat) is
  7881. # done, and the library-file branch already committed its archive
  7882. # creation. Without this the transaction opened by the first SELECT above
  7883. # stays "idle in transaction" for the entire upload — multiple seconds
  7884. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7885. # a farm dispatching many jobs at once then exhausts the pool. This was
  7886. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7887. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7888. # readable; the status writes below (upload-failure path and the
  7889. # pending->printing CAS) transparently open a fresh transaction.
  7890. # The owner is read here, after preheat, so the commit releases this read too.
  7891. toast_uid = await self._queue_owner_id(db, item)
  7892. await db.commit()
  7893. # Delete existing file if present (avoids 553 error on overwrite)
  7894. try:
  7895. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  7896. delete_result = await delete_file_async(
  7897. printer.ip_address,
  7898. printer.access_code,
  7899. remote_path,
  7900. socket_timeout=ftp_timeout,
  7901. printer_model=printer.model,
  7902. # This delete and the upload below are one bounded, user-initiated
  7903. # unit -- at most nine connections -- so neither skips on the
  7904. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  7905. # trace this delete took the TLS failure and armed the cool-off,
  7906. # and the upload's four attempts were then spent against it
  7907. # without a socket being opened.
  7908. respect_handshake_cooloff=False,
  7909. )
  7910. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  7911. except Exception as e:
  7912. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  7913. # Dispatch toast — announce the upload start with the total byte
  7914. # count so the frontend can render an honest progress bar.
  7915. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7916. try:
  7917. total_bytes = file_path.stat().st_size
  7918. except OSError:
  7919. total_bytes = 0
  7920. try:
  7921. await ws_manager.send_queue_item_uploading(
  7922. user_id=toast_uid,
  7923. queue_item_id=item.id,
  7924. printer_id=item.printer_id,
  7925. printer_name=printer.name,
  7926. file_name=toast_file_name,
  7927. total_bytes=total_bytes,
  7928. )
  7929. except Exception:
  7930. pass # toast is best-effort
  7931. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  7932. # A deadline expiry gets its own message: "check your SD card" is the
  7933. # wrong advice for a link that was simply too slow to finish (#2529).
  7934. upload_error: str | None = None
  7935. # Why the upload failed, straight from the client rather than inferred.
  7936. # Owned here, so a background fetch for another print cannot overwrite
  7937. # it between the failure and the sentence built from it (#2899).
  7938. upload_failure = FtpFailureReport()
  7939. try:
  7940. if ftp_retry_enabled:
  7941. uploaded = await with_ftp_retry(
  7942. upload_file_async,
  7943. printer.ip_address,
  7944. printer.access_code,
  7945. file_path,
  7946. remote_path,
  7947. socket_timeout=ftp_timeout,
  7948. printer_model=printer.model,
  7949. progress_callback=progress_bridge,
  7950. respect_handshake_cooloff=False,
  7951. failure=upload_failure,
  7952. max_retries=ftp_retry_count,
  7953. retry_delay=ftp_retry_delay,
  7954. operation_name=f"Upload print to {printer.name}",
  7955. )
  7956. else:
  7957. uploaded = await upload_file_async(
  7958. printer.ip_address,
  7959. printer.access_code,
  7960. file_path,
  7961. remote_path,
  7962. socket_timeout=ftp_timeout,
  7963. printer_model=printer.model,
  7964. progress_callback=progress_bridge,
  7965. respect_handshake_cooloff=False,
  7966. failure=upload_failure,
  7967. )
  7968. except UploadCancelled as e:
  7969. uploaded = False
  7970. upload_error = (
  7971. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  7972. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  7973. )
  7974. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  7975. except Exception as e:
  7976. uploaded = False
  7977. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  7978. # Clean up injected temp file after upload attempt
  7979. if injected_path and injected_path.exists():
  7980. injected_path.unlink(missing_ok=True)
  7981. # Again after the upload, which can take minutes: an owner deleted
  7982. # meanwhile gets no more toasts, and neither does whoever has their id.
  7983. toast_uid = await self._queue_owner_id(db, item)
  7984. if not uploaded:
  7985. # This used to be one string for every upload failure, telling
  7986. # everyone to check the SD card. The client knows which of seven
  7987. # things went wrong and logs each one differently; it just had no
  7988. # way to say so here, so the card got named even for a TLS
  7989. # handshake that never reached the printer's filesystem (#2899).
  7990. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  7991. failure = upload_failure.failure
  7992. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  7993. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  7994. return
  7995. if not await self._fail_dispatch(db, item, error_msg):
  7996. await self._close_cancelled_dispatch_toast(item, toast_uid)
  7997. return
  7998. logger.error(
  7999. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8000. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8001. )
  8002. # Send failure notification
  8003. await notification_service.on_queue_job_failed(
  8004. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8005. printer_id=printer.id,
  8006. printer_name=printer.name,
  8007. # The same sentence the queue shows. A push notification saying
  8008. # something different from the UI is its own small bug (#2899).
  8009. reason=error_msg,
  8010. db=db,
  8011. )
  8012. try:
  8013. await ws_manager.send_queue_item_failed(
  8014. user_id=toast_uid,
  8015. queue_item_id=item.id,
  8016. printer_id=item.printer_id,
  8017. reason="upload_failed",
  8018. )
  8019. except Exception:
  8020. pass
  8021. await self._power_off_if_needed(db, item)
  8022. return
  8023. # The printer took a file, so any run of refused uploads is over: the
  8024. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8025. self._upload_refusals.pop(printer.id, None)
  8026. self._upload_refusal_notified.discard(printer.id)
  8027. # Parse AMS mapping if stored
  8028. ams_mapping = None
  8029. if item.ams_mapping:
  8030. try:
  8031. ams_mapping = json.loads(item.ams_mapping)
  8032. except json.JSONDecodeError:
  8033. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8034. # Register as expected print so we don't create a duplicate archive
  8035. # Only applicable for archive-based prints
  8036. if archive:
  8037. from backend.app.main import register_expected_print
  8038. register_expected_print(
  8039. item.printer_id,
  8040. remote_filename,
  8041. archive.id,
  8042. ams_mapping=ams_mapping,
  8043. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8044. # no print-start email, and neither does whoever has their id.
  8045. created_by_id=toast_uid,
  8046. cost_center_id=item.cost_center_id,
  8047. # The plate actually dispatched, not the queue item's raw
  8048. # column: on None, `register_expected_print` stores nothing,
  8049. # and `extract_filament_usage_from_3mf` then books every
  8050. # filament in the file rather than the one plate that printed.
  8051. plate_id=effective_plate_id,
  8052. )
  8053. # Registration happens before the print command by necessity (the
  8054. # printer can report the print before the send returns), so record
  8055. # what to undo if we never get as far as sending. `_dispatch_one`
  8056. # rolls back anything still pending here on every exit — exception,
  8057. # early return, or cancel winning the CAS below.
  8058. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8059. # Propagate the queue item's owner into printer_manager so the
  8060. # print-complete callback can credit the user in the PrintLogEntry
  8061. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8062. # items) or when the user clicks the manual-start button.
  8063. await self._propagate_owner_to_printer_manager(db, item)
  8064. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8065. # This prevents phantom reprints if the backend crashes/restarts after the
  8066. # print command is sent but before the status update is committed.
  8067. # If we crash after this commit but before start_print(), the item will be
  8068. # in "printing" status without actually printing - but that's safer than
  8069. # accidentally reprinting the same file hours later.
  8070. #
  8071. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8072. # initial pending read at the top of check_queue and this point) flips
  8073. # the row to "cancelled" in a separate session. Without the WHERE
  8074. # status='pending' clause, the unconditional update here would silently
  8075. # overwrite that cancellation and we'd ship the MQTT start_print below
  8076. # — printer obeys, user sees "I pressed cancel and the print started".
  8077. # rowcount==0 means the user won the race; bail out, best-effort delete
  8078. # the file we just uploaded, do NOT send start_print.
  8079. now_utc = datetime.now(timezone.utc)
  8080. billing_run_id = str(uuid.uuid4())
  8081. cas = await db.execute(
  8082. update(PrintQueueItem)
  8083. .where(PrintQueueItem.id == item.id)
  8084. .where(PrintQueueItem.status == "pending")
  8085. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  8086. )
  8087. await db.commit()
  8088. if cas.rowcount == 0:
  8089. logger.info(
  8090. "Queue item %s no longer pending at print-command time "
  8091. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8092. item.id,
  8093. )
  8094. try:
  8095. await delete_file_async(
  8096. printer.ip_address,
  8097. printer.access_code,
  8098. remote_path,
  8099. socket_timeout=ftp_timeout,
  8100. printer_model=printer.model,
  8101. )
  8102. except Exception as cleanup_err:
  8103. logger.debug(
  8104. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8105. item.id,
  8106. cleanup_err,
  8107. )
  8108. try:
  8109. await ws_manager.send_queue_item_failed(
  8110. user_id=toast_uid,
  8111. queue_item_id=item.id,
  8112. printer_id=item.printer_id,
  8113. reason="cancelled_mid_dispatch",
  8114. )
  8115. except Exception:
  8116. pass
  8117. return
  8118. # Sync the in-memory item so subsequent code that reads item.status /
  8119. # item.started_at sees the values we just persisted.
  8120. item.status = "printing"
  8121. item.started_at = now_utc
  8122. item.billing_run_id = billing_run_id
  8123. if archive is not None:
  8124. archive.billing_run_id = billing_run_id
  8125. # Legacy transaction deletion used an archive-wide skip flag.
  8126. # A newly dispatched run has its own UUID/tombstone, so it must be
  8127. # billable independently of any older deleted run on this archive.
  8128. archive.wallet_charge_skipped = False
  8129. # Persist before MQTT send so completion and restart recovery can
  8130. # always recover the internal billing identity.
  8131. await db.commit()
  8132. for cleanup_path in cleanup_disk_paths:
  8133. try:
  8134. if cleanup_path.exists():
  8135. cleanup_path.unlink()
  8136. except OSError as cleanup_err:
  8137. logger.warning(
  8138. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8139. json.dumps(
  8140. {
  8141. "queue_item_id": item.id,
  8142. "path": str(cleanup_path),
  8143. "error": str(cleanup_err),
  8144. },
  8145. sort_keys=True,
  8146. ),
  8147. )
  8148. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8149. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8150. # #1898: with the opt-in default-good setting, moving on to the next
  8151. # print resolves the previous print's unanswered outcome prompt as
  8152. # "good" — this path also covers the camera-based plate detection,
  8153. # which releases the gate by allowing dispatch rather than by an
  8154. # explicit acknowledgment. Rides on the dispatch transaction.
  8155. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8156. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8157. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8158. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8159. # Capture state before dispatch so the watchdog can detect whether the
  8160. # printer actually transitioned (#967). Also capture subtask_id so the
  8161. # watchdog can recognise "command landed but state hasn't flipped yet"
  8162. # on slow H2D transitions (#1078).
  8163. pre_status = printer_manager.get_status(item.printer_id)
  8164. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8165. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8166. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8167. # #1721: respect the user's explicit timelapse choice. The #1397
  8168. # force-on at dispatch was removed because it caused per-layer nozzle
  8169. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8170. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8171. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8172. # FINISH-state fallback — no need to force a video.
  8173. effective_timelapse = bool(item.timelapse)
  8174. # Nozzle-rack fallback (#2800). A job that never passed through the
  8175. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8176. # dispatches with no nozzle field at all and chooses for itself — which
  8177. # is how a print levelled on one hotend and then printed on another,
  8178. # millimetres above the plate. Derive the per-slot extruder assignment
  8179. # from the file being dispatched.
  8180. #
  8181. # Done here rather than at queue time because this is the first point
  8182. # that knows both the actual printer and the actual file: an item can
  8183. # be created without a printer (model-based assignment), reassigned
  8184. # afterwards, or have its file swapped for a G-code-injected copy just
  8185. # above. Every queue-creation path — the print dialog, a bulk library
  8186. # add, the webhook, a pipeline run — is covered by the one call.
  8187. # Skipped when the item already carries a Bambu Studio capture: that
  8188. # one wins downstream anyway, so reading the 3MF again would be work
  8189. # thrown away on every dispatch.
  8190. # Rack position resolution (#1784), tried before the #2800 fallback
  8191. # below because it can express what that one cannot: a plate wanting a
  8192. # *different* hotend off the rack per filament group. The position per
  8193. # group is the operator's pick — the 3MF states it nowhere, proven by
  8194. # sending one plate twice with different picks and finding the two
  8195. # files identical bar float noise — so it is resolved here against the
  8196. # rack as it stands right now, after the upload, not at queue time.
  8197. resolved_nozzle_mapping = None
  8198. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8199. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8200. if rack_plan is not None:
  8201. try:
  8202. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8203. except (json.JSONDecodeError, TypeError):
  8204. stored_choice = {}
  8205. logger.warning(
  8206. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8207. item.id,
  8208. item.nozzle_rack_choice,
  8209. )
  8210. # JSON object keys are strings; the groups are ints.
  8211. choice: dict[int, int] = {}
  8212. for key, value in (stored_choice or {}).items():
  8213. try:
  8214. choice[int(key)] = int(value)
  8215. except (TypeError, ValueError):
  8216. continue
  8217. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8218. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8219. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8220. )
  8221. if resolved_nozzle_mapping is None and choice:
  8222. # An explicit pick that no longer holds stops the print. The
  8223. # operator named a hotend; printing from a different one is
  8224. # how a plate gets levelled on one nozzle and drawn with
  8225. # another, millimetres above the bed. Nothing has been sent
  8226. # to the printer yet, so failing here costs only the upload.
  8227. # The file is already on the SD card by this point, and a
  8228. # 3MF left there is a phantom print waiting to be started
  8229. # from the touchscreen. Same cleanup the start_print
  8230. # failure path below does, for the same reason.
  8231. try:
  8232. await delete_file_async(
  8233. printer.ip_address,
  8234. printer.access_code,
  8235. remote_path,
  8236. printer_model=printer.model,
  8237. )
  8238. except Exception:
  8239. pass # Best-effort — don't fail the error handler
  8240. if not await self._fail_dispatch(
  8241. db,
  8242. item,
  8243. (
  8244. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8245. "Edit the item to choose another position."
  8246. ),
  8247. ):
  8248. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8249. return
  8250. logger.warning(
  8251. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8252. item.id,
  8253. printer.name,
  8254. rack_error,
  8255. choice,
  8256. [slot.get("id") for slot in live_rack],
  8257. )
  8258. await notification_service.on_queue_job_failed(
  8259. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8260. printer_id=printer.id,
  8261. printer_name=printer.name,
  8262. reason=item.error_message,
  8263. db=db,
  8264. )
  8265. try:
  8266. await ws_manager.send_queue_item_failed(
  8267. user_id=toast_uid,
  8268. queue_item_id=item.id,
  8269. printer_id=item.printer_id,
  8270. reason="nozzle_rack_pick_stale",
  8271. )
  8272. except Exception:
  8273. pass # Best-effort — don't fail the error handler
  8274. return
  8275. if resolved_nozzle_mapping is None:
  8276. # Nothing was picked and nothing could be assigned. Falls
  8277. # through to the #2800 path, which is what ran before this
  8278. # existed — strictly not worse than today.
  8279. logger.info(
  8280. "Queue item %s: no rack positions assignable (%s); falling back",
  8281. item.id,
  8282. rack_error,
  8283. )
  8284. else:
  8285. logger.info(
  8286. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8287. item.id,
  8288. resolved_nozzle_mapping,
  8289. rack_plan.slot_groups,
  8290. choice or "auto",
  8291. )
  8292. nozzle_slot_extruders = None
  8293. if (
  8294. not item.nozzle_mapping
  8295. and resolved_nozzle_mapping is None
  8296. and file_path is not None
  8297. and is_nozzle_rack_model(printer.model)
  8298. ):
  8299. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8300. if slot_extruders:
  8301. nozzle_slot_extruders = json.dumps(slot_extruders)
  8302. # Every filament this plate prints is on the external spool -> the print
  8303. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8304. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8305. # table", which is what held the reporter's P1S at Heatbed preheating
  8306. # for ten minutes before it gave up (#3087). The MQTT command builder
  8307. # already downgrades a mapping that is *only* external ([254]), but a
  8308. # multi-filament project pads the slots this plate does not print with
  8309. # -1 — BambuStudio's own convention — and down there a -1 is
  8310. # indistinguishable from a slot that never resolved, which must never be
  8311. # sent to the spool holder (#2589). Here the plate's filament list says
  8312. # which is which, so the answer is exact rather than a guess.
  8313. #
  8314. # Deliberately narrow: this fires only when every consumed slot is an
  8315. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8316. # alone and the firmware still rejects the print, exactly as today. And
  8317. # only for single-nozzle printers, mirroring the builder's own reconcile
  8318. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8319. # whether to use the AMS, so it is not ours to rewrite.
  8320. effective_use_ams = item.use_ams
  8321. if (
  8322. effective_use_ams
  8323. and ams_mapping
  8324. and file_path is not None
  8325. # Cheap gate before opening the file: with nothing on the spool
  8326. # holder anywhere in the mapping, no subset of it can be all
  8327. # external, so most dispatches never pay for the parse. The
  8328. # isinstance also keeps a malformed stored mapping (a bare number
  8329. # from a hand-edited row) failing where it always failed, in the
  8330. # command builder, rather than here.
  8331. and isinstance(ams_mapping, list)
  8332. and any(_is_external_tray(t) for t in ams_mapping)
  8333. and not _might_be_dual_nozzle(printer.model, pre_status)
  8334. ):
  8335. from backend.app.services.filament_requirements import extract_filament_requirements
  8336. consumed = _consumed_mapping_entries(
  8337. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8338. )
  8339. if consumed and all(_is_external_tray(t) for t in consumed):
  8340. effective_use_ams = False
  8341. logger.info(
  8342. "Queue item %s: every filament plate %s prints is on the external spool "
  8343. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8344. item.id,
  8345. effective_plate_id,
  8346. ams_mapping,
  8347. )
  8348. # A slot that lost its K-profile selection (a power cycle resets every
  8349. # slot to the default K) would print on the default. The idle check in
  8350. # the status handler normally restores it first, but nothing guarantees
  8351. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8352. # Never allowed to stop the print it is protecting.
  8353. try:
  8354. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8355. except Exception:
  8356. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8357. # Start the print with AMS mapping, plate_id and print options.
  8358. # nozzle_mapping rides through verbatim — JSON string captured from
  8359. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8360. # parses + injects it only for dual-nozzle models so a null on every
  8361. # other model is a transparent pass-through. The rack fallback is
  8362. # resolved down there too, where the live rack position is known.
  8363. started = printer_manager.start_print(
  8364. item.printer_id,
  8365. remote_filename,
  8366. plate_id=effective_plate_id,
  8367. ams_mapping=ams_mapping,
  8368. bed_levelling=item.bed_levelling,
  8369. flow_cali=item.flow_cali,
  8370. vibration_cali=item.vibration_cali,
  8371. layer_inspect=item.layer_inspect,
  8372. timelapse=effective_timelapse,
  8373. use_ams=effective_use_ams,
  8374. nozzle_offset_cali=item.nozzle_offset_cali,
  8375. nozzle_mapping=item.nozzle_mapping
  8376. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8377. nozzle_slot_extruders=nozzle_slot_extruders,
  8378. )
  8379. if started:
  8380. # The command is away, so the expectation is now legitimate and must
  8381. # survive. Anything still in this dict when _dispatch_one exits gets
  8382. # rolled back.
  8383. self._unconfirmed_expected_print.pop(item.id, None)
  8384. self._unconfirmed_budget_reservations.discard(item.id)
  8385. self._unconfirmed_print_user.pop(item.id, None)
  8386. if item.printer_id is not None:
  8387. self._sent_unstarted_print[item.id] = (
  8388. item.printer_id,
  8389. remote_filename if archive else None,
  8390. archive.id if archive else None,
  8391. )
  8392. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8393. # target, chamber target, airduct heating) — the gcode owns
  8394. # heater/flap control from here. Clearing the pin prevents
  8395. # `_dispatch_one`'s finally from unwinding a live print.
  8396. self._preheat_pin.pop(item.printer_id, None)
  8397. self._preheat_pin_bed.pop(item.printer_id, None)
  8398. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8399. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8400. # status='processing' from upload start until the printer acked
  8401. # (or timed out). The frontend derives "Awaiting printer…" purely
  8402. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8403. # event would push the status chip out of 'PROCESSING' prematurely
  8404. # — which is exactly what the screenshot at #1625-followup
  8405. # complained about.
  8406. # Register the local 3MF in the cover-cache so /cover skips FTP
  8407. # (#1166 follow-up). file_path was resolved earlier from either the
  8408. # archive or the library file row.
  8409. if file_path is not None:
  8410. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8411. # Hold the printer against further dispatches until the watchdog
  8412. # confirms the printer transitioned (or until the hard timeout).
  8413. # Prevents multi-plate batches from triple-dispatching onto the
  8414. # same H2D Pro while it digests the first project_file (#1157).
  8415. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8416. # Watchdog: if the printer never transitions out of pre_state AND
  8417. # never advances subtask_id, the MQTT publish was accepted locally but
  8418. # didn't reach the printer (half-broken session — same shape as
  8419. # #887/#936). Revert the queue item so the next dispatch can pick it
  8420. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8421. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8422. # that would otherwise cause the item to re-dispatch as a reprint
  8423. # of the just-finished job (#1078).
  8424. if pre_state:
  8425. spawn_background_task(
  8426. self._watchdog_print_start(
  8427. item.id,
  8428. item.printer_id,
  8429. pre_state,
  8430. pre_subtask_id,
  8431. pre_gcode_file,
  8432. created_by_id=toast_uid,
  8433. ),
  8434. name=f"watchdog-print-start-{item.id}",
  8435. )
  8436. # Get estimated time for notification.
  8437. #
  8438. # This used to fall back to `library_file.print_time_seconds`, a column
  8439. # LibraryFile does not have — the print time it knows about lives in
  8440. # `file_metadata`. So a library print whose archive carried no parseable
  8441. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8442. # AttributeError right here, *after* the printer had already been sent
  8443. # the job: the started-notification never fired, and the exception
  8444. # unwound the whole queue pass, so every other printer still waiting to
  8445. # be dispatched on that tick silently missed its turn.
  8446. #
  8447. # The queue item caches the print time at creation ("Cached from
  8448. # archive/library"), which is the value this was reaching for.
  8449. estimated_time = None
  8450. if archive and archive.print_time_seconds:
  8451. estimated_time = archive.print_time_seconds
  8452. elif item.print_time_seconds:
  8453. estimated_time = item.print_time_seconds
  8454. # Send job started notification
  8455. await notification_service.on_queue_job_started(
  8456. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8457. printer_id=printer.id,
  8458. printer_name=printer.name,
  8459. db=db,
  8460. estimated_time=estimated_time,
  8461. )
  8462. # MQTT relay - publish queue job started
  8463. try:
  8464. await mqtt_relay.on_queue_job_started(
  8465. job_id=item.id,
  8466. filename=filename,
  8467. printer_id=printer.id,
  8468. printer_name=printer.name,
  8469. printer_serial=printer.serial_number,
  8470. )
  8471. except Exception:
  8472. pass # Don't fail if MQTT fails
  8473. else:
  8474. # Clean up uploaded file from SD card to prevent phantom prints
  8475. try:
  8476. await delete_file_async(
  8477. printer.ip_address,
  8478. printer.access_code,
  8479. remote_path,
  8480. printer_model=printer.model,
  8481. )
  8482. except Exception:
  8483. pass # Best-effort — don't fail the error handler
  8484. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8485. # state can flip from idle to active in the window between the
  8486. # pre-dispatch check above and this publish (the FTP upload takes
  8487. # seconds); start_print() then refuses to send project_file to the
  8488. # now-busy printer and returns False. Failing the item here would be
  8489. # wrong — the printer is fine, it is simply busy — so revert to
  8490. # pending and let a later tick dispatch it once the printer is idle,
  8491. # exactly like the pre-dispatch guard. Only a start_print() False on
  8492. # an idle/unknown printer is a genuine command failure.
  8493. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8494. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8495. logger.info(
  8496. "Queue item %s: printer %s became busy (state=%s) before the start "
  8497. "command was sent — deferring, reverting item to pending (#2598)",
  8498. item.id,
  8499. item.printer_id,
  8500. post_dispatch_state,
  8501. )
  8502. await self._defer_until_printer_idle(db, item)
  8503. return
  8504. # Print command failed - revert status
  8505. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8506. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8507. return
  8508. logger.error(
  8509. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8510. f"printer_manager.start_print() returned False. "
  8511. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8512. f"Check printer status and backend logs for details."
  8513. )
  8514. # Send failure notification
  8515. await notification_service.on_queue_job_failed(
  8516. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8517. printer_id=printer.id,
  8518. printer_name=printer.name,
  8519. reason="Failed to send print command to printer - check printer connection and status",
  8520. db=db,
  8521. )
  8522. try:
  8523. await ws_manager.send_queue_item_failed(
  8524. user_id=toast_uid,
  8525. queue_item_id=item.id,
  8526. printer_id=item.printer_id,
  8527. reason="start_command_failed",
  8528. )
  8529. except Exception:
  8530. pass
  8531. await self._power_off_if_needed(db, item)
  8532. @staticmethod
  8533. async def _watchdog_print_start(
  8534. queue_item_id: int,
  8535. printer_id: int,
  8536. pre_state: str,
  8537. pre_subtask_id: str | None = None,
  8538. pre_gcode_file: str | None = None,
  8539. timeout: float = 90.0,
  8540. phase_b_timeout: float = 180.0,
  8541. poll_interval: float = 3.0,
  8542. created_by_id: int | None = None,
  8543. ) -> None:
  8544. """Revert a queue item if the printer never acknowledges the start command.
  8545. Bambuddy optimistically marks the queue item as "printing" right after the
  8546. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8547. Phase A (up to ``timeout``): wait for either an active-state transition
  8548. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8549. primary signal; subtask_id advance handles the H2D case where state can
  8550. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8551. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8552. was lost on a half-broken session (#887/#936) — revert and force
  8553. reconnect (the #967 recovery path).
  8554. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8555. alone): keep watching for the active-state transition. subtask_id alone
  8556. proves the file landed but not that the printer started — and a printer
  8557. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8558. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8559. used to leave the queue item stuck in 'printing' forever because the
  8560. old watchdog returned success as soon as subtask_id advanced. If Phase
  8561. B times out, revert the queue item so the user can retry without
  8562. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8563. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8564. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8565. transitions that also don't emit an early subtask_id tick.
  8566. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8567. refuses to verify our commands will never start this job or any other,
  8568. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8569. burns an upload slot the rest of the farm is queued behind — that path
  8570. is for a printer that might still come good, which this one cannot
  8571. (#2732). It fails the item on the spot with the actual reason instead.
  8572. """
  8573. last_status = None
  8574. landed_on_subtask = False
  8575. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8576. # every push carrying an `hms` key, so the fault can come and go between
  8577. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8578. command_rejected = False
  8579. # Latched for the same reason as command_rejected: drying can finish, or
  8580. # be stopped by the user, part-way through the dispatch window. Seeing it
  8581. # once is what matters — it is the state the printer was in when it
  8582. # declined to start (#2758).
  8583. drying_ams_ids: list[int] = []
  8584. deadline = time.monotonic() + timeout
  8585. while time.monotonic() < deadline:
  8586. await asyncio.sleep(poll_interval)
  8587. status = printer_manager.get_status(printer_id)
  8588. if not status:
  8589. # Printer disconnected — don't mess with the DB. Drop the
  8590. # in-memory dispatch hold too so a fresh dispatch can retry
  8591. # once the printer comes back; the hard timeout would
  8592. # otherwise hold the printer unnecessarily.
  8593. scheduler._release_dispatch_hold(printer_id)
  8594. return
  8595. last_status = status
  8596. if status.state in _ACTIVE_PRINT_STATES:
  8597. # Printer is actively processing the job — release the
  8598. # post-dispatch hold so the next pending item for this printer
  8599. # can be evaluated normally. We do NOT accept arbitrary state
  8600. # transitions: a printer going FINISH -> IDLE (user dismissed
  8601. # the post-print prompt without accepting our project_file)
  8602. # would otherwise look like "command landed" and leave the
  8603. # queue item stuck in 'printing' forever (#1370).
  8604. scheduler._release_dispatch_hold(printer_id)
  8605. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8606. try:
  8607. await ws_manager.send_queue_item_acked(
  8608. user_id=created_by_id,
  8609. queue_item_id=queue_item_id,
  8610. printer_id=printer_id,
  8611. )
  8612. except Exception:
  8613. pass
  8614. return
  8615. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8616. # Checked only after the active-state exit above: a stale HMS left
  8617. # over from an earlier job must never abort a print that is visibly
  8618. # running. An actually-refused command leaves the printer idle, so
  8619. # this ordering costs the detection nothing.
  8620. if _mqtt_commands_rejected(status):
  8621. command_rejected = True
  8622. break
  8623. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8624. # Phase A exit — printer accepted the file (subtask_id flipped
  8625. # to our submission id). Don't return yet: the printer may
  8626. # have accepted the command but never actually start (e.g.
  8627. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8628. # B watches for the active-state transition.
  8629. landed_on_subtask = True
  8630. break
  8631. if landed_on_subtask and not command_rejected:
  8632. phase_b_deadline = time.monotonic() + phase_b_timeout
  8633. while time.monotonic() < phase_b_deadline:
  8634. await asyncio.sleep(poll_interval)
  8635. status = printer_manager.get_status(printer_id)
  8636. if not status:
  8637. scheduler._release_dispatch_hold(printer_id)
  8638. return
  8639. last_status = status
  8640. if status.state in _ACTIVE_PRINT_STATES:
  8641. scheduler._release_dispatch_hold(printer_id)
  8642. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8643. try:
  8644. await ws_manager.send_queue_item_acked(
  8645. user_id=created_by_id,
  8646. queue_item_id=queue_item_id,
  8647. printer_id=printer_id,
  8648. )
  8649. except Exception:
  8650. pass
  8651. return
  8652. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8653. # Same ordering rule as Phase A: a running print wins over a
  8654. # lingering HMS.
  8655. if _mqtt_commands_rejected(status):
  8656. command_rejected = True
  8657. break
  8658. # No active-state transition. Revert the item so the scheduler can retry.
  8659. # Drop the in-memory hold so the retry isn't blocked by it.
  8660. scheduler._release_dispatch_hold(printer_id)
  8661. # Logged on every failed dispatch window, not just the last one, so a
  8662. # support bundle shows the correlation from the first attempt rather than
  8663. # only after the retry budget is spent (#2758).
  8664. if drying_ams_ids:
  8665. logger.info(
  8666. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8667. queue_item_id,
  8668. printer_id,
  8669. ", ".join(str(i) for i in drying_ams_ids),
  8670. )
  8671. # Four outcomes from the revert attempt, each routed differently:
  8672. # "reverted": row flipped from printing -> pending, run recovery
  8673. # "gave_up": same, but the retry budget is spent — row failed
  8674. # rather than pending, so it stops going round again
  8675. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8676. # on_print_complete or user). Skip recovery entirely
  8677. # — the print clearly landed somewhere even if the
  8678. # watchdog didn't see the active-state transition.
  8679. # "revert_failed": SQLite contention exhausted retries. Still run
  8680. # recovery so the MQTT session gets a fresh client_id
  8681. # on the half-broken-session path.
  8682. #
  8683. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8684. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8685. # the watchdog again. For a printer that is genuinely wedged that loop never
  8686. # ends — the reporter had one printer "since this morning still not launch"
  8687. # — and each lap also consumes an upload slot that the other printers in the
  8688. # farm are waiting on. Retrying is right; retrying forever is not.
  8689. async def _do_revert(db):
  8690. item = await db.get(PrintQueueItem, queue_item_id)
  8691. if not item or item.status != "printing":
  8692. return "already_moved_on"
  8693. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8694. item.started_at = None
  8695. # Charge the attempt to the candidate that was actually dispatched, so
  8696. # a cross-model item (#671) reaches for its other file next lap instead
  8697. # of retrying the printer that just failed to start. Matched by file
  8698. # because that is what the resolver copied onto the row.
  8699. if item.library_file_id is not None:
  8700. await db.execute(
  8701. update(PrintQueueVariant)
  8702. .where(PrintQueueVariant.queue_item_id == item.id)
  8703. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8704. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8705. )
  8706. if command_rejected:
  8707. # No retry budget for this one: the printer refused to verify the
  8708. # command, and re-uploading the same 3MF to the same printer will
  8709. # be refused the same way. Fail now with the fix rather than after
  8710. # three laps of a message about SD cards (#2732).
  8711. item.status = "failed"
  8712. item.error_message = (
  8713. "The printer rejected the print command: MQTT command verification failed "
  8714. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8715. "then start the job again."
  8716. )
  8717. item.completed_at = datetime.now(timezone.utc)
  8718. await db.commit()
  8719. return "command_rejected"
  8720. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8721. item.status = "failed"
  8722. if drying_ams_ids:
  8723. # #2758: the generic message below sent the reporter looking
  8724. # at the SD card while the actual obstacle — AMS units in a
  8725. # drying cycle — was on screen the whole time. Name what we
  8726. # observed and let the user judge it; Bambuddy does not stop
  8727. # the cycle itself, because on this hardware drying can run
  8728. # alongside a print and stopping it may not be the fix.
  8729. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8730. item.error_message = (
  8731. f"The printer accepted the file but never started printing, after "
  8732. f"{item.dispatch_attempts} attempts. {units} "
  8733. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8734. f"some printers refuse to begin a print while an AMS is in a drying "
  8735. f"cycle, and an AMS drying without its external power supply can also "
  8736. f"leave too little power for the start-of-print calibration. Stop the "
  8737. f"drying, or connect the AMS power supply, and start the job again."
  8738. )
  8739. else:
  8740. item.error_message = (
  8741. f"The printer accepted the file but never started printing, after "
  8742. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8743. f"prompt or error, confirm its SD card is readable, and start the job again."
  8744. )
  8745. item.completed_at = datetime.now(timezone.utc)
  8746. await release_budget_reservation(
  8747. db,
  8748. source_type="print_queue",
  8749. source_id=item.id,
  8750. status="released",
  8751. )
  8752. await db.commit()
  8753. return "gave_up"
  8754. item.status = "pending"
  8755. await db.commit()
  8756. return "reverted"
  8757. try:
  8758. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8759. except Exception as e:
  8760. logger.warning(
  8761. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8762. "scheduler may keep treating this item as in-flight",
  8763. queue_item_id,
  8764. printer_id,
  8765. e,
  8766. )
  8767. revert_outcome = "revert_failed"
  8768. if revert_outcome in ("command_rejected", "gave_up"):
  8769. # The item is failed: its print user and expected print must not
  8770. # pass the printer's next print off as Bambuddy's.
  8771. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  8772. from backend.app.services.print_batch import refresh_batches_after
  8773. await refresh_batches_after([queue_item_id])
  8774. elif revert_outcome == "reverted":
  8775. # Another try claims the printer again. Until then no print on it
  8776. # is vouched for as this item's, except a late start of its file.
  8777. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  8778. elif revert_outcome == "already_moved_on":
  8779. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8780. if revert_outcome == "already_moved_on":
  8781. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8782. # other path) already moved the item past 'printing', don't run the
  8783. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8784. # session breaks ongoing prints on the same printer.
  8785. return
  8786. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8787. if revert_outcome == "command_rejected":
  8788. logger.error(
  8789. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8790. "failed) — the print command was rejected, not lost. Failing the item "
  8791. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8792. queue_item_id,
  8793. printer_id,
  8794. HMS_MQTT_VERIFY_FAILED,
  8795. )
  8796. await scheduler._notify_dispatch_gave_up(
  8797. queue_item_id,
  8798. printer_id,
  8799. created_by_id,
  8800. reason="Printer rejected the print command (MQTT command verification failed)",
  8801. )
  8802. # Same reasoning as the landed_on_subtask path below: the file is on
  8803. # the printer and a forced reconnect would only add 0500_4003 to a
  8804. # problem that has nothing to do with the MQTT session (#1150).
  8805. return
  8806. if revert_outcome == "gave_up":
  8807. logger.error(
  8808. "Queue item %s: printer %d never started the print after %d dispatch "
  8809. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8810. "re-uploading it again (#2555)",
  8811. queue_item_id,
  8812. printer_id,
  8813. DISPATCH_MAX_ATTEMPTS,
  8814. total_timeout,
  8815. )
  8816. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8817. elif revert_outcome == "reverted":
  8818. if landed_on_subtask:
  8819. logger.warning(
  8820. "Queue item %s: printer %d accepted project_file (subtask_id "
  8821. "advanced) but never transitioned to an active state within "
  8822. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8823. "for retry (#1678)",
  8824. queue_item_id,
  8825. printer_id,
  8826. total_timeout,
  8827. )
  8828. else:
  8829. logger.warning(
  8830. "Queue item %s: printer %d did not respond to print command within "
  8831. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8832. "for retry (#967)",
  8833. queue_item_id,
  8834. printer_id,
  8835. timeout,
  8836. pre_state,
  8837. pre_subtask_id,
  8838. )
  8839. # Phase B was entered iff subtask_id advanced, which means the
  8840. # project_file landed on the printer. A forced reconnect at this point
  8841. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8842. # skip the recovery entirely.
  8843. if landed_on_subtask:
  8844. return
  8845. # Phase A timeout path: if the printer's gcode_file changed since
  8846. # pre-dispatch, the project_file command landed and the printer is
  8847. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8848. # If gcode_file is unchanged, the publish was silently swallowed
  8849. # (#887/#936) and force_reconnect recovery is what we want.
  8850. client = printer_manager.get_client(printer_id)
  8851. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8852. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8853. if publish_landed:
  8854. logger.warning(
  8855. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8856. "received the command and is parsing slowly. Skipping forced "
  8857. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8858. queue_item_id,
  8859. current_gcode_file,
  8860. pre_gcode_file,
  8861. )
  8862. elif client and hasattr(client, "force_reconnect_stale_session"):
  8863. client.force_reconnect_stale_session(
  8864. f"queue print command unacknowledged after {timeout:.0f}s "
  8865. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8866. )
  8867. # Global scheduler instance
  8868. scheduler = PrintScheduler()