print_scheduler.py 531 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import InvalidFilenameError, derive_remote_filename, validate_print_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. plate_bed_temperature,
  90. select_plate_gcode_name,
  91. )
  92. logger = logging.getLogger(__name__)
  93. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  94. """Human slot name for an assignment tuple, in the spelling already in use.
  95. Composed from the notification side's own pair rather than spelled out again
  96. here. The hand-rolled version this replaces got three real slot kinds wrong:
  97. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  98. ``chr(191)``; both externals collapsed to one label, because an external
  99. assignment stores ams_id 255 with tray_id picking left or right
  100. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  101. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  102. Naming the same slot two ways is its own defect once an alert and the
  103. Inventory page are meant to be talking about the same tray, so this defers
  104. rather than adding a fifth spelling.
  105. """
  106. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  107. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  108. # interval: the fast path runs every 3 s while an upload is in flight, and a
  109. # low spool does not need answering at that resolution (#2913).
  110. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  111. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  112. # days, so a finer check would only repeat the same answer.
  113. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  114. # The settings row that holds which stock alerts have already been sent (#2955).
  115. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  116. # The Inventory page asks for this many usage records and the forecast panel
  117. # builds its rates from them; the alert reads the same window so the two agree.
  118. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  119. def _spoolman_time(value: object) -> datetime | None:
  120. """A Spoolman ISO timestamp, or None when missing or unreadable."""
  121. if not value:
  122. return None
  123. try:
  124. return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
  125. except ValueError:
  126. return None
  127. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  128. """Remaining filament as a percentage of the label weight.
  129. The same arithmetic the Inventory page's Low Stock count uses, and it works
  130. unchanged in both inventory modes: internal spools store ``weight_used``
  131. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  132. ``remaining_weight`` so the shape matches. Returns None when there is no
  133. label weight to be a percentage of -- a spool that cannot say how full it
  134. started cannot say how empty it is.
  135. """
  136. if not label_weight or label_weight <= 0:
  137. return None
  138. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  139. return remaining / float(label_weight) * 100.0
  140. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  141. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  142. # byte gate) from before the scheduler unification. Time gate keeps small
  143. # files from going silent (a single 8 KB chunk fires once and that's it);
  144. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  145. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  146. # sub-200 ms files.
  147. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  148. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  149. # How far back chamber temperature samples are retained. 2h comfortably spans
  150. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  151. # before the next print.
  152. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  153. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  154. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  155. # who clear plates promptly will want far less than this; it is deliberately
  156. # the cautious end, since the cost of it being too short is only a re-soak.
  157. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  158. # Max acceptable gap between two consecutive chamber samples before we treat
  159. # the older one as belonging to a separate observation run (printer went
  160. # offline and came back). Above ~30s cadence with a safety margin.
  161. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  162. # How long the chamber must read below target before we accept that it really
  163. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  164. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  165. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  166. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  167. # sub-target readings are therefore a door opening or noise, not lost soak,
  168. # and a plate swap (exactly when keep-warm is running) produces one. Six
  169. # minutes clears the longest such artifact observed (~5 min once bracketed by
  170. # its neighbouring samples) and still sits far below the 23-minute floor for
  171. # real cooling.
  172. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  173. # How often the preheat stage re-checks that the item it is heating for still
  174. # wants to be printed. Cancelling only writes `status` to the database — it
  175. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  176. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  177. # and the printer stays in `busy_printers`, blocking every other queued item
  178. # behind a print that is not happening.
  179. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  180. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  181. _AIRDUCT_MODE_COOLING = 0
  182. _AIRDUCT_MODE_HEATING = 1
  183. # How long a queue row may stay 'printing' while its printer sits in a terminal
  184. # state before the scheduler closes it itself (#2829).
  185. #
  186. # A real completion arrives within seconds of the printer going terminal, so
  187. # five minutes is far outside the normal path — this only ever sees a row whose
  188. # completion was refused or never delivered. It is the whole cost of the
  189. # failure to the user, though: a stranded row blocks every later job for that
  190. # printer, so it should not be raised without reason.
  191. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  192. # gcode_state values that mean the print is over, mapped to the queue status
  193. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  194. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  195. # which the queue calls cancelled) so a recovered row cannot disagree with one
  196. # closed by the normal path.
  197. _TERMINAL_STATE_QUEUE_STATUS = {
  198. "FINISH": "completed",
  199. "FAILED": "failed",
  200. "IDLE": "cancelled",
  201. }
  202. def _terminal_queue_status(state) -> str | None:
  203. """Queue status implied by *state*, or None if the print is not over.
  204. None for a disconnected printer as well as a busy one: a printer we are not
  205. talking to has a stale ``state`` field that proves nothing about what it is
  206. doing now.
  207. """
  208. if state is None or not getattr(state, "connected", False):
  209. return None
  210. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  211. @dataclass
  212. class _KeepWarmEntry:
  213. """Per-printer keep-warm state.
  214. - ``started``: monotonic time when keep-warm first fired for this printer.
  215. Used by the max-duration timeout.
  216. - ``held_target``: last bed target we successfully published. On release
  217. we only send bed-off when firmware still reports this value, so a user
  218. or subsequent print that changed the target isn't clobbered.
  219. - ``expired``: latched True when the max-duration timeout fires. Prevents
  220. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  221. release sweep drops the entry entirely once the printer leaves the
  222. candidate set.
  223. """
  224. started: float
  225. held_target: int
  226. expired: bool = False
  227. # Auto-drying re-arm guards (#2770).
  228. #
  229. # An AMS reports HIGHER relative humidity while it is warm than once it has
  230. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  231. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  232. # threshold set inside that band therefore cannot be satisfied while the box is
  233. # hot, and the firmware is free to end a cycle whenever it decides the filament
  234. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  235. # the threshold and arms another cycle. The reporter's log has five 12-hour
  236. # cycles armed inside four hours, one of them six seconds after the previous
  237. # ended.
  238. #
  239. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  240. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  241. # manual or firmware-run dry is untouched.
  242. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  243. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  244. # Sustained-humidity wait (#2518): an above-threshold streak is only
  245. # "continuous" if some pass observed it within the gap ceiling. A unit that
  246. # goes unobserved longer (print running, printer disconnected, sensor silent)
  247. # restarts its streak rather than inheriting a stale one. The ceiling is
  248. # derived from the scheduler cadence — four missed passes — with this floor so
  249. # a fast-polling configuration does not void streaks on a single hiccup.
  250. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  251. # How long a finished scheduled drying row is kept before it is pruned.
  252. SCHEDULED_DRYING_RETENTION_DAYS = 7
  253. # How often that prune actually runs. The check itself is called on every queue
  254. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  255. # write transaction, which SQLite serialises against every other writer. Rows
  256. # only become prunable a week after they finish, so anything short of hourly is
  257. # paying that cost for nothing.
  258. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  259. class _UploadProgressBridge:
  260. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  261. ``upload_file_async`` runs the FTP transfer in an executor thread and
  262. invokes its ``progress_callback`` from that thread, so the callback
  263. body cannot ``await`` directly. This bridge captures the asyncio loop
  264. at construction (on the scheduler thread) and uses
  265. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  266. matches the legacy background_dispatch.py path 1:1 so the toast feels
  267. identical to the pre-#1625 experience.
  268. Failures inside the emit are swallowed — progress is a UX nicety, the
  269. upload itself must not fail because of a WS hiccup.
  270. """
  271. def __init__(self, user_id: int | None, queue_item_id: int):
  272. self._user_id = user_id
  273. self._queue_item_id = queue_item_id
  274. try:
  275. self._loop = asyncio.get_running_loop()
  276. except RuntimeError:
  277. self._loop = None
  278. self._last_emit_bytes = 0
  279. self._last_emit_monotonic = 0.0
  280. self._has_emitted = False
  281. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  282. if self._loop is None or total_bytes <= 0:
  283. return
  284. now = time.monotonic()
  285. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  286. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  287. # the four matter most: first-call so the user sees something even
  288. # for sub-chunk-size files; uploaded >= total so the bar locks at
  289. # 100% even when the throttle would otherwise eat it.
  290. should_emit = (
  291. not self._has_emitted
  292. or bytes_transferred >= total_bytes
  293. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  294. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  295. )
  296. if not should_emit:
  297. return
  298. self._has_emitted = True
  299. self._last_emit_bytes = bytes_transferred
  300. self._last_emit_monotonic = now
  301. try:
  302. asyncio.run_coroutine_threadsafe(
  303. ws_manager.send_queue_item_upload_progress(
  304. user_id=self._user_id,
  305. queue_item_id=self._queue_item_id,
  306. bytes_transferred=bytes_transferred,
  307. total_bytes=total_bytes,
  308. ),
  309. self._loop,
  310. )
  311. except Exception:
  312. pass # progress is best-effort, never block the upload
  313. # Bambu firmware states that mean the project_file has actually been accepted
  314. # and the printer is now processing / running / paused mid-print. Used by the
  315. # dispatch watchdog (#1370): a transition into one of these states means the
  316. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  317. # a post-print prompt) is NOT a valid "command landed" signal even though the
  318. # state value did change. SLICING is included because some firmwares park
  319. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  320. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  321. # How many times the start-watchdog may revert an item to 'pending' before it
  322. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  323. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  324. # both never recovers and starves the other printers of dispatch slots. Three
  325. # is chosen to clear the transient causes the watchdog already recovers from —
  326. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  327. # force-reconnect on the very next attempt — while still bounding the loop.
  328. DISPATCH_MAX_ATTEMPTS = 3
  329. # Upload failures that mean the file never reached the printer's storage: the
  330. # file service refused or never answered (#3210). These put the item back in
  331. # the queue instead of failing it, because nothing about the job is wrong --
  332. # and failing it left the printer idle, so the next pass handed it the next
  333. # item, which failed the same way. One P2S whose file service was out of
  334. # connection slots ate 43 queued jobs in ten minutes that way.
  335. #
  336. # STORAGE (a missing, full or unusable card or USB drive) and AUTH (a rejected
  337. # access code) were left out at first, because they need the user. But
  338. # failing the item leaves the printer just as idle, and #3409's H2D with an
  339. # unusable USB stick ate seven jobs within an hour. Every job sent to that
  340. # printer fails the same way, so they wait too; the retry finds the fix once
  341. # the user has made it.
  342. #
  343. # A 553 can also be this one file: a name the card's filesystem cannot hold.
  344. # That one fails the item, see `_start_print`.
  345. #
  346. # Not here: NOT_FOUND (a path problem, which can be this one file), UNKNOWN,
  347. # and an upload that overran its deadline -- each retry of that costs a whole
  348. # upload that would be just as slow.
  349. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  350. {
  351. FtpFailureKind.HANDSHAKE,
  352. FtpFailureKind.SESSIONS,
  353. FtpFailureKind.COOLOFF,
  354. FtpFailureKind.TIMEOUT,
  355. FtpFailureKind.NETWORK,
  356. FtpFailureKind.STORAGE,
  357. FtpFailureKind.AUTH,
  358. }
  359. )
  360. def _refused_upload_hold_reason(printer_label: str, kind: FtpFailureKind | None) -> str:
  361. """What a job waiting on a printer that refused its last upload shows.
  362. Storage and the access code need the user to do something, so they say
  363. what, and so does a printer out of FTP sessions: those have been seen to
  364. stay until the printer restarts (#3474). The rest clear on their own.
  365. """
  366. if kind is FtpFailureKind.STORAGE:
  367. return f"{printer_label} refused to store the file — check its SD card or USB drive. {_REFUSED_UPLOAD_TAIL}"
  368. if kind is FtpFailureKind.AUTH:
  369. return (
  370. f"{printer_label} refused the file transfer — check its access code on the Printers page. "
  371. f"{_REFUSED_UPLOAD_TAIL}"
  372. )
  373. if kind is FtpFailureKind.SESSIONS:
  374. return (
  375. f"{printer_label} has no file-transfer sessions left (421 too many connections) — "
  376. f"if this does not clear within a few minutes, restart the printer. {_REFUSED_UPLOAD_TAIL}"
  377. )
  378. return f"{printer_label} is not accepting files — {_REFUSED_UPLOAD_TAIL}"
  379. _REFUSED_UPLOAD_TAIL = "Bambuddy will retry automatically"
  380. def _asks_nothing_new(waiting_reason: str) -> bool:
  381. """A model job's reason made only of busy printers and printers that refused an upload.
  382. The refusal sent its own notification (`_requeue_after_upload_refused`),
  383. so this one has nothing to add.
  384. """
  385. parts = [p.strip() for p in waiting_reason.split(" | ")]
  386. return all(p.startswith("Busy:") or p.endswith(_REFUSED_UPLOAD_TAIL) for p in parts)
  387. # How long a printer whose upload was put back stays out of dispatch (#3210).
  388. # The first window matches the FTP client's own handshake cool-off, so the
  389. # retry lands after the client would talk to the printer again anyway. Each
  390. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  391. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  392. # five connection attempts and a page of log. A successful upload resets it.
  393. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  394. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  395. def _upload_backoff_seconds(refusals: int) -> int:
  396. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  397. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  398. @dataclass(slots=True)
  399. class _ModelCandidate:
  400. """One (file, printer model) pair the model-based matcher may try.
  401. Model-based assignment used to have exactly one of these per item, held
  402. directly in the item's own columns. Cross-model queue items (#671) have
  403. several, held in ``print_queue_variants``. Both shapes are normalised into
  404. this so the matching, the cross-model gate and the waiting-reason handling
  405. are written once and an item without variants provably takes the same path
  406. it took before variants existed.
  407. ``variant`` is None for the item's own columns and set for a real variant
  408. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  409. item once that candidate wins.
  410. """
  411. target_model: str | None
  412. sliced_for: str | None
  413. required_filament_types: str | None
  414. filament_overrides: str | None
  415. variant: "PrintQueueVariant | None" = None
  416. def _sliced_for_model(archive, library_file) -> str | None:
  417. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  418. if archive is not None:
  419. return archive.sliced_for_model
  420. if library_file is not None and library_file.file_metadata:
  421. return library_file.file_metadata.get("sliced_for_model")
  422. return None
  423. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  424. """The filament a candidate needs, as ``(types, overrides)``.
  425. Both columns are JSON text written by the slicer step. Malformed content is
  426. treated as no constraint rather than as an error: a job whose overrides
  427. cannot be parsed still prints, it just gets no filament-based narrowing.
  428. Overrides carry their own types, so the returned type list is the union of
  429. the two — an override on one slot must not drop the requirements of the
  430. slots it says nothing about.
  431. Shared by the matcher and by the smart-plug wake step so both ask a printer
  432. for the same filament (#2876). Waking a printer the matcher would then
  433. reject on colour is the bug this exists to prevent.
  434. """
  435. required_types = None
  436. if candidate.required_filament_types:
  437. try:
  438. required_types = json.loads(candidate.required_filament_types)
  439. except json.JSONDecodeError:
  440. pass
  441. filament_overrides = None
  442. if candidate.filament_overrides:
  443. try:
  444. filament_overrides = json.loads(candidate.filament_overrides)
  445. except json.JSONDecodeError:
  446. pass
  447. effective_types = required_types
  448. if filament_overrides:
  449. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  450. if override_types:
  451. effective_types = sorted(set(required_types or []) | set(override_types))
  452. return effective_types, filament_overrides
  453. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  454. """Whether ``item`` was competing for the printer another item just took.
  455. The SJF starvation guard marks a job as jumped when a shorter one lower in
  456. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  457. compete for the same printer, so the guard has to look across both lanes
  458. (#3200); looking only inside the dispatched item's own lane let a stream of
  459. short model-based jobs hold a longer pinned job back indefinitely.
  460. Location filters are not checked: over-marking only lifts an item that was
  461. going to wait anyway, while under-marking is the starvation this prevents.
  462. """
  463. if item.printer_id is not None:
  464. return item.printer_id == printer_id
  465. if not printer_model:
  466. return False
  467. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  468. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  469. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  470. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  471. """Candidate files for ``item``, best first.
  472. An item with no variant rows yields exactly one candidate built from its own
  473. columns — the pre-#671 behaviour, unchanged.
  474. Variants come back least-attempted first, ties broken by the user's
  475. ``position``. On the first pass every count is zero, so this is purely the
  476. user's priority order. After a start-watchdog bounce the printer that failed
  477. drops behind, so the next lap tries the other machine rather than spending the
  478. item's whole retry budget on the one that is wedged. Once every candidate has
  479. been tried equally often they cycle again, which keeps the item-level
  480. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  481. still gives up, it just does not give up without trying them.
  482. """
  483. if not item.variants:
  484. if not item.archive_id and not item.library_file_id:
  485. # Nothing to print at all. Dispatching would fail deep in the upload
  486. # on "No archive_id or library_file_id"; the caller holds the item
  487. # with an explanation instead.
  488. return []
  489. return [
  490. _ModelCandidate(
  491. target_model=item.target_model,
  492. sliced_for=_sliced_for_model(item.archive, item.library_file),
  493. required_filament_types=item.required_filament_types,
  494. filament_overrides=item.filament_overrides,
  495. )
  496. ]
  497. # Drop candidates whose file is gone or in the trash. Both are reachable and
  498. # neither is covered by the schema: library deletes are soft (the row lives
  499. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  500. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  501. # fires there and a hard delete leaves the variant row pointing at nothing.
  502. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  503. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  504. return [
  505. _ModelCandidate(
  506. target_model=v.target_model,
  507. sliced_for=_sliced_for_model(None, v.library_file),
  508. required_filament_types=v.required_filament_types,
  509. filament_overrides=v.filament_overrides,
  510. variant=v,
  511. )
  512. for v in ordered
  513. ]
  514. # Why a job for any printer of a model waits when every free one's last print
  515. # failed. The queue page matches it to offer Resume for the model.
  516. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  517. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  518. """Fold one waiting reason per candidate into a single line for the item.
  519. A cross-model item produces a reason per candidate, and pasting them
  520. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  521. — on which machine?). Each reason is prefixed with its model, except in the
  522. single-candidate case where the item already displays its target model and
  523. the prefix would be noise.
  524. Identical reasons collapse rather than repeat, so three idle-less models
  525. read as one clause.
  526. When *every* candidate is merely busy the parts are joined with the ``" | "``
  527. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  528. unprefixed. That case must keep testing busy-only: a fleet that is simply
  529. printing needs no user action, and labelling the clauses would turn each pass
  530. over a two-model item into a "job waiting" notification.
  531. """
  532. reasons = [(model, reason) for model, reason in per_model if reason]
  533. if not reasons:
  534. return None
  535. if len(reasons) == 1:
  536. return reasons[0][1]
  537. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  538. if len(distinct) == 1:
  539. return distinct[0]
  540. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  541. return " | ".join(distinct)
  542. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  543. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  544. """Human label for the models an item is waiting on ("H2S or H2C").
  545. Notifications take a single target model. For a cross-model item the item's
  546. own ``target_model`` is whichever variant happens to be first, which reads as
  547. a lie once it is the H2C that actually runs — so name all of them.
  548. """
  549. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  550. if not models:
  551. return None
  552. return " or ".join(models)
  553. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  554. """True if ``mapping`` is a non-empty list whose every entry is the
  555. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  556. Such a mapping is a bug artifact: a frontend status-load race can serialize
  557. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  558. recomputed from live status at dispatch rather than trusted, otherwise it
  559. reaches the print command and is silently downgraded to external-spool mode.
  560. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  561. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  562. explicit external selection (``>= 254``) is NOT unresolved either — those
  563. keep their meaning.
  564. """
  565. if not isinstance(mapping, list) or not mapping:
  566. return False
  567. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  568. def _is_tray_id(value: object) -> bool:
  569. """True when ``value`` can be read as a global tray ID.
  570. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  571. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  572. against whatever happens to be loaded there.
  573. """
  574. return isinstance(value, int) and not isinstance(value, bool)
  575. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  576. # stages an item (#2799). The manual_start branch clears every other reason on
  577. # a staged item (#3074); this one is the reason it was staged, so it stays.
  578. _UNMATCHED_HOLD_PREFIX = "Needs "
  579. # How often an "any model" job held for low filament looks for another printer
  580. # of its model that has enough (#3137). Each look matches its filament on every
  581. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  582. _SHORT_HOLD_RECHECK_SECONDS = 120
  583. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  584. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  585. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  586. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  587. """The item's force_color_match overrides as filament requirements (#3280).
  588. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  589. read, so the checks after it judge the same list.
  590. """
  591. try:
  592. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  593. except (json.JSONDecodeError, TypeError):
  594. return []
  595. if not isinstance(overrides, list):
  596. return []
  597. return [
  598. {
  599. "slot_id": o.get("slot_id"),
  600. "type": o.get("type", ""),
  601. "color": o.get("color", ""),
  602. "tray_info_idx": o.get("tray_info_idx", ""),
  603. "force_color_match": True,
  604. }
  605. for o in overrides
  606. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  607. ]
  608. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  609. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  610. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  611. for a filament this plate does not use. A slot past the end of the mapping
  612. is unresolved too.
  613. """
  614. unresolved = []
  615. for req in required:
  616. slot_id = req.get("slot_id") or 0
  617. if slot_id <= 0:
  618. continue
  619. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  620. if not _is_tray_id(tray) or tray < 0:
  621. unresolved.append(req)
  622. return unresolved
  623. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  624. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  625. # on `_mapping_is_all_unresolved`.
  626. _EXTERNAL_TRAY_ID_MIN = 254
  627. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  628. """The ``mapping`` entries for the slots this plate actually prints.
  629. ``required`` comes from ``extract_filament_requirements``, which drops any
  630. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  631. consumes, and one absent from it is padding. That distinction is why this
  632. decision lives here and not in the MQTT command builder: a ``-1`` in the
  633. mapping means either "this plate does not print filament N" or "we never
  634. worked out which tray", and only the plate's own filament list separates
  635. them. The builder sees both as the same byte, which is how a plate whose one
  636. printed filament sat on the external spool went out as `use_ams=true` with a
  637. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  638. with 07FF_8012 (#3087).
  639. Returns None whenever the two cannot be lined up — no mapping, no parsed
  640. requirements, or a requirement the mapping is too short to cover — so every
  641. caller falls back to existing behaviour rather than acting on a guess.
  642. """
  643. if not isinstance(mapping, list) or not mapping or not required:
  644. return None
  645. entries = []
  646. for filament in required:
  647. slot_id = filament.get("slot_id")
  648. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  649. # The mapping and the requirements disagree about how many filaments
  650. # the file has. They came from different reads, so judge nothing.
  651. return None
  652. entries.append(mapping[slot_id - 1])
  653. return entries or None
  654. def _is_external_tray(tray_id) -> bool:
  655. """True for an explicit external-spool selection (254/255), not for an
  656. unresolved slot and not for an AMS tray."""
  657. if tray_id is None:
  658. return False
  659. try:
  660. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  661. except (TypeError, ValueError):
  662. return False
  663. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  664. """Whether this printer could have two extruders, judged generously.
  665. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  666. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  667. why the MQTT command builder skips its own use_ams reconcile there. Anything
  668. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  669. with, external spools or not.
  670. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  671. behaviour it has always had, while a wrong "no" would rewrite a field that
  672. steers which nozzle prints. The model name is the first answer (it is what
  673. the command builder falls back to as well), then the same live evidence the
  674. dispatcher's extruder annotation uses — a second nozzle reporting a
  675. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  676. since a single-nozzle printer has exactly one.
  677. """
  678. if is_dual_nozzle_model(printer_model):
  679. return True
  680. nozzles = getattr(status, "nozzles", None) or []
  681. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  682. return True
  683. raw = getattr(status, "raw_data", None) or {}
  684. if raw.get("ams_extruder_map"):
  685. return True
  686. vt_trays = raw.get("vt_tray") or []
  687. return isinstance(vt_trays, list) and len(vt_trays) > 1
  688. def _int_or(value, default: int) -> int:
  689. """``int(value)``, or ``default`` when the field is missing or junk.
  690. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  691. the next — and a tray id that fails to parse must not take the whole
  692. derivation down with it.
  693. """
  694. try:
  695. return int(value)
  696. except (TypeError, ValueError):
  697. return default
  698. # What a queue job's dispatch is worked out from, and an edit can change.
  699. _DISPATCH_INPUTS = (
  700. "printer_id",
  701. "status",
  702. "ams_mapping",
  703. "plate_id",
  704. "filament_overrides",
  705. "skip_filament_check",
  706. "target_model",
  707. "target_location",
  708. )
  709. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  710. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  711. The pass works on the jobs as loaded at its start, and it may have waited
  712. since: a plug powering a printer on takes minutes. A job edited meanwhile
  713. (moved to another printer, given a mapping or another plate, cancelled)
  714. is left to the next pass, which reads it fresh: deciding from the stale
  715. copy would overwrite the edit, or send the job where it no longer goes.
  716. The query flushes the pass's own pending changes first, so those don't
  717. count as edits.
  718. """
  719. row = (
  720. await db.execute(
  721. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  722. )
  723. ).one_or_none()
  724. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  725. return False
  726. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  727. return True
  728. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  729. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  730. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  731. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  732. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  733. agree or a mapping cannot be read back against live tray telemetry.
  734. """
  735. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  736. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  737. """The global tray ids ``item`` actually prints from, or None if unknown.
  738. ``ams_mapping`` is the array the print command carries: position = filament
  739. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  740. not use. None means "no usable statement" — no mapping, unparseable JSON,
  741. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  742. documents), or one that resolves to no tray at all. Callers must treat None
  743. as "consider every loaded tray" rather than "consider none": narrowing on
  744. an absent mapping would silently drop requirements the print really has.
  745. """
  746. raw = getattr(item, "ams_mapping", None)
  747. if not raw:
  748. return None
  749. if isinstance(raw, str):
  750. try:
  751. mapping = json.loads(raw)
  752. except (json.JSONDecodeError, TypeError):
  753. return None
  754. else:
  755. mapping = raw
  756. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  757. return None
  758. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  759. return used or None
  760. def _mqtt_commands_rejected(status) -> bool:
  761. """True when the printer is currently reporting that it refused a command.
  762. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  763. a control command it could not verify. Queries still answer, so the printer
  764. looks connected and idle while project_file, gcode_line and
  765. ams_change_filament are all dropped — no amount of waiting or re-uploading
  766. changes that (#2732).
  767. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  768. ``print_error`` path builds HMSError differently), so this is safe to call on
  769. every watchdog poll.
  770. """
  771. for err in getattr(status, "hms_errors", None) or []:
  772. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  773. return True
  774. return False
  775. def _drying_ams_ids(status) -> list[int]:
  776. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  777. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  778. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  779. started (#2758) — it is a diagnostic, not a gate.
  780. Deliberately not used to block or stop drying before dispatch. This printer
  781. class supports drying concurrently with an active print
  782. (``supports_drying_while_printing``), so drying is not incompatible with
  783. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  784. while two AMS units were drying, one of them without its external PSU. Until
  785. it is known whether the blocker is drying itself or the power budget
  786. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  787. hardware is perfectly happy to continue.
  788. """
  789. ids: list[int] = []
  790. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  791. if not isinstance(unit, dict):
  792. continue
  793. try:
  794. if int(unit.get("dry_time") or 0) > 0:
  795. ids.append(int(unit.get("id", 0)))
  796. except (TypeError, ValueError):
  797. continue
  798. return ids
  799. def _parse_diameter(raw) -> float | None:
  800. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  801. try:
  802. value = float(raw)
  803. except (TypeError, ValueError):
  804. return None
  805. return value if value > 0 else None
  806. def _nozzle_info_by_id(status) -> dict[int, dict]:
  807. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  808. The field name is historical: on the H2 series ``nozzle_info`` carries an
  809. entry for *every* nozzle the printer knows about — the L/R hotends under
  810. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  811. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  812. :func:`_installed_nozzle_diameters` each take the half they need.
  813. """
  814. by_id: dict[int, dict] = {}
  815. for entry in getattr(status, "nozzle_rack", None) or []:
  816. if not isinstance(entry, dict):
  817. continue
  818. try:
  819. by_id[int(entry.get("id"))] = entry
  820. except (TypeError, ValueError):
  821. continue
  822. return by_id
  823. # What the firmware puts in a nozzle's serial number when the carriage or dock
  824. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  825. # its nozzle back in the rack (#2885).
  826. _EMPTY_NOZZLE_SERIAL = "N/A"
  827. def _nozzle_is_mounted(entry: dict | None) -> bool:
  828. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  829. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  830. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  831. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  832. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  833. the dock. So the diameter is not a presence signal (#2885).
  834. Emptiness has to be stated, not merely unstated. The serial must be the
  835. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  836. absent — an empty serial only means the printer didn't say, and a firmware
  837. that reports neither field normalises to exactly that. Treating "didn't
  838. say" as "empty" would silently switch the #1899 guard off on any such
  839. machine, so everything we cannot positively call empty counts as mounted.
  840. """
  841. if entry is None:
  842. return True
  843. serial = str(entry.get("serial_number") or "").strip().upper()
  844. if serial != _EMPTY_NOZZLE_SERIAL:
  845. return True
  846. try:
  847. max_temp = float(entry.get("max_temp") or 0)
  848. except (TypeError, ValueError):
  849. return True
  850. return max_temp > 0
  851. def _installed_nozzle_diameters(status) -> list[float]:
  852. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  853. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  854. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  855. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  856. told us its nozzle hardware" — callers must treat that as unknown, not as a
  857. mismatch, so we never block a print on missing data.
  858. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  859. though ``nozzles`` still carries a diameter for it: that value is stale, and
  860. counting it would let a slice match a nozzle the machine does not have
  861. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  862. """
  863. info = _nozzle_info_by_id(status)
  864. diameters: list[float] = []
  865. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  866. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  867. try:
  868. value = float(raw)
  869. except (TypeError, ValueError):
  870. continue
  871. if value > 0 and _nozzle_is_mounted(info.get(index)):
  872. diameters.append(value)
  873. return diameters
  874. def _rack_nozzle_diameters(status) -> list[float]:
  875. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  876. Keyed off the nozzle ids themselves rather than the printer model: only a
  877. rack machine ever reports ids 16-21, so there is no model registry to keep
  878. in sync. An empty dock is simply absent from the payload — measured on an
  879. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  880. present — so appearing here already means "a nozzle is in that dock".
  881. ``stat`` is deliberately not interpreted: its values aren't known, and
  882. reading it wrongly could hide a nozzle the printer would happily fetch.
  883. """
  884. diameters: list[float] = []
  885. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  886. if nozzle_id not in _RACK_NOZZLE_IDS:
  887. continue
  888. # PrinterState spells it "diameter"; the REST schema renames it to
  889. # "nozzle_diameter". Accept either so a caller holding the serialised
  890. # shape gets the same answer.
  891. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  892. if value is not None:
  893. diameters.append(value)
  894. return diameters
  895. def _format_diameters(diameters: list[float]) -> str:
  896. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  897. Deduplicated because a loaded rack holds several nozzles of the same size,
  898. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  899. short form doesn't. Matching still runs over the full list.
  900. """
  901. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  902. def _nozzle_mismatch_message(
  903. sliced_nozzle: float | None,
  904. installed: list[float],
  905. rack: list[float] | None = None,
  906. ) -> str | None:
  907. """Return an actionable error message when the sliced nozzle can't be
  908. printed on any nozzle the machine can reach, else None (#1899).
  909. Fail-safe: returns None whenever we lack the data to judge — no sliced
  910. diameter, or the printer reported no nozzles — so a print is only ever
  911. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  912. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  913. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  914. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  915. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  916. as reachable: the printer fetches one as part of starting the print, so a
  917. slice that matches a docked nozzle is not a mismatch. Without this the
  918. guard blocked every job whose nozzle happened not to be on a hotend at
  919. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  920. diameter already mounted could ever print, and the user had to fetch the
  921. nozzle by hand on the printer's own UI first (#2885).
  922. """
  923. reachable = [*installed, *(rack or [])]
  924. if not sliced_nozzle or not reachable:
  925. return None
  926. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  927. return None
  928. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  929. if rack:
  930. where += f" and {_format_diameters(rack)} in the nozzle rack"
  931. return (
  932. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  933. f"{where}. Re-slice for an available nozzle, or fit the matching "
  934. f"nozzle before printing."
  935. )
  936. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  937. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  938. Shared by the required and loaded sides, which name their extruder
  939. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  940. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  941. 1 the left/deputy — and both are absent on single-nozzle printers, where
  942. naming a nozzle would be noise.
  943. """
  944. parts = [(entry.get("type") or "filament").upper()]
  945. if entry.get("color"):
  946. parts.append(str(entry["color"]))
  947. nozzle = entry.get(nozzle_key)
  948. if nozzle == 0:
  949. parts.append("(right nozzle)")
  950. elif nozzle == 1:
  951. parts.append("(left nozzle)")
  952. return " ".join(parts)
  953. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  954. """Explain that nothing loaded matches what the file needs (#2771).
  955. Only ever built for a printer with no AMS, where the loaded list is short
  956. enough to quote in full and there is no "load another spool and hit Resume"
  957. recovery — the external spool holder is all there is, so the user needs to
  958. be told which filament to put on it.
  959. """
  960. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  961. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  962. return (
  963. f"No filament loaded on this printer matches the file. It needs {want}; "
  964. f"the printer has {have} and no AMS. Load the required filament on the "
  965. f"external spool holder, or send this job to a printer that has it."
  966. )
  967. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  968. """Bed temperature for the plate a queued job prints, 0 when unknown.
  969. The archive stores the highest bed temperature of any filament in the
  970. project, while the job may print another plate than the one archived: a
  971. PLA plate of a project that also holds PETG is heated for PLA. Read from
  972. the archive's file for the job's own plate, falling back to the stored
  973. value when the file can't be read.
  974. """
  975. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  976. if archive is None or not archive.file_path:
  977. return stored
  978. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  979. return temperature or stored
  980. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  981. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  982. every call site below it: G-code injection, usage registration, rack-plan
  983. lookup, slot-extruder lookup, the external-spool check, and the actual
  984. print command.
  985. A positive explicit ``plate_id`` on the queue item always wins. A
  986. non-positive one is treated as "not set" and resolved from the archive,
  987. the way the rest of the queue code already reads it (``if item.plate_id:``
  988. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  989. field, and passing a 0 straight through would build a print command for
  990. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  991. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  992. Falling back to a bare ``1`` instead of reading the archive assumes a
  993. single-plate file's one G-code is numbered 1, which only holds for a
  994. plate exported on its own: one cut out of a larger project keeps its
  995. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  996. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  997. the file, throws an HMS error, and sits wedged in IDLE until
  998. power-cycled (#2947).
  999. The call sites agreed on a fallback only by accident before this:
  1000. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  1001. the archive's own default plate internally whenever the plate id it's
  1002. handed isn't in the file, so it could silently inject into a different
  1003. plate than the one the print command itself asked for.
  1004. Falls back to 1 when the archive can't be read, holds no G-code member at
  1005. all, or its default member doesn't follow the ``plate_N`` naming
  1006. convention (a slicer that doesn't use it has no number to dispatch).
  1007. An explicit plate the archive doesn't hold is logged and then sent
  1008. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  1009. to a plate that is in the file would print a model nobody asked for,
  1010. which is the worse of the two.
  1011. """
  1012. try:
  1013. with zipfile.ZipFile(file_path, "r") as zf:
  1014. names = zf.namelist()
  1015. except (OSError, zipfile.BadZipFile) as exc:
  1016. logger.warning(
  1017. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  1018. "is unavailable; dispatching plate %s",
  1019. file_path,
  1020. exc,
  1021. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  1022. )
  1023. names = None
  1024. if explicit_plate_id is not None and explicit_plate_id > 0:
  1025. if (
  1026. names is not None
  1027. and default_plate_number(names) is not None
  1028. and select_plate_gcode_name(names, explicit_plate_id) is None
  1029. ):
  1030. logger.warning(
  1031. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  1032. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  1033. "file, since printing a different plate would print the wrong model (#2947)",
  1034. file_path,
  1035. explicit_plate_id,
  1036. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  1037. explicit_plate_id,
  1038. )
  1039. return explicit_plate_id
  1040. resolved = default_plate_number(names) if names is not None else None
  1041. return resolved if resolved is not None else 1
  1042. class PrintScheduler:
  1043. """Background scheduler that processes the print queue."""
  1044. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  1045. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  1046. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  1047. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  1048. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  1049. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  1050. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1051. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1052. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1053. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1054. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1055. }
  1056. def __init__(self):
  1057. self._running = False
  1058. self._check_interval = 30 # seconds
  1059. # After a pass that actually dispatched something, loop again almost
  1060. # immediately instead of sleeping the full interval (#2555). A dispatch
  1061. # changes printer state — a batch launch fans out over several passes as
  1062. # printers free up, a wedged head-of-line job reverts to pending, an
  1063. # upload slot opens — and the next batch of ready work should not have to
  1064. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1065. # pending items are behind printers that are genuinely busy printing),
  1066. # there is nothing to react to, so we fall back to the normal interval;
  1067. # that also means this can never tight-loop, since fast ticks only
  1068. # continue while dispatches keep happening and the queue is draining.
  1069. self._fast_check_interval = 3 # seconds
  1070. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1071. self._power_on_check_interval = 10 # seconds between connection checks
  1072. # Printers whose class-target power-on failed, mapped to the monotonic
  1073. # time their cool-off expires (#2786).
  1074. #
  1075. # Without this, one printer with an unreachable plug starves every
  1076. # sibling of its model forever: the wake step walks candidates in id
  1077. # order, spends the pass's single attempt on the same broken printer
  1078. # every time, and the healthy one two slots down is never reached. It
  1079. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1080. # which delays the whole queue, not just this job.
  1081. #
  1082. # Entries expire on read rather than being cleared on success: a printer
  1083. # inside its cool-off is skipped before the power-on is reached, so a
  1084. # live entry can never be overwritten by a success anyway. A printer
  1085. # that comes back by any other route stops being a wake candidate the
  1086. # moment it connects.
  1087. self._wake_failures: dict[int, float] = {}
  1088. self._wake_failure_cooloff = 600 # seconds
  1089. # Printers whose last upload never reached them, mapped to the monotonic
  1090. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1091. # as `_wake_failures`. Without it, a printer that cannot take files is
  1092. # idle on every pass, so it is picked on every pass.
  1093. self._upload_backoff: dict[int, float] = {}
  1094. # Refused uploads in a row per printer, which sets the next backoff
  1095. # window. Cleared by a successful upload to that printer.
  1096. self._upload_refusals: dict[int, int] = {}
  1097. # Why each printer in `_upload_backoff` refused its last upload, for
  1098. # the reason its jobs show. Cleared with `_upload_refusals`.
  1099. self._upload_refusal_kind: dict[int, FtpFailureKind] = {}
  1100. # The "job waiting" text last sent for each printer's current run of
  1101. # refusals. A refusal notifies only when its text differs, so a run
  1102. # notifies once, and again only if it turns into something the user
  1103. # has to fix. Cleared with `_upload_refusals`.
  1104. self._upload_refusal_notified: dict[int, str] = {}
  1105. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1106. self._drying_in_progress: dict[int, float] = {}
  1107. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1108. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1109. # cycle and the humidity finally coming down, so the normal steady
  1110. # state is an empty dict. Fields:
  1111. # running — a cycle we armed is (or should be) on the firmware
  1112. # ended_at — monotonic when we observed that cycle end
  1113. # unproductive — consecutive armed cycles that ended with the reading
  1114. # still above the threshold
  1115. # suspended — we have stopped arming this unit and said so
  1116. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1117. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1118. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1119. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1120. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1121. # arming setdefault all act on that meaning -- a unit that is merely
  1122. # waiting out its streak must not become stoppable or judgeable.
  1123. # since -- monotonic stamp when the current continuous above-threshold
  1124. # streak began
  1125. # last -- monotonic stamp of the last pass that observed the streak
  1126. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1127. # Slots already notified as low on filament:
  1128. # {(printer_id, ams_id, tray_id, spool_id)}.
  1129. # Cleared when the slot goes back above its threshold rather than on a
  1130. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1131. # boundary must not produce an alert on every pass, and a slot that has
  1132. # been refilled has to be able to alert again. See #2913.
  1133. #
  1134. # The spool id is part of the key because the slot alone cannot clear
  1135. # itself. Pull a low spool and put a different part-used one in the same
  1136. # slot: the key survives the pass where the slot resolves to nothing --
  1137. # deliberately, so a brief Spoolman outage does not re-alert everything
  1138. # when it returns -- and the replacement never goes above the threshold,
  1139. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1140. # different key and the stale one is inert.
  1141. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1142. # The same, for the MQTT relay's filament/low event: its own record, so
  1143. # one channel having been told never silences the other.
  1144. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1145. # Earliest monotonic time the next low-filament check may run (#2913).
  1146. self._filament_low_next_check: float = 0.0
  1147. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1148. # condition is "reorder" or "break", the events are those that had a
  1149. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1150. # condition clears, so it can alert again, and when nobody wants either
  1151. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1152. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1153. # re-send one message per SKU that is still low.
  1154. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1155. # The JSON last read from or written to that row; None until it has been read.
  1156. self._stock_alerts_persisted: str | None = None
  1157. # Earliest monotonic time the next stock forecast check may run (#2955).
  1158. self._stock_forecast_next_check: float = 0.0
  1159. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1160. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1161. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1162. # both features share _drying_in_progress.
  1163. self._scheduled_drying_printer_ids: set[int] = set()
  1164. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1165. # the first pass after a restart reaps anything left behind.
  1166. self._last_scheduled_drying_prune: float | None = None
  1167. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1168. # a project_file command must not get a second dispatch until either it
  1169. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1170. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1171. # during that window the DB busy_printers seed is empirically unreliable
  1172. # (multi-plate batches double-/triple-dispatched onto the same printer
  1173. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1174. # or revert.
  1175. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1176. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1177. # Minimum cooldown between dispatches to the same printer (covers the
  1178. # H2D's project_file digestion window).
  1179. self._dispatch_min_cooldown = 60.0
  1180. # Hard timeout — drop the hold even if we never observed a transition,
  1181. # so a lost MQTT session can't lock a printer out of the queue forever.
  1182. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1183. # watchdog runs first on the unhappy path.
  1184. self._dispatch_max_hold = 180.0
  1185. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1186. # an earlier pass and is still running. `_start_print` flips the row
  1187. # pending -> printing only *after* the upload completes, so until then
  1188. # the row stays `pending`: each tick, check_queue excludes these
  1189. # item_ids from re-selection and their printers from new dispatch /
  1190. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1191. # freed slots refill on the next fast tick. check_queue is the sole,
  1192. # sequential caller and the prune done-callbacks run in the same
  1193. # event-loop thread, so this dict needs no lock.
  1194. # item_id -> (task, printer_id)
  1195. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1196. # The archive each dispatch in flight prints into, held in
  1197. # services/archive_work so a merge leaves it alone until the dispatch
  1198. # ends: item_id -> archive_id. Same threading as above.
  1199. self._held_archives: dict[int, int] = {}
  1200. # Expected prints registered by `_start_print` that have not yet had a
  1201. # print command sent. Populated at registration, dropped once
  1202. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1203. # other exit. Same threading argument as `_inflight` above: one
  1204. # sequential caller, callbacks on the same loop, so no lock.
  1205. # item_id -> (printer_id, remote_filename, archive_id)
  1206. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1207. # Budget reservations created for a dispatch whose print command has
  1208. # not been confirmed yet. `_dispatch_one` releases these on every
  1209. # unsuccessful exit; a successful start removes the item id and leaves
  1210. # the reservation for finance_billing to consume with the archive.
  1211. self._unconfirmed_budget_reservations: set[int] = set()
  1212. # The print user `_start_print` handed to printer_manager for an item
  1213. # whose print command has not been sent yet (item_id -> printer_id).
  1214. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1215. # expected print above: it marks the printer's next print as Bambuddy's.
  1216. self._unconfirmed_print_user: dict[int, int] = {}
  1217. # Prints whose command went out but which the printer has not been
  1218. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1219. # the file and archive None for a library print. The watchdog drops the
  1220. # entry once the print runs, and withdraws what it stands for when the
  1221. # print never starts (see `_forget_unstarted_print`).
  1222. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1223. # Chamber temperature history for smart soak-time reduction.
  1224. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1225. # Entries older than _chamber_history_ttl are pruned on write.
  1226. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1227. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1228. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1229. # Populated on engagement in `_apply_keep_warm`, cleared by
  1230. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1231. # when a gate setting toggles off mid-hold — the release publishes
  1232. # bed → 0 first).
  1233. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1234. # Preheat rollback registry: printer_id -> subset of
  1235. # {"bed", "chamber", "airduct"} listing which preheat commands
  1236. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1237. # every entry still present at exit unless the print successfully
  1238. # started, so a failed upload / cancel / exception never leaves the
  1239. # printer heating for a job that isn't happening.
  1240. self._preheat_pin: dict[int, set[str]] = {}
  1241. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1242. # rollback can tell its own target from one someone else has since
  1243. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1244. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1245. self._preheat_pin_bed: dict[int, int] = {}
  1246. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1247. # its preheat was still holding at temperature. Set by
  1248. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1249. # `_preheat_sleep`, and cleared when the dispatch exits.
  1250. self._cancelled_dispatches: set[int] = set()
  1251. # printer_id -> monotonic time it was first seen terminal while one of
  1252. # its queue rows was still 'printing'. Reset by any non-terminal
  1253. # observation, so it measures an unbroken run rather than a total.
  1254. # In-memory on purpose: a restart re-arms the grace period, which only
  1255. # delays a recovery that is already the exceptional path (#2829).
  1256. self._terminal_since: dict[int, float] = {}
  1257. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1258. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1259. # across idle printers repeats that for every one of them in a single
  1260. # pass. Cleared at the top of each pass so a re-sliced file is never
  1261. # served from a previous tick.
  1262. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1263. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1264. # matcher about every idle candidate, and a pass can ask again for the
  1265. # same job and printer (another variant, a previous-print retry, the
  1266. # low-filament move). Cleared with the requirement memo.
  1267. self._unmatched_memo: dict[tuple, list[str]] = {}
  1268. # When each "any model" job held for low filament last looked for
  1269. # another printer (#3137), by queue item id.
  1270. self._short_hold_checked_at: dict[int, float] = {}
  1271. async def run(self):
  1272. """Main loop - check queue every interval."""
  1273. self._running = True
  1274. logger.info("Print scheduler started")
  1275. await self._clear_stale_dispatch_claims(at_startup=True)
  1276. while self._running:
  1277. dispatched = False
  1278. try:
  1279. self._sample_chamber_temps()
  1280. # No-op while any upload is in flight; on a quiet tick it releases
  1281. # a claim whose best-effort clear failed (e.g. the database was
  1282. # briefly unreachable), instead of leaving the row wedged until
  1283. # the next restart.
  1284. await self._clear_stale_dispatch_claims()
  1285. await self._close_stranded_printing_items()
  1286. dispatched = await self.check_queue()
  1287. except Exception as e:
  1288. logger.error("Scheduler error: %s", e)
  1289. # Re-check quickly after a productive pass so a draining batch does
  1290. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1291. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1292. async def _close_stranded_printing_items(self) -> None:
  1293. """Close a ``printing`` row the completion event never closed (#2829).
  1294. ``on_print_complete`` refuses to close a row when the completion's
  1295. subtask name disagrees with the file the row was dispatched with, so a
  1296. completion meant for something else (the printer's own
  1297. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1298. The refusal has no way back, though: nothing else ever closes the row,
  1299. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1300. one bad comparison wedges that printer's queue until a human presses
  1301. cancel. That is what #2829's reporters hit, and the guard's own
  1302. docstring already called stranding the worse of the two failures.
  1303. This is the way back. When a row has been ``printing`` while its
  1304. printer sat in a terminal state for the whole grace period, the print
  1305. is over however the event was read, and the row is closed with the
  1306. status the printer's own state implies.
  1307. Deliberately conservative:
  1308. * Only a connected printer counts. A disconnected one has a stale
  1309. ``state`` and proves nothing.
  1310. * The clock is reset by any non-terminal observation, so this cannot
  1311. fire on a printer that is merely between stages.
  1312. * The grace period is far longer than the gap between a printer
  1313. finishing and its completion arriving, so the normal path always
  1314. wins the race and this only ever sees genuine strandings.
  1315. What it does *not* do is replay the completion's side effects --
  1316. notifications, billing, auto-off. It restores the queue, which is the
  1317. harm being undone; the archive was updated by the normal path
  1318. regardless, since only the queue block refuses. A recovery that
  1319. silently re-fired notifications minutes late would be its own bug.
  1320. """
  1321. try:
  1322. async with async_session() as db:
  1323. result = await db.execute(
  1324. select(PrintQueueItem)
  1325. .where(PrintQueueItem.status == "printing")
  1326. .where(PrintQueueItem.printer_id.is_not(None))
  1327. )
  1328. items = list(result.scalars().all())
  1329. if not items:
  1330. self._terminal_since.clear()
  1331. return
  1332. now = time.monotonic()
  1333. seen_printers: set[int] = set()
  1334. closed = False
  1335. for item in items:
  1336. printer_id = item.printer_id
  1337. seen_printers.add(printer_id)
  1338. state = printer_manager.get_status(printer_id)
  1339. status = _terminal_queue_status(state)
  1340. if status is None:
  1341. self._terminal_since.pop(printer_id, None)
  1342. continue
  1343. since = self._terminal_since.setdefault(printer_id, now)
  1344. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1345. continue
  1346. item.status = status
  1347. item.completed_at = datetime.now(timezone.utc)
  1348. closed = True
  1349. # The printer is idle: nothing it prints next is this item's.
  1350. self._forget_unstarted_print(item.id, unless_printing=True)
  1351. logger.warning(
  1352. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1353. "closing it as %s. Its completion event was never matched to it, which blocks "
  1354. "every later job for this printer (#2829).",
  1355. item.id,
  1356. printer_id,
  1357. getattr(state, "state", None),
  1358. now - since,
  1359. status,
  1360. )
  1361. if closed:
  1362. await db.commit()
  1363. from backend.app.services.print_batch import refresh_batches_after
  1364. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1365. for printer_id in list(self._terminal_since):
  1366. if printer_id not in seen_printers:
  1367. del self._terminal_since[printer_id]
  1368. except Exception as e:
  1369. # Best-effort, same as the claim sweep beside it: a recovery path
  1370. # that can itself break the scheduler loop is worse than the strand.
  1371. logger.error("Stranded-item sweep failed: %s", e)
  1372. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1373. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1374. A claim is only ever held by a live dispatch coroutine, so when this
  1375. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1376. is stale. At startup that is trivially true — no coroutine survives a
  1377. restart. It is equally true on any later tick where no upload is running,
  1378. which is what makes this safe to repeat rather than only run once.
  1379. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1380. the database is briefly unreachable at exactly the moment dispatch ends,
  1381. the claim survives and the row is wedged out of the selection query. That
  1382. used to last until the next restart (#2702 follow-up, seen when
  1383. PostgreSQL refused a connection mid-dispatch).
  1384. ``_inflight`` is populated when the task is spawned, before the coroutine
  1385. claims its row, and pruned by a done-callback that cannot run before the
  1386. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1387. race window and needs no age threshold. A size-derived upload deadline
  1388. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1389. """
  1390. if self._inflight:
  1391. return
  1392. try:
  1393. async with async_session() as db:
  1394. res = await db.execute(
  1395. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1396. )
  1397. await db.commit()
  1398. if res.rowcount:
  1399. logger.info(
  1400. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1401. res.rowcount,
  1402. " at startup" if at_startup else "",
  1403. )
  1404. except Exception as exc:
  1405. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1406. def stop(self):
  1407. """Stop the scheduler."""
  1408. self._running = False
  1409. logger.info("Print scheduler stopped")
  1410. def forget_printer(self, printer_id: int) -> None:
  1411. """Drop what is kept for a deleted printer, so the next printer given its
  1412. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1413. would keep it out of dispatch for up to an hour.
  1414. A dispatch already in flight keeps its own state (_inflight, the preheat
  1415. pins, unconfirmed prints): it unwinds that when it ends.
  1416. """
  1417. for keyed in (
  1418. self._upload_backoff,
  1419. self._upload_refusals,
  1420. self._upload_refusal_kind,
  1421. self._upload_refusal_notified,
  1422. self._wake_failures,
  1423. self._drying_in_progress,
  1424. self._dispatch_holds,
  1425. self._chamber_history,
  1426. self._keep_warm,
  1427. self._terminal_since,
  1428. ):
  1429. keyed.pop(printer_id, None)
  1430. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1431. for key in [key for key in keyed if key[0] == printer_id]:
  1432. del keyed[key]
  1433. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1434. del self._sent_unstarted_print[item_id]
  1435. async def check_queue(self) -> bool:
  1436. """Check for prints ready to start.
  1437. Returns True if this pass dispatched at least one item, so the caller
  1438. can loop again quickly instead of sleeping the full interval (#2555).
  1439. """
  1440. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1441. self._filament_req_memo.clear()
  1442. self._unmatched_memo.clear()
  1443. async with async_session() as db:
  1444. # Check if shortest-job-first scheduling is enabled
  1445. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1446. # Get all pending items in the one order the queue page shows them
  1447. # in (#3200). The first eligible item takes a printer, so this order
  1448. # decides who wins a printer that a pinned job and an "Any <model>"
  1449. # job both want. It used to start with ``printer_id``, which made the
  1450. # lane outrank the position: SQLite sorts NULL first, so model-based
  1451. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1452. # Neither is what the user dragged into place.
  1453. if sjf_enabled:
  1454. # SJF: items already jumped get top priority (starvation guard),
  1455. # then sort by print_time ascending. Items with no print time go
  1456. # last, and position breaks ties.
  1457. result = await db.execute(
  1458. select(PrintQueueItem)
  1459. .where(PrintQueueItem.status == "pending")
  1460. # Never re-select a row a dispatch worker has already claimed
  1461. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1462. # below, and the guard that lets an orphaned claim be ignored
  1463. # until startup reconciliation clears it.
  1464. .where(PrintQueueItem.dispatching_at.is_(None))
  1465. # archive/library_file are read by the cross-model gate
  1466. # (#2578); eager-load once per pass instead of a lazy-load
  1467. # (which would raise in async) per item.
  1468. .options(
  1469. selectinload(PrintQueueItem.archive),
  1470. selectinload(PrintQueueItem.library_file),
  1471. # Cross-model candidates (#671), plus each candidate's file
  1472. # for the same cross-model gate. Lazy-loading either would
  1473. # raise in async.
  1474. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1475. )
  1476. .order_by(
  1477. PrintQueueItem.been_jumped.desc(),
  1478. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1479. PrintQueueItem.position,
  1480. PrintQueueItem.id,
  1481. )
  1482. )
  1483. else:
  1484. result = await db.execute(
  1485. select(PrintQueueItem)
  1486. .where(PrintQueueItem.status == "pending")
  1487. # Skip rows already claimed by a dispatch worker (#2615).
  1488. .where(PrintQueueItem.dispatching_at.is_(None))
  1489. .options(
  1490. selectinload(PrintQueueItem.archive),
  1491. selectinload(PrintQueueItem.library_file),
  1492. # Cross-model candidates (#671), plus each candidate's file
  1493. # for the same cross-model gate. Lazy-loading either would
  1494. # raise in async.
  1495. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1496. )
  1497. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1498. )
  1499. items = list(result.scalars().all())
  1500. # Drop rows whose upload is still in flight from an earlier pass
  1501. # (#2602). They stay `pending` until the upload finishes, so without
  1502. # this a fast tick would re-select and re-dispatch the same row.
  1503. # Belt-and-suspenders with the printer exclusion below.
  1504. if self._inflight:
  1505. inflight_ids = set(self._inflight)
  1506. items = [it for it in items if it.id not in inflight_ids]
  1507. # Read plate-clear setting once per queue check. Default MUST be
  1508. # False to match the schema (SettingsSchema.require_plate_clear
  1509. # defaults False) and the frontend (toggle + card badge both treat a
  1510. # missing value as off). When no settings row exists, a True default
  1511. # here re-enabled the plate-clear gate the UI showed as disabled,
  1512. # blocking dispatch to FINISH-state printers forever with no UI path
  1513. # to clear it (#1865).
  1514. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1515. # Dispatch and track scheduled drying runs (#2638)
  1516. await self._check_scheduled_dryings(db)
  1517. if not items:
  1518. # No dispatchable pending items — still check auto-drying on idle
  1519. # printers, but keep any printer with an upload still in flight
  1520. # from an earlier pass out of it (#2602): its print is imminent,
  1521. # so it must not be auto-dried in the gap before the row flips to
  1522. # printing. Report the pass as productive while uploads run so the
  1523. # loop stays on the fast interval.
  1524. #
  1525. # Also release any keep-warm holds that got orphaned by the queue
  1526. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1527. # this early return, so call it directly with an empty candidate
  1528. # set. Without this, a printer whose queued item was cancelled or
  1529. # deleted would keep its bed at target until the max-duration
  1530. # timeout expired.
  1531. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1532. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1533. await self._check_auto_drying(db, [], inflight_printers)
  1534. await self._check_filament_low(db)
  1535. await self._check_stock_forecast(db)
  1536. return bool(self._inflight)
  1537. logger.info(
  1538. "Queue check: found %d pending items: %s",
  1539. len(items),
  1540. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1541. )
  1542. # Forget jobs that left the queue since they were last checked.
  1543. pending_ids = {i.id for i in items}
  1544. self._short_hold_checked_at = {
  1545. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1546. }
  1547. # Seed busy_printers with printers that already have an item in 'printing'
  1548. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1549. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1550. # lag several seconds behind the print command, so the next check_queue
  1551. # tick still sees IDLE and would double-dispatch onto the same printer.
  1552. # Without this guard, two pending items targeting the same printer
  1553. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1554. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1555. busy_result = await db.execute(
  1556. select(PrintQueueItem.printer_id)
  1557. .where(PrintQueueItem.status == "printing")
  1558. .where(PrintQueueItem.printer_id.is_not(None))
  1559. )
  1560. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1561. # Why each printer left this pass, recorded where the decision is
  1562. # made rather than re-derived when the summary is logged. #3018's
  1563. # bundle shows what the old summary produced: "printer 1 not
  1564. # available -- connected=True, state=IDLE" immediately followed by a
  1565. # dispatch to printer 1. Two things went wrong at once. The line read
  1566. # live state at log time, which by then no longer matched the state
  1567. # the decision was made on; and `busy_printers` holds both printers
  1568. # that cannot take work and printers this pass has claimed for it,
  1569. # which are opposite facts. It is the first line anyone greps for
  1570. # "why did my item not go out", so it has to say which.
  1571. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1572. # Printers this pass is dispatching to. They are in busy_printers so
  1573. # nothing else in the pass targets them -- that is a reservation, not
  1574. # an obstruction, and the summary says so.
  1575. claimed_printers: set[int] = set()
  1576. def mark_busy(printer_id: int, reason: str) -> None:
  1577. """Take ``printer_id`` out of this pass, recording why.
  1578. First reason wins: a printer already excluded by a stronger fact
  1579. -- a print running on it -- must not be relabelled by a weaker
  1580. check that ran later and would have excluded it anyway.
  1581. """
  1582. busy_printers.add(printer_id)
  1583. busy_reasons.setdefault(printer_id, reason)
  1584. def claim_printer(printer_id: int) -> None:
  1585. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1586. claimed_printers.add(printer_id)
  1587. mark_busy(printer_id, "selected for dispatch in this pass")
  1588. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1589. # worded for a different audience: the log wants "still inside its
  1590. # post-dispatch hold window", the queue row wants to know the printer
  1591. # is taken and nothing is broken. Only the cases that would read wrong
  1592. # as a plain "Busy" are recorded here; the rest fall back to it.
  1593. item_hold_reasons: dict[int, str] = {}
  1594. # Names and models for the printers this pass may have to write a
  1595. # waiting reason about, read once rather than per skip per tick. The
  1596. # model-based branch already has its names from `_printers_for_model`.
  1597. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1598. pinned_printers: dict[int, tuple[str, str]] = {}
  1599. if pinned_printer_ids:
  1600. pinned_rows = await db.execute(
  1601. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1602. )
  1603. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1604. def printer_label(printer_id: int) -> str:
  1605. """What to call this printer in a queue row."""
  1606. entry = pinned_printers.get(printer_id)
  1607. return (entry[0] if entry else "") or f"printer {printer_id}"
  1608. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1609. """Record why *item* is not going out, in the words the queue row shows.
  1610. The fixed-printer branch's single writer for ``waiting_reason``
  1611. (#3074). Before this, the sensor interlock was the only thing that
  1612. wrote the field there, so an item pinned to a printer that was
  1613. merely printing sat at `pending` with nothing to show for it —
  1614. indistinguishable from a queue that had stopped working — while
  1615. the same job queued as "Any <model>" explained itself.
  1616. Every exit from that branch now calls this, which is also what
  1617. replaced the interlock's old habit of clearing the field up front:
  1618. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1619. because whichever exit runs next overwrites it and the dispatch
  1620. path clears it.
  1621. A notification goes out when this item starts asking for
  1622. something, and only then: the new reason needs the user, and what
  1623. it replaced did not. "What it replaced did not" has to include a
  1624. busy-only reason, not just an empty one. The sequence this branch
  1625. actually produces is a print running (``Busy: X1C-01``) and then
  1626. the plate it left behind (``Waiting for plate confirmation``), and
  1627. testing "was the field empty" would call that no transition at all
  1628. and stay quiet through the one case worth saying out loud.
  1629. The cost is that a printer dropping offline, coming back busy and
  1630. dropping again asks twice rather than once. That is the honest
  1631. reading — it went wrong twice — and the alternative was a rule
  1632. that never fired for the case this was built for.
  1633. *notify* is how a caller opts out. The sensor interlock does: it
  1634. has never sent this notification, and a change about what the
  1635. queue *displays* is not the place to start (#1148).
  1636. """
  1637. if item.waiting_reason == reason:
  1638. return
  1639. # Busy-only and empty are the same thing here: neither is the
  1640. # queue asking the user for anything.
  1641. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1642. item.waiting_reason = reason
  1643. await db.commit()
  1644. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1645. return
  1646. try:
  1647. job_name = await self._get_job_name(db, item)
  1648. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1649. await notification_service.on_queue_job_waiting(
  1650. job_name=job_name,
  1651. target_model=(entry[1] if entry else "") or "",
  1652. waiting_reason=reason,
  1653. db=db,
  1654. printer_id=item.printer_id,
  1655. )
  1656. except Exception as e:
  1657. # A queue that cannot say why it is waiting is the bug being
  1658. # fixed here; a queue that stops dispatching because a
  1659. # notification provider is down would be a worse one.
  1660. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1661. async def hold_for_printer(
  1662. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1663. ) -> None:
  1664. """Take *printer_id* out of this pass and tell the item's owner why."""
  1665. mark_busy(printer_id, log_reason)
  1666. item_hold_reasons.setdefault(printer_id, item_reason)
  1667. await hold_item(item, item_reason)
  1668. # Defense-in-depth (#1157): augment busy_printers with any printer
  1669. # still in its post-dispatch hold window. Empirically, the DB seed
  1670. # above can miss in-flight items in a multi-plate batch — same-file
  1671. # plates were being dispatched 30 s apart while the H2D was still
  1672. # digesting the first project_file. The hold is keyed in-memory and
  1673. # released by the watchdog on the success path, so it adds a layer
  1674. # that doesn't depend on DB row visibility or completion-callback
  1675. # timing.
  1676. for held_printer_id in list(self._dispatch_holds.keys()):
  1677. if self._printer_in_dispatch_hold(held_printer_id):
  1678. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1679. # Exclude printers whose upload is still in flight from an earlier
  1680. # pass (#2602). The row is `pending` until the upload finishes and
  1681. # the printing-state seed / dispatch hold above only arm once the
  1682. # upload completes, so this is what holds the printer (and, via
  1683. # busy_printers, its auto-drying) out of the pass during the upload.
  1684. for _task, inflight_pid in self._inflight.values():
  1685. if inflight_pid is not None:
  1686. mark_busy(inflight_pid, "an upload to it is still in flight")
  1687. # Snapshot taken here, before the item loop adds anything (#2801).
  1688. #
  1689. # The three sources above all mean the same thing: a print on this
  1690. # printer is running or imminent. Everything the loop adds below
  1691. # means only "the queue could not dispatch to it this pass", which
  1692. # is a different statement -- a printer waiting on a plate-clear
  1693. # acknowledgment, an offline printer, one with no matching file.
  1694. #
  1695. # Auto-drying must only see the first kind. Reading the whole set
  1696. # as "is currently printing" is what put a plate-held printer down
  1697. # the mid-print path: it capped the drying temperature, logged the
  1698. # cycle as (mid-print), and skipped the very gate that was supposed
  1699. # to hold it. The interlock block below already documents the same
  1700. # hazard and works around it by staying out of busy_printers; this
  1701. # generalises that workaround instead of repeating it per case.
  1702. dispatching_printers: set[int] = set(busy_printers)
  1703. # Printers whose last upload never reached them (#3210). After the
  1704. # snapshot above on purpose: such a printer is idle, not about to
  1705. # print, and auto-drying must keep treating it as idle.
  1706. now_mono = time.monotonic()
  1707. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1708. # can leave them out: there is no print to keep a bed warm for.
  1709. # Their holds are written silently: the refusal that put a printer
  1710. # here sent the "job waiting" notification for its run (#3409).
  1711. backoff_printers: set[int] = set()
  1712. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1713. if now_mono >= retry_at:
  1714. del self._upload_backoff[backoff_pid]
  1715. continue
  1716. backoff_printers.add(backoff_pid)
  1717. mark_busy(
  1718. backoff_pid,
  1719. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1720. )
  1721. item_hold_reasons.setdefault(
  1722. backoff_pid,
  1723. _refused_upload_hold_reason(printer_label(backoff_pid), self._upload_refusal_kind.get(backoff_pid)),
  1724. )
  1725. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1726. # enclosure door left open, say. The fixed-printer branch turns
  1727. # this into a waiting_reason the user can act on; the model-based
  1728. # branch hides these printers from the matcher so an "Any <model>"
  1729. # job runs on a sibling instead of queueing behind the held one.
  1730. #
  1731. # Deliberately NOT merged into busy_printers, even though that set
  1732. # already means "unavailable this pass". _check_auto_drying reads
  1733. # it as "is currently printing" and would put an idle-but-held
  1734. # printer down the mid-print drying path, which caps the drying
  1735. # temperature and skips the queue-only gating. A held printer is
  1736. # idle; it should dry exactly as it did before.
  1737. #
  1738. # Only sensors we actually read and found alerting appear here; see
  1739. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1740. # holds nothing.
  1741. interlocked: dict[int, str] = {}
  1742. try:
  1743. interlocked = await ha_sensor_manager.blocked_printers(db)
  1744. except Exception as e:
  1745. # Never let the interlock stop the queue running. A broken
  1746. # lookup means no holds, not no dispatches.
  1747. logger.warning("Home Assistant interlock check failed: %s", e)
  1748. interlocked = {}
  1749. # Printers a smart plug can bring back, read once for the whole pass
  1750. # (#2786). Used by the model-based branch both to word "Offline" in
  1751. # the waiting reason and to decide what the wake step may switch on.
  1752. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1753. # At most one power-on per queue check. Each one blocks this loop
  1754. # for the boot wait, so a queue of ten class-targeted jobs must not
  1755. # switch on ten printers inside a single pass — the next pass wakes
  1756. # the next one (#2786).
  1757. power_on_attempted = False
  1758. # Log skip reasons once per queue check (not per item)
  1759. skip_reasons: dict[str, int] = {}
  1760. # Items selected for dispatch in this pass, one per printer. The
  1761. # loop below only *decides* — the uploads happen afterwards, in
  1762. # parallel (#2555). See _dispatch_selected().
  1763. dispatch_ids: list[int] = []
  1764. # Library rows queued with `cleanup_library_after_dispatch` (the
  1765. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1766. # that prints them: the row is deleted and the 3MF is unlinked from
  1767. # disk. That was safe only because dispatch was serial. Run two of
  1768. # them against the same row at once and the second DELETE matches no
  1769. # row (StaleDataError), and the winner's unlink can pull the file out
  1770. # from under the loser's in-flight upload.
  1771. #
  1772. # Only the cleanup flag mutates the row. An ordinary library print
  1773. # just reads it, so the common fan-out — one file, many printers,
  1774. # which is exactly the reporter's workload — still goes out fully in
  1775. # parallel. Narrow the guard to the mutating case; do not serialise
  1776. # the case the whole fix exists for.
  1777. dispatch_libs: set[int] = set()
  1778. consumed_libs: set[int] = set()
  1779. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1780. """True if dispatching `candidate` now would race another item's cleanup."""
  1781. lib_id = candidate.library_file_id
  1782. if lib_id is None:
  1783. return False
  1784. if candidate.cleanup_library_after_dispatch:
  1785. # We would delete a row someone else in this pass is reading.
  1786. return lib_id in dispatch_libs
  1787. # Someone else in this pass will delete the row out from under us.
  1788. return lib_id in consumed_libs
  1789. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1790. lib_id = candidate.library_file_id
  1791. if lib_id is None:
  1792. return
  1793. dispatch_libs.add(lib_id)
  1794. if candidate.cleanup_library_after_dispatch:
  1795. consumed_libs.add(lib_id)
  1796. # Printer scope of each job's creator (#1727), so an "any <model>"
  1797. # job only lands on a printer its creator may use. Loaded lazily,
  1798. # once per creator per pass.
  1799. from backend.app.core.auth import is_auth_enabled
  1800. scope_auth_enabled = await is_auth_enabled(db)
  1801. creator_scopes: dict[int, PrinterScope] = {}
  1802. # Printers a model job passes over while drying blocks the queue,
  1803. # as a pinned job waits for its own. A parked timer never ends,
  1804. # so it does not hold (#2896).
  1805. drying_held: set[int] = (
  1806. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1807. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1808. else set()
  1809. )
  1810. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1811. if not scope_auth_enabled or user_id is None:
  1812. return ALL_PRINTERS
  1813. if user_id not in creator_scopes:
  1814. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1815. return creator_scopes[user_id]
  1816. for item in items:
  1817. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1818. if item.scheduled_time:
  1819. sched = item.scheduled_time
  1820. if sched.tzinfo is None:
  1821. sched = sched.replace(tzinfo=timezone.utc)
  1822. if sched > datetime.now(timezone.utc):
  1823. # Waiting on the clock, not on a printer.
  1824. await hold_item(item, None)
  1825. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1826. continue
  1827. # Skip items that require manual start, except an "any model"
  1828. # job held for low filament that another idle printer can now
  1829. # run: that one is moved there and carries on below (#3137).
  1830. if item.manual_start and not (
  1831. item.filament_short
  1832. and await self._release_short_model_hold(
  1833. db,
  1834. item,
  1835. busy_printers | interlocked.keys() | drying_held,
  1836. require_plate_clear,
  1837. await _creator_scope(item.created_by_id),
  1838. )
  1839. ):
  1840. # Waiting on the user, not on a printer. Cleared here because
  1841. # this is the last pass that will look at the row: a staged
  1842. # item never reaches the branches below again, so a reason
  1843. # left from before it was staged would stand forever (#3074).
  1844. # The one exception is the unmatched-filament hold, whose
  1845. # reason was written at staging and is why the item waits:
  1846. # it names the filament to load (#2799). Pressing start
  1847. # clears manual_start, and the branches below overwrite it.
  1848. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1849. await hold_item(item, keep)
  1850. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1851. continue
  1852. if item.printer_id and item.printer_id not in pinned_printers:
  1853. # Moved by the release above to a printer no row named when
  1854. # the labels were read.
  1855. moved_to = await self._get_printer(db, item.printer_id)
  1856. if moved_to is not None:
  1857. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1858. if item.printer_id:
  1859. # Its creator may no longer use this printer (#1727): an
  1860. # admin took it away from their group after the job was
  1861. # queued, say to keep it free for a training session. Held,
  1862. # not failed, so it starts if access comes back or the user
  1863. # moves it to a printer they still have.
  1864. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1865. await hold_item(
  1866. item,
  1867. "Its owner no longer has access to this printer — move it to another printer",
  1868. notify=False,
  1869. )
  1870. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1871. continue
  1872. # Held by a sensor interlock (#1148). Checked before the
  1873. # busy_printers test that would otherwise swallow it
  1874. # silently — "waiting for a printer" and "waiting for you
  1875. # to shut the enclosure" need to read differently, and only
  1876. # one of them is something the user can fix.
  1877. #
  1878. # It used to be the only thing that wrote a waiting_reason on
  1879. # this branch, and it cleared the field up front so a lifted
  1880. # hold could not leave a shut door reading "Waiting on
  1881. # Enclosure Door". `hold_item` carries that guarantee now —
  1882. # every exit below writes — so the clear is gone and the
  1883. # interlock is an ordinary hold like the rest (#3074).
  1884. interlock_reason = interlocked.get(item.printer_id)
  1885. if interlock_reason:
  1886. # Silent, exactly as it has always been. #1148 built this
  1887. # as a hold that shows on the row, never as an alert, and
  1888. # routing it through the shared writer must not quietly
  1889. # turn every open door into a notification.
  1890. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1891. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1892. continue
  1893. # Specific printer assignment (existing behavior)
  1894. if item.printer_id in busy_printers:
  1895. # Whatever took the printer out of this pass — a print
  1896. # already running on it, a post-dispatch hold, an upload
  1897. # still in flight, an item ahead of this one in the same
  1898. # pass — reads the same way from the queue: the printer is
  1899. # taken and this item is in line for it. The exceptions
  1900. # that do not (an offline printer, say) recorded their own
  1901. # wording in `item_hold_reasons` when they held it.
  1902. await hold_item(
  1903. item,
  1904. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1905. notify=item.printer_id not in backoff_printers,
  1906. )
  1907. continue
  1908. # Check if printer is idle
  1909. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1910. printer_connected = printer_manager.is_connected(item.printer_id)
  1911. # If printer not connected, try to power on via smart plug
  1912. if not printer_connected:
  1913. plugs = await self._get_smart_plugs(db, item.printer_id)
  1914. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1915. if auto_on_plugs:
  1916. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1917. # Power on using the plug that actually feeds the printer, and
  1918. # wait for it to boot on that one only (#2629).
  1919. primary_plug = self._pick_power_plug(auto_on_plugs)
  1920. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1921. if powered_on:
  1922. # Also turn on any remaining auto_on plugs (e.g., filter)
  1923. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1924. try:
  1925. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1926. if await service.turn_on(extra_plug):
  1927. await publish_plug_state(
  1928. extra_plug.id,
  1929. extra_plug.name,
  1930. extra_plug.printer_id,
  1931. on=True,
  1932. ha_entity_id=extra_plug.ha_entity_id,
  1933. )
  1934. logger.info(
  1935. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1936. )
  1937. except Exception as e:
  1938. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1939. printer_connected = True
  1940. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1941. else:
  1942. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1943. await hold_for_printer(
  1944. item,
  1945. item.printer_id,
  1946. "smart-plug power-on failed",
  1947. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1948. )
  1949. continue
  1950. else:
  1951. # No plug or auto_on disabled. Worded exactly as the
  1952. # model-based branch words it (#2786): this is the one
  1953. # entry on that list the user has to act on, because
  1954. # Bambuddy will never switch this printer on itself.
  1955. await hold_for_printer(
  1956. item,
  1957. item.printer_id,
  1958. "offline, with no smart plug to power it on",
  1959. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1960. )
  1961. continue
  1962. # Check if printer is idle (busy with another print)
  1963. if not printer_idle:
  1964. await hold_for_printer(
  1965. item,
  1966. item.printer_id,
  1967. "not idle",
  1968. self._pinned_hold_reason(
  1969. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1970. ),
  1971. )
  1972. continue
  1973. # Drying blocks the queue, if the user asked it to. A hold
  1974. # is a skip like any other, so it belongs here with the
  1975. # rest of the availability checks.
  1976. # A parked timer (#2896) never ends, so it must not hold the
  1977. # queue; it stays tracked so the stop paths still reach it.
  1978. if (
  1979. self._drying_in_progress.get(item.printer_id)
  1980. and not self._drying_is_only_parked(item.printer_id)
  1981. and await self._get_bool_setting(db, "queue_drying_block")
  1982. ):
  1983. # Busy-shaped on purpose: the cycle ends on its own and
  1984. # the job goes out, so there is nothing to alert about.
  1985. await hold_for_printer(
  1986. item,
  1987. item.printer_id,
  1988. "drying, and drying is set to block the queue",
  1989. f"Busy: {printer_label(item.printer_id)} (drying)",
  1990. )
  1991. continue
  1992. # Check condition (previous print success)
  1993. if item.require_previous_success:
  1994. if not await self._check_previous_success(db, item):
  1995. item.status = "skipped"
  1996. item.error_message = "Previous print failed or was aborted"
  1997. item.completed_at = datetime.now(timezone.utc)
  1998. # Not pending any more, so not waiting for anything.
  1999. item.waiting_reason = None
  2000. await db.commit()
  2001. logger.info("Skipped queue item %s - previous print failed", item.id)
  2002. # Send notification
  2003. job_name = await self._get_job_name(db, item)
  2004. printer = await self._get_printer(db, item.printer_id)
  2005. await notification_service.on_queue_job_skipped(
  2006. job_name=job_name,
  2007. printer_id=item.printer_id,
  2008. printer_name=printer.name if printer else "Unknown",
  2009. reason="Previous print failed or was aborted",
  2010. db=db,
  2011. )
  2012. continue
  2013. # Resolve the AMS mapping when it's missing OR unresolved
  2014. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  2015. # frontend status-load race can persist [-1] (#2589) — and
  2016. # must be recomputed from live trays rather than trusted.
  2017. if await _edited_since_loaded(db, item):
  2018. continue
  2019. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  2020. if unmappable:
  2021. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  2022. continue
  2023. # Filament-deficit pre-dispatch check (#1496). If the
  2024. # assigned spool can't satisfy any required slot grams,
  2025. # promote the item to manual_start so the user must
  2026. # acknowledge via the ▶ button (which re-checks live).
  2027. if await self._block_on_filament_deficit(db, item):
  2028. # Now staged for the user to start by hand, and the row
  2029. # shows the filament-short badge instead. Cleared because
  2030. # a staged item never reaches this branch again.
  2031. await hold_item(item, None)
  2032. continue
  2033. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  2034. # than let the printer pick a substitute for a slot the
  2035. # matcher could not resolve on this printer.
  2036. if await self._block_on_unmatched_filament(db, item):
  2037. continue
  2038. # Hold this item back for the next pass rather than racing
  2039. # another dispatch over the same transient library row. The
  2040. # printer is still marked busy so a later item does not jump
  2041. # its place in this printer's queue.
  2042. if _library_row_conflict(item):
  2043. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2044. await hold_for_printer(
  2045. item,
  2046. item.printer_id,
  2047. "holding its place while another item releases a library row",
  2048. f"Busy: {printer_label(item.printer_id)}",
  2049. )
  2050. continue
  2051. # Print takes priority: stop a cycle Bambuddy armed, now
  2052. # that this item is definitely going out.
  2053. #
  2054. # Placement is the whole point (#2801). This used to sit up
  2055. # with the availability checks, inside the not-idle branch
  2056. # -- so it fired only on the passes where the print was NOT
  2057. # going to start, and never on the ones where it was.
  2058. # Drying is not one of the things `_is_printer_idle` looks
  2059. # at, so a stop could never have unblocked that printer
  2060. # anyway; the cycle was spent for nothing, auto-drying
  2061. # re-armed on the next tick, and a plate left
  2062. # unacknowledged turned that into a loop on the scheduler
  2063. # interval. Every skip between there and here -- a failed
  2064. # previous print, an unmappable item, a filament deficit, a
  2065. # contested library row -- is another way to lose a cycle
  2066. # for a print that never happens, which is why this waits
  2067. # until the decision is actually made.
  2068. if self._drying_in_progress.get(
  2069. item.printer_id
  2070. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2071. await self._stop_drying(item.printer_id)
  2072. # Queue the dispatch instead of running it here — see
  2073. # _dispatch_selected(). busy_printers still gets the printer
  2074. # immediately, so nothing else in this pass can target it.
  2075. #
  2076. # The reason goes first: this item is not waiting for anything
  2077. # any more, and the model-based branch clears its own at the
  2078. # equivalent moment (#3074).
  2079. await hold_item(item, None)
  2080. _claim_library_row(item)
  2081. dispatch_ids.append(item.id)
  2082. claim_printer(item.printer_id)
  2083. # SJF starvation guard: mark items that were jumped
  2084. if sjf_enabled and item.print_time_seconds is not None:
  2085. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2086. for other in items:
  2087. if (
  2088. other.id != item.id
  2089. and other.id not in dispatch_ids
  2090. and other.status == "pending"
  2091. and _could_take_printer(other, item.printer_id, pinned_model)
  2092. and not other.been_jumped
  2093. and other.position < item.position
  2094. and (
  2095. other.print_time_seconds is None
  2096. or other.print_time_seconds > item.print_time_seconds
  2097. )
  2098. ):
  2099. other.been_jumped = True
  2100. await db.commit()
  2101. elif item.target_model or item.variants:
  2102. # Model-based assignment - find any idle printer of matching model.
  2103. # A plain model-based item has exactly one candidate, built from
  2104. # its own columns. A cross-model item (#671) has one per sliced
  2105. # variant and takes the first that matches, walking them in the
  2106. # user's priority order so the pick is reproducible when more
  2107. # than one printer is free in the same pass.
  2108. candidates = _candidates_for(item)
  2109. item_scope = await _creator_scope(item.created_by_id)
  2110. printer_id = None
  2111. chosen: _ModelCandidate | None = None
  2112. per_model_reasons: list[tuple[str | None, str]] = []
  2113. # Candidates that cleared the cross-model gate below. The
  2114. # smart-plug wake step may only consider these — waking a
  2115. # printer for a file that can never legally run on it is
  2116. # worse than not waking at all (#2786).
  2117. wakeable_candidates: list[_ModelCandidate] = []
  2118. # Printers passed over because their last print failed.
  2119. gate_blocked: set[int] = set()
  2120. if not candidates:
  2121. # Every candidate file has been deleted or trashed out from
  2122. # under this item. Hold it with something the user can act
  2123. # on rather than letting it look dispatchable forever.
  2124. per_model_reasons.append(
  2125. (
  2126. item.target_model,
  2127. "Every file for this job has been deleted — add a file back or remove the item",
  2128. )
  2129. )
  2130. for candidate in candidates:
  2131. effective_types, filament_overrides = _filament_constraints(candidate)
  2132. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2133. # for an incompatible model to a printer, no matter how the
  2134. # row got into the DB (old rows, direct API writes). Held
  2135. # as pending with an actionable waiting_reason — the user
  2136. # fixes it by editing the item's target model.
  2137. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2138. per_model_reasons.append(
  2139. (
  2140. candidate.target_model,
  2141. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2142. f"{candidate.target_model} — edit the item and fix its target model",
  2143. )
  2144. )
  2145. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2146. continue
  2147. wakeable_candidates.append(candidate)
  2148. async def is_short(
  2149. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2150. ) -> bool:
  2151. # The check reads the file and plate off the item,
  2152. # so it must hold this candidate's. Resolving is
  2153. # safe to repeat, and the winner is resolved again
  2154. # below.
  2155. self._resolve_variant(item, candidate)
  2156. return await self._filament_short_on(db, item, pid)
  2157. async def unmatched_on(
  2158. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2159. ) -> list[str]:
  2160. self._resolve_variant(item, candidate)
  2161. return await self._unmatched_on(db, item, pid)
  2162. while True:
  2163. match_id, match_reason = await self._find_idle_printer_for_model(
  2164. db,
  2165. candidate.target_model,
  2166. # Sensor-held printers are unavailable to the
  2167. # matcher but stay out of busy_printers itself
  2168. # (#1148) — see where `interlocked` is built.
  2169. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2170. effective_types,
  2171. item.target_location,
  2172. filament_overrides=filament_overrides,
  2173. require_plate_clear=require_plate_clear,
  2174. wakeable_ids=wakeable_printer_ids,
  2175. printer_scope=item_scope,
  2176. is_short=is_short,
  2177. drying_ids=drying_held,
  2178. unmatched_on=unmatched_on,
  2179. refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
  2180. )
  2181. # "Only if the previous print succeeded" is about the
  2182. # printer the job lands on: one whose last print failed
  2183. # is passed over for another of the model.
  2184. if (
  2185. match_id
  2186. and item.require_previous_success
  2187. and not await self._check_previous_success(db, item, printer_id=match_id)
  2188. ):
  2189. gate_blocked.add(match_id)
  2190. continue
  2191. break
  2192. if match_id:
  2193. printer_id = match_id
  2194. chosen = candidate
  2195. break
  2196. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2197. # Nothing is available and nothing has been woken this pass:
  2198. # switch one matching printer on. Assignment is left to the
  2199. # next pass, which sees the booted printer's live state
  2200. # instead of guessing at it seconds after connect (#2786).
  2201. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2202. woken_id, attempted_id = await self._wake_printer_for_model(
  2203. db,
  2204. wakeable_candidates,
  2205. item.target_location,
  2206. busy_printers | interlocked.keys(),
  2207. wakeable_printer_ids,
  2208. require_plate_clear,
  2209. printer_scope=item_scope,
  2210. )
  2211. # An attempt spends the pass's one wake whether or not
  2212. # it worked: it has already blocked the queue loop for
  2213. # the boot wait. A failed printer is held out of later
  2214. # passes by its own cool-off, deliberately NOT by
  2215. # busy_printers — it is off, not busy, and labelling it
  2216. # busy would both misdescribe it in every later item's
  2217. # waiting reason and suppress the notification, since
  2218. # an all-busy reason is treated as needing no action.
  2219. power_on_attempted = attempted_id is not None
  2220. if woken_id is not None:
  2221. # Hold this item back rather than dispatching onto a
  2222. # printer whose AMS has not reported yet.
  2223. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2224. continue
  2225. if printer_id is None and gate_blocked:
  2226. # The matcher reports the printers passed over as busy;
  2227. # what holds the job is their failed last print.
  2228. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2229. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2230. # Fold the winning variant's file and settings onto the item
  2231. # before anything else looks at them — the guards below and
  2232. # every step of the dispatch read the item's own columns.
  2233. if chosen is not None:
  2234. self._resolve_variant(item, chosen)
  2235. # Update waiting_reason if changed and send notification when first waiting
  2236. if item.waiting_reason != waiting_reason:
  2237. was_waiting = item.waiting_reason is not None
  2238. previous_reason = item.waiting_reason
  2239. item.waiting_reason = waiting_reason
  2240. await db.commit()
  2241. # Send waiting notification only when transitioning to waiting state
  2242. # and the reason requires user action (not just "all printers busy")
  2243. # Also when a job that only waited for a busy printer
  2244. # now waits on something the user has to do.
  2245. if (
  2246. waiting_reason
  2247. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2248. and not _asks_nothing_new(waiting_reason)
  2249. ):
  2250. job_name = await self._get_job_name(db, item)
  2251. await notification_service.on_queue_job_waiting(
  2252. job_name=job_name,
  2253. target_model=_candidate_model_label(candidates) or item.target_model,
  2254. waiting_reason=waiting_reason,
  2255. db=db,
  2256. )
  2257. if printer_id:
  2258. # Before claiming the printer: hold back rather than race
  2259. # another dispatch over the same transient library row.
  2260. # Checked here so a held item does not get a printer
  2261. # assigned and then sit on it. See _library_row_conflict().
  2262. #
  2263. # No busy_printers.add() here, unlike the fixed-printer
  2264. # branch above: that one protects its printer's own queue
  2265. # ordering, but this item was never assigned to `printer_id`
  2266. # — the matcher merely offered it. Marking it busy would
  2267. # strand an idle printer for the rest of the pass.
  2268. if _library_row_conflict(item):
  2269. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2270. continue
  2271. if await _edited_since_loaded(db, item):
  2272. continue
  2273. # Assign printer and start - clear waiting reason
  2274. item.printer_id = printer_id
  2275. item.waiting_reason = None
  2276. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2277. # Send assignment notification
  2278. job_name = await self._get_job_name(db, item)
  2279. printer = await self._get_printer(db, printer_id)
  2280. await notification_service.on_queue_job_assigned(
  2281. job_name=job_name,
  2282. printer_id=printer_id,
  2283. printer_name=printer.name if printer else "Unknown",
  2284. target_model=item.target_model,
  2285. db=db,
  2286. )
  2287. # A mapping on this item was not made for the printer just
  2288. # picked: it came with a job moved here from a fixed
  2289. # printer, or from a variant. Its tray IDs can name a
  2290. # tray of the right type in another colour here, which
  2291. # the fit check lets through (#3239). Match afresh, by
  2292. # type and colour.
  2293. if item.ams_mapping:
  2294. logger.info(
  2295. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2296. item.id,
  2297. item.ams_mapping,
  2298. printer_id,
  2299. )
  2300. item.ams_mapping = None
  2301. # On a nozzle-rack printer its own nozzle mapping likewise
  2302. # (set through the API or an order's plate spec): it names
  2303. # rack positions, and the dispatch sends a stored one as-is
  2304. # instead of resolving this printer's rack. Elsewhere it
  2305. # holds extruder indices, the same on every printer of the
  2306. # model (an H2D VP keeps the slicer's for that reason), and
  2307. # one that came with the chosen variant belongs to that
  2308. # variant's file: both stay.
  2309. if (
  2310. (chosen is None or chosen.variant is None)
  2311. and printer is not None
  2312. and is_nozzle_rack_model(printer.model)
  2313. ):
  2314. item.nozzle_mapping = None
  2315. # Resolve the AMS mapping for the assigned printer. It is
  2316. # always missing here, so this computes it, and it also
  2317. # self-heals a bogus stored [-1] (#2589).
  2318. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2319. if unmappable:
  2320. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2321. continue
  2322. # Filament-deficit pre-dispatch check (#1496).
  2323. if await self._block_on_filament_deficit(db, item):
  2324. continue
  2325. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2326. # selection already filters on filament type, so this is a
  2327. # backstop for an AMS that changed between assignment and
  2328. # dispatch, and for a type loaded on the wrong nozzle.
  2329. # The assignment made above is released with the hold —
  2330. # this item asked for a model, not this printer.
  2331. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2332. continue
  2333. # As for a pinned job: drying stops once the print is
  2334. # decided, unless it may run through it.
  2335. if self._drying_in_progress.get(
  2336. printer_id
  2337. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2338. await self._stop_drying(printer_id)
  2339. _claim_library_row(item)
  2340. dispatch_ids.append(item.id)
  2341. claim_printer(printer_id)
  2342. # SJF starvation guard: mark items that were jumped
  2343. if sjf_enabled and item.print_time_seconds is not None:
  2344. for other in items:
  2345. if (
  2346. other.id != item.id
  2347. and other.id not in dispatch_ids
  2348. and other.status == "pending"
  2349. and _could_take_printer(other, printer_id, item.target_model)
  2350. and not other.been_jumped
  2351. and other.position < item.position
  2352. and (
  2353. other.print_time_seconds is None
  2354. or other.print_time_seconds > item.print_time_seconds
  2355. )
  2356. ):
  2357. other.been_jumped = True
  2358. await db.commit()
  2359. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2360. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2361. # skip summary that only lands after the transfers have finished is
  2362. # useless for working out why an item did not go out.
  2363. if skip_reasons:
  2364. logger.info("Queue skip summary: %s", skip_reasons)
  2365. for pid in sorted(busy_printers):
  2366. reason = busy_reasons.get(pid, "no reason recorded")
  2367. if pid in claimed_printers:
  2368. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2369. continue
  2370. # The three live fields stay, because they are what someone
  2371. # reading a bundle wants next -- but they are labelled as read
  2372. # now, not as the state the decision was made on, which is what
  2373. # made the old line contradict itself.
  2374. state = printer_manager.get_status(pid)
  2375. logger.info(
  2376. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2377. pid,
  2378. reason,
  2379. printer_manager.is_connected(pid),
  2380. state.state if state else "NO_STATUS",
  2381. printer_manager.is_awaiting_plate_clear(pid),
  2382. )
  2383. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2384. # selection and `_launch_uploads`, so anything raising here would
  2385. # discard this tick's selections — computed AMS mappings and all —
  2386. # and, on a persistent fault, stop the queue dispatching entirely.
  2387. # Same reasoning as the deficit check's guard below: never let an
  2388. # auxiliary check wedge the queue. The bed simply stays wherever it
  2389. # was, and the next tick tries again.
  2390. try:
  2391. await self._apply_keep_warm(
  2392. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2393. )
  2394. except Exception as e:
  2395. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2396. # Read the concurrency limit BEFORE the commit below, not inside
  2397. # _dispatch_selected(). A SELECT on this session after the commit
  2398. # implicitly opens a fresh transaction that nothing then closes, and
  2399. # it would stay open for the whole dispatch — minutes of "idle in
  2400. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2401. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2402. # checkpointed while every dispatch is writing to it.
  2403. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2404. # Selection is done; every decision above is recorded on `db`
  2405. # (model-based printer assignment, computed ams_mapping). Flush it
  2406. # before the dispatch tasks open their own sessions, or they will
  2407. # read a row that still says printer_id=None. This also releases the
  2408. # connection back to the pool for the duration of the dispatch.
  2409. await db.commit()
  2410. if dispatch_ids:
  2411. item_printers = {it.id: it.printer_id for it in items}
  2412. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2413. # Auto-drying: start drying on idle printers that have no pending queue items
  2414. await self._check_auto_drying(db, items, dispatching_printers)
  2415. # Low filament: alert on assigned spools that have crossed their
  2416. # low-stock threshold (#2913). Runs on both paths out of this method
  2417. # for the same reason auto-drying does — an empty queue does not mean
  2418. # the spools in the printers stopped mattering.
  2419. await self._check_filament_low(db)
  2420. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2421. # is about to run out before a replenishment could arrive (#2955).
  2422. await self._check_stock_forecast(db)
  2423. # Keep the loop on the fast interval while any upload is in flight so
  2424. # a slot freed mid-tick refills within seconds rather than after the
  2425. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2426. # deferred because the pool was full) also counts as productive.
  2427. return bool(dispatch_ids) or bool(self._inflight)
  2428. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2429. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2430. Dispatch used to happen inline in the selection loop: ``await
  2431. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2432. performs the FTP upload, that serialized every printer behind every
  2433. other printer's transfer even though the printers are independent
  2434. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2435. gather was awaited before ``check_queue`` returned, so the run loop
  2436. stayed blocked until the *slowest* upload in the batch finished — a
  2437. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2438. 93-printer farm even as other printers came free (#2602).
  2439. Each upload now runs as an independent background task tracked in
  2440. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2441. `pending` until their upload completes) and their printers from the
  2442. next pass's selection, and this method launches at most
  2443. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2444. the next fast tick instead of waiting out the whole batch. The bound
  2445. exists because the printers are independent but the host is not: each
  2446. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2447. file handle.
  2448. The no-overlapping-dispatch invariant the batch-await used to provide
  2449. is now carried by the in-flight exclusion in check_queue. Everything
  2450. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2451. per-printer hold, and each item's independent failure handling — still
  2452. lives in ``_start_print`` and runs per task exactly as before.
  2453. Synchronous on purpose: it registers every launched task into
  2454. ``self._inflight`` before returning, so the next (sequential) tick sees
  2455. an accurate in-flight count with no interleaving await.
  2456. """
  2457. free = limit - len(self._inflight)
  2458. if free <= 0:
  2459. logger.info(
  2460. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2461. len(self._inflight),
  2462. limit,
  2463. len(item_ids),
  2464. item_ids,
  2465. )
  2466. return
  2467. to_launch = item_ids[:free]
  2468. deferred = item_ids[free:]
  2469. logger.info(
  2470. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2471. len(to_launch),
  2472. len(self._inflight),
  2473. limit,
  2474. f" — deferring {deferred} to a later tick" if deferred else "",
  2475. )
  2476. for item_id in to_launch:
  2477. task = spawn_background_task(
  2478. self._dispatch_one(item_id, item_printers.get(item_id)),
  2479. name=f"queue-upload-{item_id}",
  2480. )
  2481. self._inflight[item_id] = (task, item_printers.get(item_id))
  2482. # Prune on completion so the freed slot is refillable next tick.
  2483. # spawn_background_task already logs any uncaught exception; this
  2484. # only reclaims the pool slot (fires on success, failure, or cancel).
  2485. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2486. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2487. """Upload + start one queue item in its own session (pool worker, #2602).
  2488. Its own session: pool workers run concurrently and an AsyncSession is
  2489. not safe to share across tasks; it also keeps a slow upload from pinning
  2490. the scheduler's session (and, on SQLite, its transaction) open for the
  2491. transfer's duration.
  2492. ``selected_printer_id`` is the printer this item was selected for, taken
  2493. from the same snapshot the caller used. It exists so the preheat pin can
  2494. be unwound on the paths that never reach the ``finally`` below — see the
  2495. claim failure a few lines down. Optional so the direct-call tests keep
  2496. working; when it is absent those paths simply behave as they did before.
  2497. """
  2498. async with async_session() as item_db:
  2499. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2500. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2501. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2502. # routes reject reassignment (409), so printer_id can't change out from
  2503. # under the in-flight upload and split the queue row from the
  2504. # archive/expected-print/physical command.
  2505. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2506. logger.info(
  2507. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2508. item_id,
  2509. )
  2510. # This return is outside the try/finally below, so the rollback
  2511. # has to happen here. Selecting this item already handed any
  2512. # keep-warm hold on its printer over to the preheat pin
  2513. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2514. # unwind it. Bailing without doing so leaves the bed hot with
  2515. # nothing tracking it: the keep-warm entry is gone, so the
  2516. # max-duration cap no longer applies, and if this was the
  2517. # printer's last pending item nothing else will ever turn it
  2518. # off. Reachable whenever a cancel or delete lands between
  2519. # selection and the claim.
  2520. if selected_printer_id is not None:
  2521. self._rollback_preheat_pin(item_id, selected_printer_id)
  2522. return
  2523. # Seeded from the caller's snapshot so the `item vanished` return
  2524. # below still unwinds the pin; overwritten with the row's own
  2525. # printer_id as soon as we have it.
  2526. item_printer_id: int | None = selected_printer_id
  2527. try:
  2528. item = await item_db.get(PrintQueueItem, item_id)
  2529. if not item:
  2530. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2531. return
  2532. item_printer_id = item.printer_id
  2533. await self._start_print(item_db, item)
  2534. finally:
  2535. # Undo an expected-print registration whose print command never
  2536. # went out. One choke point covers every way `_start_print` can
  2537. # end without sending: a raised exception (a DB failure mid-
  2538. # dispatch is the reported case), an early return, a cancel
  2539. # winning the #1853 CAS, or `start_print()` returning False.
  2540. # A confirmed send removes the entry itself, so this is a no-op
  2541. # on the happy path.
  2542. self._rollback_unconfirmed_expected_print(item_id)
  2543. # Likewise the print user it set: the printer's next print is
  2544. # not this item's.
  2545. self._rollback_unconfirmed_print_user(item_id)
  2546. # Its archive is no longer held for it (archive_work).
  2547. self._release_held_archive(item_id)
  2548. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2549. # reservation survives only after start_print() accepted the
  2550. # command. Failure, cancellation, deferral, and exceptions all
  2551. # release it here.
  2552. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2553. # Unwind preheat state (bed/chamber/airduct) if the
  2554. # dispatch aborted before the print's own gcode took over.
  2555. # `_start_print` clears the pin on successful `start_print()`;
  2556. # anything still present here is by definition an aborted
  2557. # dispatch and gets rolled back so the printer isn't left
  2558. # heating for a job that isn't happening.
  2559. if item_printer_id is not None:
  2560. self._rollback_preheat_pin(item_id, item_printer_id)
  2561. # The cancellation flag only has meaning while this dispatch is
  2562. # running; drop it so the set cannot grow without bound and a
  2563. # re-queued item never inherits a stale cancellation.
  2564. self._cancelled_dispatches.discard(item_id)
  2565. # Release the claim on every exit. Once dispatch has finished the
  2566. # row's status carries the lock (printing/failed/cancelled are all
  2567. # != pending), so the token is only needed for the duration of the
  2568. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2569. # dispatchable again on the next tick.
  2570. await self._clear_dispatch_claim(item_db, item_id)
  2571. async def _requeue_after_upload_refused(
  2572. self,
  2573. db: AsyncSession,
  2574. item: PrintQueueItem,
  2575. printer: Printer,
  2576. error_msg: str,
  2577. toast_uid: int | None,
  2578. kind: FtpFailureKind,
  2579. ) -> None:
  2580. """Put an item back in the queue after its file never reached the printer (#3210).
  2581. The printer goes into `_upload_backoff`, which keeps every item away
  2582. from it until the window ends. The window grows with each refusal in a
  2583. row; see ``_upload_backoff_seconds``.
  2584. An item pinned to this printer keeps it, waits there, and is the one
  2585. that knocks again. An item for "Any <model>" goes back to the pool
  2586. instead, so another printer of the model can take it (#3409). Only the
  2587. assignment goes: the next model assignment drops whatever on the row
  2588. was worked out for one printer, as it does for every model job.
  2589. The first refusal in a run sends the one "Job waiting" notification,
  2590. and a later one only if it asks for something else (a card after a
  2591. dropped connection). It cannot wait for the hold the way it used to: a
  2592. released item is not held on this printer, so nothing would say why
  2593. it stopped. A job cancelled or moved during the upload sends none.
  2594. `dispatch_attempts` is not charged: that budget bounds a printer that
  2595. takes the file and then never starts, which this is not.
  2596. """
  2597. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2598. self._upload_refusals[printer.id] = refusals
  2599. self._upload_refusal_kind[printer.id] = kind
  2600. backoff = _upload_backoff_seconds(refusals)
  2601. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2602. released = False
  2603. if item.target_model:
  2604. # Only while it is still pending on this printer: a cancel, or a
  2605. # move the user made during the upload, stands.
  2606. result = cast(
  2607. CursorResult,
  2608. await db.execute(
  2609. update(PrintQueueItem)
  2610. .where(PrintQueueItem.id == item.id)
  2611. .where(PrintQueueItem.status == "pending")
  2612. .where(PrintQueueItem.printer_id == printer.id)
  2613. .values(printer_id=None, error_message=None)
  2614. .execution_options(synchronize_session=False)
  2615. ),
  2616. )
  2617. await db.commit()
  2618. released = result.rowcount > 0
  2619. elif item.error_message:
  2620. # The row is still `pending` -- it only moves to `printing` after a
  2621. # successful upload -- so there is no status to write back. Writing
  2622. # one anyway would undo a cancel that landed during the upload.
  2623. item.error_message = None
  2624. await db.commit()
  2625. logger.warning(
  2626. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue%s; "
  2627. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2628. item.id,
  2629. printer.id,
  2630. printer.name,
  2631. error_msg,
  2632. " and returned to the pool" if released else "",
  2633. refusals,
  2634. backoff,
  2635. )
  2636. reason = _refused_upload_hold_reason(printer.name or f"printer {printer.id}", kind)
  2637. if self._upload_refusal_notified.get(printer.id) != reason and await self._still_waiting_on(
  2638. db, item.id, None if released else printer.id
  2639. ):
  2640. self._upload_refusal_notified[printer.id] = reason
  2641. try:
  2642. await notification_service.on_queue_job_waiting(
  2643. job_name=await self._get_job_name(db, item),
  2644. target_model=item.target_model or printer.model or "",
  2645. waiting_reason=reason,
  2646. db=db,
  2647. printer_id=printer.id,
  2648. )
  2649. except Exception as e:
  2650. # The job is safe in the queue either way.
  2651. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  2652. try:
  2653. # Closes the dispatch toast for this attempt. Without it the toast
  2654. # keeps spinning on an upload that has ended.
  2655. await ws_manager.send_queue_item_failed(
  2656. user_id=toast_uid,
  2657. queue_item_id=item.id,
  2658. printer_id=printer.id,
  2659. reason="upload_failed",
  2660. )
  2661. except Exception:
  2662. pass # toast is best-effort
  2663. @staticmethod
  2664. async def _still_waiting_on(db: AsyncSession, item_id: int, printer_id: int | None) -> bool:
  2665. """Whether the item is still pending, on *printer_id* (None: unassigned)."""
  2666. row = (
  2667. await db.execute(
  2668. select(PrintQueueItem.status, PrintQueueItem.printer_id).where(PrintQueueItem.id == item_id)
  2669. )
  2670. ).one_or_none()
  2671. return row is not None and row.status == "pending" and row.printer_id == printer_id
  2672. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2673. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2674. if printer_id is not None:
  2675. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2676. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2677. """Withdraw the expected print and print user of a sent print that never started.
  2678. Both tell the rest of Bambuddy that the printer's next print is this
  2679. item's: left behind, a print started by hand later is taken for it.
  2680. With ``unless_printing``, a printer that is printing after all keeps
  2681. them, as that print is most likely this one starting late.
  2682. ``keep_expected`` withdraws only the print user, which vouches for any
  2683. print on the printer. The expected print names this item's file, so a
  2684. late start of it is still matched to its archive.
  2685. """
  2686. sent = self._sent_unstarted_print.get(item_id)
  2687. if sent is None:
  2688. return
  2689. printer_id, remote_filename, archive_id = sent
  2690. if unless_printing:
  2691. status = printer_manager.get_status(printer_id)
  2692. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2693. return
  2694. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2695. if keep_expected:
  2696. return
  2697. del self._sent_unstarted_print[item_id]
  2698. if remote_filename is not None and archive_id is not None:
  2699. try:
  2700. from backend.app.main import unregister_expected_print
  2701. unregister_expected_print(printer_id, remote_filename, archive_id)
  2702. except Exception:
  2703. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2704. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2705. """Drop an expectation for a print command that was never sent.
  2706. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2707. where the interesting exception is usually the one already propagating.
  2708. """
  2709. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2710. if pending is None:
  2711. return
  2712. printer_id, remote_filename, archive_id = pending
  2713. try:
  2714. from backend.app.main import unregister_expected_print
  2715. unregister_expected_print(printer_id, remote_filename, archive_id)
  2716. except Exception:
  2717. logger.warning(
  2718. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2719. item_id,
  2720. printer_id,
  2721. remote_filename,
  2722. archive_id,
  2723. exc_info=True,
  2724. )
  2725. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2726. """Release a queue reservation without touching the dispatch session."""
  2727. if item_id not in self._unconfirmed_budget_reservations:
  2728. return
  2729. for attempt in range(1, 4):
  2730. async with async_session() as cleanup_db:
  2731. try:
  2732. await release_budget_reservation(
  2733. cleanup_db,
  2734. source_type="print_queue",
  2735. source_id=item_id,
  2736. status="released",
  2737. )
  2738. await cleanup_db.commit()
  2739. self._unconfirmed_budget_reservations.discard(item_id)
  2740. return
  2741. except Exception as exc:
  2742. try:
  2743. await cleanup_db.rollback()
  2744. except Exception:
  2745. pass
  2746. if attempt == 3:
  2747. logger.error(
  2748. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2749. item_id,
  2750. attempt,
  2751. exc,
  2752. )
  2753. return
  2754. await asyncio.sleep(0.5 * attempt)
  2755. @staticmethod
  2756. def _reported_bed_target(printer_id: int) -> int | None:
  2757. """The bed target firmware currently reports, or None if it can't be read.
  2758. None means "no evidence", not "zero" — callers must not treat it as a
  2759. temperature. Deliberately total: this feeds cleanup paths that run in a
  2760. ``finally``, where a malformed status must not become the exception the
  2761. caller sees.
  2762. """
  2763. try:
  2764. state = printer_manager.get_status(printer_id)
  2765. if state is None:
  2766. return None
  2767. temps = state.temperatures
  2768. if not isinstance(temps, dict):
  2769. return None
  2770. return int(float(temps.get("bed_target", 0) or 0))
  2771. except (TypeError, ValueError, AttributeError):
  2772. return None
  2773. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2774. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2775. Turns the bed heater off, the chamber heater off, and opens the
  2776. airduct flap back to cooling — for whichever of those preheat
  2777. actually applied. `_start_print` clears the pin on successful
  2778. `start_print()`; anything still present when `_dispatch_one` exits
  2779. is by definition an aborted dispatch and gets rolled back here.
  2780. The bed is the one action that can be declined: if firmware has since
  2781. been given a target other than the one we pinned, it belongs to someone
  2782. else and is left alone. See the comment at that branch.
  2783. Also called directly from `_dispatch_one`'s claim-failure return, which
  2784. never reaches the ``finally``.
  2785. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2786. """
  2787. pin = self._preheat_pin.pop(printer_id, set())
  2788. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2789. if not pin:
  2790. return
  2791. client = printer_manager.get_client(printer_id)
  2792. if client is None:
  2793. logger.info(
  2794. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2795. item_id,
  2796. printer_id,
  2797. )
  2798. return
  2799. if "bed" in pin:
  2800. # Only undo our own target. If firmware reports something else, the
  2801. # user or another writer owns the bed now and zeroing it would
  2802. # clobber their choice -- the same guard `_release_keep_warm`
  2803. # applies to a keep-warm hold.
  2804. #
  2805. # Every uncertain case switches the bed off rather than leaving it:
  2806. # no recorded target (a pin written before this bookkeeping, or a
  2807. # setter that raised after pinning) and an unreadable status both
  2808. # fall through. A bed left hot with no owner is the worse failure,
  2809. # and this runs in a `finally` where raising would mask the real
  2810. # exception.
  2811. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2812. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2813. logger.info(
  2814. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2815. item_id,
  2816. printer_id,
  2817. cur_bed_target,
  2818. pinned_bed,
  2819. )
  2820. else:
  2821. try:
  2822. client.set_bed_temperature(0)
  2823. except Exception as exc:
  2824. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2825. if "chamber" in pin:
  2826. try:
  2827. client.set_chamber_temperature(0)
  2828. except Exception as exc:
  2829. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2830. if "airduct" in pin:
  2831. try:
  2832. client.set_airduct_mode("cooling")
  2833. except Exception as exc:
  2834. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2835. logger.info(
  2836. "Dispatch item %s (printer %d): preheat rollback → %s",
  2837. item_id,
  2838. printer_id,
  2839. sorted(pin),
  2840. )
  2841. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2842. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2843. Returns True if this call won the claim, False if the row was already
  2844. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2845. the load-bearing guard against reassign-during-dispatch (#2615).
  2846. ``printer_id`` is the printer the item was selected for: a row moved to
  2847. another printer since is not claimed, and the next pass selects it for
  2848. that one."""
  2849. query = (
  2850. update(PrintQueueItem)
  2851. .where(PrintQueueItem.id == item_id)
  2852. .where(PrintQueueItem.status == "pending")
  2853. .where(PrintQueueItem.dispatching_at.is_(None))
  2854. )
  2855. if printer_id is not None:
  2856. query = query.where(PrintQueueItem.printer_id == printer_id)
  2857. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2858. await db.commit()
  2859. return res.rowcount > 0
  2860. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2861. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2862. mask the dispatch outcome.
  2863. Retried, because the failure mode in practice is transient and narrow: a
  2864. database that is momentarily unreachable — PostgreSQL out of connection
  2865. slots is the observed case — refuses this write for a second or two while
  2866. the dispatch that just ended is still holding the row out of the selection
  2867. query. One attempt was enough to wedge the item; a couple of spaced
  2868. attempts clear it. Each attempt rolls back first, since a failed write
  2869. leaves the session needing it before it can be reused.
  2870. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2871. on the next quiet tick.
  2872. """
  2873. for attempt in range(1, 4):
  2874. try:
  2875. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2876. await db.commit()
  2877. return
  2878. except Exception as exc:
  2879. try:
  2880. await db.rollback()
  2881. except Exception:
  2882. pass
  2883. if attempt == 3:
  2884. logger.warning(
  2885. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2886. "— a later quiet tick will release it",
  2887. item_id,
  2888. attempt,
  2889. exc,
  2890. )
  2891. return
  2892. await asyncio.sleep(0.5 * attempt)
  2893. async def _printers_for_model(
  2894. self,
  2895. db: AsyncSession,
  2896. model: str,
  2897. target_location: str | None = None,
  2898. printer_scope: PrinterScope = ALL_PRINTERS,
  2899. ) -> list[Printer]:
  2900. """Active printers of *model*, optionally narrowed to one location.
  2901. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2902. answer "which printers can this job run on" from one query — a job can
  2903. only be woken onto a printer the matcher would also have considered.
  2904. ``printer_scope`` is the job creator's (#1727).
  2905. """
  2906. normalized_model = normalize_printer_model(model) or model
  2907. query = (
  2908. select(Printer)
  2909. .where(func.lower(Printer.model) == normalized_model.lower())
  2910. .where(Printer.is_active == True) # noqa: E712
  2911. )
  2912. if target_location:
  2913. query = query.where(Printer.location == target_location)
  2914. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2915. query = query.where(clause)
  2916. result = await db.execute(query)
  2917. return list(result.scalars().all())
  2918. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2919. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2920. Read once per queue check rather than per printer: it decides both
  2921. whether the wake step has anything to do and how an offline printer is
  2922. worded in the waiting reason — "Offline" and "offline with no Auto On
  2923. plug" are different problems, and the second is the one the user has to
  2924. fix themselves (#2786).
  2925. """
  2926. result = await db.execute(
  2927. select(SmartPlug.printer_id)
  2928. .where(SmartPlug.printer_id.is_not(None))
  2929. .where(SmartPlug.enabled == True) # noqa: E712
  2930. .where(SmartPlug.auto_on == True) # noqa: E712
  2931. )
  2932. return {pid for (pid,) in result.all() if pid is not None}
  2933. def _wake_recently_failed(self, printer_id: int) -> bool:
  2934. """True while this printer's failed power-on is still cooling off (#2786)."""
  2935. deadline = self._wake_failures.get(printer_id)
  2936. if deadline is None:
  2937. return False
  2938. if time.monotonic() >= deadline:
  2939. del self._wake_failures[printer_id]
  2940. return False
  2941. return True
  2942. async def _wake_printer_for_model(
  2943. self,
  2944. db: AsyncSession,
  2945. candidates: list[_ModelCandidate],
  2946. target_location: str | None,
  2947. exclude_ids: set[int],
  2948. wakeable_ids: set[int],
  2949. require_plate_clear: bool,
  2950. printer_scope: PrinterScope = ALL_PRINTERS,
  2951. ) -> tuple[int | None, int | None]:
  2952. """Power on one offline printer a model-based item could run on (#2786).
  2953. The fixed-printer branch has powered a printer on since smart plugs
  2954. existed. The model-based branch never could: its matcher drops an
  2955. offline printer into the "Offline:" waiting reason and nothing looks at
  2956. its plugs, so a class-targeted job with every matching printer switched
  2957. off sat pending forever. The reporter's log is the controlled
  2958. experiment — the same item, same plug, same Auto On setting, dispatched
  2959. the moment they edited it onto a specific printer.
  2960. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2961. power-on was actually tried, so the caller can tell "nothing here was
  2962. wakeable" (both None — cheap, other items may still find something)
  2963. from "we tried and it did not come up" (only ``attempted_id`` — the
  2964. boot timeout has already been spent).
  2965. A printer whose last known trays cannot satisfy the job is passed over
  2966. rather than woken (#2876): the colours are readable while it is off, so
  2967. switching a farm on one machine at a time to discover them wakes
  2968. printers that could never have taken the job.
  2969. Deliberately does NOT go on to match the job once a printer is up: AMS
  2970. trays arrive with the first status push after connect, so a filament
  2971. check against a printer that booted seconds ago can reject the printer
  2972. we just woke. The next queue pass matches it with live state.
  2973. At most one printer per pass. Each wake blocks the queue loop for the
  2974. boot wait, and a queue of ten class-targeted jobs must not switch on
  2975. ten printers inside one check.
  2976. """
  2977. for candidate in candidates:
  2978. if not candidate.target_model:
  2979. continue
  2980. required_types, filament_overrides = _filament_constraints(candidate)
  2981. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2982. for printer in sorted(printers, key=lambda p: p.id):
  2983. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2984. continue
  2985. if printer_manager.is_connected(printer.id):
  2986. continue
  2987. if self._wake_recently_failed(printer.id):
  2988. # Its plug did not bring it back a moment ago. Move on to a
  2989. # sibling instead of spending this pass — and every pass —
  2990. # on the same printer.
  2991. continue
  2992. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2993. # Waking this one buys nothing: it would boot into IDLE and
  2994. # then be held by the plate-clear gate, which is exactly
  2995. # what the reporter's log shows happening for 80 minutes
  2996. # after a fixed-printer wake. The flag is Bambuddy-side and
  2997. # persisted, so it is readable while the printer is off.
  2998. logger.info(
  2999. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  3000. printer.id,
  3001. candidate.target_model,
  3002. )
  3003. continue
  3004. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  3005. if shortfall:
  3006. logger.info(
  3007. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  3008. printer.id,
  3009. candidate.target_model,
  3010. ", ".join(shortfall),
  3011. )
  3012. continue
  3013. plugs = await self._get_smart_plugs(db, printer.id)
  3014. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  3015. if not auto_on_plugs:
  3016. # wakeable_ids said otherwise — the plug changed under us
  3017. # mid-pass. Nothing to do but move on.
  3018. continue
  3019. logger.info(
  3020. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  3021. candidate.target_model,
  3022. printer.id,
  3023. )
  3024. primary_plug = self._pick_power_plug(auto_on_plugs)
  3025. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  3026. logger.warning(
  3027. "Could not power on printer %s via smart plug; not trying it again for %ss",
  3028. printer.id,
  3029. self._wake_failure_cooloff,
  3030. )
  3031. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  3032. return None, printer.id
  3033. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  3034. try:
  3035. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  3036. if await service.turn_on(extra_plug):
  3037. await publish_plug_state(
  3038. extra_plug.id,
  3039. extra_plug.name,
  3040. extra_plug.printer_id,
  3041. on=True,
  3042. ha_entity_id=extra_plug.ha_entity_id,
  3043. )
  3044. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  3045. except Exception as e:
  3046. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  3047. return printer.id, printer.id
  3048. return None, None
  3049. async def _find_idle_printer_for_model(
  3050. self,
  3051. db: AsyncSession,
  3052. model: str,
  3053. exclude_ids: set[int],
  3054. required_filament_types: list[str] | None = None,
  3055. target_location: str | None = None,
  3056. filament_overrides: list[dict] | None = None,
  3057. require_plate_clear: bool = True,
  3058. wakeable_ids: set[int] | None = None,
  3059. printer_scope: PrinterScope = ALL_PRINTERS,
  3060. is_short: Callable[[int], Awaitable[bool]] | None = None,
  3061. drying_ids: set[int] | None = None,
  3062. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  3063. refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
  3064. ) -> tuple[int | None, str | None]:
  3065. """Find an idle, connected printer matching the model with compatible filaments.
  3066. Args:
  3067. db: Database session
  3068. model: Printer model to match (e.g., "X1C", "P1S")
  3069. exclude_ids: Printer IDs to exclude (already busy)
  3070. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  3071. If provided, only printers with all required types loaded will match.
  3072. target_location: Optional location filter. If provided, only printers in this location are considered.
  3073. filament_overrides: Optional list of override dicts. Each entry may include
  3074. ``force_color_match: true`` to require an exact type+color match
  3075. on the printer for that slot. Without the flag the existing
  3076. colour-preference logic applies.
  3077. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  3078. offline printer is worded: one Bambuddy will switch on reads
  3079. differently from one the user has to go and switch on themselves.
  3080. is_short: Says whether a printer's spools are too light for the job (#3137).
  3081. A printer it flags is passed over while another eligible one
  3082. is not. When every eligible printer is short, the first is
  3083. returned all the same, so the deficit gate holds the job there
  3084. and "Print Anyway" still has a printer to print on.
  3085. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  3086. in the reason, as a pinned job's wait is.
  3087. unmatched_on: Names the filaments the slot matcher would leave without a
  3088. tray on a printer (#3280). A printer it names any for is
  3089. passed over like one missing a filament type: the checks
  3090. above only ask whether each type and forced colour is
  3091. loaded somewhere, not on the right nozzle or once per slot.
  3092. refused_uploads: Excluded printers out of dispatch after a refused upload,
  3093. with why (#3409). Each is named with the reason its own
  3094. queue rows show, not as "Busy".
  3095. Returns:
  3096. Tuple of (printer_id, waiting_reason):
  3097. - (printer_id, None) if a matching printer was found
  3098. - (None, reason) if no printer is available, with explanation
  3099. """
  3100. normalized_model = normalize_printer_model(model) or model
  3101. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  3102. location_suffix = f" in {target_location}" if target_location else ""
  3103. if not printers:
  3104. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3105. # Separate force-matched overrides from preference-only overrides
  3106. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3107. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3108. # Track reasons for skipping printers
  3109. printers_busy = []
  3110. # Printers out of dispatch after a refused upload, worded as the
  3111. # printer's own queue rows word it: "Busy" would read as printing (#3409).
  3112. printers_refused: list[str] = []
  3113. printers_offline = []
  3114. printers_offline_no_plug = []
  3115. printers_missing_filament: list[tuple[str, list[str]]] = []
  3116. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3117. # The first eligible printer that is short on filament, kept in case
  3118. # every eligible printer is (#3137).
  3119. short_fallback: int | None = None
  3120. for printer in printers:
  3121. if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
  3122. printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
  3123. continue
  3124. if printer.id in exclude_ids:
  3125. # Printer is already claimed by another job in this scheduling run.
  3126. # For force-color jobs, still check if the color would match — if not,
  3127. # report it as a color mismatch rather than plain "Busy" so the user
  3128. # knows the job needs a filament change, not just to wait for availability.
  3129. if force_overrides and not pref_overrides:
  3130. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3131. if missing_colors:
  3132. printers_missing_filament.append((printer.name, missing_colors))
  3133. continue
  3134. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3135. continue
  3136. is_connected = printer_manager.is_connected(printer.id)
  3137. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3138. if not is_connected:
  3139. # An offline printer whose last known filament cannot run this
  3140. # job is reported as needing filament rather than as offline
  3141. # (#2876). It is also the printer the smart-plug step will now
  3142. # decline to switch on, and "Offline:" on its own would leave
  3143. # that decision looking like nothing happening at all.
  3144. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3145. if shortfall:
  3146. printers_missing_filament.append((printer.name, shortfall))
  3147. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3148. printers_offline_no_plug.append(printer.name)
  3149. else:
  3150. printers_offline.append(printer.name)
  3151. continue
  3152. if not is_idle:
  3153. # Printer is currently printing. For force-color jobs, check whether the
  3154. # loaded color would satisfy the requirement — if not, surface it as a
  3155. # color-mismatch reason rather than plain "Busy" so the user understands
  3156. # that the job is waiting for a filament change, not just printer availability.
  3157. if force_overrides and not pref_overrides:
  3158. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3159. if missing_colors:
  3160. printers_missing_filament.append((printer.name, missing_colors))
  3161. logger.debug(
  3162. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3163. printer.id,
  3164. printer.name,
  3165. missing_colors,
  3166. )
  3167. continue
  3168. printers_busy.append(printer.name)
  3169. continue
  3170. # Validate filament compatibility if required types are specified
  3171. if required_filament_types:
  3172. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3173. if missing:
  3174. # When force_overrides are present, enrich missing entries with color info
  3175. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3176. if force_overrides:
  3177. force_color_map = {
  3178. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3179. for o in force_overrides
  3180. }
  3181. missing_enriched = [
  3182. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3183. for t in missing
  3184. ]
  3185. printers_missing_filament.append((printer.name, missing_enriched))
  3186. else:
  3187. printers_missing_filament.append((printer.name, missing))
  3188. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3189. continue
  3190. # Force color match: ALL flagged slots must have an exact type+color match
  3191. if force_overrides:
  3192. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3193. if missing_colors:
  3194. printers_missing_filament.append((printer.name, missing_colors))
  3195. logger.debug(
  3196. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3197. printer.id,
  3198. printer.name,
  3199. missing_colors,
  3200. )
  3201. continue
  3202. # The matcher has the last word: a printer it cannot map would be
  3203. # held and given back, then chosen again on the next pass (#3280).
  3204. if unmatched_on is not None:
  3205. unmatched = await unmatched_on(printer.id)
  3206. if unmatched:
  3207. printers_missing_filament.append((printer.name, unmatched))
  3208. logger.debug(
  3209. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3210. printer.id,
  3211. printer.name,
  3212. unmatched,
  3213. )
  3214. continue
  3215. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3216. if pref_overrides:
  3217. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3218. if color_matches > 0:
  3219. candidates.append((printer.id, color_matches))
  3220. else:
  3221. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3222. printers_missing_filament.append((printer.name, override_colors))
  3223. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3224. continue
  3225. else:
  3226. # No preference ordering needed: the first eligible printer
  3227. # wins, unless its spools are too light for the job (#3137).
  3228. if is_short is not None and await is_short(printer.id):
  3229. if short_fallback is None:
  3230. short_fallback = printer.id
  3231. logger.info(
  3232. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3233. printer.id,
  3234. printer.name,
  3235. )
  3236. continue
  3237. return printer.id, None
  3238. # If we have candidates from preference override matching, pick the one with most color matches
  3239. if candidates:
  3240. candidates.sort(key=lambda c: c[1], reverse=True)
  3241. if is_short is not None:
  3242. for candidate_id, _ in candidates:
  3243. if not await is_short(candidate_id):
  3244. return candidate_id, None
  3245. logger.info(
  3246. "Model-based assignment: passing over printer %s, not enough filament",
  3247. candidate_id,
  3248. )
  3249. return candidates[0][0], None
  3250. if short_fallback is not None:
  3251. return short_fallback, None
  3252. # Build waiting reason from what we found
  3253. reasons = []
  3254. if printers_missing_filament:
  3255. # Filament/color mismatch is most actionable - show first
  3256. if force_overrides and not pref_overrides:
  3257. # All mismatches are force-color failures — use descriptive message only;
  3258. # but only if there are no busy printers that DO have the matching color.
  3259. # If a printer has the right color but is busy, surface "Busy" instead so
  3260. # the user knows the job will start automatically once that printer is free.
  3261. # Same for a printer that is merely offline: Bambuddy switches that one on
  3262. # by itself, so the job is not actually waiting on anybody to change a
  3263. # spool (#2876 — offline printers reach this list now that a switched-off
  3264. # printer's own filament is read).
  3265. if not printers_busy and not printers_offline and not printers_refused:
  3266. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3267. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3268. # else: fall through — the self-resolving entries are appended below
  3269. else:
  3270. names_and_missing = [
  3271. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3272. ]
  3273. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3274. reasons.extend(printers_refused)
  3275. if printers_busy:
  3276. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3277. if printers_offline:
  3278. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3279. if printers_offline_no_plug:
  3280. # Named separately because it is the one entry on this list the
  3281. # user has to act on: no enabled Auto On plug means Bambuddy will
  3282. # never power this printer on for the queue (#2786).
  3283. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3284. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3285. @staticmethod
  3286. def _is_busy_only(waiting_reason: str) -> bool:
  3287. """Check if the waiting reason only contains 'Busy' entries.
  3288. When all matching printers are simply busy printing, the queued job
  3289. will start automatically once a printer finishes — no user action
  3290. is required, so we skip the notification.
  3291. """
  3292. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3293. return all(p.startswith("Busy:") for p in parts)
  3294. def _get_missing_force_color_slots(
  3295. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3296. ) -> list[str]:
  3297. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3298. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3299. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3300. with an exact type+color match.
  3301. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3302. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3303. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3304. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3305. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3306. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3307. setups are unaffected.
  3308. Returns:
  3309. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3310. """
  3311. if raw_data is None:
  3312. status = printer_manager.get_status(printer_id)
  3313. if not status:
  3314. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3315. raw_data = status.raw_data
  3316. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3317. loaded: list[tuple[str, str, str]] = []
  3318. for ams_unit in raw_data.get("ams", []):
  3319. for tray in ams_unit.get("tray", []):
  3320. tray_type = tray.get("tray_type")
  3321. if tray_type:
  3322. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3323. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3324. for vt in raw_data.get("vt_tray") or []:
  3325. vt_type = vt.get("tray_type")
  3326. if vt_type:
  3327. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3328. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3329. # One spool per slot, the way the matcher assigns them: two slots asking
  3330. # for the same filament need two spools of it (#3280). Slots naming a
  3331. # variant go first and take that variant before a spool naming none, so
  3332. # a slot open to any variant cannot use up the one a later slot needs.
  3333. missing = []
  3334. taken: set[int] = set()
  3335. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3336. o_type = canonical_filament_type(o.get("type") or "")
  3337. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3338. o_idx = o.get("tray_info_idx") or ""
  3339. fits = [
  3340. i
  3341. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3342. if i not in taken
  3343. and t_type == o_type
  3344. and t_color == o_color
  3345. and (not o_idx or not t_idx or o_idx == t_idx)
  3346. ]
  3347. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3348. if pick is not None:
  3349. taken.add(pick)
  3350. else:
  3351. color_label = o.get("color_name") or o.get("color", "?")
  3352. missing.append(f"{o_type} ({color_label})")
  3353. return missing
  3354. def _get_missing_filament_types(
  3355. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3356. ) -> list[str]:
  3357. """Get the list of required filament types that are not loaded on the printer.
  3358. Args:
  3359. printer_id: The printer ID
  3360. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3361. Returns:
  3362. List of missing filament types (empty if all are loaded)
  3363. """
  3364. if raw_data is None:
  3365. status = printer_manager.get_status(printer_id)
  3366. if not status:
  3367. return required_types # Can't determine, assume all missing
  3368. raw_data = status.raw_data
  3369. # Collect all filament types loaded on this printer (AMS units + external spool)
  3370. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3371. loaded_types: set[str] = set()
  3372. # Check AMS units (stored in raw_data["ams"])
  3373. ams_data = raw_data.get("ams", [])
  3374. if ams_data:
  3375. for ams_unit in ams_data:
  3376. for tray in ams_unit.get("tray", []):
  3377. tray_type = tray.get("tray_type")
  3378. if tray_type:
  3379. loaded_types.add(canonical_filament_type(tray_type))
  3380. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3381. for vt in raw_data.get("vt_tray") or []:
  3382. vt_type = vt.get("tray_type")
  3383. if vt_type:
  3384. loaded_types.add(canonical_filament_type(vt_type))
  3385. # Find which required types are missing (using canonical type for equivalence)
  3386. missing = []
  3387. for req_type in required_types:
  3388. if canonical_filament_type(req_type) not in loaded_types:
  3389. missing.append(req_type)
  3390. return missing
  3391. def _count_override_color_matches(
  3392. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3393. ) -> int:
  3394. """Count how many filament overrides have an exact color match on the printer.
  3395. Used to prefer printers that already have the desired override colors loaded.
  3396. """
  3397. if raw_data is None:
  3398. status = printer_manager.get_status(printer_id)
  3399. if not status:
  3400. return 0
  3401. raw_data = status.raw_data
  3402. # Collect loaded filaments' type+color pairs
  3403. loaded: set[tuple[str, str]] = set()
  3404. for ams_unit in raw_data.get("ams", []):
  3405. for tray in ams_unit.get("tray", []):
  3406. tray_type = tray.get("tray_type")
  3407. # `or ""`, not a dict default: a slot can carry the key with a
  3408. # null value, and this now runs against switched-off printers
  3409. # too, where nobody is watching for the AttributeError.
  3410. tray_color = tray.get("tray_color") or ""
  3411. if tray_type:
  3412. color_norm = tray_color.replace("#", "").lower()[:6]
  3413. loaded.add((canonical_filament_type(tray_type), color_norm))
  3414. for vt in raw_data.get("vt_tray") or []:
  3415. vt_type = vt.get("tray_type")
  3416. if vt_type:
  3417. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3418. loaded.add((canonical_filament_type(vt_type), color_norm))
  3419. # Types compared as the type check compares them: a PA12-CF override
  3420. # is met by PA-CF in its colour.
  3421. matches = 0
  3422. for o in overrides:
  3423. o_type = canonical_filament_type(o.get("type") or "")
  3424. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3425. if (o_type, o_color) in loaded:
  3426. matches += 1
  3427. return matches
  3428. @staticmethod
  3429. def _tray_reading(printer_id: int) -> dict:
  3430. """The best tray reading available for a printer that is not printing.
  3431. Live status first: a printer keeps its last status after the power
  3432. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3433. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3434. for when the client itself has been dropped and taken its status with
  3435. it — which is what every power-on attempt does.
  3436. An empty result means "we have never heard", not "nothing is loaded":
  3437. the two are indistinguishable from here, and only the second would be
  3438. safe to act on.
  3439. """
  3440. status = printer_manager.get_status(printer_id)
  3441. raw = (status.raw_data if status else None) or {}
  3442. for ams_unit in raw.get("ams") or []:
  3443. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3444. return raw
  3445. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3446. return raw
  3447. return printer_manager.last_known_trays(printer_id)
  3448. def _cached_filament_shortfall(
  3449. self,
  3450. printer_id: int,
  3451. required_types: list[str] | None,
  3452. filament_overrides: list[dict] | None,
  3453. ) -> list[str]:
  3454. """What a switched-off printer's last known filament cannot provide (#2876).
  3455. The smart-plug wake step used to consider only the model, so a job for a
  3456. colour loaded on the last printer in ID order switched on every earlier
  3457. one in turn, evaluated it, rejected it on colour and left it running.
  3458. Bambuddy knew those colours the whole time. This asks the same three
  3459. questions the matcher asks a live printer — required types, forced
  3460. colours, preferred colours — of the trays it last reported, and returns
  3461. the answers in the same shape the "Waiting for filament" reason uses.
  3462. Empty means the printer may still be able to take the job.
  3463. Fails open, and deliberately: with no tray reading (never connected
  3464. since Bambuddy started, or the cache dropped by a reconnect) this
  3465. returns nothing to report and the printer is treated as it was before.
  3466. A farm restarted while its printers were off must not conclude that
  3467. none of them can print.
  3468. """
  3469. if not required_types and not filament_overrides:
  3470. return []
  3471. raw_data = self._tray_reading(printer_id)
  3472. if not raw_data:
  3473. return []
  3474. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3475. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3476. if required_types:
  3477. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3478. if missing:
  3479. # Same enrichment the live path applies: a bare "PLA" is not
  3480. # much help when what is missing is a particular PLA.
  3481. force_color_map = {
  3482. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3483. }
  3484. return [
  3485. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3486. for t in missing
  3487. ]
  3488. if force_overrides:
  3489. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3490. if missing_colors:
  3491. return missing_colors
  3492. # Preference overrides read as a preference but the matcher treats zero
  3493. # matches as a skip, so a printer with none of the wanted colours is
  3494. # rejected there too. Waking it would only produce that same rejection.
  3495. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3496. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3497. return []
  3498. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3499. """Fold the winning candidate's file and settings onto the queue row (#671).
  3500. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3501. never escapes the selection loop. By the time the pass commits, the row
  3502. looks exactly like an ordinary single-file model-based item, so the upload,
  3503. archive creation, expected-print registration, print history and reprint
  3504. paths need no knowledge that variants exist.
  3505. No-ops for a non-variant candidate, which is already the item's own columns.
  3506. Safe to run and re-run: the item's file columns are only ever *read* when it
  3507. has no variants, so an item that gets resolved and then skipped (library-row
  3508. conflict, previous-print gate) is simply resolved again on the next pass.
  3509. """
  3510. variant = candidate.variant
  3511. if variant is None:
  3512. return
  3513. item.library_file_id = variant.library_file_id
  3514. item.library_file = variant.library_file
  3515. # The dispatcher checks archive_id first and would print that instead of
  3516. # the file we just picked. Creation refuses to combine the two, so this
  3517. # only ever fires on a hand-written row — clear it rather than silently
  3518. # dispatch something the matcher never considered.
  3519. item.archive_id = None
  3520. item.archive = None
  3521. item.target_model = variant.target_model
  3522. item.plate_id = variant.plate_id
  3523. item.ams_mapping = variant.ams_mapping
  3524. item.nozzle_mapping = variant.nozzle_mapping
  3525. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3526. item.filament_overrides = variant.filament_overrides
  3527. item.required_filament_types = variant.required_filament_types
  3528. if variant.print_time_seconds is not None:
  3529. # The row carried the shortest candidate's estimate so SJF could order
  3530. # it before a printer was known; now that one is chosen, record what is
  3531. # actually going to run so history and the ETA agree with reality.
  3532. item.print_time_seconds = variant.print_time_seconds
  3533. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3534. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3535. Recomputes from live printer status when the stored mapping is missing OR
  3536. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3537. frontend status-load race can serialize [-1] before the printer's AMS
  3538. trays are known (#2589) — and must not be trusted: downstream it would be
  3539. silently downgraded to external-spool mode and print against an empty
  3540. feed. A resolved mapping is re-checked against the target printer's
  3541. live trays before it is trusted (#2799) and recomputed when it does not
  3542. fit. When it does fit, its resolved slots are kept as they are and only
  3543. the slots the plate prints that are still unresolved are matched again;
  3544. all of it is left alone when the user has acknowledged it with "Print
  3545. Anyway".
  3546. When recompute cannot resolve it either (no compatible tray loaded), the
  3547. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3548. external selection. On a printer that reported loaded trays,
  3549. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3550. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3551. and the firmware surfaces a clear AMS-mapping error instead of silently
  3552. printing to the empty external feed.
  3553. Returns an actionable message when that firmware error is the only
  3554. possible outcome — the matcher ran, matched nothing, and the printer has
  3555. no AMS to load a different spool into (#2771). The caller fails the item
  3556. on it instead of spending an upload on a print that cannot start.
  3557. Returns None everywhere else, including every case where we simply lack
  3558. the data to judge, so dispatch is only ever blocked on a positive
  3559. finding.
  3560. """
  3561. stored_mapping: list | None = None
  3562. if item.ams_mapping:
  3563. try:
  3564. stored_mapping = json.loads(item.ams_mapping)
  3565. except (json.JSONDecodeError, TypeError):
  3566. stored_mapping = None
  3567. # Present and resolved. Global tray IDs only mean something relative to
  3568. # the printer they were resolved against, so "resolved" is not the same
  3569. # as "resolved *here*" — check the mapping still fits the printer that
  3570. # is about to run this item before trusting it (#2799). "Print anyway"
  3571. # is the user overriding exactly this judgement, so it short-circuits.
  3572. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3573. if item.skip_filament_check:
  3574. return None
  3575. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3576. if conflict is None:
  3577. # It fits, but a slot the plate prints may still be empty: the
  3578. # spool was missing when it was mapped, and has perhaps been
  3579. # loaded since. Nothing else would ever look at that slot again,
  3580. # so a job held for it would be held again on every Start.
  3581. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3582. if filled is not None:
  3583. item.ams_mapping = json.dumps(filled)
  3584. logger.info(
  3585. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3586. item.id,
  3587. stored_mapping,
  3588. printer_id,
  3589. filled,
  3590. )
  3591. await db.commit()
  3592. return None
  3593. logger.warning(
  3594. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3595. item.id,
  3596. stored_mapping,
  3597. printer_id,
  3598. conflict,
  3599. )
  3600. # Drop it before recomputing so a failed recompute cannot fall back
  3601. # to the mapping we just rejected.
  3602. item.ams_mapping = None
  3603. stored_mapping = None
  3604. await db.commit()
  3605. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3606. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3607. item.ams_mapping = json.dumps(computed_mapping)
  3608. logger.info(
  3609. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3610. item.id,
  3611. printer_id,
  3612. computed_mapping,
  3613. )
  3614. await db.commit()
  3615. return None
  3616. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3617. if external_only is not None:
  3618. item.ams_mapping = json.dumps(external_only)
  3619. logger.info(
  3620. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3621. "mapping every filament to it: %s",
  3622. item.id,
  3623. printer_id,
  3624. external_only,
  3625. )
  3626. await db.commit()
  3627. return None
  3628. if _mapping_is_all_unresolved(stored_mapping):
  3629. logger.warning(
  3630. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3631. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3632. item.id,
  3633. stored_mapping,
  3634. printer_id,
  3635. )
  3636. item.ams_mapping = None
  3637. await db.commit()
  3638. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3639. async def _external_spool_only_mapping(
  3640. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3641. ) -> list[int] | None:
  3642. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3643. A printer without an AMS prints from its external spool, and an external
  3644. spool whose filament was never set reports no type, so the matcher has
  3645. nothing to match. Sent without a mapping, the print goes out with the AMS
  3646. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3647. to carry such a job through; a job placed by model or location no longer
  3648. keeps one, and one queued that way never had one.
  3649. Only on a positive report: the printer has said it has no AMS, it has a
  3650. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3651. is not ours to pick), and no feed has a filament set — with one set, the
  3652. matcher has already given its answer. Not for a job that asked for its
  3653. colours to be matched strictly: a spool without a filament set has no
  3654. colour to check. Returns None otherwise.
  3655. """
  3656. if item.filament_overrides:
  3657. try:
  3658. overrides = json.loads(item.filament_overrides)
  3659. except (json.JSONDecodeError, TypeError):
  3660. return None
  3661. if not isinstance(overrides, list) or any(
  3662. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3663. ):
  3664. return None
  3665. status = printer_manager.get_status(printer_id)
  3666. if status is None or not isinstance(status.raw_data, dict):
  3667. return None
  3668. ams_units = status.raw_data.get("ams")
  3669. if not isinstance(ams_units, list) or ams_units:
  3670. return None
  3671. vt_trays = status.raw_data.get("vt_tray")
  3672. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3673. return None
  3674. if self._build_loaded_filaments(status):
  3675. return None
  3676. printer = await self._get_printer(db, printer_id)
  3677. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3678. return None
  3679. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3680. if external < _EXTERNAL_TRAY_ID_MIN:
  3681. return None
  3682. required = await self._get_filament_requirements(db, item)
  3683. slot_ids = [r.get("slot_id") for r in required or []]
  3684. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3685. if not slot_ids:
  3686. return None
  3687. mapping = [-1] * max(slot_ids)
  3688. for slot_id in slot_ids:
  3689. mapping[slot_id - 1] = external
  3690. return mapping
  3691. async def _fill_unresolved_slots(
  3692. self,
  3693. db: AsyncSession,
  3694. printer_id: int,
  3695. item: PrintQueueItem,
  3696. stored_mapping: list | None,
  3697. ) -> list | None:
  3698. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3699. Every resolved entry is kept, so a tray the user picked by hand stays
  3700. picked. Only the plate's unresolved slots are matched, and only against
  3701. trays the mapping does not already use: the matcher never gives two
  3702. slots one tray, and filling a gap with a tray the user assigned to
  3703. another slot would print that slot's filament twice.
  3704. Returns None when there is nothing to fill or nothing could be filled.
  3705. """
  3706. if not isinstance(stored_mapping, list) or not stored_mapping:
  3707. return None
  3708. required = await self._get_filament_requirements(db, item)
  3709. if not required:
  3710. return None
  3711. self._apply_filament_overrides(item, required)
  3712. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3713. if not gaps:
  3714. return None
  3715. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3716. computed = await self._compute_ams_mapping_for_printer(
  3717. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3718. )
  3719. if not computed:
  3720. return None
  3721. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3722. filled = False
  3723. for slot_id in gaps:
  3724. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3725. if _is_tray_id(tray) and tray >= 0:
  3726. merged[slot_id - 1] = tray
  3727. filled = True
  3728. return merged if filled else None
  3729. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3730. """What a staged item would be held for if it were started now (#2799).
  3731. The Start button asks this before releasing an item, so that a job whose
  3732. filament is still not loaded offers "Print Anyway" instead of being
  3733. released, held again by the scheduler and leaving no way past the hold.
  3734. It reaches the same answer the dispatch path would: a stored mapping
  3735. that fits is kept and only its gaps are matched again, and one that
  3736. does not fit (or is missing) is replaced by a fresh match.
  3737. Returns the missing filaments, described the way the queue row
  3738. describes them, or None when nothing is missing or there is not enough
  3739. evidence to say: no printer yet (a model-based item picks one at
  3740. dispatch), no status, no trays reported, or no readable 3MF.
  3741. """
  3742. if item.skip_filament_check or not item.printer_id:
  3743. return None
  3744. status = printer_manager.get_status(item.printer_id)
  3745. if status is None or not self._build_loaded_filaments(status):
  3746. return None
  3747. # Called from a request, not from a pass: drop whatever the last pass
  3748. # memoised so this reads the file as it is now. A pass running at the
  3749. # same time only loses its cache.
  3750. self._filament_req_memo.clear()
  3751. mapping: list | None = None
  3752. if item.ams_mapping:
  3753. try:
  3754. mapping = json.loads(item.ams_mapping)
  3755. except (json.JSONDecodeError, TypeError):
  3756. mapping = None
  3757. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3758. mapping = None
  3759. if mapping is not None:
  3760. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3761. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3762. else:
  3763. mapping = None
  3764. if mapping is None:
  3765. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3766. required = await self._get_filament_requirements(db, item)
  3767. if required:
  3768. self._apply_filament_overrides(item, required)
  3769. else:
  3770. # The same fallback the hold uses, or Start would release a job the
  3771. # next pass holds again (#3280).
  3772. required = _forced_override_requirements(item)
  3773. if not required:
  3774. return None
  3775. missing = _unresolved_required(required, mapping)
  3776. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3777. async def _stored_mapping_conflict(
  3778. self,
  3779. db: AsyncSession,
  3780. printer_id: int,
  3781. item: PrintQueueItem,
  3782. stored_mapping: list | None,
  3783. ) -> str | None:
  3784. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3785. A mapping is a list of global tray IDs, and those are only meaningful
  3786. relative to the printer they were resolved against — the same rule
  3787. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3788. arrives at a printer it was not resolved for:
  3789. * the print dialog stamps one mapping onto every selected printer, so a
  3790. mapping computed against the first printer is dispatched verbatim to
  3791. the rest, whose AMS slot order differs;
  3792. * a spool is moved between queueing and dispatch.
  3793. Both end the same way: the slot index still resolves, so nothing looks
  3794. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3795. the firmware's own type check, so a PETG slot happily prints in ASA.
  3796. Returns a short reason when the mapping names a tray this printer does
  3797. not have loaded, points a slot at a tray holding a different filament
  3798. type, or points it at an external spool this printer reports empty while
  3799. its AMS holds that slot's filament (#3239). Returns None when the
  3800. mapping fits, and — deliberately — whenever we lack the evidence to
  3801. judge, so a recompute only ever follows a positive finding.
  3802. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3803. matcher had nothing, not that the mapping belongs to another printer,
  3804. and destroying a partially hand-resolved mapping over it would lose the
  3805. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3806. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3807. item when that finds nothing.
  3808. """
  3809. if not isinstance(stored_mapping, list) or not stored_mapping:
  3810. return None
  3811. status = printer_manager.get_status(printer_id)
  3812. if status is None:
  3813. return None
  3814. loaded = self._build_loaded_filaments(status)
  3815. if not loaded:
  3816. # Nothing reported yet (reconnect, first push pending). Saying
  3817. # "tray not loaded" here would recompute against an AMS we cannot
  3818. # see, which is how #2589 produced a bogus all-[-1] in the first
  3819. # place.
  3820. return None
  3821. by_tray = {f["global_tray_id"]: f for f in loaded}
  3822. # Cheap pass first, on live status alone: every tray the mapping names
  3823. # has to exist here. This catches a foreign mapping without opening the
  3824. # 3MF, which is worth doing because the parse below is neither cached
  3825. # nor free.
  3826. for index, tray in enumerate(stored_mapping):
  3827. if not _is_tray_id(tray) or tray < 0:
  3828. continue
  3829. if tray in by_tray:
  3830. continue
  3831. if tray >= 254:
  3832. # An external feed we have not heard about is absence of
  3833. # evidence about *that slot* — the rest of the mapping is still
  3834. # worth judging, so skip it rather than abandoning the pass.
  3835. continue
  3836. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3837. # Only now is the 3MF worth opening: the type check needs to know what
  3838. # each slot actually asked for. The external spool is checked the same
  3839. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3840. # two printers with different filament in the external feed is the same
  3841. # failure this method exists to catch.
  3842. required = await self._get_filament_requirements(db, item)
  3843. if not required:
  3844. return None
  3845. self._apply_filament_overrides(item, required)
  3846. # External feeds the printer reports and reports as empty. That is
  3847. # evidence, unlike an external feed it says nothing about (#3239).
  3848. empty_external: set[int] = set()
  3849. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3850. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3851. if isinstance(vt, dict) and not vt.get("tray_type"):
  3852. try:
  3853. empty_external.add(int(vt.get("id", 254)))
  3854. except (TypeError, ValueError):
  3855. continue
  3856. for req in required:
  3857. slot_id = req.get("slot_id") or 0
  3858. if slot_id <= 0:
  3859. continue
  3860. if slot_id > len(stored_mapping):
  3861. return f"slot {slot_id} is not covered by the mapping"
  3862. tray = stored_mapping[slot_id - 1]
  3863. if not _is_tray_id(tray) or tray < 0:
  3864. continue
  3865. loaded_tray = by_tray.get(tray)
  3866. if loaded_tray is None:
  3867. # A mapping made for a printer that feeds this slot from its
  3868. # external spool, sent to one whose external spool is empty and
  3869. # whose AMS holds the filament (#3239). Only then: an external
  3870. # spool can be loaded without its filament set, and on a printer
  3871. # with nothing else to offer that job printed before. The colour
  3872. # has to match too: with only another colour in the AMS, the
  3873. # printer asking for the spool beats printing in that colour.
  3874. want = canonical_filament_type(req.get("type"))
  3875. if tray >= 254 and tray in empty_external and want:
  3876. ams_tray = next(
  3877. (
  3878. f
  3879. for f in loaded
  3880. if not f.get("is_external")
  3881. and canonical_filament_type(f.get("type")) == want
  3882. and self._colors_are_similar(f.get("color"), req.get("color"))
  3883. ),
  3884. None,
  3885. )
  3886. if ams_tray is not None:
  3887. return (
  3888. f"slot {slot_id} points at the external spool, which is empty, "
  3889. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3890. )
  3891. continue
  3892. want = canonical_filament_type(req.get("type"))
  3893. have = canonical_filament_type(loaded_tray.get("type"))
  3894. if want and have and want != have:
  3895. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3896. # A forced slot fits only a tray the matcher would give it (#3280).
  3897. if req.get("force_color_match"):
  3898. want_idx = req.get("tray_info_idx") or ""
  3899. have_idx = loaded_tray.get("tray_info_idx") or ""
  3900. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3901. loaded_tray.get("color")
  3902. ) or (want_idx and have_idx and want_idx != have_idx):
  3903. return (
  3904. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3905. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3906. )
  3907. return None
  3908. async def _unmappable_without_ams_message(
  3909. self,
  3910. db: AsyncSession,
  3911. printer_id: int,
  3912. item: PrintQueueItem,
  3913. computed_mapping: list[int] | None,
  3914. ) -> str | None:
  3915. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3916. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3917. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3918. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3919. uploaded several megabytes and burned its dispatch retries. This method
  3920. speaks only for the AMS-less case: there is nothing to resume into — the
  3921. external spool holder is the whole inventory — so the useful answer is to
  3922. say which filament is missing and stop. With an AMS attached it returns
  3923. None: where live status reported loaded trays,
  3924. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3925. reported none the print goes out and the firmware error is the answer —
  3926. the user can load the right spool and press Resume.
  3927. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3928. every branch that lacks the evidence to be sure returns None.
  3929. """
  3930. # None means the matcher never ran (no requirements parsed from the 3MF,
  3931. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3932. # dispatch as they always have.
  3933. if not _mapping_is_all_unresolved(computed_mapping):
  3934. return None
  3935. status = printer_manager.get_status(printer_id)
  3936. if status is None:
  3937. return None
  3938. # "No AMS" has to be a fact the printer stated, not the absence of a
  3939. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3940. # handled and is preserved across partial pushes thereafter, so a missing
  3941. # key means we have not heard yet — most likely a reconnect, where the
  3942. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3943. # empty list is the positive report of a printer with no AMS.
  3944. ams_units = status.raw_data.get("ams")
  3945. if not isinstance(ams_units, list) or ams_units:
  3946. return None
  3947. required = await self._get_filament_requirements(db, item)
  3948. loaded = self._build_loaded_filaments(status)
  3949. if not required or not loaded:
  3950. # Both were non-empty moments ago or the matcher could not have run.
  3951. # If the picture changed under us, say nothing rather than fail an
  3952. # item on stale evidence.
  3953. return None
  3954. self._apply_filament_overrides(item, required)
  3955. if any(r.get("force_color_match") for r in required):
  3956. # A forced colour is a spool the user can load on the external
  3957. # holder, so the unmatched hold stages the job instead (#3280).
  3958. return None
  3959. return _unmatched_filament_message(required, loaded)
  3960. async def _fail_unmappable_item(
  3961. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3962. ) -> None:
  3963. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3964. This replaces a failure, not a success: without it the item is uploaded,
  3965. rejected by the firmware with 0700_8012, retried twice more and failed
  3966. anyway with "never started the print after N dispatch attempts". So this
  3967. applies on the model-based path too. There it is rarely reached: choosing
  3968. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  3969. over one it cannot map, so an "Any <model>" job tries its siblings and
  3970. otherwise waits; this remains for a match that failed at selection time.
  3971. """
  3972. item.status = "failed"
  3973. item.error_message = message
  3974. item.completed_at = datetime.now(timezone.utc)
  3975. item.waiting_reason = None
  3976. await db.commit()
  3977. from backend.app.services.print_batch import refresh_batches_after
  3978. await refresh_batches_after([item.id])
  3979. logger.warning(
  3980. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3981. item.id,
  3982. printer_id,
  3983. message,
  3984. )
  3985. job_name = await self._get_job_name(db, item)
  3986. printer = await self._get_printer(db, printer_id)
  3987. await notification_service.on_queue_job_failed(
  3988. job_name=job_name,
  3989. printer_id=printer_id,
  3990. printer_name=printer.name if printer else "Unknown",
  3991. reason=message,
  3992. db=db,
  3993. )
  3994. try:
  3995. await ws_manager.send_queue_item_failed(
  3996. user_id=item.created_by_id,
  3997. queue_item_id=item.id,
  3998. printer_id=printer_id,
  3999. reason="filament_unmappable",
  4000. )
  4001. except Exception:
  4002. pass
  4003. async def _compute_ams_mapping_for_printer(
  4004. self,
  4005. db: AsyncSession,
  4006. printer_id: int,
  4007. item: PrintQueueItem,
  4008. *,
  4009. only_slots: set[int] | None = None,
  4010. reserved_trays: set[int] | None = None,
  4011. ) -> list[int] | None:
  4012. """Compute AMS mapping for a printer based on filament requirements.
  4013. Called when a queue item has no ams_mapping set — either for model-based
  4014. items after printer assignment, or printer-specific items (e.g. from VP).
  4015. Args:
  4016. db: Database session
  4017. printer_id: The assigned printer ID
  4018. item: The queue item (contains archive_id or library_file_id)
  4019. only_slots: Match only these filament slots; every other slot comes
  4020. back unresolved (-1). Used to fill the gaps of a stored mapping.
  4021. reserved_trays: Global tray IDs to leave out of the match, because
  4022. the stored mapping already gives them to another slot.
  4023. Returns:
  4024. AMS mapping array or None if no mapping needed/possible
  4025. """
  4026. # Get printer status
  4027. status = printer_manager.get_status(printer_id)
  4028. if not status:
  4029. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  4030. return None
  4031. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  4032. # either extruder, so the per-nozzle hard filter below must NOT apply.
  4033. # Otherwise a print on one nozzle can't use a spool physically loaded in
  4034. # an AMS on the *other* nozzle, and the matcher falls through to a
  4035. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  4036. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  4037. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  4038. # Get filament requirements from source file
  4039. filament_reqs = await self._get_filament_requirements(db, item)
  4040. if not filament_reqs:
  4041. # When the 3MF can't be read but force-color overrides are present, build a
  4042. # direct mapping from the overrides so the printer uses the correct AMS slot.
  4043. if item.filament_overrides:
  4044. try:
  4045. overrides = json.loads(item.filament_overrides)
  4046. force_overrides = [o for o in overrides if o.get("force_color_match")]
  4047. if force_overrides:
  4048. logger.info(
  4049. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  4050. "force-color override(s)",
  4051. item.id,
  4052. len(force_overrides),
  4053. )
  4054. return self._build_override_direct_mapping(force_overrides, status)
  4055. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4056. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  4057. logger.debug("No filament requirements found for queue item %s", item.id)
  4058. return None
  4059. self._apply_filament_overrides(item, filament_reqs)
  4060. if only_slots is not None:
  4061. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  4062. if not filament_reqs:
  4063. return None
  4064. # Build loaded filaments from printer status
  4065. loaded_filaments = self._build_loaded_filaments(status)
  4066. if reserved_trays:
  4067. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  4068. if not loaded_filaments:
  4069. logger.debug("No filaments loaded on printer %s", printer_id)
  4070. return None
  4071. # Check if user prefers lowest remaining filament when multiple spools match
  4072. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  4073. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  4074. # Without backup, the printer will not switch to a second spool when the
  4075. # picked one runs out — so sorting toward the lowest leaves the print
  4076. # at risk of running dry mid-job. None (unknown: no status report with
  4077. # cfg or home_flag yet) preserves today's behaviour intentionally.
  4078. if prefer_lowest and status.ams_filament_backup is False:
  4079. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  4080. prefer_lowest = False
  4081. # When the preference is on, surface Bambuddy's inventory-side
  4082. # remaining for each slot that's bound to a tracked spool, so the
  4083. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  4084. # entirely when the preference is off — no behaviour change for
  4085. # users who haven't opted in.
  4086. inventory_remain_overrides: dict[int, float] | None = None
  4087. if prefer_lowest:
  4088. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  4089. # Compute mapping: match required filaments to available slots
  4090. return self._match_filaments_to_slots(
  4091. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  4092. )
  4093. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  4094. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  4095. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  4096. diagnosis (#2771) describes the filament the matcher actually looked
  4097. for, not the one the 3MF was sliced with — naming the pre-override
  4098. filament in a user-facing error would send the user to load the wrong
  4099. spool.
  4100. """
  4101. if not item.filament_overrides:
  4102. return
  4103. try:
  4104. overrides = json.loads(item.filament_overrides)
  4105. override_map = {o["slot_id"]: o for o in overrides}
  4106. for req in filament_reqs:
  4107. if req["slot_id"] in override_map:
  4108. override = override_map[req["slot_id"]]
  4109. req["type"] = override["type"]
  4110. req["color"] = override["color"]
  4111. # A manual/preference override SWAPS the slot's filament, so the
  4112. # 3MF's original tray_info_idx now points at the old spool and must
  4113. # be cleared — matching then falls back to type+colour. A
  4114. # force_color_match override is not a swap: it carries the 3MF's
  4115. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4116. # it here too, letting the matcher pin the correct variant slot on a
  4117. # printer holding two same-colour spools of different variants (#2650).
  4118. # A spool that names no variant still counts; one naming another
  4119. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4120. req["tray_info_idx"] = (
  4121. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4122. )
  4123. # The matcher satisfies a forced slot only the way
  4124. # `_get_missing_force_color_slots` does, never by a similar
  4125. # colour or the type alone (#3280).
  4126. req["force_color_match"] = bool(override.get("force_color_match"))
  4127. logger.debug(
  4128. "Queue item %s: Override slot %d -> %s %s",
  4129. item.id,
  4130. req["slot_id"],
  4131. override["type"],
  4132. override["color"],
  4133. )
  4134. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4135. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4136. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4137. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4138. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4139. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4140. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4141. treated as the filament requirement for that slot and matched against the
  4142. current AMS state of the printer.
  4143. Returns the same format as ``_match_filaments_to_slots``, or None when
  4144. the AMS has no loaded filaments.
  4145. """
  4146. loaded = self._build_loaded_filaments(status)
  4147. if not loaded:
  4148. return None
  4149. reqs = [
  4150. {
  4151. "slot_id": o["slot_id"],
  4152. "type": o.get("type", ""),
  4153. "color": o.get("color", ""),
  4154. # These are all force_color_match overrides, so the idx (when the
  4155. # 3MF carried one) is the intended variant, not a stale swap —
  4156. # keep it so the matcher pins the right variant slot (#2650); a
  4157. # spool naming another variant does not satisfy it (#3280).
  4158. "tray_info_idx": o.get("tray_info_idx", ""),
  4159. "force_color_match": True,
  4160. }
  4161. for o in force_overrides
  4162. ]
  4163. return self._match_filaments_to_slots(reqs, loaded)
  4164. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4165. """Resolve the queue item's source 3MF and parse the per-slot
  4166. filament requirements out of it. Thin DB-resolver wrapper around
  4167. ``filament_requirements.extract_filament_requirements`` so the VP
  4168. queue-mode write path (#1188) can reuse the same parser at upload
  4169. time.
  4170. """
  4171. from backend.app.services.filament_requirements import extract_filament_requirements
  4172. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4173. # so every caller gets its own copy — a shared list would leak one
  4174. # item's overrides into the next item that happens to print the same
  4175. # plate.
  4176. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4177. if memo_key in self._filament_req_memo:
  4178. cached = self._filament_req_memo[memo_key]
  4179. return [dict(r) for r in cached] if cached else None
  4180. file_path: Path | None = None
  4181. if item.archive_id:
  4182. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4183. archive = result.scalar_one_or_none()
  4184. if archive:
  4185. file_path = settings.base_dir / archive.file_path
  4186. elif item.library_file_id:
  4187. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4188. library_file = result.scalar_one_or_none()
  4189. if library_file:
  4190. lib_path = Path(library_file.file_path)
  4191. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4192. if not file_path or not file_path.exists():
  4193. self._filament_req_memo[memo_key] = None
  4194. return None
  4195. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4196. self._filament_req_memo[memo_key] = filaments or None
  4197. return [dict(r) for r in filaments] if filaments else None
  4198. def _build_loaded_filaments(self, status) -> list[dict]:
  4199. """Build list of loaded filaments from printer status.
  4200. Args:
  4201. status: PrinterState from printer_manager
  4202. Returns:
  4203. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4204. """
  4205. filaments = []
  4206. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4207. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4208. # Routes external spools to an extruder (#2771). Mirrors
  4209. # `buildLoadedFilaments` in the frontend.
  4210. vt_trays = status.raw_data.get("vt_tray") or []
  4211. is_dual_nozzle = reports_two_nozzles(status)
  4212. # Parse AMS units from raw_data
  4213. ams_data = status.raw_data.get("ams", [])
  4214. for ams_unit in ams_data:
  4215. ams_id = int(ams_unit.get("id", 0))
  4216. trays = ams_unit.get("tray", [])
  4217. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4218. for tray in trays:
  4219. tray_type = tray.get("tray_type")
  4220. if tray_type:
  4221. tray_id = int(tray.get("id", 0))
  4222. tray_color = tray.get("tray_color", "")
  4223. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4224. tray_info_idx = tray.get("tray_info_idx", "")
  4225. # Normalize color: remove alpha, add hash
  4226. color = self._normalize_color(tray_color)
  4227. # Calculate global tray ID
  4228. # AMS-HT units have IDs starting at 128 with a single tray
  4229. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4230. filaments.append(
  4231. {
  4232. "type": tray_type,
  4233. "color": color,
  4234. # `color` reads a missing colour as #808080; this
  4235. # says whether the printer reported one at all.
  4236. "color_known": bool(tray_color),
  4237. "tray_info_idx": tray_info_idx,
  4238. "ams_id": ams_id,
  4239. "tray_id": tray_id,
  4240. "is_ht": is_ht,
  4241. "is_external": False,
  4242. "global_tray_id": global_tray_id,
  4243. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4244. "remain": tray.get("remain", -1),
  4245. }
  4246. )
  4247. # Check external spool(s) (vt_tray is a list)
  4248. for idx, vt in enumerate(vt_trays):
  4249. if vt.get("tray_type"):
  4250. color = self._normalize_color(vt.get("tray_color", ""))
  4251. tray_id = int(vt.get("id", 254))
  4252. filaments.append(
  4253. {
  4254. "type": vt["tray_type"],
  4255. "color": color,
  4256. "color_known": bool(vt.get("tray_color")),
  4257. "tray_info_idx": vt.get("tray_info_idx", ""),
  4258. "ams_id": -1,
  4259. "tray_id": idx,
  4260. "is_ht": False,
  4261. "is_external": True,
  4262. "global_tray_id": tray_id,
  4263. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4264. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4265. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4266. "remain": vt.get("remain", -1),
  4267. }
  4268. )
  4269. return filaments
  4270. def _normalize_color(self, color: str | None) -> str:
  4271. """Normalize color to #RRGGBB format."""
  4272. if not color:
  4273. return "#808080"
  4274. hex_color = color.replace("#", "")[:6]
  4275. return f"#{hex_color}"
  4276. def _normalize_color_for_compare(self, color: str | None) -> str:
  4277. """Normalize color for comparison (lowercase, no hash)."""
  4278. if not color:
  4279. return ""
  4280. return color.replace("#", "").lower()[:6]
  4281. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4282. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4283. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4284. stays the per-channel box that shipped — this only decides which of
  4285. several eligible spools is closest, so nothing becomes usable or
  4286. unusable because of it.
  4287. It ranks by how far apart the colours *look*, not how far apart their
  4288. numbers are. RGB distance overweights blue badly enough to invert the
  4289. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4290. the nearer of two eligible spools by RGB and the further by a factor of
  4291. four once measured perceptually.
  4292. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4293. transparent filament is not a colour the user chose, and counting it
  4294. would stop a transparent filament matching itself.
  4295. """
  4296. return perceptual_color_distance(color1, color2)
  4297. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4298. """Check if two colors are visually similar within a threshold."""
  4299. hex1 = self._normalize_color_for_compare(color1)
  4300. hex2 = self._normalize_color_for_compare(color2)
  4301. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4302. return False
  4303. try:
  4304. r1 = int(hex1[0:2], 16)
  4305. g1 = int(hex1[2:4], 16)
  4306. b1 = int(hex1[4:6], 16)
  4307. r2 = int(hex2[0:2], 16)
  4308. g2 = int(hex2[2:4], 16)
  4309. b2 = int(hex2[4:6], 16)
  4310. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4311. except ValueError:
  4312. return False
  4313. async def _build_inventory_remain_overrides(
  4314. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4315. ) -> dict[int, float]:
  4316. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4317. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4318. The MQTT ``remain`` field on a tray is the printer firmware's
  4319. RFID-decremented value, which has two limitations the "Prefer Lowest
  4320. Remaining Filament" feature has been ignoring (#1508):
  4321. - it's only meaningful for Bambu RFID spools; everything else reports
  4322. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4323. compare equal and the sort collapses to AMS-slot order — the user
  4324. who's curating inventory weights gets the lower-slot pick instead
  4325. of the lower-remaining pick;
  4326. - even when set, it's the *printer's* counter, not Bambuddy's
  4327. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4328. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4329. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4330. When the user has bound a spool to a slot, their own inventory
  4331. tracking is authoritative; this helper surfaces that value so the
  4332. sort can prefer it. Slots without a binding are absent from the
  4333. returned map — the caller then falls back to MQTT ``remain`` for
  4334. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4335. Returns an empty map on any failure (no inventory bindings, DB
  4336. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4337. is a preference, not a guarantee.
  4338. """
  4339. if not loaded:
  4340. return {}
  4341. # External / virtual-tray slots are tracked separately from AMS — skip
  4342. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4343. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4344. # match is fiddly and out of scope for this fix).
  4345. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4346. if not tracked_slots:
  4347. return {}
  4348. is_spoolman = await self._is_spoolman_mode(db)
  4349. overrides: dict[int, float] = {}
  4350. if is_spoolman:
  4351. result = await db.execute(
  4352. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4353. )
  4354. assignments = list(result.scalars().all())
  4355. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4356. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4357. for ams_id, tray_id, gtid in tracked_slots:
  4358. spoolman_id = by_slot.get((ams_id, tray_id))
  4359. if spoolman_id is None:
  4360. continue
  4361. grams = await _spoolman_remaining_grams(spoolman_id)
  4362. if grams is not None:
  4363. overrides[gtid] = grams
  4364. return overrides
  4365. # Internal inventory mode (default). selectinload matches the pattern
  4366. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4367. # plus an eager-loaded relationship rather than an explicit join, so
  4368. # the row-attribute shape is exactly what those routes already rely on.
  4369. result = await db.execute(
  4370. select(SpoolAssignment)
  4371. .options(selectinload(SpoolAssignment.spool))
  4372. .where(SpoolAssignment.printer_id == printer_id)
  4373. )
  4374. assignments = list(result.scalars().all())
  4375. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4376. for ams_id, tray_id, gtid in tracked_slots:
  4377. spool = by_slot.get((ams_id, tray_id))
  4378. if spool is None:
  4379. continue
  4380. label = float(spool.label_weight or 0)
  4381. used = float(spool.weight_used or 0)
  4382. overrides[gtid] = max(0.0, label - used)
  4383. return overrides
  4384. @staticmethod
  4385. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4386. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4387. here to avoid making this module import-dependent on that private
  4388. helper's signature."""
  4389. try:
  4390. from backend.app.api.routes.settings import get_setting
  4391. v = await get_setting(db, "spoolman_enabled")
  4392. return bool(v) and v.lower() == "true"
  4393. except Exception:
  4394. return False
  4395. @staticmethod
  4396. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4397. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4398. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4399. so a tied sort produces the same physical-position order the pre-#1508
  4400. stable sort did (preserves the regression-free baseline):
  4401. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4402. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4403. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4404. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4405. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4406. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4407. """
  4408. if ams_id is None or ams_id < 0:
  4409. return 10_000
  4410. if ams_id >= 128:
  4411. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4412. return ams_id * 4 + (tray_id or 0)
  4413. @staticmethod
  4414. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4415. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4416. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4417. non-tracked spools (the user has told us they care about these
  4418. specifically), then ascending by remaining within each tier, then
  4419. ascending by AMS slot position as the deterministic tie-breaker.
  4420. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4421. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4422. because the tier flag dominates — which is what lets us mix grams
  4423. (inventory) and percent (MQTT) without a unit conversion.
  4424. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4425. spools the printer DOES know something about sort ahead of those
  4426. it knows nothing about — preserves pre-#1508 behaviour for the
  4427. no-inventory-binding case.
  4428. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4429. external on ties, matching the legacy emission-order stable sort.
  4430. """
  4431. gtid = f.get("global_tray_id")
  4432. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4433. if overrides and gtid in overrides:
  4434. return (0, overrides[gtid], slot_order)
  4435. remain = f.get("remain", -1)
  4436. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4437. def _match_filaments_to_slots(
  4438. self,
  4439. required: list[dict],
  4440. loaded: list[dict],
  4441. prefer_lowest: bool = False,
  4442. inventory_remain_overrides: dict[int, float] | None = None,
  4443. fts_installed: bool = False,
  4444. ) -> list[int] | None:
  4445. """Match required filaments to loaded filaments and build AMS mapping.
  4446. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4447. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4448. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4449. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4450. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4451. matching among those trays.
  4452. Args:
  4453. required: List of required filaments with slot_id, type, color, tray_info_idx
  4454. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4455. Returns:
  4456. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4457. """
  4458. if not required:
  4459. return None
  4460. # Track used trays to avoid duplicate assignment
  4461. used_tray_ids: set[int] = set()
  4462. comparisons = []
  4463. # Forced slots first: a slot that would take any tray of its type must
  4464. # not take the one tray a forced slot can use (#3280). The mapping is
  4465. # built by slot_id below, so the order only decides who goes first.
  4466. # Among forced slots, those naming a variant first, as
  4467. # `_get_missing_force_color_slots` counts them.
  4468. for req in sorted(
  4469. required,
  4470. key=lambda r: (
  4471. not r.get("force_color_match"),
  4472. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4473. ),
  4474. ):
  4475. req_type = (req.get("type") or "").upper()
  4476. req_color = req.get("color", "")
  4477. req_tray_info_idx = req.get("tray_info_idx", "")
  4478. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4479. idx_match = None
  4480. exact_match = None
  4481. similar_match = None
  4482. similar_distance = float("inf")
  4483. type_only_match = None
  4484. # Get available trays (not already used)
  4485. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4486. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4487. # Hard filter — cross-nozzle assignment causes print failures
  4488. # ("position of left hotend is abnormal"), so never fall back.
  4489. # Skipped when an FTS is installed: it routes any AMS slot to either
  4490. # extruder, so restricting to one nozzle would wrongly exclude the
  4491. # correct spool sitting in the other nozzle's AMS (#2186).
  4492. req_nozzle_id = req.get("nozzle_id")
  4493. if req_nozzle_id is not None and not fts_installed:
  4494. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4495. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4496. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4497. # _prefer_lowest_sort_key for the full rationale.
  4498. if prefer_lowest:
  4499. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4500. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4501. # One line per filament req so a bug report can be diagnosed
  4502. # without enabling debug logging: shows what the matcher saw
  4503. # (req shape + sorted candidate trays with their remain values
  4504. # and any inventory override that was applied). Mirrored by
  4505. # the picked-match log at the bottom of the loop.
  4506. logger.info(
  4507. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4508. req.get("slot_id"),
  4509. req_type,
  4510. req_color,
  4511. req_tray_info_idx,
  4512. req_nozzle_id,
  4513. [
  4514. {
  4515. "gtid": f.get("global_tray_id"),
  4516. "type": f.get("type"),
  4517. "color": f.get("color"),
  4518. "tii": f.get("tray_info_idx"),
  4519. "remain": f.get("remain"),
  4520. "inv_g": (
  4521. inventory_remain_overrides.get(f.get("global_tray_id"))
  4522. if inventory_remain_overrides
  4523. else None
  4524. ),
  4525. }
  4526. for f in available
  4527. ],
  4528. )
  4529. # A forced slot takes only what `_get_missing_force_color_slots`
  4530. # accepts: same type, exact colour, and the same variant when both
  4531. # sides name one -- preferring the tray that does. Nothing looser:
  4532. # the model-based path holds a job the printer cannot satisfy this
  4533. # way, and a printer-pinned job fell through to type_only and
  4534. # printed in whatever colour came first (#3280).
  4535. forced = bool(req.get("force_color_match"))
  4536. if forced:
  4537. want_type = canonical_filament_type(req_type)
  4538. want_color = self._normalize_color_for_compare(req_color)
  4539. candidates = [
  4540. f
  4541. for f in available
  4542. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4543. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4544. and (
  4545. not req_tray_info_idx
  4546. or not f.get("tray_info_idx")
  4547. or f.get("tray_info_idx") == req_tray_info_idx
  4548. )
  4549. ]
  4550. exact_match = next(
  4551. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4552. candidates[0] if candidates else None,
  4553. )
  4554. # Check if tray_info_idx is unique among available trays
  4555. if req_tray_info_idx and not forced:
  4556. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4557. if len(idx_matches) == 1:
  4558. # Unique tray_info_idx - use it as definitive match
  4559. idx_match = idx_matches[0]
  4560. logger.debug(
  4561. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4562. f"-> tray {idx_match['global_tray_id']}"
  4563. )
  4564. elif len(idx_matches) > 1:
  4565. # Multiple trays with same tray_info_idx - use color matching among them
  4566. logger.debug(
  4567. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4568. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4569. )
  4570. if prefer_lowest:
  4571. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4572. # Use color matching within this subset
  4573. for f in idx_matches:
  4574. f_color = f.get("color", "")
  4575. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4576. if not exact_match:
  4577. exact_match = f
  4578. elif self._colors_are_similar(f_color, req_color):
  4579. distance = self._color_distance(f_color, req_color)
  4580. if distance is not None and distance < similar_distance:
  4581. similar_match = f
  4582. similar_distance = distance
  4583. elif not type_only_match:
  4584. type_only_match = f
  4585. # If no idx_match yet, do standard type/color matching on all available trays
  4586. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4587. for f in available:
  4588. f_type = (f.get("type") or "").upper()
  4589. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4590. continue
  4591. # Type matches - check color
  4592. f_color = f.get("color", "")
  4593. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4594. if not exact_match:
  4595. exact_match = f
  4596. elif self._colors_are_similar(f_color, req_color):
  4597. # Nearest wins, not first-in-tray-order. `available` is
  4598. # already in the caller's order (slot order, or the
  4599. # prefer-lowest sort), and `<` keeps the earliest of
  4600. # equally close spools — so that order survives as the
  4601. # tie-break (#2804).
  4602. distance = self._color_distance(f_color, req_color)
  4603. if distance is not None and distance < similar_distance:
  4604. similar_match = f
  4605. similar_distance = distance
  4606. elif not type_only_match:
  4607. type_only_match = f
  4608. match = idx_match or exact_match or similar_match or type_only_match
  4609. if match:
  4610. used_tray_ids.add(match["global_tray_id"])
  4611. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4612. else:
  4613. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4614. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4615. # "Why did it pick that spool" is the question every wrong-filament
  4616. # report starts with, and a `similar_color` win is now a ranked
  4617. # choice among several eligible spools rather than whichever tray
  4618. # came first, so it is worth being able to see after the fact.
  4619. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4620. # is on (#1766).
  4621. if match:
  4622. bucket = (
  4623. "idx"
  4624. if idx_match is not None
  4625. else "exact_color"
  4626. if exact_match is not None
  4627. else "similar_color"
  4628. if similar_match is not None
  4629. else "type_only"
  4630. )
  4631. logger.info(
  4632. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4633. match["global_tray_id"],
  4634. bucket,
  4635. req.get("slot_id"),
  4636. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4637. )
  4638. else:
  4639. logger.info(
  4640. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4641. req.get("slot_id"),
  4642. req_type,
  4643. req_color,
  4644. req_tray_info_idx,
  4645. ", force color match" if forced else "",
  4646. )
  4647. # Build mapping array
  4648. if not comparisons:
  4649. return None
  4650. max_slot_id = max(c["slot_id"] for c in comparisons)
  4651. if max_slot_id <= 0:
  4652. return None
  4653. mapping = [-1] * max_slot_id
  4654. for c in comparisons:
  4655. slot_id = c["slot_id"]
  4656. if slot_id and slot_id > 0:
  4657. mapping[slot_id - 1] = c["global_tray_id"]
  4658. return mapping
  4659. def _mark_printer_dispatched(
  4660. self,
  4661. printer_id: int,
  4662. pre_state: str | None,
  4663. pre_subtask_id: str | None,
  4664. ) -> None:
  4665. """Record that a print command was just sent to ``printer_id``.
  4666. Held until either the watchdog observes a state/subtask transition
  4667. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4668. """
  4669. if not pre_state:
  4670. # No pre_state means we can't detect a transition — fall back to a
  4671. # pure time-based hold using empty string as a sentinel that won't
  4672. # match any real printer state.
  4673. pre_state = ""
  4674. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4675. def _release_dispatch_hold(self, printer_id: int) -> None:
  4676. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4677. self._dispatch_holds.pop(printer_id, None)
  4678. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4679. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4680. Returns False (and clears the hold) once any of these are true:
  4681. - hard timeout (``_dispatch_max_hold``) has elapsed
  4682. - the printer has transitioned out of pre_state and we're past the
  4683. minimum cooldown
  4684. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4685. past the minimum cooldown
  4686. Otherwise the printer is held — caller should treat it as busy.
  4687. """
  4688. entry = self._dispatch_holds.get(printer_id)
  4689. if not entry:
  4690. return False
  4691. started_at, pre_state, pre_subtask_id = entry
  4692. elapsed = time.monotonic() - started_at
  4693. if elapsed >= self._dispatch_max_hold:
  4694. self._dispatch_holds.pop(printer_id, None)
  4695. return False
  4696. # Without a pre_state we can't detect a transition — fall back to the
  4697. # min cooldown alone, then drop the hold.
  4698. if not pre_state:
  4699. if elapsed >= self._dispatch_min_cooldown:
  4700. self._dispatch_holds.pop(printer_id, None)
  4701. return False
  4702. return True
  4703. status = printer_manager.get_status(printer_id)
  4704. current_state = getattr(status, "state", None) if status else None
  4705. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4706. transitioned = (current_state is not None and current_state != pre_state) or (
  4707. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4708. )
  4709. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4710. self._dispatch_holds.pop(printer_id, None)
  4711. return False
  4712. return True
  4713. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4714. """Check if a printer is connected and idle."""
  4715. if not printer_manager.is_connected(printer_id):
  4716. logger.debug("Printer %d: not connected", printer_id)
  4717. return False
  4718. state = printer_manager.get_status(printer_id)
  4719. if not state:
  4720. logger.debug("Printer %d: no status available", printer_id)
  4721. return False
  4722. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4723. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4724. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4725. # printer, it boots back into IDLE with no memory of the previous finish; without
  4726. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4727. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4728. logger.debug(
  4729. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4730. printer_id,
  4731. state.state,
  4732. )
  4733. return False
  4734. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4735. if not idle:
  4736. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4737. return False
  4738. # A print would run from the SD card the firmware is being written to.
  4739. from backend.app.services.firmware_update import upload_in_progress
  4740. if upload_in_progress(printer_id):
  4741. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4742. return False
  4743. return True
  4744. @staticmethod
  4745. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4746. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4747. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4748. and that the fixed-printer branch has already found connected, so the two
  4749. offline cases answer at their own exits and never arrive here.
  4750. The default is the model-based branch's ``Busy:`` wording, which
  4751. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4752. the right answer for the connected-but-no-telemetry second or two after a
  4753. reconnect: the model-based branch has always reported it that way, and it
  4754. is not something to wake anybody up for.
  4755. A plate nobody has confirmed is the one case here that does not resolve
  4756. itself — somebody has to walk over to the printer — so it is worded as
  4757. itself and allowed to notify.
  4758. """
  4759. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4760. return f"Waiting for plate confirmation: {printer_name}"
  4761. return f"Busy: {printer_name}"
  4762. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4763. """Read a setting value from the database."""
  4764. result = await db.execute(select(Settings).where(Settings.key == key))
  4765. setting = result.scalar_one_or_none()
  4766. return setting.value if setting else None
  4767. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4768. """Read a boolean setting from the database."""
  4769. result = await db.execute(select(Settings).where(Settings.key == key))
  4770. setting = result.scalar_one_or_none()
  4771. if setting:
  4772. return setting.value.lower() == "true"
  4773. return default
  4774. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4775. """Read an int setting; falls back to default on missing/unparseable rows."""
  4776. result = await db.execute(select(Settings).where(Settings.key == key))
  4777. setting = result.scalar_one_or_none()
  4778. if setting and setting.value:
  4779. try:
  4780. return int(setting.value)
  4781. except ValueError:
  4782. pass
  4783. return default
  4784. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4785. """Get drying presets (user-configured or built-in defaults)."""
  4786. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4787. setting = result.scalar_one_or_none()
  4788. if setting and setting.value:
  4789. try:
  4790. presets = json.loads(setting.value)
  4791. if isinstance(presets, dict) and presets:
  4792. return presets
  4793. except json.JSONDecodeError:
  4794. pass
  4795. return self.DEFAULT_DRYING_PRESETS
  4796. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4797. """Per-filament humidity thresholds (#1605).
  4798. Returns the user-configured overrides map keyed by normalized filament
  4799. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4800. unknown / unmapped types. Empty / unset → empty dict, in which case
  4801. callers fall back to ``ams_humidity_fair``.
  4802. """
  4803. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4804. setting = result.scalar_one_or_none()
  4805. if not setting or not setting.value:
  4806. return {}
  4807. try:
  4808. data = json.loads(setting.value)
  4809. except json.JSONDecodeError:
  4810. return {}
  4811. if not isinstance(data, dict):
  4812. return {}
  4813. out: dict[str, int] = {}
  4814. for key, value in data.items():
  4815. try:
  4816. out[str(key).upper() if key != "default" else "default"] = int(value)
  4817. except (TypeError, ValueError):
  4818. continue
  4819. return out
  4820. # Materials whose AMS spelling differs from the key the tables above use.
  4821. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4822. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4823. # good PA row (#3067).
  4824. #
  4825. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4826. # The drying popover has resolved these correctly since #2774 and the
  4827. # scheduler never did, which is exactly why #3067's reporter could dry a
  4828. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4829. #
  4830. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4831. # of nylon, so it is the one entry that is a judgement rather than a
  4832. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4833. # way, and PA's row is the hottest the table has. Drying it there is closer
  4834. # to right than not drying it at all, which is what it got before.
  4835. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4836. "NYLON": "PA",
  4837. "PA6": "PA",
  4838. "PA11": "PA",
  4839. "PA12": "PA",
  4840. "PAHT": "PA",
  4841. "PPA": "PA",
  4842. }
  4843. @classmethod
  4844. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4845. """The key in *table* that answers for this tray's material, or None.
  4846. The printer reports the material in ``tray_type``, and it spells filled
  4847. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4848. tables here are keyed by base material, so matching the raw string alone
  4849. found a row for 8 of the 41 types a printer can report and skipped the
  4850. rest -- silently, because every caller reads "no row" as "nothing to do
  4851. for this tray". Auto-drying therefore ignored every composite spool on
  4852. the install (#3067).
  4853. Exact match first, so a table the user has extended with a row of its
  4854. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4855. base material's. Then the suffix is dropped, then the alias map above
  4856. answers for the polyamide spellings.
  4857. Returns None rather than a default: what to do with an unrecognised
  4858. material differs per caller, and only the caller knows whether "no row"
  4859. means skip the tray or fall back to a catch-all. Nothing here invents a
  4860. temperature for a material the table does not list.
  4861. """
  4862. raw = cls._normalize_filament_type(tray_type or "")
  4863. if not raw:
  4864. return None
  4865. for candidate in (raw, raw.split("-")[0]):
  4866. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4867. if key in table:
  4868. return key
  4869. return None
  4870. @staticmethod
  4871. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4872. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4873. For mixed filament types loaded into one AMS, returns the most
  4874. restrictive (lowest) threshold across all loaded tray types — matches
  4875. the conservative-params strategy already used for drying temp/hours.
  4876. Empty / unloaded trays contribute no constraint. Unknown types use the
  4877. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4878. when no per-type map is configured at all.
  4879. """
  4880. default = thresholds.get("default", fallback)
  4881. if not thresholds:
  4882. return fallback
  4883. candidates: list[int] = []
  4884. for tray in trays:
  4885. tray_type = str(tray.get("tray_type") or "").strip()
  4886. if not tray_type:
  4887. continue
  4888. # A composite carries its base material's threshold when it has no
  4889. # row of its own, the same way it takes its drying preset (#3067).
  4890. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4891. candidates.append(thresholds[key] if key is not None else default)
  4892. if not candidates:
  4893. return default
  4894. return min(candidates)
  4895. def _get_conservative_drying_params(
  4896. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4897. ) -> tuple[int, int, str] | None:
  4898. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4899. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4900. """
  4901. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4902. hours_key = f"{temp_key}_hours"
  4903. min_temp = None
  4904. max_hours = None
  4905. filament_type = ""
  4906. for tray in trays:
  4907. tray_type = tray.get("tray_type", "")
  4908. if not tray_type:
  4909. continue
  4910. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4911. # which is what stopped auto-drying on every composite spool (#3067).
  4912. base_type = self._resolve_filament_key(tray_type, presets)
  4913. if base_type is None:
  4914. continue
  4915. # The table is user-editable JSON with no per-row validation, so a
  4916. # row can be present and empty. That has always meant "skip this
  4917. # material", and it has to keep meaning it: the reads below fall
  4918. # back to 55C/12h per missing field, which is a temperature nobody
  4919. # chose and would deform a PLA spool.
  4920. preset = presets[base_type]
  4921. if not preset:
  4922. continue
  4923. temp = preset.get(temp_key, 55)
  4924. hours = preset.get(hours_key, 12)
  4925. # Conservative: lowest temp, longest duration
  4926. if min_temp is None or temp < min_temp:
  4927. min_temp = temp
  4928. if max_hours is None or hours > max_hours:
  4929. max_hours = hours
  4930. if not filament_type:
  4931. filament_type = base_type
  4932. if min_temp is None:
  4933. return None
  4934. return (min_temp, max_hours or 12, filament_type)
  4935. async def _check_filament_low(self, db: AsyncSession) -> None:
  4936. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4937. ``on_filament_low`` has had a column, a schema field, a route, a template
  4938. and a UI toggle since the notification system was built, and no caller --
  4939. so the toggle could be switched on and could never fire. This is the
  4940. producer.
  4941. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4942. ``low_stock_threshold_pct`` override is already exactly this decision:
  4943. already configurable, already surfaced, already driving the Inventory
  4944. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4945. consulted -- it has been measured up to 56 points out against a scale,
  4946. which is not a number to page someone on.
  4947. Only slots with an assigned spool produce an event. A slot Bambuddy
  4948. cannot resolve to a spool has no remaining weight it can stand behind,
  4949. and guessing one is how the remain percentage would have got in.
  4950. """
  4951. from backend.app.models.spool import Spool
  4952. # Time-gated rather than run on every pass. run() sleeps
  4953. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4954. # early-return path counts as productive while an upload is in flight
  4955. # (#2602), so an unthrottled check would re-read the whole spool
  4956. # collection every 3 seconds for the length of a batch drain. In
  4957. # Spoolman mode that is a request storm against a third-party service,
  4958. # which is the thing this producer's design note argues against; and
  4959. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4960. # check_queue holding the scheduler's session, so the outage would
  4961. # throttle the print queue itself. A low spool is not a 3-second
  4962. # concern -- the idle interval is the natural resolution.
  4963. now = time.monotonic()
  4964. if now < self._filament_low_next_check:
  4965. return
  4966. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4967. try:
  4968. # on_filament_low defaults to off on every provider, so on most
  4969. # installs nobody wants this alert. Without this the check would
  4970. # still read every assigned spool each interval -- the whole
  4971. # collection over HTTP in Spoolman mode -- for an event that is
  4972. # switched off. One query against the provider table settles it
  4973. # before any spool work, the same guard the bed-cooled waiter uses.
  4974. # No printer_id: this asks whether any provider wants the event at
  4975. # all; per-printer scoping is applied when the event is sent.
  4976. #
  4977. # While nobody wants it, no pass sees a slot go back above its
  4978. # threshold, so nothing can re-arm; a spool refilled under the same
  4979. # id in that time would stay silenced until a restart. Forgetting
  4980. # what was sent is right anyway: whoever switches the event back on
  4981. # is told about the spools that are low now.
  4982. #
  4983. # The MQTT relay publishes the same event, so a connected relay is
  4984. # reason enough to run the check. Its record is forgotten when the
  4985. # relay is switched off, not when the broker drops: a reconnect must
  4986. # not re-send every low slot.
  4987. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4988. relay = mqtt_relay.enabled and mqtt_relay.connected
  4989. if not notify:
  4990. self._notified_filament_low.clear()
  4991. if not mqtt_relay.enabled:
  4992. self._relayed_filament_low.clear()
  4993. if not notify and not relay:
  4994. return
  4995. global_threshold = await self._get_low_stock_threshold(db)
  4996. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4997. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4998. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4999. if spoolman_on:
  5000. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  5001. else:
  5002. rows = (
  5003. await db.execute(
  5004. select(SpoolAssignment, Spool)
  5005. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  5006. # An archived spool is not stock. The Inventory page's
  5007. # Low Stock count skips them (InventoryPage.tsx:1089)
  5008. # and get_all_spools without allow_archived already
  5009. # excludes them in Spoolman mode, so without this the
  5010. # internal path is the only one that alerts on them.
  5011. .where(Spool.archived_at.is_(None))
  5012. )
  5013. ).all()
  5014. for assignment, spool in rows:
  5015. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  5016. if pct is None:
  5017. continue
  5018. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  5019. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  5020. pct,
  5021. threshold,
  5022. spool.color_name,
  5023. )
  5024. if not slots:
  5025. # Nothing resolvable this pass. Deliberately not clearing the
  5026. # notified set: a Spoolman that is briefly unreachable would
  5027. # otherwise re-alert on every spool as soon as it came back.
  5028. return
  5029. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  5030. except Exception as e:
  5031. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  5032. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  5033. """The global low-stock percentage, defaulting to the schema's 20.0."""
  5034. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  5035. if raw is None or raw.value is None:
  5036. return 20.0
  5037. try:
  5038. value = float(raw.value)
  5039. except (TypeError, ValueError):
  5040. return 20.0
  5041. return value if 0 < value <= 100 else 20.0
  5042. async def _filament_low_slots_spoolman(
  5043. self, db: AsyncSession, global_threshold: float
  5044. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  5045. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  5046. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  5047. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  5048. so the global threshold is the only one that applies here. That matches
  5049. what the Inventory page already does in this mode.
  5050. One ``get_all_spools`` call covers every slot rather than a request per
  5051. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  5052. without ``allow_archived`` -- which is the behaviour the internal path
  5053. has to ask for explicitly.
  5054. An unreachable Spoolman returns no slots rather than raising. It is an
  5055. ordinary state for a third-party service, not an error in this pass: the
  5056. caller's "nothing resolvable" branch already leaves the notified set
  5057. alone, which is exactly right here, whereas letting it reach the broad
  5058. ``except`` would write a full traceback every time the check runs.
  5059. """
  5060. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5061. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5062. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  5063. if not assignments:
  5064. return {}
  5065. client = await get_spoolman_client()
  5066. if client is None:
  5067. return {}
  5068. try:
  5069. all_spools = await client.get_all_spools()
  5070. except SpoolmanUnavailableError as e:
  5071. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  5072. return {}
  5073. by_id: dict[int, dict] = {}
  5074. for raw in all_spools:
  5075. raw_id = raw.get("id")
  5076. if isinstance(raw_id, int):
  5077. by_id[raw_id] = raw
  5078. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5079. for assignment in assignments:
  5080. raw = by_id.get(assignment.spoolman_spool_id)
  5081. if raw is None:
  5082. continue
  5083. try:
  5084. mapped = _map_spoolman_spool(raw)
  5085. except ValueError:
  5086. continue
  5087. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  5088. if pct is None:
  5089. continue
  5090. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  5091. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  5092. return slots
  5093. async def _emit_filament_low(
  5094. self,
  5095. db: AsyncSession,
  5096. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  5097. *,
  5098. notify: bool = True,
  5099. relay: bool = False,
  5100. ) -> None:
  5101. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  5102. printers: dict[int, Printer] = {}
  5103. for key, (pct, threshold, color) in slots.items():
  5104. printer_id, ams_id, tray_id, spool_id = key
  5105. if pct >= threshold:
  5106. # Back above the line: re-arm rather than expire on a timer, so a
  5107. # refilled slot can alert again and a spool sitting just under the
  5108. # threshold stays quiet.
  5109. self._notified_filament_low.discard(key)
  5110. self._relayed_filament_low.discard(key)
  5111. continue
  5112. send_notification = notify and key not in self._notified_filament_low
  5113. # Only while connected, so a crossing the relay missed reaches it
  5114. # after the reconnect.
  5115. send_relay = relay and key not in self._relayed_filament_low
  5116. if not send_notification and not send_relay:
  5117. continue
  5118. # Marked before sending, which is a choice rather than the only
  5119. # option, and it is the opposite failure mode from the one the
  5120. # debounce argues against: one transient provider failure loses this
  5121. # alert until the spool goes back above the threshold and crosses it
  5122. # again. Marking after a successful send would trade that for
  5123. # re-alerting on every pass while a provider is down -- which is the
  5124. # repetition the whole debounce exists to prevent, and the louder of
  5125. # the two failures. A spool that is low stays low, so the next real
  5126. # signal is not far away; a provider stuck retrying is a signal that
  5127. # never stops.
  5128. if send_notification:
  5129. self._notified_filament_low.add(key)
  5130. if send_relay:
  5131. self._relayed_filament_low.add(key)
  5132. if printer_id not in printers:
  5133. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5134. if printer is None:
  5135. continue
  5136. printers[printer_id] = printer
  5137. printer = printers[printer_id]
  5138. slot = _ams_slot_label(ams_id, tray_id)
  5139. if send_notification:
  5140. try:
  5141. await notification_service.on_filament_low(
  5142. printer_id,
  5143. printer.name,
  5144. slot,
  5145. int(pct),
  5146. db,
  5147. color=color,
  5148. )
  5149. except Exception as e:
  5150. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5151. if send_relay:
  5152. try:
  5153. await mqtt_relay.on_filament_low(
  5154. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5155. )
  5156. except Exception as e:
  5157. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5158. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5159. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5160. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5161. a schema field, a template and a UI toggle, and nothing that computes the
  5162. condition -- the Forecast panel does it in the browser, so with no page
  5163. open nothing could ever alert. This runs the same arithmetic
  5164. (``stock_forecast``) from the scheduler loop.
  5165. An alert is sent when a SKU *moves into* a condition, once, and again
  5166. after the condition has cleared. A SKU that worsens from reorder to break
  5167. alerts again as a break, because the panel treats the two as exclusive; one
  5168. that eases from break back to reorder does not alert again.
  5169. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5170. while it is still low tells you.
  5171. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5172. loop runs every 3 s while an upload is in flight, and the whole spool
  5173. collection is read over HTTP in Spoolman mode. Both events default to off
  5174. on every provider, so nothing is read unless a provider wants one.
  5175. """
  5176. now = time.monotonic()
  5177. if now < self._stock_forecast_next_check:
  5178. return
  5179. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5180. try:
  5181. if self._stock_alerts_persisted is None:
  5182. await self._load_stock_alerts(db)
  5183. wanted = {
  5184. "reorder": bool(
  5185. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5186. ),
  5187. "break": bool(
  5188. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5189. ),
  5190. }
  5191. if not any(wanted.values()):
  5192. # Nobody wants either event. Forget what was sent, so whoever
  5193. # switches one on is told about the SKUs that are low now.
  5194. self._notified_stock_alerts.clear()
  5195. await self._save_stock_alerts(db)
  5196. return
  5197. forecasts = await self._stock_forecasts(db)
  5198. if forecasts is None:
  5199. # Spoolman unreachable. Deliberately not clearing the notified
  5200. # set: a brief outage would otherwise re-alert every SKU when it
  5201. # came back.
  5202. return
  5203. await self._emit_stock_alerts(db, forecasts, wanted)
  5204. await self._save_stock_alerts(db)
  5205. except Exception as e:
  5206. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5207. def _serialize_stock_alerts(self) -> str:
  5208. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5209. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5210. return json.dumps(rows)
  5211. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5212. """Read the notified set saved by the last run, once per process.
  5213. A missing or unreadable row is an empty set: the worst that does is one
  5214. repeat of what a restart used to cause every time.
  5215. """
  5216. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5217. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5218. if raw and raw.value:
  5219. try:
  5220. for key, kind, events in json.loads(raw.value):
  5221. if len(key) == 4 and kind in ("reorder", "break"):
  5222. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5223. except (ValueError, TypeError):
  5224. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5225. loaded = {}
  5226. self._notified_stock_alerts = loaded
  5227. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5228. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5229. """Write the notified set to its settings row if it changed since it was last read or written."""
  5230. serialized = self._serialize_stock_alerts()
  5231. if serialized == self._stock_alerts_persisted:
  5232. return
  5233. from backend.app.core.db_dialect import upsert_setting
  5234. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5235. await db.commit()
  5236. self._stock_alerts_persisted = serialized
  5237. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5238. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5239. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5240. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5241. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5242. sku_settings = {
  5243. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5244. lead_time_days=row.lead_time_days,
  5245. safety_margin_value=row.safety_margin_value,
  5246. safety_margin_unit=row.safety_margin_unit,
  5247. alerts_snoozed=bool(row.alerts_snoozed),
  5248. )
  5249. for row in sku_rows
  5250. }
  5251. if await self._get_bool_setting(db, "spoolman_enabled"):
  5252. spools = await self._stock_spools_spoolman()
  5253. if spools is None:
  5254. return None
  5255. # The Spoolman spools' own rows (#3407), keyed by Spoolman id. Never
  5256. # the built-in ones: a Spoolman id that matches a local spool id
  5257. # (left over from before Spoolman was switched on) would borrow an
  5258. # unrelated spool's history (#3406).
  5259. history = await self._stock_usage_history(db, spoolman=True)
  5260. history = {
  5261. spool.id: stock_forecast.own_records(spool, history[spool.id])
  5262. for spool in spools
  5263. if spool.id in history
  5264. }
  5265. else:
  5266. spools = await self._stock_spools_internal(db)
  5267. history = await self._stock_usage_history(db)
  5268. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5269. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5270. from backend.app.models.spool import Spool
  5271. # Every spool: stock, the recently archived ones that count towards the
  5272. # rate, and the older ones that tell it the SKU was in use before its
  5273. # window (#3407). stock_forecast.forecast_all sorts them.
  5274. rows = (await db.execute(select(Spool))).scalars().all()
  5275. return [
  5276. stock_forecast.StockSpool(
  5277. id=spool.id,
  5278. material=spool.material,
  5279. subtype=spool.subtype,
  5280. brand=spool.brand,
  5281. color_name=spool.color_name,
  5282. label_weight=float(spool.label_weight or 0),
  5283. weight_used=float(spool.weight_used or 0),
  5284. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5285. created_at=spool.created_at,
  5286. archived_at=spool.archived_at,
  5287. last_used_at=spool.last_used,
  5288. )
  5289. for spool in rows
  5290. ]
  5291. async def _stock_usage_history(
  5292. self, db: AsyncSession, *, spoolman: bool = False
  5293. ) -> dict[int, list[stock_forecast.UsageRecord]]:
  5294. """Usage rows by spool id, for one inventory: its own ids, as the forecast
  5295. panel reads them from the usage endpoint."""
  5296. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5297. spool_id = SpoolUsageHistory.spoolman_spool_id if spoolman else SpoolUsageHistory.spool_id
  5298. rows = (
  5299. await db.execute(
  5300. select(spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5301. .where(
  5302. SpoolUsageHistory.spoolman_spool_id.is_not(None)
  5303. if spoolman
  5304. else SpoolUsageHistory.spoolman_spool_id.is_(None)
  5305. )
  5306. .order_by(SpoolUsageHistory.created_at.desc())
  5307. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5308. )
  5309. ).all()
  5310. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5311. for spool_id, created_at, weight_used in rows:
  5312. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5313. # filtered before the limit, so the window matches the forecast panel's.
  5314. if created_at is None or spool_id is None:
  5315. continue
  5316. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5317. return history
  5318. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5319. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5320. Archived ones too: a recently used-up spool counts towards its SKU's
  5321. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5322. page (and so the panel) reads; it dates archiving by the spool's last
  5323. use, as Spoolman records no archive date.
  5324. """
  5325. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5326. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5327. client = await get_spoolman_client()
  5328. if client is None:
  5329. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5330. return None
  5331. try:
  5332. raw_spools = await client.get_all_spools(allow_archived=True)
  5333. except SpoolmanUnavailableError as e:
  5334. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5335. return None
  5336. spools: list[stock_forecast.StockSpool] = []
  5337. for raw in raw_spools:
  5338. try:
  5339. mapped = _map_spoolman_spool(raw)
  5340. except ValueError:
  5341. continue
  5342. created_at = _spoolman_time(mapped.get("created_at"))
  5343. archived_at = None
  5344. if raw.get("archived"):
  5345. # Archived without a date to tell when: not stock, and too old to
  5346. # count towards the rate.
  5347. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5348. spools.append(
  5349. stock_forecast.StockSpool(
  5350. id=mapped["id"],
  5351. material=mapped["material"],
  5352. subtype=mapped.get("subtype"),
  5353. brand=mapped.get("brand"),
  5354. color_name=mapped.get("color_name"),
  5355. label_weight=float(mapped.get("label_weight") or 0),
  5356. weight_used=float(mapped.get("weight_used") or 0),
  5357. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5358. created_at=created_at,
  5359. archived_at=archived_at,
  5360. first_used_at=_spoolman_time(mapped.get("first_used")),
  5361. last_used_at=_spoolman_time(mapped.get("last_used")),
  5362. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5363. )
  5364. )
  5365. return spools
  5366. async def _emit_stock_alerts(
  5367. self,
  5368. db: AsyncSession,
  5369. forecasts: stock_forecast.ForecastMap,
  5370. wanted: dict[str, bool],
  5371. ) -> None:
  5372. """Send the notifications for each SKU that has moved into a stock alert condition.
  5373. A SKU in break has also reached its reorder point, so both events apply to
  5374. it: the break event goes to providers that have it on, and the reorder event
  5375. to the providers that have only that one on. A provider with both on gets the
  5376. break and no second message.
  5377. What is remembered per SKU is the condition and which events had a
  5378. subscriber when it was sent. An event with no subscriber is forgotten, so
  5379. switching it on later reports the SKUs already in that condition.
  5380. """
  5381. active_events = {event for event, on in wanted.items() if on}
  5382. for key, (forecast, spool) in forecasts.items():
  5383. kind: str | None = None
  5384. if not forecast.snoozed:
  5385. if forecast.stock_break_alert:
  5386. kind = "break"
  5387. elif forecast.reorder_alert:
  5388. kind = "reorder"
  5389. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5390. events = applicable & active_events
  5391. if not events:
  5392. self._notified_stock_alerts.pop(key, None)
  5393. continue
  5394. previous = self._notified_stock_alerts.get(key)
  5395. told = (previous[1] & active_events) if previous else frozenset()
  5396. # Trimmed to the events this condition can send. That is what makes easing from
  5397. # break back to reorder silent (the reorder event was told with the break) and
  5398. # worsening again news again (the break event is no longer remembered).
  5399. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5400. # Recorded before sending, for the reason _emit_filament_low gives: a
  5401. # provider that is down should lose this alert, not repeat it every hour.
  5402. to_send = events - told
  5403. # Both flags imply a positive rate and so a day count.
  5404. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5405. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5406. color = None if spool.color_name_is_synthesized else spool.color_name
  5407. try:
  5408. if "break" in to_send:
  5409. await notification_service.on_stock_break_alert(
  5410. spool.material,
  5411. spool.brand,
  5412. forecast.remaining_g,
  5413. rate,
  5414. days_left,
  5415. forecast.effective_lead_time_days,
  5416. db,
  5417. subtype=spool.subtype,
  5418. color=color,
  5419. )
  5420. if "reorder" in to_send:
  5421. await notification_service.on_stock_reorder_alert(
  5422. spool.material,
  5423. spool.brand,
  5424. forecast.remaining_g,
  5425. rate,
  5426. days_left,
  5427. db,
  5428. subtype=spool.subtype,
  5429. color=color,
  5430. skip_break_subscribers=kind == "break",
  5431. )
  5432. except Exception as e:
  5433. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5434. # A SKU with no spools left is no longer alerting.
  5435. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5436. del self._notified_stock_alerts[key]
  5437. @staticmethod
  5438. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5439. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5440. from backend.app.core.auth import is_auth_enabled
  5441. if user_id is None or not await is_auth_enabled(db):
  5442. return ALL_PRINTERS
  5443. return await resolve_user_id_printer_scope(db, user_id)
  5444. async def _model_job_printer_ids(
  5445. self,
  5446. db: AsyncSession,
  5447. item: PrintQueueItem,
  5448. scope: PrinterScope,
  5449. cache: dict[tuple[str, str | None, int | None], set[int]],
  5450. ) -> set[int]:
  5451. """Every printer an "Any <model>" job could land on: the active printers
  5452. of each of its candidate models, in its location, that its creator may use.
  5453. ``cache`` holds one lookup per model, location and creator for the pass,
  5454. so a long queue of model jobs does not query once per job."""
  5455. printer_ids: set[int] = set()
  5456. for candidate in _candidates_for(item):
  5457. if not candidate.target_model:
  5458. continue
  5459. key = (candidate.target_model, item.target_location, item.created_by_id)
  5460. if key not in cache:
  5461. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5462. cache[key] = {printer.id for printer in printers}
  5463. printer_ids |= cache[key]
  5464. return printer_ids
  5465. async def _check_auto_drying(
  5466. self,
  5467. db: AsyncSession,
  5468. queue_items: list[PrintQueueItem],
  5469. dispatching_printers: set[int],
  5470. ):
  5471. """Start drying on idle printers based on humidity.
  5472. Three modes (can all be enabled independently):
  5473. - queue_drying_enabled: Dry between scheduled queue prints
  5474. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5475. - print_drying_enabled: Also evaluate printers that are currently printing,
  5476. when model+firmware supports "Print While Drying" (gated by
  5477. supports_drying_while_printing). Drying temperature is capped at
  5478. max(40, preset_temp - 5) to protect spools mid-print.
  5479. """
  5480. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5481. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5482. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5483. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5484. # The wait belongs to ambient drying: the settings UI only shows it while
  5485. # ambient drying is on, so a value left behind when ambient is turned off
  5486. # must not keep delaying the one path that still reaches the wait gate
  5487. # without it (a mid-print start under print_drying).
  5488. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5489. # Clear every streak as soon as the wait is inactive. An early return (or
  5490. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5491. # a quick toggle-on inherit an old streak.
  5492. if not sustained_wait_active:
  5493. self._auto_dry_above.clear()
  5494. if not queue_drying_enabled and not ambient_drying_enabled:
  5495. # Stop active drying on all printers if both features disabled
  5496. if self._drying_in_progress:
  5497. for pid in list(self._drying_in_progress):
  5498. if pid in self._scheduled_drying_printer_ids:
  5499. continue
  5500. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5501. await self._stop_drying(pid)
  5502. return
  5503. # Update drying state from printer status (handles backend restart)
  5504. self._sync_drying_state()
  5505. # Find printers with scheduled items (for queue drying mode)
  5506. # An "Any <model>" job counts for every printer it could land on.
  5507. printers_with_scheduled: set[int] = set()
  5508. # Printers with a job that could start now: the ones block mode keeps
  5509. # a new cycle off. A job waiting for its start time is what queue
  5510. # drying dries ahead of.
  5511. printers_with_ready_items: set[int] = set()
  5512. now_utc = datetime.now(timezone.utc)
  5513. creator_scopes: dict[int | None, PrinterScope] = {}
  5514. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5515. for item in queue_items:
  5516. if item.printer_id:
  5517. item_printers = {item.printer_id}
  5518. elif item.target_model or item.variants:
  5519. if item.created_by_id not in creator_scopes:
  5520. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5521. item_printers = await self._model_job_printer_ids(
  5522. db, item, creator_scopes[item.created_by_id], model_printers
  5523. )
  5524. else:
  5525. continue
  5526. if item.scheduled_time and not item.manual_start:
  5527. printers_with_scheduled |= item_printers
  5528. sched = item.scheduled_time
  5529. if sched is not None and sched.tzinfo is None:
  5530. sched = sched.replace(tzinfo=timezone.utc)
  5531. if sched is None or sched <= now_utc:
  5532. printers_with_ready_items |= item_printers
  5533. # If only queue mode is on and no printers have scheduled items, stop drying
  5534. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5535. # may still be eligible for mid-print drying regardless of queue state).
  5536. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5537. for pid in list(self._drying_in_progress):
  5538. if pid in self._scheduled_drying_printer_ids:
  5539. continue
  5540. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5541. await self._stop_drying(pid)
  5542. return
  5543. # Get humidity threshold (global fallback)
  5544. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5545. setting = result.scalar_one_or_none()
  5546. global_humidity_threshold = int(setting.value) if setting else 60
  5547. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5548. # to the global threshold for every AMS unit.
  5549. per_type_thresholds = await self._get_humidity_thresholds(db)
  5550. # Get drying presets
  5551. presets = await self._get_drying_presets(db)
  5552. # Determine if drying should be skipped for printers with pending items
  5553. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5554. # Get all active printers
  5555. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5556. for printer in all_printers.scalars():
  5557. pid = printer.id
  5558. # Resolve model+firmware up front — needed to decide whether this printer
  5559. # qualifies for mid-print drying (busy printer on capable hardware).
  5560. state = printer_manager.get_status(pid)
  5561. if not state:
  5562. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5563. continue
  5564. model = printer_manager.get_model(pid)
  5565. firmware = state.firmware_version
  5566. # "Mid-print" has to mean the printer is actually printing (#2801).
  5567. # It used to be inferred from the dispatch set, which also holds
  5568. # printers that merely could not be dispatched to -- so a printer
  5569. # sitting in FINISH behind an unacknowledged plate was treated as
  5570. # printing, had its drying temperature capped by the mid-print
  5571. # spool protection, and was logged as (mid-print) while idle.
  5572. is_printing = state.state in _ACTIVE_PRINT_STATES
  5573. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5574. # A printer whose print is running or imminent is left alone unless
  5575. # it can dry through it. `dispatching_printers` is deliberately the
  5576. # narrow set: running, held post-dispatch, or mid-upload.
  5577. if (is_printing or pid in dispatching_printers) and not mid_print:
  5578. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5579. continue
  5580. if not mid_print:
  5581. # In queue-only mode, only dry printers that have scheduled prints
  5582. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5583. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5584. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5585. await self._stop_drying(pid)
  5586. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5587. continue
  5588. # When block mode is on, don't START new drying on printers with
  5589. # a job that could start now: the cycle would hold it. One
  5590. # scheduled for later may pre-dry; if the cycle is still running
  5591. # at its time, the hold applies then. Already-drying printers go
  5592. # through so humidity auto-stop logic still runs.
  5593. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5594. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5595. continue
  5596. if not printer_manager.is_connected(pid):
  5597. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5598. continue
  5599. # Plate-clear is deliberately ignored here (#2801). It answers
  5600. # "is the bed ready for the next job", which says nothing about
  5601. # whether the AMS may heat -- and the gap between a finished print
  5602. # and the acknowledgment is exactly when drying is most useful,
  5603. # because the printer is free and nobody is waiting on it. Leaving
  5604. # the plate unacknowledged is also how people hold the queue by
  5605. # hand, and that hold should not cost them their drying.
  5606. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5607. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5608. continue
  5609. # Check drying capability. For mid-print path, supports_drying_while_printing
  5610. # was already verified when computing mid_print above.
  5611. if not mid_print and not supports_drying(model, firmware):
  5612. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5613. continue
  5614. # Check each AMS unit from raw_data
  5615. ams_list = state.raw_data.get("ams", [])
  5616. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5617. for ams_data in ams_list:
  5618. module_type = str(ams_data.get("module_type") or "")
  5619. ams_id = int(ams_data.get("id", 0))
  5620. # Only n3f/n3s support drying
  5621. if module_type not in ("n3f", "n3s"):
  5622. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5623. continue
  5624. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5625. # Most-restrictive of all loaded tray types; falls back to the
  5626. # global threshold when no overrides are configured.
  5627. trays = ams_data.get("tray", []) or []
  5628. humidity_threshold = self.resolve_humidity_threshold(
  5629. trays, per_type_thresholds, global_humidity_threshold
  5630. )
  5631. dry_time = int(ams_data.get("dry_time") or 0)
  5632. # Read humidity as a percentage. The 1-5 index is never
  5633. # substituted: it is inverted, and being unable to exceed any
  5634. # threshold it would read as "dry" forever (#3140). ``None``
  5635. # already means "skip this unit" everywhere below.
  5636. humidity_pct = ams_humidity_percent(ams_data)
  5637. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5638. unit_key = (pid, ams_id)
  5639. unit_state = self._auto_dry_units.get(unit_key)
  5640. # Already drying — let it run to its configured duration (#1892).
  5641. #
  5642. # We deliberately do NOT stop drying from a humidity re-check here.
  5643. # Relative humidity drops steeply in heated air, so the AMS sensor
  5644. # reads ~15-20% within minutes of the dryer starting even while the
  5645. # filament is still saturated. A humidity-based early-stop therefore
  5646. # always fires at the minimum-time floor, truncating both user-started
  5647. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5648. # The firmware stops when the configured duration elapses; scheduling
  5649. # stops (print takes priority, queue no longer needs drying) are
  5650. # handled separately via _stop_drying().
  5651. if dry_time > 0:
  5652. if pid not in self._drying_in_progress:
  5653. # Drying we didn't start (manual or from before restart) —
  5654. # track it so scheduling stops still apply; never auto-stop it.
  5655. self._drying_in_progress[pid] = time.monotonic()
  5656. if unit_state is not None:
  5657. unit_state["running"] = True
  5658. logger.debug(
  5659. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5660. pid,
  5661. ams_id,
  5662. dry_time,
  5663. humidity,
  5664. )
  5665. continue
  5666. # Nothing is drying. Close out a cycle we armed ourselves and
  5667. # judge whether it achieved anything (#2770).
  5668. #
  5669. # "Achieved anything" is measured against the LOWEST reading any
  5670. # cycle on this unit has ended at, not against the threshold and
  5671. # not against the previous cycle. A spool that is genuinely wet
  5672. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5673. # allowed to keep going for as long as it is still coming down,
  5674. # however far it still is from the threshold. What must not
  5675. # continue is a cycle that ends exactly where the last one did,
  5676. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5677. # Comparing against the running minimum rather than the previous
  5678. # end is what stops a sensor oscillating by one point between two
  5679. # values from reading as progress every other cycle.
  5680. if unit_state is not None and unit_state.pop("running", False):
  5681. unit_state["ended_at"] = time.monotonic()
  5682. # The streak that armed this cycle is spent; the next one
  5683. # starts fresh (and accumulates through the re-arm cooldown
  5684. # below, so the wait overlaps the cooldown, never stacks on
  5685. # top of it).
  5686. self._auto_dry_above.pop(unit_key, None)
  5687. if humidity is not None and humidity > humidity_threshold:
  5688. best = unit_state.get("best_end_humidity")
  5689. if isinstance(best, int) and humidity < best:
  5690. # Still coming down. Keep going, however far the
  5691. # threshold still is.
  5692. unproductive = 0
  5693. else:
  5694. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5695. if not isinstance(best, int) or humidity < best:
  5696. unit_state["best_end_humidity"] = humidity
  5697. unit_state["unproductive"] = unproductive
  5698. logger.info(
  5699. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5700. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5701. pid,
  5702. ams_id,
  5703. humidity,
  5704. humidity_threshold,
  5705. unit_state.get("best_end_humidity"),
  5706. unproductive,
  5707. )
  5708. # A cycle that ended at or below the threshold needs no
  5709. # counter reset here: the branch below drops the whole entry.
  5710. # Humidity below threshold — no need to start drying. This is
  5711. # also the only thing that lifts a suspension: the reading we
  5712. # gave up on has come down, so auto-drying works again and the
  5713. # unit goes back to having no history at all.
  5714. if humidity is None or humidity <= humidity_threshold:
  5715. if unit_state is not None and unit_state.get("suspended"):
  5716. logger.info(
  5717. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5718. "threshold, resuming automatic drying",
  5719. pid,
  5720. ams_id,
  5721. humidity,
  5722. humidity_threshold,
  5723. )
  5724. # Clear the judgement, keep the clock (#2801). Dropping the
  5725. # whole entry also dropped `ended_at`, and with it the
  5726. # 30-minute cooldown -- so a reading that dips to the
  5727. # threshold as the AMS cools and comes back above it once
  5728. # warm wiped its own history and re-armed immediately. That
  5729. # oscillation is the very thing #2770's cooldown exists to
  5730. # ride out, and it is worst at exactly the margin that makes
  5731. # a unit dry repeatedly: a point or two above the threshold.
  5732. if unit_state is not None:
  5733. unit_state.pop("suspended", None)
  5734. unit_state.pop("unproductive", None)
  5735. unit_state.pop("best_end_humidity", None)
  5736. # A real below-threshold reading ends any sustained-wait
  5737. # streak (#2518) -- "continuously above" means exactly that.
  5738. # An absent reading (humidity is None) is no-information and
  5739. # leaves the streak alone; the observation-gap guard handles
  5740. # a prolonged sensor silence.
  5741. if humidity is not None:
  5742. _above = self._auto_dry_above.pop(unit_key, None)
  5743. if _above is not None and sustained_wait_active:
  5744. logger.info(
  5745. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5746. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5747. pid,
  5748. ams_id,
  5749. humidity,
  5750. time.monotonic() - _above["since"],
  5751. sustained_minutes,
  5752. humidity_threshold,
  5753. )
  5754. logger.debug(
  5755. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5756. pid,
  5757. ams_id,
  5758. humidity,
  5759. humidity_threshold,
  5760. )
  5761. continue
  5762. # Sustained-humidity streak (#2518): updated on every pass that
  5763. # observes the reading above the threshold, BEFORE the
  5764. # suspension/cooldown gates below -- a suspended or cooling-down
  5765. # unit still accumulates streak time, so the wait overlaps those
  5766. # gates instead of stacking after them. Inert when the feature
  5767. # is off: no entries are written, and an entry left over from a
  5768. # toggle-off is dropped so it cannot seed a stale streak later.
  5769. if sustained_wait_active:
  5770. _now = time.monotonic()
  5771. # Four missed scheduler passes, floored: a single slow pass
  5772. # must not void a streak, but the ceiling has to scale with
  5773. # the cadence or a slow loop silently restarts every streak.
  5774. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5775. _above = self._auto_dry_above.get(unit_key)
  5776. if _above is None:
  5777. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5778. elif _now - _above["last"] > _gap_ceiling:
  5779. # Restart, and say so at the same level as the dip
  5780. # reset: a silent restart voids the streak invisibly,
  5781. # and a user who set a long wait and never gets a dry
  5782. # has no way to see why.
  5783. logger.info(
  5784. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5785. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5786. pid,
  5787. ams_id,
  5788. _now - _above["last"],
  5789. _gap_ceiling,
  5790. sustained_minutes,
  5791. )
  5792. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5793. else:
  5794. _above["last"] = _now
  5795. else:
  5796. self._auto_dry_above.pop(unit_key, None)
  5797. if unit_state is not None:
  5798. if unit_state.get("suspended"):
  5799. logger.debug(
  5800. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5801. "above the %d%% threshold",
  5802. pid,
  5803. ams_id,
  5804. int(unit_state.get("unproductive", 0)),
  5805. humidity_threshold,
  5806. )
  5807. continue
  5808. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5809. unit_state["suspended"] = True
  5810. logger.warning(
  5811. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5812. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5813. "higher while it is warm, so a threshold in that range can never be reached and "
  5814. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5815. pid,
  5816. ams_id,
  5817. int(unit_state.get("unproductive", 0)),
  5818. humidity,
  5819. humidity_threshold,
  5820. )
  5821. await self._notify_auto_drying_suspended(
  5822. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5823. )
  5824. continue
  5825. ended_at = unit_state.get("ended_at")
  5826. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5827. logger.debug(
  5828. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5829. "cycle before the humidity reading is worth acting on",
  5830. pid,
  5831. ams_id,
  5832. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5833. )
  5834. continue
  5835. # Check cannot-dry reasons (power constraints etc.). Sits
  5836. # ahead of the sustained wait so a unit the firmware refuses
  5837. # to dry never logs a wait it was never going to cash in.
  5838. sf_reasons = ams_data.get("dry_sf_reason", [])
  5839. if sf_reasons:
  5840. logger.debug(
  5841. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5842. pid,
  5843. ams_id,
  5844. sf_reasons,
  5845. )
  5846. continue
  5847. # Sustained-humidity wait (#2518): ambient-triggered starts
  5848. # wait; only a printer with a scheduled queue item pending
  5849. # keeps the instant behavior, because that drying has a real
  5850. # deadline. Mid-print is deliberately NOT exempt while ambient
  5851. # drying is on: a humidity start on a printer that happens to be
  5852. # printing is as vulnerable to a lid-open spike as one on an idle
  5853. # printer (proven live: a 2-point threshold crossing mid-print
  5854. # bought a parked 12h command). Inactive when ambient drying is
  5855. # off: print_drying then still starts mid-print cycles on its own
  5856. # (#1816, "regardless of queue state"), and those stay instant.
  5857. if sustained_wait_active and pid not in printers_with_scheduled:
  5858. _above = self._auto_dry_above.get(unit_key)
  5859. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5860. if _waited < sustained_minutes * 60:
  5861. logger.debug(
  5862. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5863. "threshold for %.0fs of the required %dm",
  5864. pid,
  5865. ams_id,
  5866. humidity,
  5867. humidity_threshold,
  5868. _waited,
  5869. sustained_minutes,
  5870. )
  5871. continue
  5872. # Get conservative drying params for mixed filaments
  5873. params = self._get_conservative_drying_params(trays, module_type, presets)
  5874. if not params:
  5875. logger.debug(
  5876. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5877. )
  5878. continue
  5879. temp, duration_hours, filament_type = params
  5880. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5881. # "drying temperature must not exceed the filament's softening temperature"
  5882. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5883. # ineffective and firmware will reject anyway.
  5884. if mid_print:
  5885. temp = max(40, temp - 5)
  5886. # Start drying
  5887. logger.info(
  5888. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5889. "starting %s drying at %d°C for %dh%s",
  5890. pid,
  5891. ams_id,
  5892. humidity,
  5893. humidity_threshold,
  5894. filament_type,
  5895. temp,
  5896. duration_hours,
  5897. " (mid-print)" if mid_print else "",
  5898. )
  5899. success = printer_manager.send_drying_command(
  5900. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5901. )
  5902. if success:
  5903. self._drying_in_progress[pid] = time.monotonic()
  5904. armed = self._auto_dry_units.setdefault(
  5905. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5906. )
  5907. armed["running"] = True
  5908. async def _notify_auto_drying_suspended(
  5909. self,
  5910. db: AsyncSession,
  5911. printer: Printer,
  5912. ams_id: int,
  5913. humidity: int,
  5914. threshold: int,
  5915. cycles: int,
  5916. ) -> None:
  5917. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5918. Fires once per suspension — the caller sets ``suspended`` before calling
  5919. and every later pass short-circuits on it — because the whole point is
  5920. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5921. building needs that to reach them, and the hourly humidity alarm they
  5922. are already getting says the opposite of what happened here.
  5923. Never raises: a notification provider being down must not stop the
  5924. suspension itself from taking effect.
  5925. """
  5926. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5927. try:
  5928. await notification_service.on_ams_drying_suspended(
  5929. printer.id,
  5930. printer.name,
  5931. ams_label,
  5932. float(humidity),
  5933. float(threshold),
  5934. cycles,
  5935. db,
  5936. )
  5937. except Exception as e:
  5938. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5939. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5940. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5941. The unproductive-cycle counter exists to notice that *drying* is not
  5942. moving the humidity reading. A cycle that ended because somebody sent a
  5943. stop says nothing about that — it was cut short before it had a chance —
  5944. so counting it would suspend auto-drying for a reason that has nothing to
  5945. do with the loop the counter is there to break.
  5946. Two callers, both of them a stop Bambuddy is responsible for: the
  5947. print-takes-priority stop below, and the manual Stop button. Left
  5948. uncalled, an install that dries between queue jobs would suspend its own
  5949. auto-drying after two prints interrupted a dry — exactly the install
  5950. queue-drying exists for.
  5951. The rest of the unit's history is kept: the cooldown before re-arming
  5952. still applies, and an earlier count still stands.
  5953. """
  5954. state = self._auto_dry_units.get((printer_id, ams_id))
  5955. if state is not None:
  5956. state.pop("running", None)
  5957. state["ended_at"] = time.monotonic()
  5958. # A stopped cycle spends the streak that armed it, same as a completed
  5959. # one (#2518).
  5960. self._auto_dry_above.pop((printer_id, ams_id), None)
  5961. def _sync_drying_state(self):
  5962. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5963. One direction only: it prunes, it never adds. A printer drying without an
  5964. entry here — because the user started the cycle from Studio, the printer's
  5965. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5966. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5967. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5968. That is deliberate for now rather than an oversight: populating this from
  5969. telemetry would hand the scheduler authority to stop drying a user started
  5970. by hand. It also means the backend-restart case this used to claim to
  5971. handle is not handled.
  5972. """
  5973. to_remove = []
  5974. for pid in self._drying_in_progress:
  5975. state = printer_manager.get_status(pid)
  5976. if not state:
  5977. to_remove.append(pid)
  5978. continue
  5979. # Check if any AMS unit is still drying
  5980. ams_list = state.raw_data.get("ams", [])
  5981. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5982. if not any_drying:
  5983. to_remove.append(pid)
  5984. for pid in to_remove:
  5985. self._drying_in_progress.pop(pid, None)
  5986. # A printer that has gone away entirely takes its per-AMS auto-drying
  5987. # history with it (#2770), so a printer deleted and re-added does not
  5988. # inherit a suspension it never earned.
  5989. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5990. self._auto_dry_units.pop(key, None)
  5991. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5992. # printer starts a fresh wait, and vanished printers do not leak
  5993. # entries.
  5994. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5995. self._auto_dry_above.pop(key, None)
  5996. @staticmethod
  5997. def _drying_is_only_parked(printer_id: int) -> bool:
  5998. """True when every AMS unit with a drying timer on this printer is parked.
  5999. A parked timer (#2896: the command was taken but the countdown never
  6000. runs) does not end on its own, so nothing may wait on it. False when no
  6001. unit reports a timer yet -- a command just sent that the firmware has not
  6002. reported back is real drying about to begin.
  6003. """
  6004. state = printer_manager.get_status(printer_id)
  6005. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  6006. timed = []
  6007. for unit in units:
  6008. try:
  6009. if int(unit.get("dry_time") or 0) > 0:
  6010. timed.append(unit)
  6011. except (TypeError, ValueError):
  6012. continue
  6013. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  6014. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  6015. """True when a running cycle can be left alone while the next print runs.
  6016. Some hardware dries happily through a print and #2758 settled that we
  6017. should not tear those cycles down: the X2D there was refusing to
  6018. *start* a job, which is a different problem, and stopping drying before
  6019. every dispatch would throw away cycles the printer was content to run.
  6020. Where the model cannot do it, or the user has not enabled it, the print
  6021. takes priority and the cycle stops -- which is what the queue_drying_block
  6022. setting has always promised in its off position.
  6023. """
  6024. if not await self._get_bool_setting(db, "print_drying_enabled"):
  6025. return False
  6026. status = printer_manager.get_status(printer_id)
  6027. return supports_drying_while_printing(
  6028. printer_manager.get_model(printer_id),
  6029. status.firmware_version if status else None,
  6030. )
  6031. async def _stop_drying(self, printer_id: int):
  6032. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  6033. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  6034. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  6035. enough to kill a cycle the user had started by hand on a *different*
  6036. unit of the same printer (#2801). That contradicted the contract
  6037. ``_sync_drying_state`` already documents -- the entry gate deliberately
  6038. only knows about cycles Bambuddy began, so the action must not reach
  6039. past them either.
  6040. """
  6041. state = printer_manager.get_status(printer_id)
  6042. if not state:
  6043. self._drying_in_progress.pop(printer_id, None)
  6044. return
  6045. ams_list = state.raw_data.get("ams", [])
  6046. for ams_data in ams_list:
  6047. dry_time = int(ams_data.get("dry_time") or 0)
  6048. if dry_time > 0:
  6049. ams_id = int(ams_data.get("id", 0))
  6050. if (printer_id, ams_id) not in self._auto_dry_units:
  6051. logger.debug(
  6052. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  6053. printer_id,
  6054. ams_id,
  6055. )
  6056. continue
  6057. logger.info(
  6058. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  6059. printer_id,
  6060. ams_id,
  6061. )
  6062. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  6063. self.forget_auto_dry_cycle(printer_id, ams_id)
  6064. self._drying_in_progress.pop(printer_id, None)
  6065. # Scheduled manual drying (#2638) -----------------------------------
  6066. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  6067. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  6068. async def _check_scheduled_dryings(self, db: AsyncSession):
  6069. """Dispatch due scheduled drying runs and track running ones."""
  6070. now = utcnow_naive()
  6071. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  6072. # Monotonic, so a clock adjustment cannot park the prune for hours.
  6073. since_prune = time.monotonic()
  6074. if (
  6075. self._last_scheduled_drying_prune is None
  6076. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  6077. ):
  6078. self._last_scheduled_drying_prune = since_prune
  6079. await db.execute(
  6080. delete(ScheduledDrying).where(
  6081. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  6082. ScheduledDrying.completed_at.is_not(None),
  6083. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  6084. )
  6085. )
  6086. # Same order as the list route: with two rows due on one printer the
  6087. # earliest scheduled wins rather than whatever the DB hands back first.
  6088. result = await db.execute(
  6089. select(ScheduledDrying)
  6090. .where(ScheduledDrying.status.in_(("pending", "running")))
  6091. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  6092. )
  6093. rows = list(result.scalars().all())
  6094. # Rebuild from the DB every tick so route-side cancels and completions
  6095. # show up. Auto-drying's stop-all branches check this set before
  6096. # stopping anything (#2638).
  6097. # Kept from the previous pass so a run that ended between passes — a
  6098. # cancel through the route, say — can still be released below.
  6099. previously_running = self._scheduled_drying_printer_ids
  6100. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6101. running_printer_ids = set(self._scheduled_drying_printer_ids)
  6102. # Model and firmware come from the printer row, not the live state.
  6103. printer_ids = {row.printer_id for row in rows}
  6104. printers_by_id: dict[int, Printer] = {}
  6105. if printer_ids:
  6106. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  6107. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  6108. for row in rows:
  6109. if row.status == "running":
  6110. self._update_running_scheduled_drying(row, now)
  6111. continue
  6112. if row.start_after is not None and row.start_after > now:
  6113. continue
  6114. state = printer_manager.get_status(row.printer_id)
  6115. if not state:
  6116. row.waiting_reason = "printer_offline"
  6117. continue
  6118. # Same preflight the immediate endpoint runs. Without it the publish
  6119. # succeeds, the row goes to running, the printer ignores the command
  6120. # and the run silently cancels itself after the grace window.
  6121. printer = printers_by_id.get(row.printer_id)
  6122. unsupported = drying_preflight.check_drying_supported(
  6123. printer.model if printer else None, state.firmware_version
  6124. )
  6125. if unsupported:
  6126. row.status = "failed"
  6127. row.error_message = unsupported
  6128. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6129. row.completed_at = now
  6130. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6131. continue
  6132. if (
  6133. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6134. ) or row.printer_id in running_printer_ids:
  6135. row.waiting_reason = "already_drying"
  6136. continue
  6137. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6138. row.waiting_reason = "printer_busy"
  6139. continue
  6140. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6141. if target is None:
  6142. row.waiting_reason = "ams_not_found"
  6143. continue
  6144. blocking = drying_preflight.blocking_reason_codes(target)
  6145. if blocking:
  6146. # Keep the power case distinct; it needs the user to act, so the
  6147. # card can say so instead of waiting silently.
  6148. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6149. continue
  6150. filament = drying_preflight.resolve_filament(target, row.filament)
  6151. logger.info(
  6152. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6153. row.id,
  6154. row.printer_id,
  6155. row.ams_id,
  6156. row.temp,
  6157. row.duration_hours,
  6158. )
  6159. success = printer_manager.send_drying_command(
  6160. row.printer_id,
  6161. row.ams_id,
  6162. row.temp,
  6163. row.duration_hours,
  6164. mode=1,
  6165. filament=filament,
  6166. rotate_tray=row.rotate_tray,
  6167. )
  6168. if success:
  6169. row.status = "running"
  6170. row.started_at = now
  6171. row.waiting_reason = None
  6172. row.filament = filament
  6173. self._drying_in_progress[row.printer_id] = time.monotonic()
  6174. self._scheduled_drying_printer_ids.add(row.printer_id)
  6175. running_printer_ids.add(row.printer_id)
  6176. else:
  6177. row.waiting_reason = "printer_offline"
  6178. # Release the printers whose run has ended. `_drying_in_progress` is
  6179. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6180. # but that call sits behind the auto-drying enabled check, and this
  6181. # method is the one writer that runs whether auto-drying is on or not.
  6182. # With it off, nothing would ever drop the entry short of a print being
  6183. # dispatched to the same printer, so the next scheduled run would wait
  6184. # on "already_drying" forever and `queue_drying_block` would hold the
  6185. # printer's prints too. Covers a run that ended during this pass and one
  6186. # cancelled through the route between passes.
  6187. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6188. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6189. self._drying_in_progress.pop(printer_id, None)
  6190. await db.commit()
  6191. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6192. """Detect completion or interruption of a running scheduled drying.
  6193. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6194. drying. Within the grace window after start we ignore dry_time==0
  6195. (the status lags the command). After that, dry_time==0 near the end
  6196. of the configured duration means completed. Much earlier means the
  6197. run was stopped: re-queue it if a print preempted the dryer, but a
  6198. stop while the printer is idle was deliberate, so cancel the row
  6199. rather than restart drying the user just stopped.
  6200. """
  6201. if row.started_at is None:
  6202. row.started_at = now
  6203. return
  6204. elapsed = (now - row.started_at).total_seconds()
  6205. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6206. return
  6207. state = printer_manager.get_status(row.printer_id)
  6208. if not state:
  6209. return # offline mid-dry; resolve when it reconnects
  6210. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6211. # throw on a malformed id would cost the whole pass including print
  6212. # dispatch, every tick.
  6213. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6214. try:
  6215. dry_time = int(target.get("dry_time") or 0) if target else 0
  6216. except (TypeError, ValueError):
  6217. dry_time = 0
  6218. if dry_time > 0 and is_countdown_parked(target):
  6219. # The printer took the command but the countdown is not running
  6220. # (#2896) and will never reach 0, so the run would stay "running"
  6221. # forever. A print in progress is the likely cause (the power budget
  6222. # is spent), so re-queue it like any interruption; the next start
  6223. # waits for the printer to be idle. Parked on an idle printer is a
  6224. # refusal, not something a retry fixes. The timer itself is left on
  6225. # the printer: it may yet start once power frees up.
  6226. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6227. logger.info(
  6228. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6229. row.id,
  6230. row.ams_id,
  6231. )
  6232. row.status = "pending"
  6233. row.started_at = None
  6234. row.waiting_reason = "interrupted"
  6235. else:
  6236. logger.warning(
  6237. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6238. row.id,
  6239. row.ams_id,
  6240. )
  6241. row.status = "failed"
  6242. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6243. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6244. row.completed_at = now
  6245. return
  6246. if dry_time > 0:
  6247. return
  6248. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6249. row.status = "completed"
  6250. row.completed_at = now
  6251. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6252. row.status = "pending"
  6253. row.started_at = None
  6254. row.waiting_reason = "interrupted"
  6255. else:
  6256. row.status = "cancelled"
  6257. row.completed_at = now
  6258. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6259. """Get all smart plugs associated with a printer."""
  6260. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6261. return list(result.scalars().all())
  6262. @staticmethod
  6263. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6264. """Pick the plug to power-cycle a printer back online with (#2629).
  6265. Only a plug flagged ``controls_printer_power`` can actually bring the
  6266. printer back; waiting for a boot on an accessory (filter fan, lights)
  6267. just burns the power-on timeout and fails the dispatch. Falls back to
  6268. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6269. Callers must pass a non-empty list.
  6270. """
  6271. for plug in auto_on_plugs:
  6272. if plug.controls_printer_power:
  6273. return plug
  6274. return auto_on_plugs[0]
  6275. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6276. # chamber-temperature recommendations BambuStudio ships for the matching
  6277. # filament profile; users can override via Settings → Workflow → Preheat
  6278. # card. "default" applies when a loaded tray's normalised type isn't in
  6279. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6280. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6281. "PLA": 0,
  6282. "PETG": 0,
  6283. "PETG-CF": 40,
  6284. "ABS": 45,
  6285. "ASA": 45,
  6286. "PA": 50,
  6287. "PA-CF": 55,
  6288. "PC": 50,
  6289. "PC-FR": 50,
  6290. "TPU": 0,
  6291. "PVA": 0,
  6292. "default": 0,
  6293. }
  6294. @classmethod
  6295. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6296. """The bundled map under the same key casing a parsed one gets.
  6297. The constant is declared with a lowercase ``default`` because that is
  6298. the key the Settings editor writes and displays. Every read of the map
  6299. happens after ``str(key).upper()``, so handing the constant back as
  6300. declared broke the contract the parser documents: an install that had
  6301. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6302. and the resolution loop's fallback silently found nothing. It read the
  6303. right number only because the bundled default happens to be 0 -- change
  6304. that constant and every unconfigured install would keep preheating to
  6305. zero with no way to tell why.
  6306. """
  6307. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6308. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6309. """Parse the user-configured filament→chamber-target map, falling back
  6310. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6311. are uppercased and the 'default' fallback is always present in the
  6312. returned dict so the resolution loop can index it unconditionally."""
  6313. raw = await self._get_setting(db, "preheat_filament_targets")
  6314. if not raw:
  6315. return self._bundled_preheat_targets()
  6316. try:
  6317. parsed = json.loads(raw)
  6318. if not isinstance(parsed, dict):
  6319. raise ValueError("not an object")
  6320. except (json.JSONDecodeError, ValueError) as exc:
  6321. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6322. return self._bundled_preheat_targets()
  6323. # Coerce values to int; drop unparseable rows so a stray string
  6324. # doesn't crash the loop.
  6325. out: dict[str, int] = {}
  6326. for key, value in parsed.items():
  6327. try:
  6328. out[str(key).upper()] = int(value)
  6329. except (TypeError, ValueError):
  6330. continue
  6331. if "DEFAULT" not in out:
  6332. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6333. return out
  6334. @staticmethod
  6335. def _normalize_filament_type(tray_type: str) -> str:
  6336. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6337. existing drying-preset normalisation (split-at-space, upper-case) so
  6338. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6339. "PA-CF" (no space to split on).
  6340. This is the first stage of ``_resolve_filament_key``, which goes on to
  6341. drop the suffix and consult the alias map; on its own it only decides
  6342. what the tray is called, not which row answers for it.
  6343. Indexing the split rather than testing the input: a tray_type of spaces
  6344. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6345. it through to an IndexError.
  6346. """
  6347. words = (tray_type or "").split()
  6348. return words[0].upper() if words else ""
  6349. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6350. """Per-filament chamber target for one tray's reported type, or 0 when
  6351. the tray is empty / RFID-less and reports no type at all.
  6352. A filled or foamed variant wants its base material's chamber when the
  6353. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6354. not the 0 an unknown type falls to. The specific type is still tried
  6355. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6356. (#2902).
  6357. That lookup is now the shared one, which adds the polyamide aliases on
  6358. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6359. too, rather than the catch-all it was landing on (#3067).
  6360. """
  6361. if not self._normalize_filament_type(tray_type or ""):
  6362. return 0
  6363. key = self._resolve_filament_key(tray_type, targets)
  6364. if key is not None:
  6365. return targets[key]
  6366. # A type the map does not list at all, which is not the same as a tray
  6367. # with nothing in it -- that already returned 0 above.
  6368. return targets.get("DEFAULT", 0)
  6369. def _derive_chamber_target(
  6370. self,
  6371. printer: Printer,
  6372. targets: dict[str, int],
  6373. item: PrintQueueItem | None = None,
  6374. ) -> int:
  6375. """Chamber target for the trays this print actually loads: the max of
  6376. their per-filament targets. Returns 0 when there is nothing to read (no
  6377. status, no AMS telemetry — e.g. external-spool prints) or when every
  6378. tray considered maps to 0, and the chamber phase then short-circuits in
  6379. the main loop.
  6380. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6381. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6382. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6383. plus soak burned ahead of each upload, on a printer whose chamber never
  6384. reaches the target anyway (#2886). An item with no usable mapping falls
  6385. back to scanning every loaded tray: that is the only signal left, and
  6386. narrowing to nothing would skip preheat on prints that genuinely need
  6387. it.
  6388. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6389. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6390. less slots have empty `tray_type` and contribute nothing. The external
  6391. spool is consulted only when the mapping names it (>= 254); it stays
  6392. out of the unnarrowed scan, so an item without a mapping derives from
  6393. the AMS alone exactly as before.
  6394. """
  6395. state = printer_manager.get_status(printer.id)
  6396. if state is None:
  6397. return 0
  6398. raw_data = state.raw_data or {}
  6399. used = _used_global_tray_ids(item)
  6400. ams_list = raw_data.get("ams")
  6401. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6402. if isinstance(ams_list, dict):
  6403. ams_list = ams_list.get("ams") or []
  6404. if not isinstance(ams_list, list):
  6405. ams_list = []
  6406. best = 0
  6407. for ams in ams_list:
  6408. if not isinstance(ams, dict):
  6409. continue
  6410. ams_id = _int_or(ams.get("id"), 0)
  6411. for tray in ams.get("tray") or []:
  6412. # A non-dict entry has never been seen from real firmware, but
  6413. # `.get` on one raises, and nothing between here and
  6414. # `_dispatch_one`'s try/finally catches it — the item would be
  6415. # left holding its dispatch claim. Preheat is best-effort by
  6416. # contract, so step over it instead.
  6417. if not isinstance(tray, dict):
  6418. continue
  6419. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6420. continue
  6421. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6422. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6423. for vt in raw_data.get("vt_tray") or []:
  6424. if not isinstance(vt, dict):
  6425. continue
  6426. # `_build_loaded_filaments` addresses external feeds by the id
  6427. # the firmware reports — 255 main, 254 deputy — defaulting to
  6428. # 254 when the field is absent. Same expression here so the two
  6429. # agree on which entry a mapping's 254/255 refers to.
  6430. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6431. continue
  6432. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6433. return best
  6434. def _release_keep_warm(self, pid: int) -> None:
  6435. """Release keep-warm on a printer that left the candidate set.
  6436. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6437. reports the target we set (``entry.held_target``), so a user or
  6438. subsequent print that changed the bed target since is not clobbered.
  6439. Best-effort, never raises.
  6440. The entry is kept, not dropped, when the printer cannot be reached
  6441. right now: a printer that is briefly offline still has a hot bed, and
  6442. holding the entry is what keeps the max-duration timeout applying and
  6443. lets a later tick retry the release. Only a printer that has left the
  6444. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6445. """
  6446. entry = self._keep_warm.get(pid)
  6447. if entry is None:
  6448. return
  6449. state = printer_manager.get_status(pid)
  6450. client = printer_manager.get_client(pid)
  6451. if state is None or client is None:
  6452. logger.debug(
  6453. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6454. pid,
  6455. )
  6456. return
  6457. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6458. if int(cur_bed_target) != entry.held_target:
  6459. # Someone else owns the bed now, so there is nothing of ours to
  6460. # undo and nothing left to track.
  6461. logger.info(
  6462. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6463. pid,
  6464. int(cur_bed_target),
  6465. entry.held_target,
  6466. )
  6467. self._keep_warm.pop(pid, None)
  6468. return
  6469. try:
  6470. client.set_bed_temperature(0)
  6471. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6472. self._keep_warm.pop(pid, None)
  6473. except Exception as exc:
  6474. # Keep the entry so the next tick tries again rather than leaving
  6475. # the bed hot with nothing tracking it.
  6476. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6477. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6478. """Release printers that dropped out of the keep-warm candidate set.
  6479. Called from ``_apply_keep_warm`` on every tick (with the current
  6480. candidate set), and from ``check_queue``'s no-pending-items early
  6481. return (with an empty candidate set) so orphaned holds still get
  6482. released when the queue empties. Also called with an empty candidate
  6483. set when any of the three gate settings toggles off, so a printer
  6484. whose feature was disabled mid-hold gets its bed released.
  6485. Printers being dispatched this tick are excluded from the bed-off
  6486. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6487. transient 0 in between would just churn against preheat. Ownership of
  6488. the hot bed transfers to the preheat rollback pin instead — if the
  6489. dispatch aborts before the print starts (failed upload, cancelled
  6490. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6491. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6492. is the ONLY thing standing between an aborted dispatch and a bed
  6493. left hot with no owner. A successful print start clears the pin and
  6494. the print's own gcode takes over, as usual.
  6495. """
  6496. for _pid in list(self._keep_warm):
  6497. if _pid in active_candidates:
  6498. continue
  6499. if _pid in dispatched:
  6500. handed_over = self._keep_warm.pop(_pid, None)
  6501. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6502. if handed_over is not None:
  6503. self._preheat_pin_bed[_pid] = handed_over.held_target
  6504. continue
  6505. self._release_keep_warm(_pid)
  6506. async def _apply_keep_warm(
  6507. self,
  6508. db: AsyncSession,
  6509. items: list[PrintQueueItem],
  6510. dispatch_ids: list[int] | set[int],
  6511. busy_printers: set[int],
  6512. require_plate_clear: bool,
  6513. ) -> None:
  6514. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6515. When a printer just finished a job (FINISH state) and the next queued
  6516. item needs chamber heating, hold the bed hot so the chamber stays warm
  6517. during the bed-clearing window. The bed is the chamber's heating
  6518. element here, not a print surface — nothing is printing during the
  6519. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6520. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6521. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6522. aftermarket chamber heaters), raised to the item's own parsed
  6523. bed_temperature when that is higher. Items whose archive metadata has
  6524. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6525. get a hold — chamber need is what gates the feature, not metadata.
  6526. Skips entirely for filaments that map to a 0°C chamber target
  6527. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6528. names, so a hot-chamber spool it never touches does not hold the bed of
  6529. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6530. whole unit, as every item was before. Printers being dispatched this
  6531. cycle are excluded:
  6532. ``_preheat_and_soak`` already handles their bed temperature.
  6533. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6534. released to 0 and the entry is latched ``expired=True`` so
  6535. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6536. MQTT: publish is skipped when firmware already has the target.
  6537. The release sweep runs BEFORE the engagement gate so a printer that
  6538. was owned by keep-warm still gets its bed released when any of the
  6539. three gate settings is toggled off mid-hold. The
  6540. ``check_queue`` early-return-when-no-items path also calls
  6541. ``_sweep_keep_warm`` directly to release orphaned holds.
  6542. """
  6543. dispatch_set = set(dispatch_ids)
  6544. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6545. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6546. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6547. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6548. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6549. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6550. # Release sweep first — must run even when gate_open is False so a
  6551. # printer owned by keep-warm when a gate toggles off gets released.
  6552. self._sweep_keep_warm(
  6553. active_candidates=warm_candidates if gate_open else set(),
  6554. dispatched=dispatched_printers,
  6555. )
  6556. if not gate_open:
  6557. return
  6558. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6559. max_hold_seconds = (
  6560. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6561. )
  6562. now_mono = time.monotonic()
  6563. filament_targets: dict[str, int] | None = None
  6564. for pid in warm_candidates:
  6565. entry = self._keep_warm.get(pid)
  6566. # Latched-expired: max-duration timeout already fired for this
  6567. # printer. Skip until the release sweep drops the entry (i.e.
  6568. # until the printer leaves the candidate set).
  6569. if entry is not None and entry.expired:
  6570. continue
  6571. # These two guards sit ahead of the max-duration check below, so an
  6572. # engaged hold only ages out while its printer is still reachable
  6573. # and still in FINISH. That is deliberate rather than a hole: with
  6574. # no status or no client there is no M140 to send anyway, and the
  6575. # elapsed check runs off `entry.started` so it fires on the first
  6576. # tick after the printer comes back. Leaving FINISH means the plate
  6577. # was cleared, which drops the printer out of `warm_candidates` and
  6578. # hands it to `_release_keep_warm` instead. The invariant worth
  6579. # preserving if this is ever reordered: every path out of an
  6580. # engaged hold ends in a bed-off, whether by timeout or release.
  6581. state = printer_manager.get_status(pid)
  6582. if state is None or state.state != "FINISH":
  6583. continue
  6584. client = printer_manager.get_client(pid)
  6585. if client is None:
  6586. continue
  6587. next_item = next((it for it in items if it.printer_id == pid), None)
  6588. if next_item is None:
  6589. continue
  6590. # Hold temperature: the configured keep-warm temp, raised to the
  6591. # item's own bed temp when the metadata reports a higher one. A
  6592. # missing bed_temperature (Orca gcode.3mf exports parse without
  6593. # one) does NOT skip the hold — chamber need gates the feature.
  6594. archive = next_item.archive
  6595. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6596. bed_target = max(item_bed, hold_temp)
  6597. if bed_target <= 0:
  6598. continue
  6599. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6600. if explicit is not None:
  6601. chamber_needed = int(explicit) > 0
  6602. else:
  6603. if filament_targets is None:
  6604. filament_targets = await self._get_preheat_filament_targets(db)
  6605. printer_obj = await self._get_printer(db, pid)
  6606. chamber_needed = (
  6607. printer_obj is not None
  6608. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6609. )
  6610. if not chamber_needed:
  6611. continue
  6612. # Seed the timer on first engagement; keep it on subsequent ticks
  6613. # (never re-seed — that would defeat the max-duration cap).
  6614. if entry is None:
  6615. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6616. self._keep_warm[pid] = entry
  6617. elapsed = now_mono - entry.started
  6618. if elapsed > max_hold_seconds:
  6619. # Timeout: publish bed → 0 once (if firmware still holds our
  6620. # target) and latch expired. The entry stays until the release
  6621. # sweep drops it, preventing the next tick from re-seeding.
  6622. logger.warning(
  6623. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6624. pid,
  6625. elapsed,
  6626. )
  6627. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6628. if int(cur_bed_target) == entry.held_target:
  6629. try:
  6630. client.set_bed_temperature(0)
  6631. except Exception as exc:
  6632. logger.warning(
  6633. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6634. pid,
  6635. exc,
  6636. )
  6637. else:
  6638. logger.info(
  6639. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6640. pid,
  6641. int(cur_bed_target),
  6642. entry.held_target,
  6643. )
  6644. entry.expired = True
  6645. continue
  6646. # Idempotence: skip publish when firmware already has our target.
  6647. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6648. if int(cur_bed_target) == bed_target:
  6649. entry.held_target = bed_target
  6650. continue
  6651. try:
  6652. client.set_bed_temperature(bed_target)
  6653. entry.held_target = bed_target
  6654. logger.info(
  6655. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6656. bed_target,
  6657. pid,
  6658. )
  6659. except Exception as exc:
  6660. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6661. def _sample_chamber_temps(self) -> None:
  6662. """Record a chamber temperature sample for every connected printer.
  6663. Called once per scheduler tick (every 3–30 s). Entries older than
  6664. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6665. Also evicts per-printer state whose printer_id is no longer registered
  6666. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6667. """
  6668. now = time.monotonic()
  6669. cutoff = now - self._chamber_history_ttl
  6670. statuses = printer_manager.get_all_statuses()
  6671. known_pids = set(statuses.keys())
  6672. for pid, status in statuses.items():
  6673. if status is None or not status.connected:
  6674. continue
  6675. temps = status.temperatures or {}
  6676. chamber = temps.get("chamber")
  6677. if chamber is None:
  6678. continue
  6679. hist = self._chamber_history.setdefault(pid, deque())
  6680. hist.append((now, float(chamber)))
  6681. while hist and hist[0][0] < cutoff:
  6682. hist.popleft()
  6683. # Evict state for printers that are no longer registered with the manager.
  6684. # This is the one place a keep-warm entry is dropped without releasing
  6685. # the bed: the printer is gone from the manager, so there is no client
  6686. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6687. # for printers that are merely unreachable, which is what makes this
  6688. # the terminal case rather than a silent leak.
  6689. for pid in list(self._chamber_history):
  6690. if pid not in known_pids:
  6691. self._chamber_history.pop(pid, None)
  6692. for pid in list(self._keep_warm):
  6693. if pid not in known_pids:
  6694. logger.info(
  6695. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6696. pid,
  6697. )
  6698. self._keep_warm.pop(pid, None)
  6699. for pid in list(self._preheat_pin):
  6700. if pid not in known_pids:
  6701. self._preheat_pin.pop(pid, None)
  6702. self._preheat_pin_bed.pop(pid, None)
  6703. def _chamber_soak_remaining(
  6704. self,
  6705. printer_id: int,
  6706. chamber_target: float,
  6707. soak_seconds: int,
  6708. tolerance: float = 2.0,
  6709. ) -> int:
  6710. """Return how many seconds of soak time are still needed.
  6711. Credits the time the chamber has already spent at temperature against
  6712. the configured soak. The credit may not start earlier than any of:
  6713. * **The newest sample.** Nothing recent means the printer stopped
  6714. reporting mid-observation and the chamber may have cooled unseen, so
  6715. the full soak is required. (A 2 h history whose last reading is half
  6716. an hour old is not evidence of anything — the measured cooling rate
  6717. is fast enough to cross the threshold in that time.)
  6718. * **The most recent contiguous run of samples.** A gap wider than
  6719. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6720. far side is not evidence of temperature.
  6721. * **The end of the most recent real dip below the threshold.**
  6722. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6723. — see that constant for the thermal reasoning. A stray low reading is
  6724. an artifact, and treating it as cooling would discard a soak that
  6725. actually happened.
  6726. Returns ``soak_seconds`` when nothing can be credited (no history,
  6727. stale history, or the chamber is below the threshold right now) and 0
  6728. once the credited time covers the whole soak.
  6729. """
  6730. hist = self._chamber_history.get(printer_id)
  6731. if not hist:
  6732. return soak_seconds
  6733. now = time.monotonic()
  6734. newest_ts, newest_temp = hist[-1]
  6735. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6736. return soak_seconds # stale — no fresh evidence to credit
  6737. threshold = chamber_target - tolerance
  6738. if newest_temp < threshold:
  6739. return soak_seconds # below target right now; nothing is soaked
  6740. samples = list(hist)
  6741. # Earliest point we have unbroken observations for.
  6742. credit_from = samples[-1][0]
  6743. for i in range(len(samples) - 1, 0, -1):
  6744. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6745. break
  6746. credit_from = samples[i - 1][0]
  6747. # Pull the credit forward to the end of the last significant dip. Each
  6748. # excursion is measured between the in-range readings that bracket it,
  6749. # so a lone stray sample is charged one sampling interval rather than
  6750. # zero, and the comparison errs towards calling a dip real.
  6751. i = 0
  6752. while i < len(samples):
  6753. if samples[i][1] >= threshold:
  6754. i += 1
  6755. continue
  6756. j = i
  6757. while j < len(samples) and samples[j][1] < threshold:
  6758. j += 1
  6759. # `newest_temp >= threshold` was checked above, so j is in range.
  6760. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6761. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6762. # Credit resumes at the last below-threshold sample rather than
  6763. # the first good one after it, so a recovered dip over-credits
  6764. # by up to one sampling interval — the opposite lean to the
  6765. # bracketing above. Both are bounded by the sample cadence and
  6766. # dwarfed by the grace period, so neither is worth the extra
  6767. # arithmetic to remove.
  6768. credit_from = max(credit_from, samples[j - 1][0])
  6769. i = j
  6770. return max(0, soak_seconds - int(now - credit_from))
  6771. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6772. """Tell an in-flight dispatch that its item no longer wants to print.
  6773. Called by the queue's cancel and delete routes. Those only write to the
  6774. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6775. observe — so preheat would keep heating for the rest of max_wait + soak
  6776. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6777. blocking every other queued item behind a print that is not happening.
  6778. Signalling in memory rather than re-reading the row keeps this off the
  6779. database entirely: no second session, no transaction held across a long
  6780. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6781. Bambuddy serves from a single uvicorn process with one scheduler task,
  6782. so the route and the dispatch always share this object. The flag is
  6783. advisory — dropping it (e.g. after a restart) only costs a wasted
  6784. preheat, never a wrongly-abandoned print.
  6785. Only ids with a dispatch actually in flight are recorded, so the set
  6786. stays bounded by the upload pool rather than growing once per cancelled
  6787. item for the life of the process. Skipping the rest loses nothing: an
  6788. item that is not in flight cannot start heating later either, because
  6789. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6790. the caller has already committed a terminal status (or deleted the row)
  6791. before calling this.
  6792. """
  6793. if item_id in self._inflight:
  6794. self._cancelled_dispatches.add(item_id)
  6795. # A print sent for it earlier that never started is not one any more.
  6796. self._forget_unstarted_print(item_id, unless_printing=False)
  6797. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6798. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6799. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6800. while it is parked, so the wait is chopped into
  6801. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6802. """
  6803. remaining = float(seconds)
  6804. while remaining > 0:
  6805. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6806. await asyncio.sleep(slice_secs)
  6807. remaining -= slice_secs
  6808. if item_id in self._cancelled_dispatches:
  6809. return False
  6810. return True
  6811. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6812. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6813. The full preheat stage does this as part of its own dispatch: an H2D
  6814. left in heating mode by the ABS job before it would otherwise cook the
  6815. PLA that follows. The skip path never reaches that code, so it calls
  6816. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6817. add to the rollback pin, because a flap set to cooling for a print that
  6818. needs no heat is where it should have been either way.
  6819. Best-effort like everything else in the stage: a refused command logs
  6820. and the dispatch carries on.
  6821. """
  6822. model = printer.model or ""
  6823. if not supports_airduct(model):
  6824. return
  6825. state = printer_manager.get_status(printer.id)
  6826. current = getattr(state, "airduct_mode", None) if state else None
  6827. if current == _AIRDUCT_MODE_COOLING:
  6828. return
  6829. client = printer_manager.get_client(printer.id)
  6830. if client is None:
  6831. return
  6832. try:
  6833. client.set_airduct_mode("cooling")
  6834. except Exception as exc:
  6835. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6836. async def _preheat_and_soak(
  6837. self,
  6838. db: AsyncSession,
  6839. item: PrintQueueItem,
  6840. printer: Printer,
  6841. archive: PrintArchive | None,
  6842. ) -> bool:
  6843. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6844. Returns True when the dispatch should carry on to the upload — including
  6845. every case where preheat is skipped, since a skipped preheat is not a
  6846. reason to abandon the print. Returns False only when the item stopped
  6847. wanting to be printed while the stage was waiting (cancelled or
  6848. deleted); the caller must then abandon the dispatch, and
  6849. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6850. Resolution order:
  6851. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6852. to the global `preheat_enabled` setting; 'on' forces the stage on
  6853. even if the global is off.
  6854. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6855. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6856. across the trays `item.ams_mapping` names (every loaded slot when
  6857. it names none).
  6858. 3. A target of 0 off the filament map skips the whole stage: the
  6859. materials this print loads want no chamber, so there is nothing to
  6860. soak for and the bed phase would only delay the upload (#3041).
  6861. An explicit 0 typed into the per-item override, or a per-item
  6862. 'on', still runs the bed phase and the soak — both are the user
  6863. asking for a warm bed in so many words.
  6864. 4. Three hardware tiers branch the wait loop:
  6865. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6866. send M141 to the resolved target, then wait for the chamber sensor
  6867. to reach it (or the max-wait timeout to elapse).
  6868. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6869. no M141; the bed is the only heat source, so we wait for the chamber
  6870. sensor to rise via bed radiation OR fall through on timeout.
  6871. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6872. temperature; the function just heats the bed and holds for the
  6873. configured soak duration.
  6874. The bed target comes from the archive's parsed metadata
  6875. (`bed_temperature`); if missing the preheat stage logs and returns
  6876. without dispatching anything, rather than guessing at a default that
  6877. might wreck filament setup.
  6878. Failures are logged but never re-raised — preheat is best-effort. A
  6879. printer that goes offline mid-soak, a refused gcode command, or a
  6880. missing temperature reading must not turn into a failed queue item; the
  6881. normal upload + start path runs immediately after this method returns.
  6882. """
  6883. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6884. if override == "off":
  6885. return True
  6886. if override == "inherit":
  6887. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6888. if not enabled:
  6889. return True
  6890. # override == "on" forces the stage on regardless of the global setting.
  6891. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6892. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6893. # Chamber target resolution:
  6894. # 1. Explicit per-item override beats everything (user knows best).
  6895. # 2. Otherwise derive from the filament types this print loads, via
  6896. # the per-filament target map. A PLA-only print derives 0 and the
  6897. # block below skips the stage without the user touching anything,
  6898. # even when an ASA spool is sitting in another slot of the same
  6899. # AMS (#2886).
  6900. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6901. if explicit_target is not None and explicit_target > 0:
  6902. chamber_target = int(explicit_target)
  6903. chamber_source = "item-override"
  6904. elif explicit_target == 0:
  6905. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6906. chamber_source = "item-override-zero"
  6907. else:
  6908. targets = await self._get_preheat_filament_targets(db)
  6909. chamber_target = self._derive_chamber_target(printer, targets, item)
  6910. chamber_source = "filament-map"
  6911. # Nothing to preheat *for*. A zero that came out of the filament map is
  6912. # the map saying this print's materials want no chamber conditioning --
  6913. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6914. # anyway heated the bed and then held it for the full soak, which
  6915. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6916. # own G-code sets the bed the moment it starts, so preheating it here
  6917. # only moves that heating ahead of the upload instead of overlapping
  6918. # with it, and the soak has no chamber to condition (#3041).
  6919. #
  6920. # An explicit statement from the user still runs the stage. Forcing the
  6921. # per-item override to 'on', or typing a chamber target of exactly 0,
  6922. # both mean "preheat the bed for this print" -- the second is
  6923. # documented as doing precisely that. Only the automatic path, the
  6924. # global toggle plus the filament map, short-circuits here.
  6925. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6926. logger.info(
  6927. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6928. "target, so there is nothing to soak for (override=%s model=%s)",
  6929. item.id,
  6930. override,
  6931. printer.model or "",
  6932. )
  6933. self._preheat_flap_to_cooling(item.id, printer)
  6934. return True
  6935. bed_target = await _queued_plate_bed_temperature(item, archive)
  6936. if bed_target <= 0:
  6937. # No bed temperature in the slicer metadata. When the print needs a
  6938. # hot chamber the bed is simply how we heat it, so fall back to the
  6939. # configured chamber-heating bed temperature rather than skipping
  6940. # the whole stage — otherwise the print starts with a cold chamber,
  6941. # which is exactly what preheat exists to prevent. Without a chamber
  6942. # requirement there is nothing to preheat *for*, so skip as before
  6943. # rather than guess a bed temperature for the print itself.
  6944. if chamber_target <= 0:
  6945. logger.info(
  6946. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6947. item.id,
  6948. )
  6949. return True
  6950. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6951. logger.info(
  6952. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6953. "%d°C to drive the chamber to %d°C",
  6954. item.id,
  6955. bed_target,
  6956. chamber_target,
  6957. )
  6958. client = printer_manager.get_client(printer.id)
  6959. if client is None:
  6960. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6961. return True
  6962. model = printer.model or ""
  6963. has_heater = supports_chamber_heater(model)
  6964. has_sensor = supports_chamber_temp(model)
  6965. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6966. # Fast path: if the chamber has been continuously above target for at
  6967. # least soak_seconds and the bed is already at temperature, skip the
  6968. # entire preheat stage. Typical case: keep-warm held the bed between
  6969. # consecutive same-material prints and the chamber never dropped.
  6970. if do_chamber and has_sensor and soak_seconds > 0:
  6971. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6972. if remaining == 0:
  6973. cur = printer_manager.get_status(printer.id)
  6974. if cur:
  6975. cur_temps = cur.temperatures or {}
  6976. if (
  6977. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6978. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6979. ):
  6980. logger.info(
  6981. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6982. "and bed is already at temperature (chamber history fast-path)",
  6983. item.id,
  6984. chamber_target,
  6985. soak_seconds,
  6986. )
  6987. # Still set targets to prevent cooling during the 3MF upload window.
  6988. # Register each successful set in the preheat pin so `_dispatch_one`
  6989. # unwinds them on any non-success exit.
  6990. pin = self._preheat_pin.setdefault(printer.id, set())
  6991. try:
  6992. client.set_bed_temperature(bed_target)
  6993. pin.add("bed")
  6994. self._preheat_pin_bed[printer.id] = bed_target
  6995. except Exception as exc:
  6996. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6997. if supports_airduct(model):
  6998. cur_airduct = getattr(cur, "airduct_mode", None)
  6999. if cur_airduct != _AIRDUCT_MODE_HEATING:
  7000. try:
  7001. client.set_airduct_mode("heating")
  7002. # Only undo what we can see we replaced. `None`
  7003. # means no mode has been observed yet, and
  7004. # rolling that back to cooling would assert a
  7005. # state the printer never reported.
  7006. if cur_airduct == _AIRDUCT_MODE_COOLING:
  7007. pin.add("airduct")
  7008. except Exception as exc:
  7009. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  7010. if has_heater:
  7011. try:
  7012. client.set_chamber_temperature(chamber_target)
  7013. pin.add("chamber")
  7014. except Exception as exc:
  7015. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  7016. return True
  7017. logger.info(
  7018. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  7019. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  7020. item.id,
  7021. bed_target,
  7022. chamber_target if do_chamber else 0,
  7023. chamber_source,
  7024. override,
  7025. model,
  7026. has_heater,
  7027. has_sensor,
  7028. max_wait,
  7029. soak_seconds,
  7030. )
  7031. # Preheat rollback registry: everything we set below is recorded here so
  7032. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  7033. # (bed off, chamber off, airduct back to cooling) on any non-success
  7034. # exit. Populated as each command succeeds; consumed and cleared by
  7035. # `_dispatch_one`.
  7036. pin = self._preheat_pin.setdefault(printer.id, set())
  7037. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  7038. # cache the target locally so the polling reads below see consistent
  7039. # state (firmware MQTT echoes lag by ~1s).
  7040. try:
  7041. client.set_bed_temperature(bed_target)
  7042. pin.add("bed")
  7043. self._preheat_pin_bed[printer.id] = bed_target
  7044. except Exception as exc:
  7045. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  7046. return True
  7047. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  7048. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  7049. # left it on, regardless of M141. Default cooling actively vents the
  7050. # chamber, so a `chamber_target > 0` print with the flap stuck in
  7051. # cooling never converges — the heater fights the open exhaust. We
  7052. # flip the flap BEFORE M141 to "heating" when the preheat wants
  7053. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  7054. # on an H2D that was previously running ABS would otherwise stay in
  7055. # heating mode and overheat PLA). The current-state read keeps the
  7056. # command idempotent — no MQTT chatter when the flap is already where
  7057. # we want it.
  7058. if supports_airduct(model):
  7059. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  7060. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  7061. current_state = printer_manager.get_status(printer.id)
  7062. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  7063. if current_airduct != desired_id:
  7064. try:
  7065. client.set_airduct_mode(desired_airduct)
  7066. # As in the fast path: only pin a rollback for a flap we
  7067. # saw in cooling. `current_airduct` of None means no mode
  7068. # has been observed, so there is nothing to restore to.
  7069. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  7070. pin.add("airduct")
  7071. except Exception as exc:
  7072. logger.warning(
  7073. "Queue item %s: preheat airduct %s mode failed: %s",
  7074. item.id,
  7075. desired_airduct,
  7076. exc,
  7077. )
  7078. if do_chamber and has_heater:
  7079. try:
  7080. client.set_chamber_temperature(chamber_target)
  7081. pin.add("chamber")
  7082. except Exception as exc:
  7083. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  7084. # Release the pooled DB connection before the (potentially many-minute)
  7085. # heat-soak wait below (#2572). Every setting this method needs is read
  7086. # above; the wait/soak loop only polls printer_manager state and sleeps —
  7087. # it never touches the DB. Without this the caller's transaction sat
  7088. # "idle in transaction" for the whole soak, pinning one pooled connection
  7089. # per preheating printer. expire_on_commit=False keeps item/printer
  7090. # readable afterwards; there are no pending writes to lose here.
  7091. await db.commit()
  7092. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  7093. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  7094. # Poll every 3s — frequent enough for responsive logging without
  7095. # spamming the MQTT state stream. The "converged" predicate is:
  7096. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  7097. # AND
  7098. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  7099. BED_TOLERANCE = 2.0
  7100. CHAMBER_TOLERANCE = 2.0
  7101. POLL_INTERVAL = 3.0
  7102. deadline = asyncio.get_event_loop().time() + max_wait
  7103. while True:
  7104. state = printer_manager.get_status(printer.id)
  7105. if state is None:
  7106. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  7107. break
  7108. temps = state.temperatures or {}
  7109. bed_now = float(temps.get("bed", 0) or 0)
  7110. chamber_now = float(temps.get("chamber", 0) or 0)
  7111. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  7112. if not do_chamber:
  7113. chamber_ok = True # phase disabled or model has neither sensor nor heater
  7114. elif not has_sensor:
  7115. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  7116. else:
  7117. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  7118. if bed_ok and chamber_ok:
  7119. logger.info(
  7120. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  7121. item.id,
  7122. bed_now,
  7123. chamber_now,
  7124. )
  7125. break
  7126. if asyncio.get_event_loop().time() >= deadline:
  7127. logger.info(
  7128. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7129. item.id,
  7130. bed_now,
  7131. bed_target,
  7132. chamber_now,
  7133. chamber_target if do_chamber else 0,
  7134. )
  7135. break
  7136. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7137. logger.info(
  7138. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7139. item.id,
  7140. )
  7141. return False
  7142. if soak_seconds > 0:
  7143. if do_chamber and has_sensor:
  7144. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7145. else:
  7146. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7147. if remaining > 0:
  7148. logger.info(
  7149. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7150. "has been above target for ~%ds already)",
  7151. item.id,
  7152. remaining,
  7153. soak_seconds,
  7154. soak_seconds - remaining,
  7155. )
  7156. if not await self._preheat_sleep(item.id, remaining):
  7157. logger.info(
  7158. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7159. item.id,
  7160. )
  7161. return False
  7162. else:
  7163. logger.info(
  7164. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7165. item.id,
  7166. chamber_target,
  7167. soak_seconds,
  7168. )
  7169. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7170. return True
  7171. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7172. """Turn on smart plug and wait for printer to connect.
  7173. Returns True if printer connected successfully within timeout.
  7174. """
  7175. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7176. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7177. # Check current plug state
  7178. status = await service.get_status(plug)
  7179. if not status.get("reachable"):
  7180. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7181. return False
  7182. # Turn on if not already on
  7183. if status.get("state") != "ON":
  7184. success = await service.turn_on(plug)
  7185. if not success:
  7186. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7187. return False
  7188. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7189. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7190. # Get printer from database for connection
  7191. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7192. printer = result.scalar_one_or_none()
  7193. if not printer:
  7194. logger.error("Printer %s not found in database", printer_id)
  7195. return False
  7196. # End the pass's transaction before waiting up to minutes for the boot:
  7197. # held open, it pins a pooled connection idle in transaction
  7198. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7199. # through it.
  7200. await db.commit()
  7201. # Wait for printer to boot (give it some time before trying to connect)
  7202. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7203. await asyncio.sleep(30)
  7204. # Try to connect to the printer periodically
  7205. elapsed = 30 # Already waited 30s
  7206. while elapsed < self._power_on_wait_time:
  7207. # Try to connect
  7208. logger.info("Attempting to connect to printer %s...", printer_id)
  7209. try:
  7210. connected = await printer_manager.connect_printer(printer)
  7211. if connected:
  7212. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7213. # Give it a moment to stabilize and get status
  7214. await asyncio.sleep(5)
  7215. return True
  7216. except Exception as e:
  7217. logger.debug("Connection attempt failed: %s", e)
  7218. await asyncio.sleep(self._power_on_check_interval)
  7219. elapsed += self._power_on_check_interval
  7220. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7221. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7222. return False
  7223. async def _check_previous_success(
  7224. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7225. ) -> bool:
  7226. """Check if the previous print on this printer succeeded.
  7227. ``printer_id`` names the printer to look at when the item has none yet
  7228. (a job for any printer of a model, checked against the one offered).
  7229. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7230. deliberate action, not a failure, so subsequent items should still
  7231. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7232. a skip isn't an actual print attempt, so it must not gate downstream
  7233. items — counting it as a failed predecessor was the cascade bug that
  7234. let a single cancellation block 18 items over 3 days for the reporter.
  7235. Only `failed` and `aborted` — real print-attempt failures — block.
  7236. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7237. action — #1818) are also excluded from the lookback so the user can
  7238. clear the gate after fixing the physical issue without having to
  7239. re-queue every downstream job.
  7240. """
  7241. result = await db.execute(
  7242. select(PrintQueueItem)
  7243. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7244. .where(PrintQueueItem.id != item.id)
  7245. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7246. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7247. # A row ended without a completion time must not count as the
  7248. # latest: PostgreSQL sorts NULL first in a descending order.
  7249. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7250. .limit(1)
  7251. )
  7252. prev_item = result.scalar_one_or_none()
  7253. # If no previous item, assume success (first in queue)
  7254. if not prev_item:
  7255. return True
  7256. return prev_item.status in ("completed", "cancelled")
  7257. def _hold_archive(self, item_id: int, archive_id: int) -> None:
  7258. """Hold the archive a dispatch prints into until it ends (archive_work)."""
  7259. from backend.app.services import archive_work
  7260. self._release_held_archive(item_id)
  7261. archive_work.hold(archive_id)
  7262. self._held_archives[item_id] = archive_id
  7263. def _release_held_archive(self, item_id: int) -> None:
  7264. from backend.app.services import archive_work
  7265. if (archive_id := self._held_archives.pop(item_id, None)) is not None:
  7266. archive_work.release(archive_id)
  7267. @staticmethod
  7268. async def _printing_elsewhere(db: AsyncSession, archive_id: int) -> bool:
  7269. """Whether a print of the archive is running (its run open)."""
  7270. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7271. return (
  7272. await db.scalar(
  7273. select(PrintLogEntry.id)
  7274. .where(PrintLogEntry.archive_id == archive_id, PrintLogEntry.status == RUN_OPEN)
  7275. .limit(1)
  7276. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7277. )
  7278. is not None
  7279. )
  7280. async def _claim_reusable_archive(
  7281. self, db: AsyncSession, item: PrintQueueItem, file_path: Path
  7282. ) -> PrintArchive | None:
  7283. """The archive a library dispatch adds its run to, or None for a new one.
  7284. The same file of the same owner, in the same project, archived from
  7285. this library file or from none (one since deleted, or a print started
  7286. elsewhere), with its copy of the file still on disk. Also while it is
  7287. printing, queued or finishing elsewhere: each print of an archive is
  7288. its own run, with its own start, end, charge, energy, outcome,
  7289. timelapse and photos (archive redesign), as for the copies of a batch.
  7290. """
  7291. from backend.app.services.archive import ArchiveService
  7292. # Off the file as it is now: the stored hash is not refreshed when the
  7293. # file changes on disk (an external folder, overwritten in place).
  7294. content_hash = await asyncio.to_thread(ArchiveService.compute_file_hash, file_path)
  7295. owner = (
  7296. PrintArchive.created_by_id.is_(None)
  7297. if item.created_by_id is None
  7298. else PrintArchive.created_by_id == item.created_by_id
  7299. )
  7300. project = (
  7301. PrintArchive.project_id.is_(None) if item.project_id is None else PrintArchive.project_id == item.project_id
  7302. )
  7303. candidates = (
  7304. await db.scalars(
  7305. select(PrintArchive)
  7306. .where(
  7307. PrintArchive.content_hash == content_hash,
  7308. owner,
  7309. project,
  7310. or_(PrintArchive.library_file_id == item.library_file_id, PrintArchive.library_file_id.is_(None)),
  7311. PrintArchive.deleted_at.is_(None),
  7312. )
  7313. .order_by(PrintArchive.id.desc())
  7314. )
  7315. ).all()
  7316. from backend.app.services import archive_work
  7317. for candidate in candidates:
  7318. # Not one a merge is moving into another archive right now; held
  7319. # from here, with no await between, until the dispatch ends.
  7320. if archive_work.is_merging(candidate.id):
  7321. continue
  7322. if candidate.file_path and (settings.base_dir / candidate.file_path).is_file():
  7323. self._hold_archive(item.id, candidate.id)
  7324. return candidate
  7325. return None
  7326. async def _repoint_siblings_at_archive(
  7327. self,
  7328. db: AsyncSession,
  7329. *,
  7330. consumed_library_file_id: int,
  7331. archive_id: int,
  7332. dispatched_item_id: int,
  7333. ) -> int:
  7334. """Move the other queue items off a library row that is about to be deleted (#2819).
  7335. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7336. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7337. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7338. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7339. clones, so the first dispatch could pull the file out from under rows that
  7340. had not run yet. What those rows did next depended on the database, and
  7341. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7342. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7343. they were left pointing at a row that no longer existed, failing with
  7344. "Library file not found" whenever someone started them -- or sitting
  7345. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7346. constraint, so there the rows were deleted outright and the queued copies
  7347. simply vanished, with no error and no history.
  7348. The archive holds its own copy of the 3MF, so the remaining copies can print
  7349. from it instead. Two things happen here, and both must happen *before* the
  7350. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7351. * every row still naming the file has ``library_file_id`` cleared, which is
  7352. what takes it out of the cascade's reach. That covers rows this cannot
  7353. re-point as well -- a copy already printing from its own archive, and the
  7354. finished ones, which are not spare parts but the record a batch order
  7355. counts its progress from.
  7356. * the rows that still need something to print are pointed at the archive.
  7357. Returns how many items were re-pointed.
  7358. """
  7359. variant_item_ids = (
  7360. (
  7361. await db.execute(
  7362. select(PrintQueueVariant.queue_item_id).where(
  7363. PrintQueueVariant.library_file_id == consumed_library_file_id
  7364. )
  7365. )
  7366. )
  7367. .scalars()
  7368. .all()
  7369. )
  7370. # Candidate rows naming the consumed file have to go rather than be
  7371. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7372. # one out of the cascade. This is what PostgreSQL already does, and
  7373. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7374. # outcome changes -- the two backends simply stop disagreeing about
  7375. # whether the row is still there.
  7376. #
  7377. # It also has to happen before the re-point below: a cross-model item
  7378. # (#671) picks a variant every pass and folds it onto the row, and
  7379. # _resolve_variant clears archive_id as it does so, which would undo the
  7380. # re-point on the very next lap.
  7381. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7382. # An item left with other candidates still has somewhere to go, and those
  7383. # carry their own target model -- pointing it at this archive would print a
  7384. # file the matcher never chose. It is excluded from the re-point and simply
  7385. # re-resolves against what is left.
  7386. surviving_variant_item_ids = set(
  7387. (
  7388. await db.execute(
  7389. select(PrintQueueVariant.queue_item_id).where(
  7390. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7391. )
  7392. )
  7393. )
  7394. .scalars()
  7395. .all()
  7396. )
  7397. repoint_ids = set(
  7398. (
  7399. await db.execute(
  7400. select(PrintQueueItem.id)
  7401. .where(PrintQueueItem.id != dispatched_item_id)
  7402. .where(PrintQueueItem.archive_id.is_(None))
  7403. # "skipped" belongs here with the two live states: it is not
  7404. # terminal. Clearing a printer's previous-success gate puts
  7405. # every item skipped by it back to "pending"
  7406. # (resume_after_failure), and one restored onto a deleted
  7407. # file is the same orphan by a slower route. "failed",
  7408. # "cancelled", "aborted" and "completed" never return.
  7409. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7410. .where(
  7411. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7412. )
  7413. .where(
  7414. or_(
  7415. PrintQueueItem.library_file_id == consumed_library_file_id,
  7416. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7417. )
  7418. )
  7419. )
  7420. )
  7421. .scalars()
  7422. .all()
  7423. )
  7424. if repoint_ids:
  7425. await db.execute(
  7426. update(PrintQueueItem)
  7427. .where(PrintQueueItem.id.in_(repoint_ids))
  7428. .values(
  7429. archive_id=archive_id,
  7430. library_file_id=None,
  7431. # The file this flag named is already consumed. Leaving it set
  7432. # would arm every re-pointed copy to delete whatever library
  7433. # row it is next given.
  7434. cleanup_library_after_dispatch=False,
  7435. )
  7436. )
  7437. logger.info(
  7438. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7439. sorted(repoint_ids),
  7440. archive_id,
  7441. consumed_library_file_id,
  7442. dispatched_item_id,
  7443. )
  7444. # Everything else that still names the file: taken out of the cascade's
  7445. # reach without touching what it prints. The file is gone either way; what
  7446. # this preserves is the row.
  7447. await db.execute(
  7448. update(PrintQueueItem)
  7449. .where(PrintQueueItem.id != dispatched_item_id)
  7450. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7451. .values(library_file_id=None)
  7452. )
  7453. return len(repoint_ids)
  7454. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7455. """Schedule power-off if the queue item enabled auto_off_after.
  7456. Delegates to the smart-plug manager so the off honours each plug's
  7457. configured strategy (time delay or temperature threshold), is cancelled
  7458. if the printer starts printing again, and never cuts power on a loaded
  7459. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7460. powered off on the timeout regardless of print state.
  7461. """
  7462. if not item.auto_off_after:
  7463. return
  7464. try:
  7465. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7466. except Exception as e:
  7467. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7468. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7469. """Get a human-readable name for a queue item."""
  7470. if item.archive_id:
  7471. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7472. archive = result.scalar_one_or_none()
  7473. if archive:
  7474. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7475. if item.library_file_id:
  7476. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7477. library_file = result.scalar_one_or_none()
  7478. if library_file:
  7479. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7480. # A cross-model item (#671) holds no file of its own until a printer is
  7481. # picked, so name it after its first candidate — otherwise every waiting
  7482. # notification for one reads "Job #12". Queried rather than read off
  7483. # item.variants because callers outside the selection loop have not
  7484. # eager-loaded them, and a lazy load raises in async.
  7485. first_variant_name = (
  7486. await db.execute(
  7487. select(LibraryFile.filename)
  7488. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7489. .where(PrintQueueVariant.queue_item_id == item.id)
  7490. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7491. .limit(1)
  7492. )
  7493. ).scalar_one_or_none()
  7494. if first_variant_name:
  7495. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7496. return f"Job #{item.id}"
  7497. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7498. """Get printer by ID."""
  7499. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7500. return result.scalar_one_or_none()
  7501. async def _notify_dispatch_gave_up(
  7502. self,
  7503. queue_item_id: int,
  7504. printer_id: int,
  7505. created_by_id: int | None,
  7506. reason: str = "Printer accepted the file but never started printing",
  7507. ) -> None:
  7508. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7509. Called from the watchdog, which is a background task with no session of
  7510. its own — hence the fresh one here. Best-effort throughout: the row is
  7511. already marked failed and that is the load-bearing part; a notification
  7512. provider being down must not resurrect the retry loop we just stopped.
  7513. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7514. path passes its own, because "accepted the file but never started" is the
  7515. opposite of what happened there — the printer refused it outright (#2732).
  7516. """
  7517. try:
  7518. async with async_session() as db:
  7519. item = await db.get(PrintQueueItem, queue_item_id)
  7520. if not item:
  7521. return
  7522. job_name = await self._get_job_name(db, item)
  7523. printer = await self._get_printer(db, printer_id)
  7524. await notification_service.on_queue_job_failed(
  7525. job_name=job_name,
  7526. printer_id=printer_id,
  7527. printer_name=printer.name if printer else "Unknown",
  7528. reason=reason,
  7529. db=db,
  7530. )
  7531. except Exception as e:
  7532. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7533. try:
  7534. await ws_manager.send_queue_item_failed(
  7535. user_id=created_by_id,
  7536. queue_item_id=queue_item_id,
  7537. printer_id=printer_id,
  7538. reason="never_started",
  7539. )
  7540. except Exception:
  7541. pass # toast is best-effort
  7542. async def _filament_short_on(
  7543. self,
  7544. db: AsyncSession,
  7545. item: PrintQueueItem,
  7546. printer_id: int,
  7547. *,
  7548. require_known: bool = False,
  7549. ) -> bool:
  7550. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7551. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7552. assigned there, with the mapping the item would get there, but changes
  7553. nothing. The model-based matcher uses it to prefer a printer whose
  7554. spools can finish the job.
  7555. False whenever the gate would let the item through: "Print Anyway",
  7556. no mapping, or a check that fails. With ``require_known`` all three of
  7557. those, and any printed slot whose remaining amount is unknown, count
  7558. as short instead: releasing a held job starts it with nobody asked, so
  7559. it needs the amount on record, not merely nothing against it.
  7560. """
  7561. if item.skip_filament_check:
  7562. return False
  7563. try:
  7564. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7565. if not mapping:
  7566. return require_known
  7567. deficit = await compute_deficit_for_queue_item(
  7568. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7569. )
  7570. except Exception as e:
  7571. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7572. return require_known
  7573. return bool(deficit)
  7574. async def _release_short_model_hold(
  7575. self,
  7576. db: AsyncSession,
  7577. item: PrintQueueItem,
  7578. unavailable: set[int],
  7579. require_plate_clear: bool,
  7580. printer_scope: PrinterScope,
  7581. ) -> bool:
  7582. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7583. The deficit gate holds a model-based job on the printer the matcher
  7584. gave it, because "Print Anyway" needs a printer to print on. When
  7585. another idle printer of the job's model has the filament, the job is
  7586. moved to that printer and its hold lifted, and the fixed-printer
  7587. branch dispatches it in this same pass, through the same checks a
  7588. held job meets when the user presses Start. It is moved rather than
  7589. put back in the pool because the model-based branch would pick again
  7590. without requiring the amounts on record (below), and could pick a
  7591. different printer. Only the deficit gate sets ``filament_short``, so a
  7592. job held for any other reason stays held.
  7593. The printer it is held on is left out: a spool loaded there is started
  7594. with Start, as before, rather than while someone may still be loading
  7595. the next one. Each job is checked at most every
  7596. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7597. on each idle printer again.
  7598. Cross-model jobs (#671) stay held: checking a variant writes its file
  7599. onto the item, which would leave a job that is not moved holding
  7600. another variant's file for the printer it waits on.
  7601. A printer qualifies only on a positive finding: every slot the plate
  7602. prints mapped to a spool whose remaining amount is on record and
  7603. enough. A printer whose spools Bambuddy does not track is not one.
  7604. Returns True when the job was moved. A check that fails keeps the hold
  7605. rather than stopping the queue pass.
  7606. """
  7607. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7608. return False
  7609. if not item.target_model or item.variants:
  7610. return False
  7611. now = time.monotonic()
  7612. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7613. return False
  7614. self._short_hold_checked_at[item.id] = now
  7615. try:
  7616. candidates = _candidates_for(item)
  7617. if not candidates:
  7618. return False
  7619. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7620. async def is_short(pid: int) -> bool:
  7621. return await self._filament_short_on(db, item, pid, require_known=True)
  7622. async def unmatched_on(pid: int) -> list[str]:
  7623. return await self._unmatched_on(db, item, pid)
  7624. match_id, _ = await self._find_idle_printer_for_model(
  7625. db,
  7626. item.target_model,
  7627. unavailable | {item.printer_id},
  7628. effective_types,
  7629. item.target_location,
  7630. filament_overrides=filament_overrides,
  7631. require_plate_clear=require_plate_clear,
  7632. printer_scope=printer_scope,
  7633. is_short=is_short,
  7634. unmatched_on=unmatched_on,
  7635. )
  7636. # Every idle printer short comes back as the first of them.
  7637. if match_id is None or await is_short(match_id):
  7638. return False
  7639. except Exception as e:
  7640. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7641. return False
  7642. logger.info(
  7643. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7644. item.id,
  7645. match_id,
  7646. item.printer_id,
  7647. )
  7648. self._short_hold_checked_at.pop(item.id, None)
  7649. item.printer_id = match_id
  7650. # Resolved against the printer it leaves (#3239): the tray mapping and
  7651. # the nozzle positions.
  7652. drop_printer_resolved(item)
  7653. item.manual_start = False
  7654. item.filament_short = False
  7655. item.waiting_reason = None
  7656. await db.commit()
  7657. try:
  7658. printer = await self._get_printer(db, match_id)
  7659. await notification_service.on_queue_job_assigned(
  7660. job_name=await self._get_job_name(db, item),
  7661. printer_id=match_id,
  7662. printer_name=printer.name if printer else "Unknown",
  7663. target_model=item.target_model,
  7664. db=db,
  7665. )
  7666. except Exception as e:
  7667. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7668. return True
  7669. async def _block_on_filament_deficit(
  7670. self,
  7671. db: AsyncSession,
  7672. item: PrintQueueItem,
  7673. ) -> bool:
  7674. """Promote the item to manual_start when the assigned spool is short (#1496).
  7675. Returns True when this dispatch attempt was blocked, False when the
  7676. item is clear to start. A previously-flagged item whose spool has
  7677. since been swapped to one with enough material clears the flag here
  7678. so the next scheduler tick dispatches it.
  7679. """
  7680. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7681. # don't re-flag, don't even compute. Without this short-circuit the
  7682. # scheduler bounces between "user said anyway" (route clears
  7683. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7684. # on identical spool state) (#1698-followup).
  7685. if item.skip_filament_check:
  7686. # #1762 diagnostic: surface the short-circuit at INFO so a
  7687. # future "Print Anyway didn't work" report (e.g. issue #1762
  7688. # comment 3) has actionable evidence in the support bundle
  7689. # without needing DEBUG enabled.
  7690. logger.info(
  7691. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7692. item.id,
  7693. )
  7694. return False
  7695. try:
  7696. deficit = await compute_deficit_for_queue_item(db, item)
  7697. except Exception as e:
  7698. # Never let a flaky deficit check wedge the queue — log and let
  7699. # dispatch proceed. The PrintModal-side check still runs on the
  7700. # manual paths.
  7701. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7702. return False
  7703. if deficit:
  7704. item.filament_short = True
  7705. item.manual_start = True
  7706. await db.commit()
  7707. job_name = await self._get_job_name(db, item)
  7708. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7709. logger.info(
  7710. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7711. item.id,
  7712. len(deficit),
  7713. )
  7714. try:
  7715. await notification_service.on_queue_job_waiting(
  7716. job_name=job_name,
  7717. target_model=(printer.model if printer else "") or "",
  7718. waiting_reason="filament_short",
  7719. db=db,
  7720. printer_id=item.printer_id,
  7721. )
  7722. except Exception as e:
  7723. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7724. return True
  7725. # No deficit — clear any stale flag from a previous tick.
  7726. if item.filament_short:
  7727. item.filament_short = False
  7728. await db.commit()
  7729. return False
  7730. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7731. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7732. Compared the way the matcher compares, so the same hex or a similar one
  7733. is a match. Only slots the plate prints, mapped to a tray the printer
  7734. reports, with a colour on both sides: anything else is not a colour the
  7735. job printed in.
  7736. """
  7737. by_tray = {f["global_tray_id"]: f for f in loaded}
  7738. found = []
  7739. for req in required:
  7740. slot_id = req.get("slot_id") or 0
  7741. if slot_id <= 0 or slot_id > len(mapping):
  7742. continue
  7743. tray_id = mapping[slot_id - 1]
  7744. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7745. if tray is not None and tray.get("color_known") is False:
  7746. # A spool without a colour set is not a different colour.
  7747. continue
  7748. wanted = self._normalize_color_for_compare(req.get("color"))
  7749. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7750. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7751. continue
  7752. found.append(
  7753. {
  7754. "slot_id": slot_id,
  7755. "type": req.get("type") or "",
  7756. "wanted": f"#{wanted.upper()}",
  7757. "got": f"#{got.upper()}",
  7758. "tray": tray_id,
  7759. }
  7760. )
  7761. return found
  7762. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7763. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7764. Read from the mapping the job is about to be sent with, whoever made
  7765. it: the matcher's same-material fallback, a preset match in another
  7766. colour, or a slot picked by hand. The file's colour is the one after
  7767. overrides, so a colour swapped on purpose is not one. None whenever
  7768. there is nothing to compare, and on any failure: a missing note must
  7769. never stop a print.
  7770. """
  7771. try:
  7772. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7773. if not isinstance(mapping, list) or not item.printer_id:
  7774. return None
  7775. status = printer_manager.get_status(item.printer_id)
  7776. if status is None:
  7777. return None
  7778. required = await self._get_filament_requirements(db, item)
  7779. if not required:
  7780. return None
  7781. self._apply_filament_overrides(item, required)
  7782. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7783. except Exception as e:
  7784. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7785. return None
  7786. if found:
  7787. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7788. return json.dumps(found) if found else None
  7789. async def _unmatched_requirements(
  7790. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7791. ) -> list[dict]:
  7792. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7793. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7794. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7795. on why an empty list is not one.
  7796. """
  7797. if mapping is None:
  7798. status = printer_manager.get_status(printer_id)
  7799. if status is None or not self._build_loaded_filaments(status):
  7800. return []
  7801. # Every required slot reads unresolved against an empty mapping.
  7802. mapping = []
  7803. required = await self._get_filament_requirements(db, item)
  7804. if required:
  7805. self._apply_filament_overrides(item, required)
  7806. else:
  7807. # An unreadable 3MF still has its forced colours to go by: they are
  7808. # what the mapping was built from (#3280).
  7809. required = _forced_override_requirements(item)
  7810. return _unresolved_required(required, mapping) if required else []
  7811. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7812. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7813. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7814. Choosing a printer for an "any model" job only checked that each type
  7815. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7816. the spool on the other nozzle, or one spool asked for twice, passes. The
  7817. hold then gave the printer back, and the next pass chose it again.
  7818. Empty when the hold would let the item through, including "Print
  7819. Anyway" and a match that fails: the printer is then chosen as before.
  7820. """
  7821. if item.skip_filament_check:
  7822. return []
  7823. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7824. if key in self._unmatched_memo:
  7825. return list(self._unmatched_memo[key])
  7826. try:
  7827. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7828. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7829. except Exception as e:
  7830. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7831. return []
  7832. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7833. self._unmatched_memo[key] = described
  7834. return list(described)
  7835. async def _block_on_unmatched_filament(
  7836. self,
  7837. db: AsyncSession,
  7838. item: PrintQueueItem,
  7839. release_assignment: bool = False,
  7840. ) -> bool:
  7841. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7842. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7843. goes ahead, letting the printer choose — which is how a job prints in the
  7844. wrong material without anyone being asked. Holding is the same answer the
  7845. deficit gate already gives for "the spool is too light", so it reuses the
  7846. same promote-and-notify machinery.
  7847. Keyed off unresolved slots in the *computed* mapping intersected with the
  7848. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7849. read: on its own it also pads slots this plate does not print, so the
  7850. array alone would hold perfectly good jobs. Reading the mapping rather
  7851. than the printer's loaded filament types also inherits the matcher's
  7852. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7853. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7854. type-only scan would wave that through.
  7855. A mapping that resolved *nothing* is the same finding arriving as an
  7856. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7857. could not replace, and dispatch then goes out as ``use_ams`` with no
  7858. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7859. That is held too, but only once live status positively reports loaded
  7860. trays: #2589's mapping is bogus precisely because the AMS was not known
  7861. yet, and its empty loaded list is that ignorance rather than a miss.
  7862. ``release_assignment`` is for the model-based path, which commits its
  7863. printer choice before the gates run. Holding an "any P2S" job would
  7864. otherwise pin it to the one P2S that could not run it.
  7865. Returns True when this dispatch attempt was blocked.
  7866. """
  7867. if item.skip_filament_check or not item.printer_id:
  7868. return False
  7869. mapping: list | None = None
  7870. if item.ams_mapping:
  7871. try:
  7872. mapping = json.loads(item.ams_mapping)
  7873. except (json.JSONDecodeError, TypeError):
  7874. return False
  7875. if not isinstance(mapping, list):
  7876. return False
  7877. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7878. if not unmatched:
  7879. # No cleanup needed here: once start is pressed the item is no
  7880. # longer staged, and whichever exit runs next overwrites the reason
  7881. # (`hold_item` on the fixed-printer branch, the assignment on the
  7882. # model-based one), as does dispatch.
  7883. return False
  7884. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7885. held_by = item.printer_id
  7886. item.manual_start = True
  7887. # Human-readable: this renders on the queue row.
  7888. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7889. if release_assignment:
  7890. # "Any P2S" means any, so the job returns to the pool rather than
  7891. # waiting on the printer that could not take it. The mapping goes
  7892. # with the assignment: its tray IDs were resolved against the
  7893. # printer being released and mean nothing on the next one (#2799),
  7894. # and keeping them would hold the job again even on a printer that
  7895. # has the filament, since an unresolved slot is deliberately not a
  7896. # conflict worth recomputing over.
  7897. item.printer_id = None
  7898. drop_printer_resolved(item)
  7899. await db.commit()
  7900. job_name = await self._get_job_name(db, item)
  7901. printer = await self._get_printer(db, held_by)
  7902. logger.info(
  7903. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7904. item.id,
  7905. held_by,
  7906. wanted,
  7907. )
  7908. try:
  7909. await notification_service.on_queue_job_waiting(
  7910. job_name=job_name,
  7911. target_model=(printer.model if printer else "") or "",
  7912. waiting_reason=f"needs {wanted}",
  7913. db=db,
  7914. # Released to the pool: no printer holds it any more.
  7915. printer_id=None if release_assignment else held_by,
  7916. )
  7917. except Exception as e:
  7918. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7919. return True
  7920. @staticmethod
  7921. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7922. """The queue item's owner as the row has it now.
  7923. item.created_by_id was read before preheat and upload, which can take
  7924. minutes; deleting the user clears the row, not this session's copy.
  7925. """
  7926. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7927. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7928. """Hand the queue item's owner to printer_manager so the
  7929. print-complete callback can credit the user in PrintLogEntry (#1670).
  7930. No-ops when the item has no `created_by_id` or the referenced user
  7931. row is missing (e.g. user deleted between queue-add and dispatch —
  7932. in that case the print log row falls back to the existing un-credited
  7933. behaviour rather than crashing the dispatch).
  7934. """
  7935. from backend.app.models.user import User
  7936. # Read from the row, not item.created_by_id or db.get: both can still
  7937. # hold a user deleted during the upload, after delete_user forgot them
  7938. # (on SQLite the id may be someone new's by the time the print ends).
  7939. # Joined with the printer too: one deleted during the upload was
  7940. # forgotten as well, and this would write the owner back under its id.
  7941. owner = (
  7942. await db.execute(
  7943. select(User.id, User.username)
  7944. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7945. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7946. .where(PrintQueueItem.id == item.id)
  7947. )
  7948. ).first()
  7949. if owner:
  7950. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7951. if item.printer_id is not None:
  7952. self._unconfirmed_print_user[item.id] = item.printer_id
  7953. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7954. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7955. A cancel lands in another session while the upload runs (the edit route
  7956. even tells users to cancel a job that is being sent). An unconditional
  7957. write here would turn that cancellation into a failure, with a failure
  7958. notification, and block the next job that needs the previous print to
  7959. have succeeded. Returns whether the item was marked failed.
  7960. """
  7961. result = cast(
  7962. CursorResult,
  7963. await db.execute(
  7964. update(PrintQueueItem)
  7965. .where(PrintQueueItem.id == item.id)
  7966. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7967. # Failed before the print started: no slot printed in any colour (#3279).
  7968. .values(
  7969. status="failed",
  7970. error_message=message,
  7971. completed_at=datetime.now(timezone.utc),
  7972. color_substitutions=None,
  7973. )
  7974. .execution_options(synchronize_session=False)
  7975. ),
  7976. )
  7977. await db.commit()
  7978. if result.rowcount == 0:
  7979. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7980. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7981. return False
  7982. await db.refresh(item)
  7983. from backend.app.services.print_batch import refresh_batches_after
  7984. await refresh_batches_after([item.id])
  7985. return True
  7986. @staticmethod
  7987. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7988. """Put a job whose printer turned busy before the start back in the queue.
  7989. Only if it is still printing: a stop that landed meanwhile stands.
  7990. """
  7991. await db.execute(
  7992. update(PrintQueueItem)
  7993. .where(PrintQueueItem.id == item.id)
  7994. .where(PrintQueueItem.status == "printing")
  7995. .values(status="pending", started_at=None, color_substitutions=None)
  7996. .execution_options(synchronize_session=False)
  7997. )
  7998. await db.commit()
  7999. @staticmethod
  8000. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  8001. """Close the dispatch toast of an item the user cancelled while it was sent."""
  8002. try:
  8003. await ws_manager.send_queue_item_failed(
  8004. user_id=toast_uid,
  8005. queue_item_id=item.id,
  8006. printer_id=item.printer_id,
  8007. reason="cancelled_mid_dispatch",
  8008. )
  8009. except Exception:
  8010. pass # toast is best-effort
  8011. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  8012. """Upload file and start print for a queue item.
  8013. Supports two sources:
  8014. - archive_id: Print from an existing archive
  8015. - library_file_id: Print from a library file (file manager)
  8016. """
  8017. logger.info("Starting queue item %s", item.id)
  8018. # Also covers a reservation left active by a process interruption
  8019. # during an earlier attempt. `_dispatch_one` releases this marker on
  8020. # every exit unless start_print() confirms that the command was sent.
  8021. self._unconfirmed_budget_reservations.add(item.id)
  8022. try:
  8023. from backend.app.models.user import User
  8024. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  8025. # Recompute at the final authorization boundary as well as enqueue
  8026. # time. This covers rows created before the server-side estimate
  8027. # migration and prevents any alternate write path from weakening
  8028. # the budget reservation.
  8029. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  8030. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  8031. item.estimated_cost = await estimate_queue_source_cost(
  8032. db,
  8033. archive=archive,
  8034. library_file=library_file,
  8035. plate_id=item.plate_id,
  8036. ams_mapping=item.ams_mapping,
  8037. printer_id=item.printer_id,
  8038. )
  8039. await validate_print_budget(
  8040. db,
  8041. cost_center_id=item.cost_center_id,
  8042. estimated_cost=item.estimated_cost,
  8043. current_user=queue_user,
  8044. exclude_queue_item_id=item.id,
  8045. exclude_reservation_source_type="print_queue",
  8046. exclude_reservation_source_id=item.id,
  8047. )
  8048. budget_reservation = await create_budget_reservation(
  8049. db,
  8050. cost_center_id=item.cost_center_id,
  8051. estimated_cost=item.estimated_cost,
  8052. current_user=queue_user,
  8053. source_type="print_queue",
  8054. source_id=item.id,
  8055. print_archive_id=item.archive_id,
  8056. exclude_queue_item_id=item.id,
  8057. )
  8058. await db.commit()
  8059. except HTTPException as exc:
  8060. if not await self._fail_dispatch(db, item, str(exc.detail)):
  8061. return
  8062. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  8063. await self._power_off_if_needed(db, item)
  8064. return
  8065. # Get printer first (needed for both paths)
  8066. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  8067. printer = result.scalar_one_or_none()
  8068. if not printer:
  8069. if not await self._fail_dispatch(db, item, "Printer not found"):
  8070. return
  8071. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  8072. await self._power_off_if_needed(db, item)
  8073. return
  8074. # Check printer is connected
  8075. if not printer_manager.is_connected(item.printer_id):
  8076. if not await self._fail_dispatch(db, item, "Printer not connected"):
  8077. return
  8078. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  8079. await self._power_off_if_needed(db, item)
  8080. return
  8081. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  8082. # `items` was taken at the top of check_queue, but the user can /cancel
  8083. # any pending row in the gap before we reach this point. Re-read the
  8084. # row and bail out cleanly instead of starting an FTP upload for a row
  8085. # that's already cancelled. The atomic CAS at the pending→printing
  8086. # transition (below, before start_print) is the load-bearing guard;
  8087. # this is the early-exit optimisation that avoids wasted FTP I/O.
  8088. await db.refresh(item)
  8089. if item.status != "pending":
  8090. logger.info(
  8091. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  8092. item.id,
  8093. item.status,
  8094. )
  8095. return
  8096. # Busy-printer guard (#2598). check_queue gates dispatch on
  8097. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  8098. # keep reporting FINISH for tens of seconds *after* it accepted a
  8099. # project_file (see the watchdog's phase-B note). A watchdog revert
  8100. # (#2555) also releases the dispatch hold, so a re-selected item can
  8101. # reach here while its printer has actually started printing. Uploading
  8102. # and dispatching then collides with the live job — the firmware answers
  8103. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  8104. # live state right before the expensive FTP upload: if the printer is
  8105. # busy, leave the item pending and let a later tick dispatch it once the
  8106. # printer is genuinely idle. No wasted upload, no collision.
  8107. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8108. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  8109. logger.info(
  8110. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  8111. "leaving item pending for a later tick (#2598)",
  8112. item.id,
  8113. item.printer_id,
  8114. pre_dispatch_state,
  8115. )
  8116. return
  8117. # Determine source: archive or library file
  8118. archive = None
  8119. library_file = None
  8120. file_path = None
  8121. filename = None
  8122. cleanup_disk_paths: list[Path] = []
  8123. # Set when a dispatch consumes its library file, so the photos can be
  8124. # carried over after the commit that removes the row (#3077).
  8125. consumed_library_file_id: int | None = None
  8126. consumed_photos: list[str] = []
  8127. if item.archive_id:
  8128. # Print from archive
  8129. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  8130. archive = result.scalar_one_or_none()
  8131. if archive is not None and archive.deleted_at is not None:
  8132. # Merged into another archive since it was queued (archive
  8133. # redesign P2): print that one, whose file it now holds.
  8134. from backend.app.services.archive_merge import resolve_alias
  8135. if (into := await resolve_alias(db, archive.id)) is not None:
  8136. archive = await db.get(PrintArchive, into)
  8137. if archive is not None:
  8138. item.archive_id = archive.id
  8139. if not archive:
  8140. if not await self._fail_dispatch(db, item, "Archive not found"):
  8141. return
  8142. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  8143. await self._power_off_if_needed(db, item)
  8144. return
  8145. # Persist the queue item's selected plate onto the archive so Print
  8146. # History can show the actual plate after cancel/fail/complete (#2603).
  8147. # The archive shows its latest run's plate; each run keeps its own
  8148. # on its print log entry.
  8149. if item.plate_id is not None:
  8150. archive.plate_id = item.plate_id
  8151. # Ask-for-outcome opt-in rides from the queue item to the archive
  8152. # the same way (#1898); never cleared here so a reprint of an
  8153. # archive that already asked keeps asking.
  8154. if item.confirm_outcome:
  8155. archive.confirm_requested = True
  8156. file_path = settings.base_dir / archive.file_path
  8157. filename = archive.filename
  8158. elif item.library_file_id:
  8159. # Print from library file (file manager)
  8160. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  8161. library_file = result.scalar_one_or_none()
  8162. if not library_file:
  8163. # "Not found" covers two different situations and only one of
  8164. # them is recoverable, so say which. A trashed file is still
  8165. # there and restoring it makes a re-queued job work; a file that
  8166. # is really gone needs a different one. Neither is knowable from
  8167. # the queue, which is the whole complaint about this message.
  8168. trashed = (
  8169. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  8170. ).scalar_one_or_none()
  8171. if not await self._fail_dispatch(
  8172. db,
  8173. item,
  8174. (
  8175. f"'{trashed}' is in the library trash — restore it and queue the print again"
  8176. if trashed
  8177. else "Library file not found — it was deleted after this job was queued"
  8178. ),
  8179. ):
  8180. return
  8181. logger.error(
  8182. "Queue item %s: library file %s is %s",
  8183. item.id,
  8184. item.library_file_id,
  8185. "in the trash" if trashed else "gone",
  8186. )
  8187. await self._power_off_if_needed(db, item)
  8188. return
  8189. # Library files store absolute paths
  8190. lib_path = Path(library_file.file_path)
  8191. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  8192. filename = library_file.filename
  8193. # Create archive from library file so usage tracking has access to the 3MF
  8194. queue_item_id = item.id
  8195. # Held separately: a cleanup dispatch clears item.library_file_id
  8196. # below, and the log line at the end of this block reported that
  8197. # cleared field -- so every consumed print logged "from library
  8198. # file None", which is the one case worth being able to trace.
  8199. source_library_file_id = item.library_file_id
  8200. reused_archive = False
  8201. try:
  8202. from backend.app.services.archive import ArchiveService
  8203. # The file printed before: this run joins its archive rather
  8204. # than archiving the same file a second time.
  8205. archive = await self._claim_reusable_archive(db, item, file_path)
  8206. if archive is not None:
  8207. reused_archive = True
  8208. if archive.library_file_id is None:
  8209. archive.library_file_id = item.library_file_id
  8210. # This run's, as a new archive would have them: the
  8211. # archive shows its latest run's plate, and a print
  8212. # without a queue item falls back to the archive's plate
  8213. # and cost centre. Not while another print of it runs: they
  8214. # are that print's (this one's run has its own, from the
  8215. # dispatch), and the archive takes the latest run's plate
  8216. # once none prints (print_log.mirror_latest_run).
  8217. if not await self._printing_elsewhere(db, archive.id):
  8218. if item.plate_id is not None:
  8219. archive.plate_id = item.plate_id
  8220. archive.cost_center_id = item.cost_center_id
  8221. else:
  8222. archive_service = ArchiveService(db)
  8223. archive = await archive_service.archive_print(
  8224. printer_id=item.printer_id,
  8225. source_file=file_path,
  8226. original_filename=filename,
  8227. created_by_id=item.created_by_id,
  8228. project_id=item.project_id,
  8229. cost_center_id=item.cost_center_id,
  8230. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8231. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8232. )
  8233. if archive:
  8234. self._hold_archive(item.id, archive.id)
  8235. item.archive_id = archive.id
  8236. if item.confirm_outcome:
  8237. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8238. if budget_reservation is not None:
  8239. budget_reservation.print_archive_id = archive.id
  8240. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8241. consumed_library_file_id = library_file.id
  8242. item.library_file_id = None
  8243. cleanup_disk_paths.append(file_path)
  8244. if library_file.thumbnail_path:
  8245. thumb_path = Path(library_file.thumbnail_path)
  8246. if not thumb_path.is_absolute():
  8247. thumb_path = settings.base_dir / library_file.thumbnail_path
  8248. cleanup_disk_paths.append(thumb_path)
  8249. # Before the delete, not after: on PostgreSQL the FK
  8250. # cascade would already have taken these rows (#2819).
  8251. await self._repoint_siblings_at_archive(
  8252. db,
  8253. consumed_library_file_id=consumed_library_file_id,
  8254. archive_id=archive.id,
  8255. dispatched_item_id=item.id,
  8256. )
  8257. # Read while the row is still here; the photos move
  8258. # below, once the delete has actually committed.
  8259. consumed_photos = list(library_file.photos or [])
  8260. # The delete clears the link on the earlier archives of
  8261. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8262. # SQLite). This one is loaded, so set it here too, or it
  8263. # keeps the stale id in the session.
  8264. archive.library_file_id = None
  8265. await db.delete(library_file)
  8266. file_path = settings.base_dir / archive.file_path
  8267. filename = archive.filename
  8268. # Commit, not flush — flush opens the SQLite write
  8269. # transaction (item.archive_id update + library_file
  8270. # delete) and would hold the WAL writer lock through the
  8271. # FTP upload below, causing "database is locked" cascades
  8272. # for sensor history + concurrent cancels (#1853).
  8273. await db.commit()
  8274. logger.info(
  8275. "Queue item %s: %s archive %s from library file %s",
  8276. item.id,
  8277. "Reused" if reused_archive else "Created",
  8278. archive.id,
  8279. source_library_file_id,
  8280. )
  8281. except Exception as e:
  8282. logger.warning(
  8283. "Queue item %s: Failed to create archive from library file: %s",
  8284. queue_item_id,
  8285. e,
  8286. exc_info=True,
  8287. )
  8288. await db.rollback()
  8289. item = await db.get(PrintQueueItem, queue_item_id)
  8290. if item:
  8291. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8292. return
  8293. await self._power_off_if_needed(db, item)
  8294. return
  8295. if not archive:
  8296. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8297. return
  8298. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8299. await self._power_off_if_needed(db, item)
  8300. return
  8301. # The photos follow the file into the archive that replaces it, for
  8302. # the same reason the siblings do (#3077). After the commit above,
  8303. # never before it: that commit can fail ("database is locked",
  8304. # #1853) and roll the library row back, and photos already moved
  8305. # would leave it naming a directory that no longer exists. The
  8306. # file and thumbnail unlinks are deferred for the same reason.
  8307. if consumed_library_file_id is not None and consumed_photos:
  8308. # Held as a plain int, read here while the session is still
  8309. # healthy, because the handler below may not touch an ORM
  8310. # instance at all. The commit it exists for fails inside the
  8311. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8312. # first DML statement, so a busy writer surfaces as "database
  8313. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8314. # internally through safe_reraise before re-raising, which
  8315. # expires every loaded instance and leaves the session in
  8316. # pending-rollback state -- so `archive.id` inside the except
  8317. # would itself raise PendingRollbackError and the rollback
  8318. # below would never be reached.
  8319. archive_id = archive.id
  8320. try:
  8321. carried_photos = move_library_photos(
  8322. consumed_library_file_id,
  8323. consumed_photos,
  8324. archive_photos_dir(archive),
  8325. )
  8326. if carried_photos:
  8327. archive.photos = list(archive.photos or []) + carried_photos
  8328. await db.commit()
  8329. except Exception as e:
  8330. # The archive and the delete are already committed; the
  8331. # print goes ahead either way. Worst case the pictures sit
  8332. # unnamed in the archive's own directory.
  8333. #
  8334. # Ints only until the rollback has run, per the note above,
  8335. # which is why this logs queue_item_id and not item.id --
  8336. # the sibling handler forty lines up does the same.
  8337. logger.warning(
  8338. "Queue item %s: failed to carry library photos into archive %s: %s",
  8339. queue_item_id,
  8340. archive_id,
  8341. e,
  8342. )
  8343. await db.rollback()
  8344. # rollback() expires every loaded instance, and in async
  8345. # SQLAlchemy the next plain attribute read is lazy IO
  8346. # outside the greenlet -- MissingGreenlet, which would turn
  8347. # this cosmetic failure into a dispatch crash in exactly the
  8348. # "database is locked" case the block exists for (#1853).
  8349. # The nozzle guard, the upload and the start all keep
  8350. # reading item, archive and printer, so all three go back
  8351. # into the session before falling through.
  8352. item = await db.get(PrintQueueItem, queue_item_id)
  8353. archive = await db.get(PrintArchive, archive_id)
  8354. printer = await db.get(Printer, item.printer_id) if item else None
  8355. if not item or not archive or not printer:
  8356. logger.error(
  8357. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8358. queue_item_id,
  8359. archive_id,
  8360. )
  8361. return
  8362. else:
  8363. # Neither archive nor library file specified
  8364. if not await self._fail_dispatch(db, item, "No source file specified"):
  8365. return
  8366. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8367. await self._power_off_if_needed(db, item)
  8368. return
  8369. # Check file exists on disk
  8370. if not file_path.exists():
  8371. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8372. return
  8373. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8374. await self._power_off_if_needed(db, item)
  8375. return
  8376. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8377. # size dispatched to a printer with a different nozzle installed is
  8378. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8379. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8380. # gives the user no idea what went wrong. Catch it here, before we spend
  8381. # time preheating and uploading, and fail with an actionable message.
  8382. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8383. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8384. # the printer hasn't reported its nozzles yet, we fall through and let the
  8385. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8386. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8387. # as one of the two hotends is a 0.6.
  8388. #
  8389. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8390. # (#2885): the printer fetches one as part of starting the print, so the
  8391. # set to test against is "reachable", not "currently mounted". This runs
  8392. # well before the rack picker at the bottom of this method, so without
  8393. # the rack in scope here that picker never got the chance to run.
  8394. sliced_nozzle = archive.nozzle_diameter if archive else None
  8395. if sliced_nozzle:
  8396. nozzle_status = printer_manager.get_status(item.printer_id)
  8397. installed = _installed_nozzle_diameters(nozzle_status)
  8398. rack = _rack_nozzle_diameters(nozzle_status)
  8399. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8400. if mismatch_msg:
  8401. if not await self._fail_dispatch(db, item, mismatch_msg):
  8402. return
  8403. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8404. await notification_service.on_queue_job_failed(
  8405. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8406. printer_id=printer.id,
  8407. printer_name=printer.name,
  8408. reason=mismatch_msg,
  8409. db=db,
  8410. )
  8411. try:
  8412. await ws_manager.send_queue_item_failed(
  8413. user_id=item.created_by_id,
  8414. queue_item_id=item.id,
  8415. printer_id=item.printer_id,
  8416. reason="nozzle_mismatch",
  8417. )
  8418. except Exception:
  8419. pass
  8420. await self._power_off_if_needed(db, item)
  8421. return
  8422. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8423. # bed (and chamber, if applicable) is at temperature when the firmware
  8424. # starts the actual print routine. Best-effort: any failure logs and
  8425. # falls through to the normal upload+start path rather than turning a
  8426. # configuration issue into a failed queue item.
  8427. # Returns False only when the item was cancelled or deleted while the
  8428. # stage was holding at temperature. Uploading and starting it anyway
  8429. # would print a job the user has already called off, so abandon the
  8430. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8431. if not await self._preheat_and_soak(db, item, printer, archive):
  8432. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8433. return
  8434. # See `_effective_plate_id` for why this is resolved once here rather
  8435. # than each site below repeating `item.plate_id or 1`.
  8436. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8437. # G-code injection for auto-print systems (#422)
  8438. injected_path = None
  8439. # #2547: tracked separately from `injected_path`, which is also set when
  8440. # only a START snippet was injected. Only an END snippet changes what the
  8441. # camera sees at print completion.
  8442. end_gcode_injected = False
  8443. if item.gcode_injection:
  8444. try:
  8445. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8446. if snippets_raw:
  8447. snippets = json.loads(snippets_raw)
  8448. model_snippets = snippets.get(printer.model, {})
  8449. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8450. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8451. if start_gc or end_gc:
  8452. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8453. injected_path = inject_gcode_into_3mf(
  8454. file_path, effective_plate_id, start_gc or None, end_gc or None
  8455. )
  8456. if injected_path:
  8457. file_path = injected_path
  8458. end_gcode_injected = bool(end_gc)
  8459. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8460. else:
  8461. logger.warning(
  8462. "Queue item %s: G-code injection returned no result, using original", item.id
  8463. )
  8464. except Exception as e:
  8465. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8466. # #2547: the finish-photo path can't learn from telemetry that this print
  8467. # ends with user End G-code — which means the plate may be gone by the
  8468. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8469. # the print once the printer confirms it running.
  8470. if end_gcode_injected:
  8471. print_dispatch_context.mark_pending(printer.id)
  8472. # Upload to root directory (not /cache/) - the start_print command references
  8473. # files by name only (ftp://{filename}), so they must be in the root
  8474. remote_filename = derive_remote_filename(filename)
  8475. remote_path = f"/{remote_filename}"
  8476. # Get FTP retry settings
  8477. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8478. logger.info(
  8479. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8480. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8481. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8482. )
  8483. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8484. # Every read this method needs (printer, archive/library, preheat) is
  8485. # done, and the library-file branch already committed its archive
  8486. # creation. Without this the transaction opened by the first SELECT above
  8487. # stays "idle in transaction" for the entire upload — multiple seconds
  8488. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8489. # a farm dispatching many jobs at once then exhausts the pool. This was
  8490. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8491. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8492. # readable; the status writes below (upload-failure path and the
  8493. # pending->printing CAS) transparently open a fresh transaction.
  8494. # The owner is read here, after preheat, so the commit releases this read too.
  8495. toast_uid = await self._queue_owner_id(db, item)
  8496. await db.commit()
  8497. # Delete existing file if present (avoids 553 error on overwrite)
  8498. try:
  8499. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8500. delete_result = await delete_file_async(
  8501. printer.ip_address,
  8502. printer.access_code,
  8503. remote_path,
  8504. socket_timeout=ftp_timeout,
  8505. printer_model=printer.model,
  8506. # This delete and the upload below are one bounded, user-initiated
  8507. # unit -- at most nine connections -- so neither skips on the
  8508. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8509. # trace this delete took the TLS failure and armed the cool-off,
  8510. # and the upload's four attempts were then spent against it
  8511. # without a socket being opened.
  8512. respect_handshake_cooloff=False,
  8513. )
  8514. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8515. except Exception as e:
  8516. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8517. # Dispatch toast — announce the upload start with the total byte
  8518. # count so the frontend can render an honest progress bar.
  8519. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8520. try:
  8521. total_bytes = file_path.stat().st_size
  8522. except OSError:
  8523. total_bytes = 0
  8524. try:
  8525. await ws_manager.send_queue_item_uploading(
  8526. user_id=toast_uid,
  8527. queue_item_id=item.id,
  8528. printer_id=item.printer_id,
  8529. printer_name=printer.name,
  8530. file_name=toast_file_name,
  8531. total_bytes=total_bytes,
  8532. )
  8533. except Exception:
  8534. pass # toast is best-effort
  8535. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8536. # A deadline expiry gets its own message: "check your SD card" is the
  8537. # wrong advice for a link that was simply too slow to finish (#2529).
  8538. upload_error: str | None = None
  8539. # Why the upload failed, straight from the client rather than inferred.
  8540. # Owned here, so a background fetch for another print cannot overwrite
  8541. # it between the failure and the sentence built from it (#2899).
  8542. upload_failure = FtpFailureReport()
  8543. try:
  8544. if ftp_retry_enabled:
  8545. uploaded = await with_ftp_retry(
  8546. upload_file_async,
  8547. printer.ip_address,
  8548. printer.access_code,
  8549. file_path,
  8550. remote_path,
  8551. socket_timeout=ftp_timeout,
  8552. printer_model=printer.model,
  8553. progress_callback=progress_bridge,
  8554. respect_handshake_cooloff=False,
  8555. failure=upload_failure,
  8556. max_retries=ftp_retry_count,
  8557. retry_delay=ftp_retry_delay,
  8558. operation_name=f"Upload print to {printer.name}",
  8559. )
  8560. else:
  8561. uploaded = await upload_file_async(
  8562. printer.ip_address,
  8563. printer.access_code,
  8564. file_path,
  8565. remote_path,
  8566. socket_timeout=ftp_timeout,
  8567. printer_model=printer.model,
  8568. progress_callback=progress_bridge,
  8569. respect_handshake_cooloff=False,
  8570. failure=upload_failure,
  8571. )
  8572. except UploadCancelled as e:
  8573. uploaded = False
  8574. upload_error = (
  8575. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8576. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8577. )
  8578. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8579. except Exception as e:
  8580. uploaded = False
  8581. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8582. # Clean up injected temp file after upload attempt
  8583. if injected_path and injected_path.exists():
  8584. injected_path.unlink(missing_ok=True)
  8585. # Again after the upload, which can take minutes: an owner deleted
  8586. # meanwhile gets no more toasts, and neither does whoever has their id.
  8587. toast_uid = await self._queue_owner_id(db, item)
  8588. # The printer's copy at this path was replaced (or deleted above): the
  8589. # file browser's previews must not show the old one.
  8590. from backend.app.services.printer_file_cache import printer_file_cache
  8591. printer_file_cache.forget(printer.id, remote_path)
  8592. if not uploaded:
  8593. # This used to be one string for every upload failure, telling
  8594. # everyone to check the SD card. The client knows which of seven
  8595. # things went wrong and logs each one differently; it just had no
  8596. # way to say so here, so the card got named even for a TLS
  8597. # handshake that never reached the printer's filesystem (#2899).
  8598. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8599. failure = upload_failure.failure
  8600. if failure is not None and failure.kind is FtpFailureKind.STORAGE:
  8601. try:
  8602. validate_print_filename(remote_filename)
  8603. except InvalidFilenameError as e:
  8604. # This 553 is the file's name, which no card can hold, not
  8605. # the printer's storage: it would be refused on every retry
  8606. # and every printer, so this item fails and the queue goes on.
  8607. upload_error = f"The printer could not create the file {remote_filename!r}: {e}. Rename the file."
  8608. error_msg = upload_error
  8609. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8610. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid, failure.kind)
  8611. return
  8612. if not await self._fail_dispatch(db, item, error_msg):
  8613. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8614. return
  8615. logger.error(
  8616. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8617. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8618. )
  8619. # Send failure notification
  8620. await notification_service.on_queue_job_failed(
  8621. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8622. printer_id=printer.id,
  8623. printer_name=printer.name,
  8624. # The same sentence the queue shows. A push notification saying
  8625. # something different from the UI is its own small bug (#2899).
  8626. reason=error_msg,
  8627. db=db,
  8628. )
  8629. try:
  8630. await ws_manager.send_queue_item_failed(
  8631. user_id=toast_uid,
  8632. queue_item_id=item.id,
  8633. printer_id=item.printer_id,
  8634. reason="upload_failed",
  8635. )
  8636. except Exception:
  8637. pass
  8638. await self._power_off_if_needed(db, item)
  8639. return
  8640. # The printer took a file, so any run of refused uploads is over: the
  8641. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8642. self._upload_refusals.pop(printer.id, None)
  8643. self._upload_refusal_kind.pop(printer.id, None)
  8644. self._upload_refusal_notified.pop(printer.id, None)
  8645. # Parse AMS mapping if stored
  8646. ams_mapping = None
  8647. if item.ams_mapping:
  8648. try:
  8649. ams_mapping = json.loads(item.ams_mapping)
  8650. except json.JSONDecodeError:
  8651. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8652. # Register as expected print so we don't create a duplicate archive
  8653. # Only applicable for archive-based prints
  8654. if archive:
  8655. from backend.app.main import register_expected_print
  8656. register_expected_print(
  8657. item.printer_id,
  8658. remote_filename,
  8659. archive.id,
  8660. ams_mapping=ams_mapping,
  8661. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8662. # no print-start email, and neither does whoever has their id.
  8663. created_by_id=toast_uid,
  8664. cost_center_id=item.cost_center_id,
  8665. # The plate actually dispatched, not the queue item's raw
  8666. # column: on None, `register_expected_print` stores nothing,
  8667. # and `extract_filament_usage_from_3mf` then books every
  8668. # filament in the file rather than the one plate that printed.
  8669. plate_id=effective_plate_id,
  8670. )
  8671. # Registration happens before the print command by necessity (the
  8672. # printer can report the print before the send returns), so record
  8673. # what to undo if we never get as far as sending. `_dispatch_one`
  8674. # rolls back anything still pending here on every exit — exception,
  8675. # early return, or cancel winning the CAS below.
  8676. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8677. # Propagate the queue item's owner into printer_manager so the
  8678. # print-complete callback can credit the user in the PrintLogEntry
  8679. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8680. # items) or when the user clicks the manual-start button.
  8681. await self._propagate_owner_to_printer_manager(db, item)
  8682. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8683. # This prevents phantom reprints if the backend crashes/restarts after the
  8684. # print command is sent but before the status update is committed.
  8685. # If we crash after this commit but before start_print(), the item will be
  8686. # in "printing" status without actually printing - but that's safer than
  8687. # accidentally reprinting the same file hours later.
  8688. #
  8689. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8690. # initial pending read at the top of check_queue and this point) flips
  8691. # the row to "cancelled" in a separate session. Without the WHERE
  8692. # status='pending' clause, the unconditional update here would silently
  8693. # overwrite that cancellation and we'd ship the MQTT start_print below
  8694. # — printer obeys, user sees "I pressed cancel and the print started".
  8695. # rowcount==0 means the user won the race; bail out, best-effort delete
  8696. # the file we just uploaded, do NOT send start_print.
  8697. now_utc = datetime.now(timezone.utc)
  8698. billing_run_id = str(uuid.uuid4())
  8699. # Written with the move to printing, so a retried send replaces the
  8700. # last answer and a cancelled one leaves the row alone (#3279).
  8701. color_substitutions = await self._color_substitutions_for(db, item)
  8702. cas = await db.execute(
  8703. update(PrintQueueItem)
  8704. .where(PrintQueueItem.id == item.id)
  8705. .where(PrintQueueItem.status == "pending")
  8706. .values(
  8707. status="printing",
  8708. started_at=now_utc,
  8709. billing_run_id=billing_run_id,
  8710. color_substitutions=color_substitutions,
  8711. )
  8712. )
  8713. await db.commit()
  8714. if cas.rowcount == 0:
  8715. logger.info(
  8716. "Queue item %s no longer pending at print-command time "
  8717. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8718. item.id,
  8719. )
  8720. try:
  8721. await delete_file_async(
  8722. printer.ip_address,
  8723. printer.access_code,
  8724. remote_path,
  8725. socket_timeout=ftp_timeout,
  8726. printer_model=printer.model,
  8727. )
  8728. except Exception as cleanup_err:
  8729. logger.debug(
  8730. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8731. item.id,
  8732. cleanup_err,
  8733. )
  8734. try:
  8735. await ws_manager.send_queue_item_failed(
  8736. user_id=toast_uid,
  8737. queue_item_id=item.id,
  8738. printer_id=item.printer_id,
  8739. reason="cancelled_mid_dispatch",
  8740. )
  8741. except Exception:
  8742. pass
  8743. return
  8744. # Sync the in-memory item so subsequent code that reads item.status /
  8745. # item.started_at sees the values we just persisted.
  8746. item.status = "printing"
  8747. item.started_at = now_utc
  8748. item.billing_run_id = billing_run_id
  8749. if archive is not None:
  8750. archive.billing_run_id = billing_run_id
  8751. # Legacy transaction deletion used an archive-wide skip flag.
  8752. # A newly dispatched run has its own UUID/tombstone, so it must be
  8753. # billable independently of any older deleted run on this archive.
  8754. archive.wallet_charge_skipped = False
  8755. # Persist before MQTT send so completion and restart recovery can
  8756. # always recover the internal billing identity.
  8757. await db.commit()
  8758. for cleanup_path in cleanup_disk_paths:
  8759. try:
  8760. if cleanup_path.exists():
  8761. cleanup_path.unlink()
  8762. except OSError as cleanup_err:
  8763. logger.warning(
  8764. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8765. json.dumps(
  8766. {
  8767. "queue_item_id": item.id,
  8768. "path": str(cleanup_path),
  8769. "error": str(cleanup_err),
  8770. },
  8771. sort_keys=True,
  8772. ),
  8773. )
  8774. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8775. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8776. # #1898: with the opt-in default-good setting, moving on to the next
  8777. # print resolves the previous print's unanswered outcome prompt as
  8778. # "good" — this path also covers the camera-based plate detection,
  8779. # which releases the gate by allowing dispatch rather than by an
  8780. # explicit acknowledgment. Rides on the dispatch transaction.
  8781. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8782. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8783. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8784. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8785. # Capture state before dispatch so the watchdog can detect whether the
  8786. # printer actually transitioned (#967). Also capture subtask_id so the
  8787. # watchdog can recognise "command landed but state hasn't flipped yet"
  8788. # on slow H2D transitions (#1078).
  8789. pre_status = printer_manager.get_status(item.printer_id)
  8790. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8791. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8792. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8793. # #1721: respect the user's explicit timelapse choice. The #1397
  8794. # force-on at dispatch was removed because it caused per-layer nozzle
  8795. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8796. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8797. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8798. # FINISH-state fallback — no need to force a video.
  8799. effective_timelapse = bool(item.timelapse)
  8800. # Nozzle-rack fallback (#2800). A job that never passed through the
  8801. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8802. # dispatches with no nozzle field at all and chooses for itself — which
  8803. # is how a print levelled on one hotend and then printed on another,
  8804. # millimetres above the plate. Derive the per-slot extruder assignment
  8805. # from the file being dispatched.
  8806. #
  8807. # Done here rather than at queue time because this is the first point
  8808. # that knows both the actual printer and the actual file: an item can
  8809. # be created without a printer (model-based assignment), reassigned
  8810. # afterwards, or have its file swapped for a G-code-injected copy just
  8811. # above. Every queue-creation path — the print dialog, a bulk library
  8812. # add, the webhook, a pipeline run — is covered by the one call.
  8813. # Skipped when the item already carries a Bambu Studio capture: that
  8814. # one wins downstream anyway, so reading the 3MF again would be work
  8815. # thrown away on every dispatch.
  8816. # Rack position resolution (#1784), tried before the #2800 fallback
  8817. # below because it can express what that one cannot: a plate wanting a
  8818. # *different* hotend off the rack per filament group. The position per
  8819. # group is the operator's pick — the 3MF states it nowhere, proven by
  8820. # sending one plate twice with different picks and finding the two
  8821. # files identical bar float noise — so it is resolved here against the
  8822. # rack as it stands right now, after the upload, not at queue time.
  8823. resolved_nozzle_mapping = None
  8824. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8825. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8826. if rack_plan is not None:
  8827. try:
  8828. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8829. except (json.JSONDecodeError, TypeError):
  8830. stored_choice = {}
  8831. logger.warning(
  8832. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8833. item.id,
  8834. item.nozzle_rack_choice,
  8835. )
  8836. # JSON object keys are strings; the groups are ints.
  8837. choice: dict[int, int] = {}
  8838. for key, value in (stored_choice or {}).items():
  8839. try:
  8840. choice[int(key)] = int(value)
  8841. except (TypeError, ValueError):
  8842. continue
  8843. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8844. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8845. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8846. )
  8847. if resolved_nozzle_mapping is None and choice:
  8848. # An explicit pick that no longer holds stops the print. The
  8849. # operator named a hotend; printing from a different one is
  8850. # how a plate gets levelled on one nozzle and drawn with
  8851. # another, millimetres above the bed. Nothing has been sent
  8852. # to the printer yet, so failing here costs only the upload.
  8853. # The file is already on the SD card by this point, and a
  8854. # 3MF left there is a phantom print waiting to be started
  8855. # from the touchscreen. Same cleanup the start_print
  8856. # failure path below does, for the same reason.
  8857. try:
  8858. await delete_file_async(
  8859. printer.ip_address,
  8860. printer.access_code,
  8861. remote_path,
  8862. printer_model=printer.model,
  8863. )
  8864. except Exception:
  8865. pass # Best-effort — don't fail the error handler
  8866. if not await self._fail_dispatch(
  8867. db,
  8868. item,
  8869. (
  8870. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8871. "Edit the item to choose another position."
  8872. ),
  8873. ):
  8874. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8875. return
  8876. logger.warning(
  8877. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8878. item.id,
  8879. printer.name,
  8880. rack_error,
  8881. choice,
  8882. [slot.get("id") for slot in live_rack],
  8883. )
  8884. await notification_service.on_queue_job_failed(
  8885. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8886. printer_id=printer.id,
  8887. printer_name=printer.name,
  8888. reason=item.error_message,
  8889. db=db,
  8890. )
  8891. try:
  8892. await ws_manager.send_queue_item_failed(
  8893. user_id=toast_uid,
  8894. queue_item_id=item.id,
  8895. printer_id=item.printer_id,
  8896. reason="nozzle_rack_pick_stale",
  8897. )
  8898. except Exception:
  8899. pass # Best-effort — don't fail the error handler
  8900. return
  8901. if resolved_nozzle_mapping is None:
  8902. # Nothing was picked and nothing could be assigned. Falls
  8903. # through to the #2800 path, which is what ran before this
  8904. # existed — strictly not worse than today.
  8905. logger.info(
  8906. "Queue item %s: no rack positions assignable (%s); falling back",
  8907. item.id,
  8908. rack_error,
  8909. )
  8910. else:
  8911. logger.info(
  8912. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8913. item.id,
  8914. resolved_nozzle_mapping,
  8915. rack_plan.slot_groups,
  8916. choice or "auto",
  8917. )
  8918. nozzle_slot_extruders = None
  8919. if (
  8920. not item.nozzle_mapping
  8921. and resolved_nozzle_mapping is None
  8922. and file_path is not None
  8923. and is_nozzle_rack_model(printer.model)
  8924. ):
  8925. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8926. if slot_extruders:
  8927. nozzle_slot_extruders = json.dumps(slot_extruders)
  8928. # Every filament this plate prints is on the external spool -> the print
  8929. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8930. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8931. # table", which is what held the reporter's P1S at Heatbed preheating
  8932. # for ten minutes before it gave up (#3087). The MQTT command builder
  8933. # already downgrades a mapping that is *only* external ([254]), but a
  8934. # multi-filament project pads the slots this plate does not print with
  8935. # -1 — BambuStudio's own convention — and down there a -1 is
  8936. # indistinguishable from a slot that never resolved, which must never be
  8937. # sent to the spool holder (#2589). Here the plate's filament list says
  8938. # which is which, so the answer is exact rather than a guess.
  8939. #
  8940. # Deliberately narrow: this fires only when every consumed slot is an
  8941. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8942. # alone and the firmware still rejects the print, exactly as today. And
  8943. # only for single-nozzle printers, mirroring the builder's own reconcile
  8944. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8945. # whether to use the AMS, so it is not ours to rewrite.
  8946. effective_use_ams = item.use_ams
  8947. plate_uses_only_external = False
  8948. if (
  8949. ams_mapping
  8950. and file_path is not None
  8951. # Cheap gate before opening the file: with nothing on the spool
  8952. # holder anywhere in the mapping, no subset of it can be all
  8953. # external, so most dispatches never pay for the parse. The
  8954. # isinstance also keeps a malformed stored mapping (a bare number
  8955. # from a hand-edited row) failing where it always failed, in the
  8956. # command builder, rather than here.
  8957. and isinstance(ams_mapping, list)
  8958. and any(_is_external_tray(t) for t in ams_mapping)
  8959. and not _might_be_dual_nozzle(printer.model, pre_status)
  8960. ):
  8961. from backend.app.services.filament_requirements import extract_filament_requirements
  8962. consumed = _consumed_mapping_entries(
  8963. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8964. )
  8965. if consumed and all(_is_external_tray(t) for t in consumed):
  8966. # Exact for this plate: the command builder must not turn the
  8967. # AMS back on for a real tray another plate of the file uses,
  8968. # whether the job asked for the AMS or already had it off.
  8969. plate_uses_only_external = True
  8970. if plate_uses_only_external and effective_use_ams:
  8971. effective_use_ams = False
  8972. logger.info(
  8973. "Queue item %s: every filament plate %s prints is on the external spool "
  8974. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8975. item.id,
  8976. effective_plate_id,
  8977. ams_mapping,
  8978. )
  8979. # A slot that lost its K-profile selection (a power cycle resets every
  8980. # slot to the default K) would print on the default. The idle check in
  8981. # the status handler normally restores it first, but nothing guarantees
  8982. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8983. # Never allowed to stop the print it is protecting.
  8984. try:
  8985. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8986. except Exception:
  8987. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8988. # Start the print with AMS mapping, plate_id and print options.
  8989. # nozzle_mapping rides through verbatim — JSON string captured from
  8990. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8991. # parses + injects it only for dual-nozzle models so a null on every
  8992. # other model is a transparent pass-through. The rack fallback is
  8993. # resolved down there too, where the live rack position is known.
  8994. started = printer_manager.start_print(
  8995. item.printer_id,
  8996. remote_filename,
  8997. plate_id=effective_plate_id,
  8998. ams_mapping=ams_mapping,
  8999. bed_levelling=item.bed_levelling,
  9000. flow_cali=item.flow_cali,
  9001. vibration_cali=item.vibration_cali,
  9002. layer_inspect=item.layer_inspect,
  9003. timelapse=effective_timelapse,
  9004. use_ams=effective_use_ams,
  9005. plate_uses_only_external=plate_uses_only_external,
  9006. nozzle_offset_cali=item.nozzle_offset_cali,
  9007. nozzle_mapping=item.nozzle_mapping
  9008. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  9009. nozzle_slot_extruders=nozzle_slot_extruders,
  9010. )
  9011. if started:
  9012. # The command is away, so the expectation is now legitimate and must
  9013. # survive. Anything still in this dict when _dispatch_one exits gets
  9014. # rolled back.
  9015. self._unconfirmed_expected_print.pop(item.id, None)
  9016. self._unconfirmed_budget_reservations.discard(item.id)
  9017. self._unconfirmed_print_user.pop(item.id, None)
  9018. if item.printer_id is not None:
  9019. self._sent_unstarted_print[item.id] = (
  9020. item.printer_id,
  9021. remote_filename if archive else None,
  9022. archive.id if archive else None,
  9023. )
  9024. # Handoff to the print's own gcode: keep whatever preheat set (bed
  9025. # target, chamber target, airduct heating) — the gcode owns
  9026. # heater/flap control from here. Clearing the pin prevents
  9027. # `_dispatch_one`'s finally from unwinding a live print.
  9028. self._preheat_pin.pop(item.printer_id, None)
  9029. self._preheat_pin_bed.pop(item.printer_id, None)
  9030. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  9031. # No dispatch-toast event here: the legacy bg-dispatch path kept
  9032. # status='processing' from upload start until the printer acked
  9033. # (or timed out). The frontend derives "Awaiting printer…" purely
  9034. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  9035. # event would push the status chip out of 'PROCESSING' prematurely
  9036. # — which is exactly what the screenshot at #1625-followup
  9037. # complained about.
  9038. # Register the local 3MF in the cover-cache so /cover skips FTP
  9039. # (#1166 follow-up). file_path was resolved earlier from either the
  9040. # archive or the library file row.
  9041. if file_path is not None:
  9042. cache_3mf_download(item.printer_id, remote_filename, file_path)
  9043. # Hold the printer against further dispatches until the watchdog
  9044. # confirms the printer transitioned (or until the hard timeout).
  9045. # Prevents multi-plate batches from triple-dispatching onto the
  9046. # same H2D Pro while it digests the first project_file (#1157).
  9047. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  9048. # Watchdog: if the printer never transitions out of pre_state AND
  9049. # never advances subtask_id, the MQTT publish was accepted locally but
  9050. # didn't reach the printer (half-broken session — same shape as
  9051. # #887/#936). Revert the queue item so the next dispatch can pick it
  9052. # up instead of leaving it stuck in "printing" (#967). subtask_id
  9053. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  9054. # that would otherwise cause the item to re-dispatch as a reprint
  9055. # of the just-finished job (#1078).
  9056. if pre_state:
  9057. spawn_background_task(
  9058. self._watchdog_print_start(
  9059. item.id,
  9060. item.printer_id,
  9061. pre_state,
  9062. pre_subtask_id,
  9063. pre_gcode_file,
  9064. created_by_id=toast_uid,
  9065. ),
  9066. name=f"watchdog-print-start-{item.id}",
  9067. )
  9068. # Get estimated time for notification.
  9069. #
  9070. # This used to fall back to `library_file.print_time_seconds`, a column
  9071. # LibraryFile does not have — the print time it knows about lives in
  9072. # `file_metadata`. So a library print whose archive carried no parseable
  9073. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  9074. # AttributeError right here, *after* the printer had already been sent
  9075. # the job: the started-notification never fired, and the exception
  9076. # unwound the whole queue pass, so every other printer still waiting to
  9077. # be dispatched on that tick silently missed its turn.
  9078. #
  9079. # The queue item caches the print time at creation ("Cached from
  9080. # archive/library"), which is the value this was reaching for.
  9081. # The item's is its plate's; the archive's adds every plate of the
  9082. # file up (#3375).
  9083. estimated_time = None
  9084. if item.print_time_seconds:
  9085. estimated_time = item.print_time_seconds
  9086. elif archive and archive.print_time_seconds:
  9087. estimated_time = archive.print_time_seconds
  9088. # Send job started notification
  9089. await notification_service.on_queue_job_started(
  9090. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9091. printer_id=printer.id,
  9092. printer_name=printer.name,
  9093. db=db,
  9094. estimated_time=estimated_time,
  9095. )
  9096. # MQTT relay - publish queue job started
  9097. try:
  9098. await mqtt_relay.on_queue_job_started(
  9099. job_id=item.id,
  9100. filename=filename,
  9101. printer_id=printer.id,
  9102. printer_name=printer.name,
  9103. printer_serial=printer.serial_number,
  9104. )
  9105. except Exception:
  9106. pass # Don't fail if MQTT fails
  9107. else:
  9108. # Clean up uploaded file from SD card to prevent phantom prints
  9109. try:
  9110. await delete_file_async(
  9111. printer.ip_address,
  9112. printer.access_code,
  9113. remote_path,
  9114. printer_model=printer.model,
  9115. )
  9116. except Exception:
  9117. pass # Best-effort — don't fail the error handler
  9118. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  9119. # state can flip from idle to active in the window between the
  9120. # pre-dispatch check above and this publish (the FTP upload takes
  9121. # seconds); start_print() then refuses to send project_file to the
  9122. # now-busy printer and returns False. Failing the item here would be
  9123. # wrong — the printer is fine, it is simply busy — so revert to
  9124. # pending and let a later tick dispatch it once the printer is idle,
  9125. # exactly like the pre-dispatch guard. Only a start_print() False on
  9126. # an idle/unknown printer is a genuine command failure.
  9127. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  9128. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  9129. logger.info(
  9130. "Queue item %s: printer %s became busy (state=%s) before the start "
  9131. "command was sent — deferring, reverting item to pending (#2598)",
  9132. item.id,
  9133. item.printer_id,
  9134. post_dispatch_state,
  9135. )
  9136. await self._defer_until_printer_idle(db, item)
  9137. return
  9138. # Print command failed - revert status
  9139. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  9140. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9141. return
  9142. logger.error(
  9143. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  9144. f"printer_manager.start_print() returned False. "
  9145. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  9146. f"Check printer status and backend logs for details."
  9147. )
  9148. # Send failure notification
  9149. await notification_service.on_queue_job_failed(
  9150. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9151. printer_id=printer.id,
  9152. printer_name=printer.name,
  9153. reason="Failed to send print command to printer - check printer connection and status",
  9154. db=db,
  9155. )
  9156. try:
  9157. await ws_manager.send_queue_item_failed(
  9158. user_id=toast_uid,
  9159. queue_item_id=item.id,
  9160. printer_id=item.printer_id,
  9161. reason="start_command_failed",
  9162. )
  9163. except Exception:
  9164. pass
  9165. await self._power_off_if_needed(db, item)
  9166. @staticmethod
  9167. async def _watchdog_print_start(
  9168. queue_item_id: int,
  9169. printer_id: int,
  9170. pre_state: str,
  9171. pre_subtask_id: str | None = None,
  9172. pre_gcode_file: str | None = None,
  9173. timeout: float = 90.0,
  9174. phase_b_timeout: float = 180.0,
  9175. poll_interval: float = 3.0,
  9176. created_by_id: int | None = None,
  9177. ) -> None:
  9178. """Revert a queue item if the printer never acknowledges the start command.
  9179. Bambuddy optimistically marks the queue item as "printing" right after the
  9180. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  9181. Phase A (up to ``timeout``): wait for either an active-state transition
  9182. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  9183. primary signal; subtask_id advance handles the H2D case where state can
  9184. sit at FINISH for ~50 s after the printer accepted ``project_file``
  9185. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  9186. was lost on a half-broken session (#887/#936) — revert and force
  9187. reconnect (the #967 recovery path).
  9188. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  9189. alone): keep watching for the active-state transition. subtask_id alone
  9190. proves the file landed but not that the printer started — and a printer
  9191. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  9192. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  9193. used to leave the queue item stuck in 'printing' forever because the
  9194. old watchdog returned success as soon as subtask_id advanced. If Phase
  9195. B times out, revert the queue item so the user can retry without
  9196. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  9197. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9198. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  9199. transitions that also don't emit an early subtask_id tick.
  9200. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  9201. refuses to verify our commands will never start this job or any other,
  9202. so waiting out the full 270 s and re-uploading the 3MF twice more only
  9203. burns an upload slot the rest of the farm is queued behind — that path
  9204. is for a printer that might still come good, which this one cannot
  9205. (#2732). It fails the item on the spot with the actual reason instead.
  9206. """
  9207. last_status = None
  9208. landed_on_subtask = False
  9209. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  9210. # every push carrying an `hms` key, so the fault can come and go between
  9211. # 3-second polls. Seeing it once inside the dispatch window is enough.
  9212. command_rejected = False
  9213. # Latched for the same reason as command_rejected: drying can finish, or
  9214. # be stopped by the user, part-way through the dispatch window. Seeing it
  9215. # once is what matters — it is the state the printer was in when it
  9216. # declined to start (#2758).
  9217. drying_ams_ids: list[int] = []
  9218. # The printer answered the start with a refusal: nothing will start,
  9219. # and the command was not lost, so no reconnect either.
  9220. start_refusal: tuple[str, str | None] | None = None
  9221. deadline = time.monotonic() + timeout
  9222. while time.monotonic() < deadline:
  9223. await asyncio.sleep(poll_interval)
  9224. status = printer_manager.get_status(printer_id)
  9225. if not status:
  9226. # Printer disconnected — don't mess with the DB. Drop the
  9227. # in-memory dispatch hold too so a fresh dispatch can retry
  9228. # once the printer comes back; the hard timeout would
  9229. # otherwise hold the printer unnecessarily.
  9230. scheduler._release_dispatch_hold(printer_id)
  9231. return
  9232. last_status = status
  9233. if status.state in _ACTIVE_PRINT_STATES:
  9234. # Printer is actively processing the job — release the
  9235. # post-dispatch hold so the next pending item for this printer
  9236. # can be evaluated normally. We do NOT accept arbitrary state
  9237. # transitions: a printer going FINISH -> IDLE (user dismissed
  9238. # the post-print prompt without accepting our project_file)
  9239. # would otherwise look like "command landed" and leave the
  9240. # queue item stuck in 'printing' forever (#1370).
  9241. scheduler._release_dispatch_hold(printer_id)
  9242. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9243. try:
  9244. await ws_manager.send_queue_item_acked(
  9245. user_id=created_by_id,
  9246. queue_item_id=queue_item_id,
  9247. printer_id=printer_id,
  9248. )
  9249. except Exception:
  9250. pass
  9251. return
  9252. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9253. # Checked only after the active-state exit above: a stale HMS left
  9254. # over from an earlier job must never abort a print that is visibly
  9255. # running. An actually-refused command leaves the printer idle, so
  9256. # this ordering costs the detection nothing.
  9257. if _mqtt_commands_rejected(status):
  9258. command_rejected = True
  9259. break
  9260. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9261. if isinstance(refusal, tuple):
  9262. start_refusal = refusal
  9263. break
  9264. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9265. # Phase A exit — printer accepted the file (subtask_id flipped
  9266. # to our submission id). Don't return yet: the printer may
  9267. # have accepted the command but never actually start (e.g.
  9268. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9269. # B watches for the active-state transition.
  9270. landed_on_subtask = True
  9271. break
  9272. if landed_on_subtask and not command_rejected:
  9273. phase_b_deadline = time.monotonic() + phase_b_timeout
  9274. while time.monotonic() < phase_b_deadline:
  9275. await asyncio.sleep(poll_interval)
  9276. status = printer_manager.get_status(printer_id)
  9277. if not status:
  9278. scheduler._release_dispatch_hold(printer_id)
  9279. return
  9280. last_status = status
  9281. if status.state in _ACTIVE_PRINT_STATES:
  9282. scheduler._release_dispatch_hold(printer_id)
  9283. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9284. try:
  9285. await ws_manager.send_queue_item_acked(
  9286. user_id=created_by_id,
  9287. queue_item_id=queue_item_id,
  9288. printer_id=printer_id,
  9289. )
  9290. except Exception:
  9291. pass
  9292. return
  9293. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9294. # Same ordering rule as Phase A: a running print wins over a
  9295. # lingering HMS.
  9296. if _mqtt_commands_rejected(status):
  9297. command_rejected = True
  9298. break
  9299. # No active-state transition. Revert the item so the scheduler can retry.
  9300. # Drop the in-memory hold so the retry isn't blocked by it.
  9301. scheduler._release_dispatch_hold(printer_id)
  9302. # Logged on every failed dispatch window, not just the last one, so a
  9303. # support bundle shows the correlation from the first attempt rather than
  9304. # only after the retry budget is spent (#2758).
  9305. if drying_ams_ids:
  9306. logger.info(
  9307. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9308. queue_item_id,
  9309. printer_id,
  9310. ", ".join(str(i) for i in drying_ams_ids),
  9311. )
  9312. # Four outcomes from the revert attempt, each routed differently:
  9313. # "reverted": row flipped from printing -> pending, run recovery
  9314. # "gave_up": same, but the retry budget is spent — row failed
  9315. # rather than pending, so it stops going round again
  9316. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9317. # on_print_complete or user). Skip recovery entirely
  9318. # — the print clearly landed somewhere even if the
  9319. # watchdog didn't see the active-state transition.
  9320. # "revert_failed": SQLite contention exhausted retries. Still run
  9321. # recovery so the MQTT session gets a fresh client_id
  9322. # on the half-broken-session path.
  9323. #
  9324. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9325. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9326. # the watchdog again. For a printer that is genuinely wedged that loop never
  9327. # ends — the reporter had one printer "since this morning still not launch"
  9328. # — and each lap also consumes an upload slot that the other printers in the
  9329. # farm are waiting on. Retrying is right; retrying forever is not.
  9330. async def _do_revert(db):
  9331. item = await db.get(PrintQueueItem, queue_item_id)
  9332. if not item or item.status != "printing":
  9333. return "already_moved_on"
  9334. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9335. item.started_at = None
  9336. # The print never started: no slot printed in any colour (#3279).
  9337. item.color_substitutions = None
  9338. # Charge the attempt to the candidate that was actually dispatched, so
  9339. # a cross-model item (#671) reaches for its other file next lap instead
  9340. # of retrying the printer that just failed to start. Matched by file
  9341. # because that is what the resolver copied onto the row.
  9342. if item.library_file_id is not None:
  9343. await db.execute(
  9344. update(PrintQueueVariant)
  9345. .where(PrintQueueVariant.queue_item_id == item.id)
  9346. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9347. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9348. )
  9349. if command_rejected:
  9350. # No retry budget for this one: the printer refused to verify the
  9351. # command, and re-uploading the same 3MF to the same printer will
  9352. # be refused the same way. Fail now with the fix rather than after
  9353. # three laps of a message about SD cards (#2732).
  9354. item.status = "failed"
  9355. item.error_message = (
  9356. "The printer rejected the print command: MQTT command verification failed "
  9357. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9358. "then start the job again."
  9359. )
  9360. item.completed_at = datetime.now(timezone.utc)
  9361. await db.commit()
  9362. return "command_rejected"
  9363. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9364. item.status = "failed"
  9365. if drying_ams_ids:
  9366. # #2758: the generic message below sent the reporter looking
  9367. # at the SD card while the actual obstacle — AMS units in a
  9368. # drying cycle — was on screen the whole time. Name what we
  9369. # observed and let the user judge it; Bambuddy does not stop
  9370. # the cycle itself, because on this hardware drying can run
  9371. # alongside a print and stopping it may not be the fix.
  9372. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9373. item.error_message = (
  9374. f"The printer accepted the file but never started printing, after "
  9375. f"{item.dispatch_attempts} attempts. {units} "
  9376. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9377. f"some printers refuse to begin a print while an AMS is in a drying "
  9378. f"cycle, and an AMS drying without its external power supply can also "
  9379. f"leave too little power for the start-of-print calibration. Stop the "
  9380. f"drying, or connect the AMS power supply, and start the job again."
  9381. )
  9382. else:
  9383. item.error_message = (
  9384. f"The printer accepted the file but never started printing, after "
  9385. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9386. f"prompt or error, confirm its SD card is readable, and start the job again."
  9387. )
  9388. item.completed_at = datetime.now(timezone.utc)
  9389. await release_budget_reservation(
  9390. db,
  9391. source_type="print_queue",
  9392. source_id=item.id,
  9393. status="released",
  9394. )
  9395. await db.commit()
  9396. return "gave_up"
  9397. item.status = "pending"
  9398. await db.commit()
  9399. return "reverted"
  9400. try:
  9401. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9402. except Exception as e:
  9403. logger.warning(
  9404. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9405. "scheduler may keep treating this item as in-flight",
  9406. queue_item_id,
  9407. printer_id,
  9408. e,
  9409. )
  9410. revert_outcome = "revert_failed"
  9411. if revert_outcome in ("command_rejected", "gave_up"):
  9412. # The item is failed: its print user and expected print must not
  9413. # pass the printer's next print off as Bambuddy's.
  9414. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9415. from backend.app.services.print_batch import refresh_batches_after
  9416. await refresh_batches_after([queue_item_id])
  9417. elif revert_outcome == "reverted":
  9418. # Another try claims the printer again. Until then no print on it
  9419. # is vouched for as this item's, except a late start of its file.
  9420. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9421. elif revert_outcome == "already_moved_on":
  9422. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9423. if revert_outcome == "already_moved_on":
  9424. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9425. # other path) already moved the item past 'printing', don't run the
  9426. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9427. # session breaks ongoing prints on the same printer.
  9428. return
  9429. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9430. if revert_outcome == "command_rejected":
  9431. logger.error(
  9432. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9433. "failed) — the print command was rejected, not lost. Failing the item "
  9434. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9435. queue_item_id,
  9436. printer_id,
  9437. HMS_MQTT_VERIFY_FAILED,
  9438. )
  9439. await scheduler._notify_dispatch_gave_up(
  9440. queue_item_id,
  9441. printer_id,
  9442. created_by_id,
  9443. reason="Printer rejected the print command (MQTT command verification failed)",
  9444. )
  9445. # Same reasoning as the landed_on_subtask path below: the file is on
  9446. # the printer and a forced reconnect would only add 0500_4003 to a
  9447. # problem that has nothing to do with the MQTT session (#1150).
  9448. return
  9449. if revert_outcome == "gave_up":
  9450. logger.error(
  9451. "Queue item %s: printer %d never started the print after %d dispatch "
  9452. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9453. "re-uploading it again (#2555)",
  9454. queue_item_id,
  9455. printer_id,
  9456. DISPATCH_MAX_ATTEMPTS,
  9457. total_timeout,
  9458. )
  9459. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9460. elif revert_outcome == "reverted":
  9461. if start_refusal is not None:
  9462. logger.warning(
  9463. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9464. "reverted to 'pending' for retry",
  9465. queue_item_id,
  9466. printer_id,
  9467. start_refusal[0],
  9468. start_refusal[1],
  9469. )
  9470. elif landed_on_subtask:
  9471. logger.warning(
  9472. "Queue item %s: printer %d accepted project_file (subtask_id "
  9473. "advanced) but never transitioned to an active state within "
  9474. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9475. "for retry (#1678)",
  9476. queue_item_id,
  9477. printer_id,
  9478. total_timeout,
  9479. )
  9480. else:
  9481. logger.warning(
  9482. "Queue item %s: printer %d did not respond to print command within "
  9483. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9484. "for retry (#967)",
  9485. queue_item_id,
  9486. printer_id,
  9487. timeout,
  9488. pre_state,
  9489. pre_subtask_id,
  9490. )
  9491. # Phase B was entered iff subtask_id advanced, which means the
  9492. # project_file landed on the printer. A forced reconnect at this point
  9493. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9494. # skip the recovery entirely.
  9495. if landed_on_subtask or start_refusal is not None:
  9496. return
  9497. # Phase A timeout path: if the printer's gcode_file changed since
  9498. # pre-dispatch, the project_file command landed and the printer is
  9499. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9500. # If gcode_file is unchanged, the publish was silently swallowed
  9501. # (#887/#936) and force_reconnect recovery is what we want.
  9502. client = printer_manager.get_client(printer_id)
  9503. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9504. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9505. if publish_landed:
  9506. logger.warning(
  9507. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9508. "received the command and is parsing slowly. Skipping forced "
  9509. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9510. queue_item_id,
  9511. current_gcode_file,
  9512. pre_gcode_file,
  9513. )
  9514. elif client and hasattr(client, "force_reconnect_stale_session"):
  9515. client.force_reconnect_stale_session(
  9516. f"queue print command unacknowledged after {timeout:.0f}s "
  9517. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9518. )
  9519. # Global scheduler instance
  9520. scheduler = PrintScheduler()