print_scheduler.py 546 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800
  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. BambuFTPClient,
  36. FtpFailureKind,
  37. FtpFailureReport,
  38. UploadCancelled,
  39. cache_3mf_download,
  40. delete_file_async,
  41. describe_upload_failure,
  42. get_ftp_retry_settings,
  43. upload_file_async,
  44. with_ftp_retry,
  45. )
  46. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  47. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  48. from backend.app.services.finance_budget import (
  49. create_budget_reservation,
  50. release_budget_reservation,
  51. validate_print_budget,
  52. )
  53. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  54. from backend.app.services.mqtt_relay import mqtt_relay
  55. from backend.app.services.notification_service import notification_service
  56. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  57. from backend.app.services.printer_manager import (
  58. printer_manager,
  59. printer_tray_layout,
  60. supports_airduct,
  61. supports_chamber_heater,
  62. supports_chamber_temp,
  63. supports_drying,
  64. supports_drying_while_printing,
  65. )
  66. from backend.app.services.queue_item_printer import drop_printer_resolved
  67. from backend.app.services.slot_nozzle import reports_two_nozzles
  68. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  69. from backend.app.services.spool_assignment_notifications import (
  70. _global_tray_from_assignment,
  71. _slot_label_from_global_tray,
  72. )
  73. from backend.app.utils.ams_drying import is_countdown_parked
  74. from backend.app.utils.ams_humidity import ams_humidity_percent
  75. from backend.app.utils.archive_paths import archive_photos_dir
  76. from backend.app.utils.color_utils import perceptual_color_distance
  77. from backend.app.utils.filament_types import canonical_filament_type
  78. from backend.app.utils.filename import InvalidFilenameError, derive_remote_filename, validate_print_filename
  79. from backend.app.utils.library_paths import move_library_photos
  80. from backend.app.utils.local_time import utcnow_naive
  81. from backend.app.utils.printer_models import (
  82. is_dual_nozzle_model,
  83. is_gcode_compatible,
  84. is_nozzle_rack_model,
  85. normalize_printer_model,
  86. )
  87. from backend.app.utils.threemf_tools import (
  88. default_plate_number,
  89. extract_rack_plan_from_3mf,
  90. extract_slot_extruders_from_3mf,
  91. plate_bed_temperature,
  92. select_plate_gcode_name,
  93. )
  94. from backend.app.utils.tray_ids import (
  95. TrayLayout,
  96. is_ams_ht_id,
  97. is_external_tray,
  98. unit_label,
  99. )
  100. logger = logging.getLogger(__name__)
  101. def _ams_slot_label(ams_id: int, tray_id: int, layout: TrayLayout | None = None) -> str:
  102. """Human slot name for an assignment tuple, in the spelling already in use.
  103. Composed from the notification side's own pair rather than spelled out again
  104. here. The hand-rolled version this replaces got three real slot kinds wrong:
  105. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  106. ``chr(191)``; both externals collapsed to one label, because an external
  107. assignment stores ams_id 255 with tray_id picking left or right
  108. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  109. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  110. Naming the same slot two ways is its own defect once an alert and the
  111. Inventory page are meant to be talking about the same tray, so this defers
  112. rather than adding a fifth spelling.
  113. ``layout`` is the printer's (``printer_tray_layout``): an H3C names its
  114. per-hotend external inputs "Ext-n".
  115. """
  116. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id, layout), layout)
  117. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  118. # interval: the fast path runs every 3 s while an upload is in flight, and a
  119. # low spool does not need answering at that resolution (#2913).
  120. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  121. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  122. # days, so a finer check would only repeat the same answer.
  123. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  124. # The settings row that holds which stock alerts have already been sent (#2955).
  125. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  126. # The Inventory page asks for this many usage records and the forecast panel
  127. # builds its rates from them; the alert reads the same window so the two agree.
  128. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  129. def _spoolman_time(value: object) -> datetime | None:
  130. """A Spoolman ISO timestamp, or None when missing or unreadable."""
  131. if not value:
  132. return None
  133. try:
  134. return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
  135. except ValueError:
  136. return None
  137. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  138. """Remaining filament as a percentage of the label weight.
  139. The same arithmetic the Inventory page's Low Stock count uses, and it works
  140. unchanged in both inventory modes: internal spools store ``weight_used``
  141. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  142. ``remaining_weight`` so the shape matches. Returns None when there is no
  143. label weight to be a percentage of -- a spool that cannot say how full it
  144. started cannot say how empty it is.
  145. """
  146. if not label_weight or label_weight <= 0:
  147. return None
  148. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  149. return remaining / float(label_weight) * 100.0
  150. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  151. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  152. # byte gate) from before the scheduler unification. Time gate keeps small
  153. # files from going silent (a single 8 KB chunk fires once and that's it);
  154. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  155. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  156. # sub-200 ms files.
  157. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  158. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  159. # How far back chamber temperature samples are retained. 2h comfortably spans
  160. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  161. # before the next print.
  162. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  163. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  164. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  165. # who clear plates promptly will want far less than this; it is deliberately
  166. # the cautious end, since the cost of it being too short is only a re-soak.
  167. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  168. # Max acceptable gap between two consecutive chamber samples before we treat
  169. # the older one as belonging to a separate observation run (printer went
  170. # offline and came back). Above ~30s cadence with a safety margin.
  171. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  172. # How long the chamber must read below target before we accept that it really
  173. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  174. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  175. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  176. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  177. # sub-target readings are therefore a door opening or noise, not lost soak,
  178. # and a plate swap (exactly when keep-warm is running) produces one. Six
  179. # minutes clears the longest such artifact observed (~5 min once bracketed by
  180. # its neighbouring samples) and still sits far below the 23-minute floor for
  181. # real cooling.
  182. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  183. # How often the preheat stage re-checks that the item it is heating for still
  184. # wants to be printed. Cancelling only writes `status` to the database — it
  185. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  186. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  187. # and the printer stays in `busy_printers`, blocking every other queued item
  188. # behind a print that is not happening.
  189. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  190. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  191. _AIRDUCT_MODE_COOLING = 0
  192. _AIRDUCT_MODE_HEATING = 1
  193. # How long a queue row may stay 'printing' while its printer sits in a terminal
  194. # state before the scheduler closes it itself (#2829).
  195. #
  196. # A real completion arrives within seconds of the printer going terminal, so
  197. # five minutes is far outside the normal path — this only ever sees a row whose
  198. # completion was refused or never delivered. It is the whole cost of the
  199. # failure to the user, though: a stranded row blocks every later job for that
  200. # printer, so it should not be raised without reason.
  201. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  202. # gcode_state values that mean the print is over, mapped to the queue status
  203. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  204. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  205. # which the queue calls cancelled) so a recovered row cannot disagree with one
  206. # closed by the normal path.
  207. _TERMINAL_STATE_QUEUE_STATUS = {
  208. "FINISH": "completed",
  209. "FAILED": "failed",
  210. "IDLE": "cancelled",
  211. }
  212. def _terminal_queue_status(state) -> str | None:
  213. """Queue status implied by *state*, or None if the print is not over.
  214. None for a disconnected printer as well as a busy one: a printer we are not
  215. talking to has a stale ``state`` field that proves nothing about what it is
  216. doing now.
  217. """
  218. if state is None or not getattr(state, "connected", False):
  219. return None
  220. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  221. @dataclass
  222. class _KeepWarmEntry:
  223. """Per-printer keep-warm state.
  224. - ``started``: monotonic time when keep-warm first fired for this printer.
  225. Used by the max-duration timeout.
  226. - ``held_target``: last bed target we successfully published. On release
  227. we only send bed-off when firmware still reports this value, so a user
  228. or subsequent print that changed the target isn't clobbered.
  229. - ``expired``: latched True when the max-duration timeout fires. Prevents
  230. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  231. release sweep drops the entry entirely once the printer leaves the
  232. candidate set.
  233. """
  234. started: float
  235. held_target: int
  236. expired: bool = False
  237. # Auto-drying re-arm guards (#2770).
  238. #
  239. # An AMS reports HIGHER relative humidity while it is warm than once it has
  240. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  241. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  242. # threshold set inside that band therefore cannot be satisfied while the box is
  243. # hot, and the firmware is free to end a cycle whenever it decides the filament
  244. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  245. # the threshold and arms another cycle. The reporter's log has five 12-hour
  246. # cycles armed inside four hours, one of them six seconds after the previous
  247. # ended.
  248. #
  249. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  250. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  251. # manual or firmware-run dry is untouched.
  252. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  253. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  254. # A cycle whose timer stood still (#3478): the firmware took the command and
  255. # left the heater off, so dry_time stays put with dry_status Off. It tells
  256. # nothing about humidity, so it has its own counter; this many in a row
  257. # suspends the unit with a message that says the unit did not heat, not that
  258. # the threshold is too low.
  259. AUTO_DRY_MAX_NEVER_HEATED_CYCLES = 2
  260. def _never_heated(unit_state: dict[str, object]) -> int:
  261. """Cycles in a row whose timer stood still on this unit (#3478)."""
  262. count = unit_state.get("never_heated")
  263. return count if isinstance(count, int) else 0
  264. # Sustained-humidity wait (#2518): an above-threshold streak is only
  265. # "continuous" if some pass observed it within the gap ceiling. A unit that
  266. # goes unobserved longer (print running, printer disconnected, sensor silent)
  267. # restarts its streak rather than inheriting a stale one. The ceiling is
  268. # derived from the scheduler cadence — four missed passes — with this floor so
  269. # a fast-polling configuration does not void streaks on a single hiccup.
  270. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  271. # How long a finished scheduled drying row is kept before it is pruned.
  272. SCHEDULED_DRYING_RETENTION_DAYS = 7
  273. # How often that prune actually runs. The check itself is called on every queue
  274. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  275. # write transaction, which SQLite serialises against every other writer. Rows
  276. # only become prunable a week after they finish, so anything short of hourly is
  277. # paying that cost for nothing.
  278. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  279. class _UploadProgressBridge:
  280. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  281. ``upload_file_async`` runs the FTP transfer in an executor thread and
  282. invokes its ``progress_callback`` from that thread, so the callback
  283. body cannot ``await`` directly. This bridge captures the asyncio loop
  284. at construction (on the scheduler thread) and uses
  285. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  286. matches the legacy background_dispatch.py path 1:1 so the toast feels
  287. identical to the pre-#1625 experience.
  288. Failures inside the emit are swallowed — progress is a UX nicety, the
  289. upload itself must not fail because of a WS hiccup.
  290. """
  291. def __init__(self, user_id: int | None, queue_item_id: int):
  292. self._user_id = user_id
  293. self._queue_item_id = queue_item_id
  294. try:
  295. self._loop = asyncio.get_running_loop()
  296. except RuntimeError:
  297. self._loop = None
  298. self._last_emit_bytes = 0
  299. self._last_emit_monotonic = 0.0
  300. self._has_emitted = False
  301. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  302. if self._loop is None or total_bytes <= 0:
  303. return
  304. now = time.monotonic()
  305. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  306. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  307. # the four matter most: first-call so the user sees something even
  308. # for sub-chunk-size files; uploaded >= total so the bar locks at
  309. # 100% even when the throttle would otherwise eat it.
  310. should_emit = (
  311. not self._has_emitted
  312. or bytes_transferred >= total_bytes
  313. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  314. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  315. )
  316. if not should_emit:
  317. return
  318. self._has_emitted = True
  319. self._last_emit_bytes = bytes_transferred
  320. self._last_emit_monotonic = now
  321. try:
  322. asyncio.run_coroutine_threadsafe(
  323. ws_manager.send_queue_item_upload_progress(
  324. user_id=self._user_id,
  325. queue_item_id=self._queue_item_id,
  326. bytes_transferred=bytes_transferred,
  327. total_bytes=total_bytes,
  328. ),
  329. self._loop,
  330. )
  331. except Exception:
  332. pass # progress is best-effort, never block the upload
  333. # Bambu firmware states that mean the project_file has actually been accepted
  334. # and the printer is now processing / running / paused mid-print. Used by the
  335. # dispatch watchdog (#1370): a transition into one of these states means the
  336. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  337. # a post-print prompt) is NOT a valid "command landed" signal even though the
  338. # state value did change. SLICING is included because some firmwares park
  339. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  340. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  341. # How many times the start-watchdog may revert an item to 'pending' before it
  342. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  343. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  344. # both never recovers and starves the other printers of dispatch slots. Three
  345. # is chosen to clear the transient causes the watchdog already recovers from —
  346. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  347. # force-reconnect on the very next attempt — while still bounding the loop.
  348. DISPATCH_MAX_ATTEMPTS = 3
  349. # Upload failures that mean the file never reached the printer's storage: the
  350. # file service refused or never answered (#3210). These put the item back in
  351. # the queue instead of failing it, because nothing about the job is wrong --
  352. # and failing it left the printer idle, so the next pass handed it the next
  353. # item, which failed the same way. One P2S whose file service was out of
  354. # connection slots ate 43 queued jobs in ten minutes that way.
  355. #
  356. # STORAGE (a missing, full or unusable card or USB drive) and AUTH (a rejected
  357. # access code) were left out at first, because they need the user. But
  358. # failing the item leaves the printer just as idle, and #3409's H2D with an
  359. # unusable USB stick ate seven jobs within an hour. Every job sent to that
  360. # printer fails the same way, so they wait too; the retry finds the fix once
  361. # the user has made it.
  362. #
  363. # A 553 can also be this one file: a name the card's filesystem cannot hold.
  364. # That one fails the item, see `_start_print`.
  365. #
  366. # Not here: NOT_FOUND (a path problem, which can be this one file), UNKNOWN,
  367. # and an upload that overran its deadline -- each retry of that costs a whole
  368. # upload that would be just as slow.
  369. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  370. {
  371. FtpFailureKind.HANDSHAKE,
  372. FtpFailureKind.SESSIONS,
  373. FtpFailureKind.COOLOFF,
  374. FtpFailureKind.TIMEOUT,
  375. FtpFailureKind.NETWORK,
  376. FtpFailureKind.STORAGE,
  377. FtpFailureKind.AUTH,
  378. }
  379. )
  380. def _refused_upload_hold_reason(printer_label: str, kind: FtpFailureKind | None) -> str:
  381. """What a job waiting on a printer that refused its last upload shows.
  382. Storage and the access code need the user to do something, so they say
  383. what, and so does a printer out of FTP sessions: those have been seen to
  384. stay until the printer restarts (#3474). The rest clear on their own.
  385. """
  386. if kind is FtpFailureKind.STORAGE:
  387. return f"{printer_label} refused to store the file — check its SD card or USB drive. {_REFUSED_UPLOAD_TAIL}"
  388. if kind is FtpFailureKind.AUTH:
  389. return (
  390. f"{printer_label} refused the file transfer — check its access code on the Printers page. "
  391. f"{_REFUSED_UPLOAD_TAIL}"
  392. )
  393. if kind is FtpFailureKind.SESSIONS:
  394. return (
  395. f"{printer_label} has no file-transfer sessions left (421 too many connections) — "
  396. f"if this does not clear within a few minutes, restart the printer. {_REFUSED_UPLOAD_TAIL}"
  397. )
  398. return f"{printer_label} is not accepting files — {_REFUSED_UPLOAD_TAIL}"
  399. _REFUSED_UPLOAD_TAIL = "Bambuddy will retry automatically"
  400. def _asks_nothing_new(waiting_reason: str) -> bool:
  401. """A model job's reason made only of busy printers and printers that refused an upload.
  402. The refusal sent its own notification (`_requeue_after_upload_refused`),
  403. so this one has nothing to add.
  404. """
  405. parts = [p.strip() for p in waiting_reason.split(" | ")]
  406. return all(p.startswith("Busy:") or p.endswith(_REFUSED_UPLOAD_TAIL) for p in parts)
  407. # How long a printer whose upload was put back stays out of dispatch (#3210).
  408. # The first window matches the FTP client's own handshake cool-off, so the
  409. # retry lands after the client would talk to the printer again anyway. Each
  410. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  411. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  412. # five connection attempts and a page of log. A successful upload resets it.
  413. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  414. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  415. def _upload_backoff_seconds(refusals: int) -> int:
  416. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  417. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  418. @dataclass(slots=True)
  419. class _ModelCandidate:
  420. """One (file, printer model) pair the model-based matcher may try.
  421. Model-based assignment used to have exactly one of these per item, held
  422. directly in the item's own columns. Cross-model queue items (#671) have
  423. several, held in ``print_queue_variants``. Both shapes are normalised into
  424. this so the matching, the cross-model gate and the waiting-reason handling
  425. are written once and an item without variants provably takes the same path
  426. it took before variants existed.
  427. ``variant`` is None for the item's own columns and set for a real variant
  428. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  429. item once that candidate wins.
  430. """
  431. target_model: str | None
  432. sliced_for: str | None
  433. required_filament_types: str | None
  434. filament_overrides: str | None
  435. variant: "PrintQueueVariant | None" = None
  436. # Nozzle diameter (mm) the file was sliced for, None when unknown (#3536).
  437. sliced_nozzle: float | None = None
  438. def _sliced_for_model(archive, library_file) -> str | None:
  439. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  440. if archive is not None:
  441. return archive.sliced_for_model
  442. if library_file is not None and library_file.file_metadata:
  443. return library_file.file_metadata.get("sliced_for_model")
  444. return None
  445. def _sliced_nozzle(archive, library_file) -> float | None:
  446. """Nozzle diameter (mm) a 3MF was sliced for, None when unknown (#3536).
  447. Fail-safe: a missing, unparsable or non-positive value means "unknown", and
  448. unknown never excludes a printer. Not rounded here; the tolerance lives in
  449. ``_nozzle_mismatch_message``.
  450. """
  451. if archive is not None:
  452. raw = archive.nozzle_diameter
  453. elif library_file is not None and library_file.file_metadata:
  454. raw = library_file.file_metadata.get("nozzle_diameter")
  455. else:
  456. return None
  457. try:
  458. value = float(raw)
  459. except (TypeError, ValueError):
  460. return None
  461. return value if value > 0 else None
  462. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  463. """The filament a candidate needs, as ``(types, overrides)``.
  464. Both columns are JSON text written by the slicer step. Malformed content is
  465. treated as no constraint rather than as an error: a job whose overrides
  466. cannot be parsed still prints, it just gets no filament-based narrowing.
  467. Overrides carry their own types, so the returned type list is the union of
  468. the two — an override on one slot must not drop the requirements of the
  469. slots it says nothing about.
  470. Shared by the matcher and by the smart-plug wake step so both ask a printer
  471. for the same filament (#2876). Waking a printer the matcher would then
  472. reject on colour is the bug this exists to prevent.
  473. """
  474. required_types = None
  475. if candidate.required_filament_types:
  476. try:
  477. required_types = json.loads(candidate.required_filament_types)
  478. except json.JSONDecodeError:
  479. pass
  480. filament_overrides = None
  481. if candidate.filament_overrides:
  482. try:
  483. filament_overrides = json.loads(candidate.filament_overrides)
  484. except json.JSONDecodeError:
  485. pass
  486. effective_types = required_types
  487. if filament_overrides:
  488. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  489. if override_types:
  490. effective_types = sorted(set(required_types or []) | set(override_types))
  491. return effective_types, filament_overrides
  492. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  493. """Whether ``item`` was competing for the printer another item just took.
  494. The SJF starvation guard marks a job as jumped when a shorter one lower in
  495. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  496. compete for the same printer, so the guard has to look across both lanes
  497. (#3200); looking only inside the dispatched item's own lane let a stream of
  498. short model-based jobs hold a longer pinned job back indefinitely.
  499. Location filters are not checked: over-marking only lifts an item that was
  500. going to wait anyway, while under-marking is the starvation this prevents.
  501. """
  502. if item.printer_id is not None:
  503. return item.printer_id == printer_id
  504. if not printer_model:
  505. return False
  506. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  507. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  508. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  509. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  510. """Candidate files for ``item``, best first.
  511. An item with no variant rows yields exactly one candidate built from its own
  512. columns — the pre-#671 behaviour, unchanged.
  513. Variants come back least-attempted first, ties broken by the user's
  514. ``position``. On the first pass every count is zero, so this is purely the
  515. user's priority order. After a start-watchdog bounce the printer that failed
  516. drops behind, so the next lap tries the other machine rather than spending the
  517. item's whole retry budget on the one that is wedged. Once every candidate has
  518. been tried equally often they cycle again, which keeps the item-level
  519. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  520. still gives up, it just does not give up without trying them.
  521. """
  522. if not item.variants:
  523. if not item.archive_id and not item.library_file_id:
  524. # Nothing to print at all. Dispatching would fail deep in the upload
  525. # on "No archive_id or library_file_id"; the caller holds the item
  526. # with an explanation instead.
  527. return []
  528. return [
  529. _ModelCandidate(
  530. target_model=item.target_model,
  531. sliced_for=_sliced_for_model(item.archive, item.library_file),
  532. required_filament_types=item.required_filament_types,
  533. filament_overrides=item.filament_overrides,
  534. sliced_nozzle=_sliced_nozzle(item.archive, item.library_file),
  535. )
  536. ]
  537. # Drop candidates whose file is gone or in the trash. Both are reachable and
  538. # neither is covered by the schema: library deletes are soft (the row lives
  539. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  540. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  541. # fires there and a hard delete leaves the variant row pointing at nothing.
  542. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  543. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  544. return [
  545. _ModelCandidate(
  546. target_model=v.target_model,
  547. sliced_for=_sliced_for_model(None, v.library_file),
  548. required_filament_types=v.required_filament_types,
  549. filament_overrides=v.filament_overrides,
  550. variant=v,
  551. sliced_nozzle=_sliced_nozzle(None, v.library_file),
  552. )
  553. for v in ordered
  554. ]
  555. # Why a job for any printer of a model waits when every free one's last print
  556. # failed. The queue page matches it to offer Resume for the model.
  557. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  558. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  559. """Fold one waiting reason per candidate into a single line for the item.
  560. A cross-model item produces a reason per candidate, and pasting them
  561. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  562. — on which machine?). Each reason is prefixed with its model, except in the
  563. single-candidate case where the item already displays its target model and
  564. the prefix would be noise.
  565. Identical reasons collapse rather than repeat, so three idle-less models
  566. read as one clause.
  567. When *every* candidate is merely busy the parts are joined with the ``" | "``
  568. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  569. unprefixed. That case must keep testing busy-only: a fleet that is simply
  570. printing needs no user action, and labelling the clauses would turn each pass
  571. over a two-model item into a "job waiting" notification.
  572. """
  573. reasons = [(model, reason) for model, reason in per_model if reason]
  574. if not reasons:
  575. return None
  576. if len(reasons) == 1:
  577. return reasons[0][1]
  578. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  579. if len(distinct) == 1:
  580. return distinct[0]
  581. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  582. return " | ".join(distinct)
  583. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  584. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  585. """Human label for the models an item is waiting on ("H2S or H2C").
  586. Notifications take a single target model. For a cross-model item the item's
  587. own ``target_model`` is whichever variant happens to be first, which reads as
  588. a lie once it is the H2C that actually runs — so name all of them.
  589. """
  590. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  591. if not models:
  592. return None
  593. return " or ".join(models)
  594. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  595. """True if ``mapping`` is a non-empty list whose every entry is the
  596. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  597. Such a mapping is a bug artifact: a frontend status-load race can serialize
  598. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  599. recomputed from live status at dispatch rather than trusted, otherwise it
  600. reaches the print command and is silently downgraded to external-spool mode.
  601. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  602. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  603. explicit external selection (``>= 254``) is NOT unresolved either — those
  604. keep their meaning.
  605. """
  606. if not isinstance(mapping, list) or not mapping:
  607. return False
  608. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  609. def _is_tray_id(value: object) -> bool:
  610. """True when ``value`` can be read as a global tray ID.
  611. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  612. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  613. against whatever happens to be loaded there.
  614. """
  615. return isinstance(value, int) and not isinstance(value, bool)
  616. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  617. # stages an item (#2799). The manual_start branch clears every other reason on
  618. # a staged item (#3074); this one is the reason it was staged, so it stays.
  619. _UNMATCHED_HOLD_PREFIX = "Needs "
  620. # How often an "any model" job held for low filament looks for another printer
  621. # of its model that has enough (#3137). Each look matches its filament on every
  622. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  623. _SHORT_HOLD_RECHECK_SECONDS = 120
  624. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  625. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  626. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  627. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  628. """The item's force_color_match overrides as filament requirements (#3280).
  629. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  630. read, so the checks after it judge the same list.
  631. """
  632. try:
  633. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  634. except (json.JSONDecodeError, TypeError):
  635. return []
  636. if not isinstance(overrides, list):
  637. return []
  638. return [
  639. {
  640. "slot_id": o.get("slot_id"),
  641. "type": o.get("type", ""),
  642. "color": o.get("color", ""),
  643. "tray_info_idx": o.get("tray_info_idx", ""),
  644. "force_color_match": True,
  645. }
  646. for o in overrides
  647. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  648. ]
  649. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  650. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  651. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  652. for a filament this plate does not use. A slot past the end of the mapping
  653. is unresolved too.
  654. """
  655. unresolved = []
  656. for req in required:
  657. slot_id = req.get("slot_id") or 0
  658. if slot_id <= 0:
  659. continue
  660. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  661. if not _is_tray_id(tray) or tray < 0:
  662. unresolved.append(req)
  663. return unresolved
  664. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  665. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  666. # on `_mapping_is_all_unresolved`.
  667. _EXTERNAL_TRAY_ID_MIN = 254
  668. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  669. """The ``mapping`` entries for the slots this plate actually prints.
  670. ``required`` comes from ``extract_filament_requirements``, which drops any
  671. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  672. consumes, and one absent from it is padding. That distinction is why this
  673. decision lives here and not in the MQTT command builder: a ``-1`` in the
  674. mapping means either "this plate does not print filament N" or "we never
  675. worked out which tray", and only the plate's own filament list separates
  676. them. The builder sees both as the same byte, which is how a plate whose one
  677. printed filament sat on the external spool went out as `use_ams=true` with a
  678. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  679. with 07FF_8012 (#3087).
  680. Returns None whenever the two cannot be lined up — no mapping, no parsed
  681. requirements, or a requirement the mapping is too short to cover — so every
  682. caller falls back to existing behaviour rather than acting on a guess.
  683. """
  684. if not isinstance(mapping, list) or not mapping or not required:
  685. return None
  686. entries = []
  687. for filament in required:
  688. slot_id = filament.get("slot_id")
  689. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  690. # The mapping and the requirements disagree about how many filaments
  691. # the file has. They came from different reads, so judge nothing.
  692. return None
  693. entries.append(mapping[slot_id - 1])
  694. return entries or None
  695. def _is_external_tray(tray_id, rack: bool = False) -> bool:
  696. """True for an explicit external-spool selection (254/255, and 247-253 on a
  697. ``rack`` printer), not for an unresolved slot and not for an AMS tray."""
  698. if tray_id is None:
  699. return False
  700. try:
  701. value = int(tray_id)
  702. except (TypeError, ValueError):
  703. return False
  704. return value >= _EXTERNAL_TRAY_ID_MIN or is_external_tray(value, rack)
  705. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  706. """Whether this printer could have two extruders, judged generously.
  707. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  708. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  709. why the MQTT command builder skips its own use_ams reconcile there. Anything
  710. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  711. with, external spools or not.
  712. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  713. behaviour it has always had, while a wrong "no" would rewrite a field that
  714. steers which nozzle prints. The model name is the first answer (it is what
  715. the command builder falls back to as well), then the same live evidence the
  716. dispatcher's extruder annotation uses — a second nozzle reporting a
  717. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  718. since a single-nozzle printer has exactly one.
  719. """
  720. if is_dual_nozzle_model(printer_model):
  721. return True
  722. nozzles = getattr(status, "nozzles", None) or []
  723. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  724. return True
  725. raw = getattr(status, "raw_data", None) or {}
  726. if raw.get("ams_extruder_map"):
  727. return True
  728. vt_trays = raw.get("vt_tray") or []
  729. # Not a nozzle-rack printer's one external input per hotend (H3C, 247-255).
  730. return isinstance(vt_trays, list) and len(vt_trays) > 1 and not TrayLayout.from_units(None, vt_trays).rack
  731. def _int_or(value, default: int) -> int:
  732. """``int(value)``, or ``default`` when the field is missing or junk.
  733. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  734. the next — and a tray id that fails to parse must not take the whole
  735. derivation down with it.
  736. """
  737. try:
  738. return int(value)
  739. except (TypeError, ValueError):
  740. return default
  741. # What a queue job's dispatch is worked out from, and an edit can change.
  742. _DISPATCH_INPUTS = (
  743. "printer_id",
  744. "status",
  745. "ams_mapping",
  746. "plate_id",
  747. "filament_overrides",
  748. "skip_filament_check",
  749. "target_model",
  750. "target_location",
  751. )
  752. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  753. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  754. The pass works on the jobs as loaded at its start, and it may have waited
  755. since: a plug powering a printer on takes minutes. A job edited meanwhile
  756. (moved to another printer, given a mapping or another plate, cancelled)
  757. is left to the next pass, which reads it fresh: deciding from the stale
  758. copy would overwrite the edit, or send the job where it no longer goes.
  759. The query flushes the pass's own pending changes first, so those don't
  760. count as edits.
  761. """
  762. row = (
  763. await db.execute(
  764. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  765. )
  766. ).one_or_none()
  767. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  768. return False
  769. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  770. return True
  771. def _global_tray_id(ams_id: int, tray_id: int, layout: TrayLayout | None = None) -> int:
  772. """Bambu Studio's global tray id (``utils.tray_ids``) of a slot on the printer ``layout`` describes.
  773. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  774. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  775. agree or a mapping cannot be read back against live tray telemetry.
  776. """
  777. return (layout or TrayLayout()).global_tray_id(ams_id, tray_id)
  778. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  779. """The global tray ids ``item`` actually prints from, or None if unknown.
  780. ``ams_mapping`` is the array the print command carries: position = filament
  781. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  782. not use. None means "no usable statement" — no mapping, unparseable JSON,
  783. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  784. documents), or one that resolves to no tray at all. Callers must treat None
  785. as "consider every loaded tray" rather than "consider none": narrowing on
  786. an absent mapping would silently drop requirements the print really has.
  787. """
  788. raw = getattr(item, "ams_mapping", None)
  789. if not raw:
  790. return None
  791. if isinstance(raw, str):
  792. try:
  793. mapping = json.loads(raw)
  794. except (json.JSONDecodeError, TypeError):
  795. return None
  796. else:
  797. mapping = raw
  798. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  799. return None
  800. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  801. return used or None
  802. def _mqtt_commands_rejected(status) -> bool:
  803. """True when the printer is currently reporting that it refused a command.
  804. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  805. a control command it could not verify. Queries still answer, so the printer
  806. looks connected and idle while project_file, gcode_line and
  807. ams_change_filament are all dropped — no amount of waiting or re-uploading
  808. changes that (#2732).
  809. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  810. ``print_error`` path builds HMSError differently), so this is safe to call on
  811. every watchdog poll.
  812. """
  813. for err in getattr(status, "hms_errors", None) or []:
  814. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  815. return True
  816. return False
  817. def _drying_ams_ids(status) -> list[int]:
  818. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  819. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  820. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  821. started (#2758) — it is a diagnostic, not a gate.
  822. Deliberately not used to block or stop drying before dispatch. This printer
  823. class supports drying concurrently with an active print
  824. (``supports_drying_while_printing``), so drying is not incompatible with
  825. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  826. while two AMS units were drying, one of them without its external PSU. Until
  827. it is known whether the blocker is drying itself or the power budget
  828. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  829. hardware is perfectly happy to continue.
  830. """
  831. ids: list[int] = []
  832. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  833. if not isinstance(unit, dict):
  834. continue
  835. try:
  836. if int(unit.get("dry_time") or 0) > 0:
  837. ids.append(int(unit.get("id", 0)))
  838. except (TypeError, ValueError):
  839. continue
  840. return ids
  841. def _parse_diameter(raw) -> float | None:
  842. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  843. try:
  844. value = float(raw)
  845. except (TypeError, ValueError):
  846. return None
  847. return value if value > 0 else None
  848. def _nozzle_info_by_id(status) -> dict[int, dict]:
  849. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  850. The field name is historical: on the H2 series ``nozzle_info`` carries an
  851. entry for *every* nozzle the printer knows about — the L/R hotends under
  852. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  853. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  854. :func:`_installed_nozzle_diameters` each take the half they need.
  855. """
  856. by_id: dict[int, dict] = {}
  857. for entry in getattr(status, "nozzle_rack", None) or []:
  858. if not isinstance(entry, dict):
  859. continue
  860. try:
  861. by_id[int(entry.get("id"))] = entry
  862. except (TypeError, ValueError):
  863. continue
  864. return by_id
  865. # What the firmware puts in a nozzle's serial number when the carriage or dock
  866. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  867. # its nozzle back in the rack (#2885).
  868. _EMPTY_NOZZLE_SERIAL = "N/A"
  869. def _nozzle_is_mounted(entry: dict | None) -> bool:
  870. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  871. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  872. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  873. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  874. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  875. the dock. So the diameter is not a presence signal (#2885).
  876. Emptiness has to be stated, not merely unstated. The serial must be the
  877. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  878. absent — an empty serial only means the printer didn't say, and a firmware
  879. that reports neither field normalises to exactly that. Treating "didn't
  880. say" as "empty" would silently switch the #1899 guard off on any such
  881. machine, so everything we cannot positively call empty counts as mounted.
  882. """
  883. if entry is None:
  884. return True
  885. serial = str(entry.get("serial_number") or "").strip().upper()
  886. if serial != _EMPTY_NOZZLE_SERIAL:
  887. return True
  888. try:
  889. max_temp = float(entry.get("max_temp") or 0)
  890. except (TypeError, ValueError):
  891. return True
  892. return max_temp > 0
  893. def _installed_nozzle_diameters(status) -> list[float]:
  894. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  895. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  896. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  897. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  898. told us its nozzle hardware" — callers must treat that as unknown, not as a
  899. mismatch, so we never block a print on missing data.
  900. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  901. though ``nozzles`` still carries a diameter for it: that value is stale, and
  902. counting it would let a slice match a nozzle the machine does not have
  903. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  904. """
  905. info = _nozzle_info_by_id(status)
  906. diameters: list[float] = []
  907. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  908. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  909. try:
  910. value = float(raw)
  911. except (TypeError, ValueError):
  912. continue
  913. if value > 0 and _nozzle_is_mounted(info.get(index)):
  914. diameters.append(value)
  915. return diameters
  916. def _rack_nozzle_diameters(status) -> list[float]:
  917. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  918. Keyed off the nozzle ids themselves rather than the printer model: only a
  919. rack machine ever reports ids 16-21, so there is no model registry to keep
  920. in sync. An empty dock is simply absent from the payload — measured on an
  921. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  922. present — so appearing here already means "a nozzle is in that dock".
  923. ``stat`` is deliberately not interpreted: its values aren't known, and
  924. reading it wrongly could hide a nozzle the printer would happily fetch.
  925. """
  926. diameters: list[float] = []
  927. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  928. if nozzle_id not in _RACK_NOZZLE_IDS:
  929. continue
  930. # PrinterState spells it "diameter"; the REST schema renames it to
  931. # "nozzle_diameter". Accept either so a caller holding the serialised
  932. # shape gets the same answer.
  933. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  934. if value is not None:
  935. diameters.append(value)
  936. return diameters
  937. def _format_diameters(diameters: list[float]) -> str:
  938. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  939. Deduplicated because a loaded rack holds several nozzles of the same size,
  940. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  941. short form doesn't. Matching still runs over the full list.
  942. """
  943. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  944. def _nozzle_mismatch_message(
  945. sliced_nozzle: float | None,
  946. installed: list[float],
  947. rack: list[float] | None = None,
  948. ) -> str | None:
  949. """Return an actionable error message when the sliced nozzle can't be
  950. printed on any nozzle the machine can reach, else None (#1899).
  951. Fail-safe: returns None whenever we lack the data to judge — no sliced
  952. diameter, or the printer reported no nozzles — so a print is only ever
  953. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  954. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  955. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  956. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  957. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  958. as reachable: the printer fetches one as part of starting the print, so a
  959. slice that matches a docked nozzle is not a mismatch. Without this the
  960. guard blocked every job whose nozzle happened not to be on a hotend at
  961. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  962. diameter already mounted could ever print, and the user had to fetch the
  963. nozzle by hand on the printer's own UI first (#2885).
  964. """
  965. reachable = [*installed, *(rack or [])]
  966. if not sliced_nozzle or not reachable:
  967. return None
  968. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  969. return None
  970. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  971. if rack:
  972. where += f" and {_format_diameters(rack)} in the nozzle rack"
  973. return (
  974. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  975. f"{where}. Re-slice for an available nozzle, or fit the matching "
  976. f"nozzle before printing."
  977. )
  978. def _wrong_nozzle_label(printer_name: str, status, sliced_nozzle: float | None) -> str | None:
  979. """Label of a printer that cannot print a *sliced_nozzle* file, else None (#3536).
  980. Used by the "Any <model>" pick, which before #3536 ignored the nozzle and
  981. handed a 0.6 file to a 0.4 printer that then failed in ``_start_print``.
  982. None means "fits or unknown" (no status, no sliced diameter, no reported
  983. nozzles), so a printer is only ever skipped on a POSITIVE mismatch. The
  984. decision stays in ``_nozzle_mismatch_message`` (same tolerance, same rack
  985. rule as the start guard); this only formats the name for the wait reason.
  986. """
  987. if status is None:
  988. return None
  989. installed = _installed_nozzle_diameters(status)
  990. rack = _rack_nozzle_diameters(status)
  991. if _nozzle_mismatch_message(sliced_nozzle, installed, rack) is None:
  992. return None
  993. where = _format_diameters(installed) if installed else "no nozzle mounted"
  994. if rack:
  995. where += f", rack {_format_diameters(rack)}"
  996. return f"{printer_name} ({where})"
  997. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  998. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  999. Shared by the required and loaded sides, which name their extruder
  1000. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  1001. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  1002. 1 the left/deputy — and both are absent on single-nozzle printers, where
  1003. naming a nozzle would be noise.
  1004. """
  1005. parts = [(entry.get("type") or "filament").upper()]
  1006. if entry.get("color"):
  1007. parts.append(str(entry["color"]))
  1008. nozzle = entry.get(nozzle_key)
  1009. if nozzle == 0:
  1010. parts.append("(right nozzle)")
  1011. elif nozzle == 1:
  1012. parts.append("(left nozzle)")
  1013. return " ".join(parts)
  1014. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  1015. """Explain that nothing loaded matches what the file needs (#2771).
  1016. Only ever built for a printer with no AMS, where the loaded list is short
  1017. enough to quote in full and there is no "load another spool and hit Resume"
  1018. recovery — the external spool holder is all there is, so the user needs to
  1019. be told which filament to put on it.
  1020. """
  1021. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  1022. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  1023. return (
  1024. f"No filament loaded on this printer matches the file. It needs {want}; "
  1025. f"the printer has {have} and no AMS. Load the required filament on the "
  1026. f"external spool holder, or send this job to a printer that has it."
  1027. )
  1028. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  1029. """Bed temperature for the plate a queued job prints, 0 when unknown.
  1030. The archive stores the highest bed temperature of any filament in the
  1031. project, while the job may print another plate than the one archived: a
  1032. PLA plate of a project that also holds PETG is heated for PLA. Read from
  1033. the archive's file for the job's own plate, falling back to the stored
  1034. value when the file can't be read.
  1035. """
  1036. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  1037. if archive is None or not archive.file_path:
  1038. return stored
  1039. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  1040. return temperature or stored
  1041. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  1042. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  1043. every call site below it: G-code injection, usage registration, rack-plan
  1044. lookup, slot-extruder lookup, the external-spool check, and the actual
  1045. print command.
  1046. A positive explicit ``plate_id`` on the queue item always wins. A
  1047. non-positive one is treated as "not set" and resolved from the archive,
  1048. the way the rest of the queue code already reads it (``if item.plate_id:``
  1049. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  1050. field, and passing a 0 straight through would build a print command for
  1051. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  1052. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  1053. Falling back to a bare ``1`` instead of reading the archive assumes a
  1054. single-plate file's one G-code is numbered 1, which only holds for a
  1055. plate exported on its own: one cut out of a larger project keeps its
  1056. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  1057. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  1058. the file, throws an HMS error, and sits wedged in IDLE until
  1059. power-cycled (#2947).
  1060. The call sites agreed on a fallback only by accident before this:
  1061. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  1062. the archive's own default plate internally whenever the plate id it's
  1063. handed isn't in the file, so it could silently inject into a different
  1064. plate than the one the print command itself asked for.
  1065. Falls back to 1 when the archive can't be read, holds no G-code member at
  1066. all, or its default member doesn't follow the ``plate_N`` naming
  1067. convention (a slicer that doesn't use it has no number to dispatch).
  1068. An explicit plate the archive doesn't hold is logged and then sent
  1069. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  1070. to a plate that is in the file would print a model nobody asked for,
  1071. which is the worse of the two.
  1072. """
  1073. try:
  1074. with zipfile.ZipFile(file_path, "r") as zf:
  1075. names = zf.namelist()
  1076. except (OSError, zipfile.BadZipFile) as exc:
  1077. logger.warning(
  1078. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  1079. "is unavailable; dispatching plate %s",
  1080. file_path,
  1081. exc,
  1082. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  1083. )
  1084. names = None
  1085. if explicit_plate_id is not None and explicit_plate_id > 0:
  1086. if (
  1087. names is not None
  1088. and default_plate_number(names) is not None
  1089. and select_plate_gcode_name(names, explicit_plate_id) is None
  1090. ):
  1091. logger.warning(
  1092. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  1093. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  1094. "file, since printing a different plate would print the wrong model (#2947)",
  1095. file_path,
  1096. explicit_plate_id,
  1097. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  1098. explicit_plate_id,
  1099. )
  1100. return explicit_plate_id
  1101. resolved = default_plate_number(names) if names is not None else None
  1102. return resolved if resolved is not None else 1
  1103. def _wear_order(printer: Printer) -> tuple[float, int]:
  1104. """Sort key for printers a model job could run on: fewest print hours, then id (#3480).
  1105. The same hours as maintenance's ``get_printer_total_hours``: the runtime
  1106. counter plus the baseline offset a user set for a second-hand or reset
  1107. machine.
  1108. """
  1109. hours = (printer.runtime_seconds or 0) / 3600.0 + (printer.print_hours_offset or 0.0)
  1110. return hours, printer.id
  1111. def _hours_of(printer: Printer) -> float:
  1112. return (printer.runtime_seconds or 0) / 3600.0 + (printer.print_hours_offset or 0.0)
  1113. def _order_printers(
  1114. printers: list[Printer], order: str, last_finished: dict[int, datetime] | None = None
  1115. ) -> list[Printer]:
  1116. """Sort the printers an "Any model" job could take into the order they are picked (#2915).
  1117. Whatever the strategy, ties fall back to the printer id, so the outcome is
  1118. reproducible.
  1119. * ``fewest_hours`` (the default, #3480): the least worn machine first.
  1120. * ``most_hours``: the most worn first, to use up the machines already near
  1121. replacement.
  1122. * ``least_recently_used``: the printer that finished a print longest ago;
  1123. one that never has goes first.
  1124. * ``priority``: the printers' own ``dispatch_priority``, lowest first; one
  1125. without goes last.
  1126. """
  1127. if order == "most_hours":
  1128. return sorted(printers, key=lambda p: (-_hours_of(p), p.id))
  1129. if order == "least_recently_used":
  1130. finished = last_finished or {}
  1131. never = datetime.min
  1132. return sorted(printers, key=lambda p: (finished.get(p.id, never), p.id))
  1133. if order == "priority":
  1134. return sorted(
  1135. printers,
  1136. key=lambda p: (
  1137. p.dispatch_priority is None,
  1138. p.dispatch_priority if p.dispatch_priority is not None else 0,
  1139. p.id,
  1140. ),
  1141. )
  1142. return sorted(printers, key=_wear_order)
  1143. class PrintScheduler:
  1144. """Background scheduler that processes the print queue."""
  1145. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  1146. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  1147. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  1148. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  1149. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  1150. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  1151. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1152. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1153. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1154. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1155. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1156. }
  1157. def __init__(self):
  1158. self._running = False
  1159. self._check_interval = 30 # seconds
  1160. # After a pass that actually dispatched something, loop again almost
  1161. # immediately instead of sleeping the full interval (#2555). A dispatch
  1162. # changes printer state — a batch launch fans out over several passes as
  1163. # printers free up, a wedged head-of-line job reverts to pending, an
  1164. # upload slot opens — and the next batch of ready work should not have to
  1165. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1166. # pending items are behind printers that are genuinely busy printing),
  1167. # there is nothing to react to, so we fall back to the normal interval;
  1168. # that also means this can never tight-loop, since fast ticks only
  1169. # continue while dispatches keep happening and the queue is draining.
  1170. self._fast_check_interval = 3 # seconds
  1171. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1172. self._power_on_check_interval = 10 # seconds between connection checks
  1173. # Printers whose class-target power-on failed, mapped to the monotonic
  1174. # time their cool-off expires (#2786).
  1175. #
  1176. # Without this, one printer with an unreachable plug starves every
  1177. # sibling of its model forever: the wake step walks candidates in id
  1178. # order, spends the pass's single attempt on the same broken printer
  1179. # every time, and the healthy one two slots down is never reached. It
  1180. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1181. # which delays the whole queue, not just this job.
  1182. #
  1183. # Entries expire on read rather than being cleared on success: a printer
  1184. # inside its cool-off is skipped before the power-on is reached, so a
  1185. # live entry can never be overwritten by a success anyway. A printer
  1186. # that comes back by any other route stops being a wake candidate the
  1187. # moment it connects.
  1188. self._wake_failures: dict[int, float] = {}
  1189. self._wake_failure_cooloff = 600 # seconds
  1190. # Printers whose last upload never reached them, mapped to the monotonic
  1191. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1192. # as `_wake_failures`. Without it, a printer that cannot take files is
  1193. # idle on every pass, so it is picked on every pass.
  1194. self._upload_backoff: dict[int, float] = {}
  1195. # Refused uploads in a row per printer, which sets the next backoff
  1196. # window. Cleared by a successful upload to that printer.
  1197. self._upload_refusals: dict[int, int] = {}
  1198. # Why each printer in `_upload_backoff` refused its last upload, for
  1199. # the reason its jobs show. Cleared with `_upload_refusals`.
  1200. self._upload_refusal_kind: dict[int, FtpFailureKind] = {}
  1201. # The "job waiting" text last sent for each printer's current run of
  1202. # refusals. A refusal notifies only when its text differs, so a run
  1203. # notifies once, and again only if it turns into something the user
  1204. # has to fix. Cleared with `_upload_refusals`.
  1205. self._upload_refusal_notified: dict[int, str] = {}
  1206. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1207. self._drying_in_progress: dict[int, float] = {}
  1208. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1209. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1210. # cycle and the humidity finally coming down, so the normal steady
  1211. # state is an empty dict. Fields:
  1212. # running — a cycle we armed is (or should be) on the firmware
  1213. # ended_at — monotonic when we observed that cycle end
  1214. # unproductive — consecutive armed cycles that ended with the reading
  1215. # still above the threshold
  1216. # suspended — we have stopped arming this unit and said so
  1217. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1218. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1219. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1220. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1221. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1222. # arming setdefault all act on that meaning -- a unit that is merely
  1223. # waiting out its streak must not become stoppable or judgeable.
  1224. # since -- monotonic stamp when the current continuous above-threshold
  1225. # streak began
  1226. # last -- monotonic stamp of the last pass that observed the streak
  1227. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1228. # Slots already notified as low on filament:
  1229. # {(printer_id, ams_id, tray_id, spool_id)}.
  1230. # Cleared when the slot goes back above its threshold rather than on a
  1231. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1232. # boundary must not produce an alert on every pass, and a slot that has
  1233. # been refilled has to be able to alert again. See #2913.
  1234. #
  1235. # The spool id is part of the key because the slot alone cannot clear
  1236. # itself. Pull a low spool and put a different part-used one in the same
  1237. # slot: the key survives the pass where the slot resolves to nothing --
  1238. # deliberately, so a brief Spoolman outage does not re-alert everything
  1239. # when it returns -- and the replacement never goes above the threshold,
  1240. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1241. # different key and the stale one is inert.
  1242. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1243. # The same, for the MQTT relay's filament/low event: its own record, so
  1244. # one channel having been told never silences the other.
  1245. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1246. # Earliest monotonic time the next low-filament check may run (#2913).
  1247. self._filament_low_next_check: float = 0.0
  1248. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1249. # condition is "reorder" or "break", the events are those that had a
  1250. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1251. # condition clears, so it can alert again, and when nobody wants either
  1252. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1253. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1254. # re-send one message per SKU that is still low.
  1255. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1256. # The JSON last read from or written to that row; None until it has been read.
  1257. self._stock_alerts_persisted: str | None = None
  1258. # Earliest monotonic time the next stock forecast check may run (#2955).
  1259. self._stock_forecast_next_check: float = 0.0
  1260. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1261. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1262. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1263. # both features share _drying_in_progress.
  1264. self._scheduled_drying_printer_ids: set[int] = set()
  1265. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1266. # the first pass after a restart reaps anything left behind.
  1267. self._last_scheduled_drying_prune: float | None = None
  1268. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1269. # a project_file command must not get a second dispatch until either it
  1270. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1271. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1272. # during that window the DB busy_printers seed is empirically unreliable
  1273. # (multi-plate batches double-/triple-dispatched onto the same printer
  1274. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1275. # or revert.
  1276. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1277. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1278. # Minimum cooldown between dispatches to the same printer (covers the
  1279. # H2D's project_file digestion window).
  1280. self._dispatch_min_cooldown = 60.0
  1281. # Hard timeout — drop the hold even if we never observed a transition,
  1282. # so a lost MQTT session can't lock a printer out of the queue forever.
  1283. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1284. # watchdog runs first on the unhappy path.
  1285. self._dispatch_max_hold = 180.0
  1286. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1287. # an earlier pass and is still running. `_start_print` flips the row
  1288. # pending -> printing only *after* the upload completes, so until then
  1289. # the row stays `pending`: each tick, check_queue excludes these
  1290. # item_ids from re-selection and their printers from new dispatch /
  1291. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1292. # freed slots refill on the next fast tick. check_queue is the sole,
  1293. # sequential caller and the prune done-callbacks run in the same
  1294. # event-loop thread, so this dict needs no lock.
  1295. # item_id -> (task, printer_id)
  1296. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1297. # The archive each dispatch in flight prints into, held in
  1298. # services/archive_work so a merge leaves it alone until the dispatch
  1299. # ends: item_id -> archive_id. Same threading as above.
  1300. self._held_archives: dict[int, int] = {}
  1301. # Expected prints registered by `_start_print` that have not yet had a
  1302. # print command sent. Populated at registration, dropped once
  1303. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1304. # other exit. Same threading argument as `_inflight` above: one
  1305. # sequential caller, callbacks on the same loop, so no lock.
  1306. # item_id -> (printer_id, remote_filename, archive_id)
  1307. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1308. # Budget reservations created for a dispatch whose print command has
  1309. # not been confirmed yet. `_dispatch_one` releases these on every
  1310. # unsuccessful exit; a successful start removes the item id and leaves
  1311. # the reservation for finance_billing to consume with the archive.
  1312. self._unconfirmed_budget_reservations: set[int] = set()
  1313. # The print user `_start_print` handed to printer_manager for an item
  1314. # whose print command has not been sent yet (item_id -> printer_id).
  1315. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1316. # expected print above: it marks the printer's next print as Bambuddy's.
  1317. self._unconfirmed_print_user: dict[int, int] = {}
  1318. # Prints whose command went out but which the printer has not been
  1319. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1320. # the file and archive None for a library print. The watchdog drops the
  1321. # entry once the print runs, and withdraws what it stands for when the
  1322. # print never starts (see `_forget_unstarted_print`).
  1323. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1324. # Chamber temperature history for smart soak-time reduction.
  1325. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1326. # Entries older than _chamber_history_ttl are pruned on write.
  1327. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1328. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1329. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1330. # Populated on engagement in `_apply_keep_warm`, cleared by
  1331. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1332. # when a gate setting toggles off mid-hold — the release publishes
  1333. # bed → 0 first).
  1334. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1335. # Preheat rollback registry: printer_id -> subset of
  1336. # {"bed", "chamber", "airduct"} listing which preheat commands
  1337. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1338. # every entry still present at exit unless the print successfully
  1339. # started, so a failed upload / cancel / exception never leaves the
  1340. # printer heating for a job that isn't happening.
  1341. self._preheat_pin: dict[int, set[str]] = {}
  1342. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1343. # rollback can tell its own target from one someone else has since
  1344. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1345. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1346. self._preheat_pin_bed: dict[int, int] = {}
  1347. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1348. # its preheat was still holding at temperature. Set by
  1349. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1350. # `_preheat_sleep`, and cleared when the dispatch exits.
  1351. self._cancelled_dispatches: set[int] = set()
  1352. # printer_id -> monotonic time it was first seen terminal while one of
  1353. # its queue rows was still 'printing'. Reset by any non-terminal
  1354. # observation, so it measures an unbroken run rather than a total.
  1355. # In-memory on purpose: a restart re-arms the grace period, which only
  1356. # delays a recovery that is already the exceptional path (#2829).
  1357. self._terminal_since: dict[int, float] = {}
  1358. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1359. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1360. # across idle printers repeats that for every one of them in a single
  1361. # pass. Cleared at the top of each pass so a re-sliced file is never
  1362. # served from a previous tick.
  1363. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1364. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1365. # matcher about every idle candidate, and a pass can ask again for the
  1366. # same job and printer (another variant, a previous-print retry, the
  1367. # low-filament move). Cleared with the requirement memo.
  1368. self._unmatched_memo: dict[tuple, list[str]] = {}
  1369. # When each "any model" job held for low filament last looked for
  1370. # another printer (#3137), by queue item id.
  1371. self._short_hold_checked_at: dict[int, float] = {}
  1372. async def run(self):
  1373. """Main loop - check queue every interval."""
  1374. self._running = True
  1375. logger.info("Print scheduler started")
  1376. await self._clear_stale_dispatch_claims(at_startup=True)
  1377. while self._running:
  1378. dispatched = False
  1379. try:
  1380. self._sample_chamber_temps()
  1381. # No-op while any upload is in flight; on a quiet tick it releases
  1382. # a claim whose best-effort clear failed (e.g. the database was
  1383. # briefly unreachable), instead of leaving the row wedged until
  1384. # the next restart.
  1385. await self._clear_stale_dispatch_claims()
  1386. await self._close_stranded_printing_items()
  1387. dispatched = await self.check_queue()
  1388. except Exception as e:
  1389. logger.error("Scheduler error: %s", e)
  1390. # Re-check quickly after a productive pass so a draining batch does
  1391. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1392. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1393. async def _close_stranded_printing_items(self) -> None:
  1394. """Close a ``printing`` row the completion event never closed (#2829).
  1395. ``on_print_complete`` refuses to close a row when the completion's
  1396. subtask name disagrees with the file the row was dispatched with, so a
  1397. completion meant for something else (the printer's own
  1398. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1399. The refusal has no way back, though: nothing else ever closes the row,
  1400. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1401. one bad comparison wedges that printer's queue until a human presses
  1402. cancel. That is what #2829's reporters hit, and the guard's own
  1403. docstring already called stranding the worse of the two failures.
  1404. This is the way back. When a row has been ``printing`` while its
  1405. printer sat in a terminal state for the whole grace period, the print
  1406. is over however the event was read, and the row is closed with the
  1407. status the printer's own state implies.
  1408. Deliberately conservative:
  1409. * Only a connected printer counts. A disconnected one has a stale
  1410. ``state`` and proves nothing.
  1411. * The clock is reset by any non-terminal observation, so this cannot
  1412. fire on a printer that is merely between stages.
  1413. * The grace period is far longer than the gap between a printer
  1414. finishing and its completion arriving, so the normal path always
  1415. wins the race and this only ever sees genuine strandings.
  1416. What it does *not* do is replay the completion's side effects --
  1417. notifications, billing, auto-off. It restores the queue, which is the
  1418. harm being undone; the archive was updated by the normal path
  1419. regardless, since only the queue block refuses. A recovery that
  1420. silently re-fired notifications minutes late would be its own bug.
  1421. """
  1422. try:
  1423. async with async_session() as db:
  1424. result = await db.execute(
  1425. select(PrintQueueItem)
  1426. .where(PrintQueueItem.status == "printing")
  1427. .where(PrintQueueItem.printer_id.is_not(None))
  1428. )
  1429. items = list(result.scalars().all())
  1430. if not items:
  1431. self._terminal_since.clear()
  1432. return
  1433. now = time.monotonic()
  1434. seen_printers: set[int] = set()
  1435. closed = False
  1436. for item in items:
  1437. printer_id = item.printer_id
  1438. seen_printers.add(printer_id)
  1439. state = printer_manager.get_status(printer_id)
  1440. status = _terminal_queue_status(state)
  1441. if status is None:
  1442. self._terminal_since.pop(printer_id, None)
  1443. continue
  1444. since = self._terminal_since.setdefault(printer_id, now)
  1445. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1446. continue
  1447. item.status = status
  1448. item.completed_at = datetime.now(timezone.utc)
  1449. closed = True
  1450. # The printer is idle: nothing it prints next is this item's.
  1451. self._forget_unstarted_print(item.id, unless_printing=True)
  1452. logger.warning(
  1453. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1454. "closing it as %s. Its completion event was never matched to it, which blocks "
  1455. "every later job for this printer (#2829).",
  1456. item.id,
  1457. printer_id,
  1458. getattr(state, "state", None),
  1459. now - since,
  1460. status,
  1461. )
  1462. if closed:
  1463. await db.commit()
  1464. from backend.app.services.print_batch import refresh_batches_after
  1465. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1466. for printer_id in list(self._terminal_since):
  1467. if printer_id not in seen_printers:
  1468. del self._terminal_since[printer_id]
  1469. except Exception as e:
  1470. # Best-effort, same as the claim sweep beside it: a recovery path
  1471. # that can itself break the scheduler loop is worse than the strand.
  1472. logger.error("Stranded-item sweep failed: %s", e)
  1473. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1474. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1475. A claim is only ever held by a live dispatch coroutine, so when this
  1476. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1477. is stale. At startup that is trivially true — no coroutine survives a
  1478. restart. It is equally true on any later tick where no upload is running,
  1479. which is what makes this safe to repeat rather than only run once.
  1480. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1481. the database is briefly unreachable at exactly the moment dispatch ends,
  1482. the claim survives and the row is wedged out of the selection query. That
  1483. used to last until the next restart (#2702 follow-up, seen when
  1484. PostgreSQL refused a connection mid-dispatch).
  1485. ``_inflight`` is populated when the task is spawned, before the coroutine
  1486. claims its row, and pruned by a done-callback that cannot run before the
  1487. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1488. race window and needs no age threshold. A size-derived upload deadline
  1489. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1490. """
  1491. if self._inflight:
  1492. return
  1493. try:
  1494. async with async_session() as db:
  1495. res = await db.execute(
  1496. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1497. )
  1498. await db.commit()
  1499. if res.rowcount:
  1500. logger.info(
  1501. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1502. res.rowcount,
  1503. " at startup" if at_startup else "",
  1504. )
  1505. except Exception as exc:
  1506. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1507. def stop(self):
  1508. """Stop the scheduler."""
  1509. self._running = False
  1510. logger.info("Print scheduler stopped")
  1511. def forget_printer(self, printer_id: int) -> None:
  1512. """Drop what is kept for a deleted printer, so the next printer given its
  1513. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1514. would keep it out of dispatch for up to an hour.
  1515. A dispatch already in flight keeps its own state (_inflight, the preheat
  1516. pins, unconfirmed prints): it unwinds that when it ends.
  1517. """
  1518. for keyed in (
  1519. self._upload_backoff,
  1520. self._upload_refusals,
  1521. self._upload_refusal_kind,
  1522. self._upload_refusal_notified,
  1523. self._wake_failures,
  1524. self._drying_in_progress,
  1525. self._dispatch_holds,
  1526. self._chamber_history,
  1527. self._keep_warm,
  1528. self._terminal_since,
  1529. ):
  1530. keyed.pop(printer_id, None)
  1531. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1532. for key in [key for key in keyed if key[0] == printer_id]:
  1533. del keyed[key]
  1534. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1535. del self._sent_unstarted_print[item_id]
  1536. def printer_reconnected(self, printer_id: int, ip_address: str | None) -> None:
  1537. """Let a printer that has just reconnected take an upload on the next pass (#3563).
  1538. A printer whose file service stopped answering is often fixed by a
  1539. restart, but its upload backoff ran on for up to an hour, and nothing
  1540. but the timer ended it. A reconnect ends the window. The refusal count
  1541. and the notified text stay: a printer that still refuses gets the next,
  1542. longer window and no second "job waiting", and a successful upload
  1543. resets them as before.
  1544. The FTP client's handshake cool-off for the printer goes too. It dates
  1545. from before the reconnect, and inside it the first retry would fail
  1546. without reaching the printer and count as another refusal.
  1547. """
  1548. if self._upload_backoff.pop(printer_id, None) is not None:
  1549. logger.info("Printer %s reconnected; retrying uploads to it without waiting for the backoff", printer_id)
  1550. if ip_address:
  1551. BambuFTPClient.clear_handshake_cooloff(ip_address)
  1552. async def check_queue(self) -> bool:
  1553. """Check for prints ready to start.
  1554. Returns True if this pass dispatched at least one item, so the caller
  1555. can loop again quickly instead of sleeping the full interval (#2555).
  1556. """
  1557. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1558. self._filament_req_memo.clear()
  1559. self._unmatched_memo.clear()
  1560. async with async_session() as db:
  1561. # Check if shortest-job-first scheduling is enabled
  1562. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1563. # Get all pending items in the one order the queue page shows them
  1564. # in (#3200). The first eligible item takes a printer, so this order
  1565. # decides who wins a printer that a pinned job and an "Any <model>"
  1566. # job both want. It used to start with ``printer_id``, which made the
  1567. # lane outrank the position: SQLite sorts NULL first, so model-based
  1568. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1569. # Neither is what the user dragged into place.
  1570. if sjf_enabled:
  1571. # SJF: items already jumped get top priority (starvation guard),
  1572. # then sort by print_time ascending. Items with no print time go
  1573. # last, and position breaks ties.
  1574. result = await db.execute(
  1575. select(PrintQueueItem)
  1576. .where(PrintQueueItem.status == "pending")
  1577. # Never re-select a row a dispatch worker has already claimed
  1578. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1579. # below, and the guard that lets an orphaned claim be ignored
  1580. # until startup reconciliation clears it.
  1581. .where(PrintQueueItem.dispatching_at.is_(None))
  1582. # archive/library_file are read by the cross-model gate
  1583. # (#2578); eager-load once per pass instead of a lazy-load
  1584. # (which would raise in async) per item.
  1585. .options(
  1586. selectinload(PrintQueueItem.archive),
  1587. selectinload(PrintQueueItem.library_file),
  1588. # Cross-model candidates (#671), plus each candidate's file
  1589. # for the same cross-model gate. Lazy-loading either would
  1590. # raise in async.
  1591. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1592. )
  1593. .order_by(
  1594. PrintQueueItem.been_jumped.desc(),
  1595. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1596. PrintQueueItem.position,
  1597. PrintQueueItem.id,
  1598. )
  1599. )
  1600. else:
  1601. result = await db.execute(
  1602. select(PrintQueueItem)
  1603. .where(PrintQueueItem.status == "pending")
  1604. # Skip rows already claimed by a dispatch worker (#2615).
  1605. .where(PrintQueueItem.dispatching_at.is_(None))
  1606. .options(
  1607. selectinload(PrintQueueItem.archive),
  1608. selectinload(PrintQueueItem.library_file),
  1609. # Cross-model candidates (#671), plus each candidate's file
  1610. # for the same cross-model gate. Lazy-loading either would
  1611. # raise in async.
  1612. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1613. )
  1614. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1615. )
  1616. items = list(result.scalars().all())
  1617. # Drop rows whose upload is still in flight from an earlier pass
  1618. # (#2602). They stay `pending` until the upload finishes, so without
  1619. # this a fast tick would re-select and re-dispatch the same row.
  1620. # Belt-and-suspenders with the printer exclusion below.
  1621. if self._inflight:
  1622. inflight_ids = set(self._inflight)
  1623. items = [it for it in items if it.id not in inflight_ids]
  1624. # Read plate-clear setting once per queue check. Default MUST be
  1625. # False to match the schema (SettingsSchema.require_plate_clear
  1626. # defaults False) and the frontend (toggle + card badge both treat a
  1627. # missing value as off). When no settings row exists, a True default
  1628. # here re-enabled the plate-clear gate the UI showed as disabled,
  1629. # blocking dispatch to FINISH-state printers forever with no UI path
  1630. # to clear it (#1865).
  1631. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1632. # Dispatch and track scheduled drying runs (#2638)
  1633. await self._check_scheduled_dryings(db)
  1634. if not items:
  1635. # No dispatchable pending items — still check auto-drying on idle
  1636. # printers, but keep any printer with an upload still in flight
  1637. # from an earlier pass out of it (#2602): its print is imminent,
  1638. # so it must not be auto-dried in the gap before the row flips to
  1639. # printing. Report the pass as productive while uploads run so the
  1640. # loop stays on the fast interval.
  1641. #
  1642. # Also release any keep-warm holds that got orphaned by the queue
  1643. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1644. # this early return, so call it directly with an empty candidate
  1645. # set. Without this, a printer whose queued item was cancelled or
  1646. # deleted would keep its bed at target until the max-duration
  1647. # timeout expired.
  1648. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1649. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1650. await self._check_auto_drying(db, [], inflight_printers)
  1651. await self._check_filament_low(db)
  1652. await self._check_stock_forecast(db)
  1653. return bool(self._inflight)
  1654. logger.info(
  1655. "Queue check: found %d pending items: %s",
  1656. len(items),
  1657. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1658. )
  1659. # Forget jobs that left the queue since they were last checked.
  1660. pending_ids = {i.id for i in items}
  1661. self._short_hold_checked_at = {
  1662. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1663. }
  1664. # Seed busy_printers with printers that already have an item in 'printing'
  1665. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1666. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1667. # lag several seconds behind the print command, so the next check_queue
  1668. # tick still sees IDLE and would double-dispatch onto the same printer.
  1669. # Without this guard, two pending items targeting the same printer
  1670. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1671. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1672. busy_result = await db.execute(
  1673. select(PrintQueueItem.printer_id)
  1674. .where(PrintQueueItem.status == "printing")
  1675. .where(PrintQueueItem.printer_id.is_not(None))
  1676. )
  1677. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1678. # Why each printer left this pass, recorded where the decision is
  1679. # made rather than re-derived when the summary is logged. #3018's
  1680. # bundle shows what the old summary produced: "printer 1 not
  1681. # available -- connected=True, state=IDLE" immediately followed by a
  1682. # dispatch to printer 1. Two things went wrong at once. The line read
  1683. # live state at log time, which by then no longer matched the state
  1684. # the decision was made on; and `busy_printers` holds both printers
  1685. # that cannot take work and printers this pass has claimed for it,
  1686. # which are opposite facts. It is the first line anyone greps for
  1687. # "why did my item not go out", so it has to say which.
  1688. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1689. # Printers this pass is dispatching to. They are in busy_printers so
  1690. # nothing else in the pass targets them -- that is a reservation, not
  1691. # an obstruction, and the summary says so.
  1692. claimed_printers: set[int] = set()
  1693. def mark_busy(printer_id: int, reason: str) -> None:
  1694. """Take ``printer_id`` out of this pass, recording why.
  1695. First reason wins: a printer already excluded by a stronger fact
  1696. -- a print running on it -- must not be relabelled by a weaker
  1697. check that ran later and would have excluded it anyway.
  1698. """
  1699. busy_printers.add(printer_id)
  1700. busy_reasons.setdefault(printer_id, reason)
  1701. def claim_printer(printer_id: int) -> None:
  1702. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1703. claimed_printers.add(printer_id)
  1704. mark_busy(printer_id, "selected for dispatch in this pass")
  1705. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1706. # worded for a different audience: the log wants "still inside its
  1707. # post-dispatch hold window", the queue row wants to know the printer
  1708. # is taken and nothing is broken. Only the cases that would read wrong
  1709. # as a plain "Busy" are recorded here; the rest fall back to it.
  1710. item_hold_reasons: dict[int, str] = {}
  1711. # Names and models for the printers this pass may have to write a
  1712. # waiting reason about, read once rather than per skip per tick. The
  1713. # model-based branch already has its names from `_printers_for_model`.
  1714. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1715. pinned_printers: dict[int, tuple[str, str]] = {}
  1716. if pinned_printer_ids:
  1717. pinned_rows = await db.execute(
  1718. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1719. )
  1720. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1721. def printer_label(printer_id: int) -> str:
  1722. """What to call this printer in a queue row."""
  1723. entry = pinned_printers.get(printer_id)
  1724. return (entry[0] if entry else "") or f"printer {printer_id}"
  1725. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1726. """Record why *item* is not going out, in the words the queue row shows.
  1727. The fixed-printer branch's single writer for ``waiting_reason``
  1728. (#3074). Before this, the sensor interlock was the only thing that
  1729. wrote the field there, so an item pinned to a printer that was
  1730. merely printing sat at `pending` with nothing to show for it —
  1731. indistinguishable from a queue that had stopped working — while
  1732. the same job queued as "Any <model>" explained itself.
  1733. Every exit from that branch now calls this, which is also what
  1734. replaced the interlock's old habit of clearing the field up front:
  1735. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1736. because whichever exit runs next overwrites it and the dispatch
  1737. path clears it.
  1738. A notification goes out when this item starts asking for
  1739. something, and only then: the new reason needs the user, and what
  1740. it replaced did not. "What it replaced did not" has to include a
  1741. busy-only reason, not just an empty one. The sequence this branch
  1742. actually produces is a print running (``Busy: X1C-01``) and then
  1743. the plate it left behind (``Waiting for plate confirmation``), and
  1744. testing "was the field empty" would call that no transition at all
  1745. and stay quiet through the one case worth saying out loud.
  1746. The cost is that a printer dropping offline, coming back busy and
  1747. dropping again asks twice rather than once. That is the honest
  1748. reading — it went wrong twice — and the alternative was a rule
  1749. that never fired for the case this was built for.
  1750. *notify* is how a caller opts out. The sensor interlock does: it
  1751. has never sent this notification, and a change about what the
  1752. queue *displays* is not the place to start (#1148).
  1753. """
  1754. if item.waiting_reason == reason:
  1755. return
  1756. # Busy-only and empty are the same thing here: neither is the
  1757. # queue asking the user for anything.
  1758. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1759. item.waiting_reason = reason
  1760. await db.commit()
  1761. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1762. return
  1763. try:
  1764. job_name = await self._get_job_name(db, item)
  1765. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1766. await notification_service.on_queue_job_waiting(
  1767. job_name=job_name,
  1768. target_model=(entry[1] if entry else "") or "",
  1769. waiting_reason=reason,
  1770. db=db,
  1771. printer_id=item.printer_id,
  1772. )
  1773. except Exception as e:
  1774. # A queue that cannot say why it is waiting is the bug being
  1775. # fixed here; a queue that stops dispatching because a
  1776. # notification provider is down would be a worse one.
  1777. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1778. async def hold_for_printer(
  1779. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1780. ) -> None:
  1781. """Take *printer_id* out of this pass and tell the item's owner why."""
  1782. mark_busy(printer_id, log_reason)
  1783. item_hold_reasons.setdefault(printer_id, item_reason)
  1784. await hold_item(item, item_reason)
  1785. # Defense-in-depth (#1157): augment busy_printers with any printer
  1786. # still in its post-dispatch hold window. Empirically, the DB seed
  1787. # above can miss in-flight items in a multi-plate batch — same-file
  1788. # plates were being dispatched 30 s apart while the H2D was still
  1789. # digesting the first project_file. The hold is keyed in-memory and
  1790. # released by the watchdog on the success path, so it adds a layer
  1791. # that doesn't depend on DB row visibility or completion-callback
  1792. # timing.
  1793. for held_printer_id in list(self._dispatch_holds.keys()):
  1794. if self._printer_in_dispatch_hold(held_printer_id):
  1795. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1796. # Exclude printers whose upload is still in flight from an earlier
  1797. # pass (#2602). The row is `pending` until the upload finishes and
  1798. # the printing-state seed / dispatch hold above only arm once the
  1799. # upload completes, so this is what holds the printer (and, via
  1800. # busy_printers, its auto-drying) out of the pass during the upload.
  1801. for _task, inflight_pid in self._inflight.values():
  1802. if inflight_pid is not None:
  1803. mark_busy(inflight_pid, "an upload to it is still in flight")
  1804. # Snapshot taken here, before the item loop adds anything (#2801).
  1805. #
  1806. # The three sources above all mean the same thing: a print on this
  1807. # printer is running or imminent. Everything the loop adds below
  1808. # means only "the queue could not dispatch to it this pass", which
  1809. # is a different statement -- a printer waiting on a plate-clear
  1810. # acknowledgment, an offline printer, one with no matching file.
  1811. #
  1812. # Auto-drying must only see the first kind. Reading the whole set
  1813. # as "is currently printing" is what put a plate-held printer down
  1814. # the mid-print path: it capped the drying temperature, logged the
  1815. # cycle as (mid-print), and skipped the very gate that was supposed
  1816. # to hold it. The interlock block below already documents the same
  1817. # hazard and works around it by staying out of busy_printers; this
  1818. # generalises that workaround instead of repeating it per case.
  1819. dispatching_printers: set[int] = set(busy_printers)
  1820. # Printers whose last upload never reached them (#3210). After the
  1821. # snapshot above on purpose: such a printer is idle, not about to
  1822. # print, and auto-drying must keep treating it as idle.
  1823. now_mono = time.monotonic()
  1824. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1825. # can leave them out: there is no print to keep a bed warm for.
  1826. # Their holds are written silently: the refusal that put a printer
  1827. # here sent the "job waiting" notification for its run (#3409).
  1828. backoff_printers: set[int] = set()
  1829. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1830. if now_mono >= retry_at:
  1831. del self._upload_backoff[backoff_pid]
  1832. continue
  1833. backoff_printers.add(backoff_pid)
  1834. mark_busy(
  1835. backoff_pid,
  1836. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1837. )
  1838. item_hold_reasons.setdefault(
  1839. backoff_pid,
  1840. _refused_upload_hold_reason(printer_label(backoff_pid), self._upload_refusal_kind.get(backoff_pid)),
  1841. )
  1842. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1843. # enclosure door left open, say. The fixed-printer branch turns
  1844. # this into a waiting_reason the user can act on; the model-based
  1845. # branch hides these printers from the matcher so an "Any <model>"
  1846. # job runs on a sibling instead of queueing behind the held one.
  1847. #
  1848. # Deliberately NOT merged into busy_printers, even though that set
  1849. # already means "unavailable this pass". _check_auto_drying reads
  1850. # it as "is currently printing" and would put an idle-but-held
  1851. # printer down the mid-print drying path, which caps the drying
  1852. # temperature and skips the queue-only gating. A held printer is
  1853. # idle; it should dry exactly as it did before.
  1854. #
  1855. # Only sensors we actually read and found alerting appear here; see
  1856. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1857. # holds nothing.
  1858. interlocked: dict[int, str] = {}
  1859. try:
  1860. interlocked = await ha_sensor_manager.blocked_printers(db)
  1861. except Exception as e:
  1862. # Never let the interlock stop the queue running. A broken
  1863. # lookup means no holds, not no dispatches.
  1864. logger.warning("Home Assistant interlock check failed: %s", e)
  1865. interlocked = {}
  1866. # Printers a smart plug can bring back, read once for the whole pass
  1867. # (#2786). Used by the model-based branch both to word "Offline" in
  1868. # the waiting reason and to decide what the wake step may switch on.
  1869. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1870. # At most one power-on per queue check. Each one blocks this loop
  1871. # for the boot wait, so a queue of ten class-targeted jobs must not
  1872. # switch on ten printers inside a single pass — the next pass wakes
  1873. # the next one (#2786).
  1874. power_on_attempted = False
  1875. # Log skip reasons once per queue check (not per item)
  1876. skip_reasons: dict[str, int] = {}
  1877. # Items selected for dispatch in this pass, one per printer. The
  1878. # loop below only *decides* — the uploads happen afterwards, in
  1879. # parallel (#2555). See _dispatch_selected().
  1880. dispatch_ids: list[int] = []
  1881. # Library rows queued with `cleanup_library_after_dispatch` (the
  1882. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1883. # that prints them: the row is deleted and the 3MF is unlinked from
  1884. # disk. That was safe only because dispatch was serial. Run two of
  1885. # them against the same row at once and the second DELETE matches no
  1886. # row (StaleDataError), and the winner's unlink can pull the file out
  1887. # from under the loser's in-flight upload.
  1888. #
  1889. # Only the cleanup flag mutates the row. An ordinary library print
  1890. # just reads it, so the common fan-out — one file, many printers,
  1891. # which is exactly the reporter's workload — still goes out fully in
  1892. # parallel. Narrow the guard to the mutating case; do not serialise
  1893. # the case the whole fix exists for.
  1894. dispatch_libs: set[int] = set()
  1895. consumed_libs: set[int] = set()
  1896. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1897. """True if dispatching `candidate` now would race another item's cleanup."""
  1898. lib_id = candidate.library_file_id
  1899. if lib_id is None:
  1900. return False
  1901. if candidate.cleanup_library_after_dispatch:
  1902. # We would delete a row someone else in this pass is reading.
  1903. return lib_id in dispatch_libs
  1904. # Someone else in this pass will delete the row out from under us.
  1905. return lib_id in consumed_libs
  1906. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1907. lib_id = candidate.library_file_id
  1908. if lib_id is None:
  1909. return
  1910. dispatch_libs.add(lib_id)
  1911. if candidate.cleanup_library_after_dispatch:
  1912. consumed_libs.add(lib_id)
  1913. # Printer scope of each job's creator (#1727), so an "any <model>"
  1914. # job only lands on a printer its creator may use. Loaded lazily,
  1915. # once per creator per pass.
  1916. from backend.app.core.auth import is_auth_enabled
  1917. scope_auth_enabled = await is_auth_enabled(db)
  1918. creator_scopes: dict[int, PrinterScope] = {}
  1919. # Printers a model job passes over while drying blocks the queue,
  1920. # as a pinned job waits for its own. A parked timer never ends,
  1921. # so it does not hold (#2896).
  1922. drying_held: set[int] = (
  1923. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1924. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1925. else set()
  1926. )
  1927. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1928. if not scope_auth_enabled or user_id is None:
  1929. return ALL_PRINTERS
  1930. if user_id not in creator_scopes:
  1931. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1932. return creator_scopes[user_id]
  1933. for item in items:
  1934. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1935. if item.scheduled_time:
  1936. sched = item.scheduled_time
  1937. if sched.tzinfo is None:
  1938. sched = sched.replace(tzinfo=timezone.utc)
  1939. if sched > datetime.now(timezone.utc):
  1940. # Waiting on the clock, not on a printer.
  1941. await hold_item(item, None)
  1942. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1943. continue
  1944. # Skip items that require manual start, except an "any model"
  1945. # job held for low filament that another idle printer can now
  1946. # run: that one is moved there and carries on below (#3137).
  1947. if item.manual_start and not (
  1948. item.filament_short
  1949. and await self._release_short_model_hold(
  1950. db,
  1951. item,
  1952. busy_printers | interlocked.keys() | drying_held,
  1953. require_plate_clear,
  1954. await _creator_scope(item.created_by_id),
  1955. )
  1956. ):
  1957. # Waiting on the user, not on a printer. Cleared here because
  1958. # this is the last pass that will look at the row: a staged
  1959. # item never reaches the branches below again, so a reason
  1960. # left from before it was staged would stand forever (#3074).
  1961. # The one exception is the unmatched-filament hold, whose
  1962. # reason was written at staging and is why the item waits:
  1963. # it names the filament to load (#2799). Pressing start
  1964. # clears manual_start, and the branches below overwrite it.
  1965. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1966. await hold_item(item, keep)
  1967. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1968. continue
  1969. if item.printer_id and item.printer_id not in pinned_printers:
  1970. # Moved by the release above to a printer no row named when
  1971. # the labels were read.
  1972. moved_to = await self._get_printer(db, item.printer_id)
  1973. if moved_to is not None:
  1974. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1975. if item.printer_id:
  1976. # Its creator may no longer use this printer (#1727): an
  1977. # admin took it away from their group after the job was
  1978. # queued, say to keep it free for a training session. Held,
  1979. # not failed, so it starts if access comes back or the user
  1980. # moves it to a printer they still have.
  1981. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1982. await hold_item(
  1983. item,
  1984. "Its owner no longer has access to this printer — move it to another printer",
  1985. notify=False,
  1986. )
  1987. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1988. continue
  1989. # Held by a sensor interlock (#1148). Checked before the
  1990. # busy_printers test that would otherwise swallow it
  1991. # silently — "waiting for a printer" and "waiting for you
  1992. # to shut the enclosure" need to read differently, and only
  1993. # one of them is something the user can fix.
  1994. #
  1995. # It used to be the only thing that wrote a waiting_reason on
  1996. # this branch, and it cleared the field up front so a lifted
  1997. # hold could not leave a shut door reading "Waiting on
  1998. # Enclosure Door". `hold_item` carries that guarantee now —
  1999. # every exit below writes — so the clear is gone and the
  2000. # interlock is an ordinary hold like the rest (#3074).
  2001. interlock_reason = interlocked.get(item.printer_id)
  2002. if interlock_reason:
  2003. # Silent, exactly as it has always been. #1148 built this
  2004. # as a hold that shows on the row, never as an alert, and
  2005. # routing it through the shared writer must not quietly
  2006. # turn every open door into a notification.
  2007. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  2008. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  2009. continue
  2010. # Specific printer assignment (existing behavior)
  2011. if item.printer_id in busy_printers:
  2012. # Whatever took the printer out of this pass — a print
  2013. # already running on it, a post-dispatch hold, an upload
  2014. # still in flight, an item ahead of this one in the same
  2015. # pass — reads the same way from the queue: the printer is
  2016. # taken and this item is in line for it. The exceptions
  2017. # that do not (an offline printer, say) recorded their own
  2018. # wording in `item_hold_reasons` when they held it.
  2019. await hold_item(
  2020. item,
  2021. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  2022. notify=item.printer_id not in backoff_printers,
  2023. )
  2024. continue
  2025. # Check if printer is idle
  2026. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  2027. printer_connected = printer_manager.is_connected(item.printer_id)
  2028. # If printer not connected, try to power on via smart plug
  2029. if not printer_connected:
  2030. plugs = await self._get_smart_plugs(db, item.printer_id)
  2031. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2032. if auto_on_plugs:
  2033. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  2034. # Power on using the plug that actually feeds the printer, and
  2035. # wait for it to boot on that one only (#2629).
  2036. primary_plug = self._pick_power_plug(auto_on_plugs)
  2037. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  2038. if powered_on:
  2039. # Also turn on any remaining auto_on plugs (e.g., filter)
  2040. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2041. try:
  2042. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2043. if await service.turn_on(extra_plug):
  2044. await publish_plug_state(
  2045. extra_plug.id,
  2046. extra_plug.name,
  2047. extra_plug.printer_id,
  2048. on=True,
  2049. ha_entity_id=extra_plug.ha_entity_id,
  2050. )
  2051. logger.info(
  2052. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  2053. )
  2054. except Exception as e:
  2055. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2056. printer_connected = True
  2057. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  2058. else:
  2059. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  2060. await hold_for_printer(
  2061. item,
  2062. item.printer_id,
  2063. "smart-plug power-on failed",
  2064. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  2065. )
  2066. continue
  2067. else:
  2068. # No plug or auto_on disabled. Worded exactly as the
  2069. # model-based branch words it (#2786): this is the one
  2070. # entry on that list the user has to act on, because
  2071. # Bambuddy will never switch this printer on itself.
  2072. await hold_for_printer(
  2073. item,
  2074. item.printer_id,
  2075. "offline, with no smart plug to power it on",
  2076. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  2077. )
  2078. continue
  2079. # Check if printer is idle (busy with another print)
  2080. if not printer_idle:
  2081. await hold_for_printer(
  2082. item,
  2083. item.printer_id,
  2084. "not idle",
  2085. self._pinned_hold_reason(
  2086. item.printer_id, printer_label(item.printer_id), require_plate_clear
  2087. ),
  2088. )
  2089. continue
  2090. # Drying blocks the queue, if the user asked it to. A hold
  2091. # is a skip like any other, so it belongs here with the
  2092. # rest of the availability checks.
  2093. # A parked timer (#2896) never ends, so it must not hold the
  2094. # queue; it stays tracked so the stop paths still reach it.
  2095. if (
  2096. self._drying_in_progress.get(item.printer_id)
  2097. and not self._drying_is_only_parked(item.printer_id)
  2098. and await self._get_bool_setting(db, "queue_drying_block")
  2099. ):
  2100. # Busy-shaped on purpose: the cycle ends on its own and
  2101. # the job goes out, so there is nothing to alert about.
  2102. await hold_for_printer(
  2103. item,
  2104. item.printer_id,
  2105. "drying, and drying is set to block the queue",
  2106. f"Busy: {printer_label(item.printer_id)} (drying)",
  2107. )
  2108. continue
  2109. # Check condition (previous print success)
  2110. if item.require_previous_success:
  2111. if not await self._check_previous_success(db, item):
  2112. item.status = "skipped"
  2113. item.error_message = "Previous print failed or was aborted"
  2114. item.completed_at = datetime.now(timezone.utc)
  2115. # Not pending any more, so not waiting for anything.
  2116. item.waiting_reason = None
  2117. await db.commit()
  2118. logger.info("Skipped queue item %s - previous print failed", item.id)
  2119. # Send notification
  2120. job_name = await self._get_job_name(db, item)
  2121. printer = await self._get_printer(db, item.printer_id)
  2122. await notification_service.on_queue_job_skipped(
  2123. job_name=job_name,
  2124. printer_id=item.printer_id,
  2125. printer_name=printer.name if printer else "Unknown",
  2126. reason="Previous print failed or was aborted",
  2127. db=db,
  2128. )
  2129. continue
  2130. # Resolve the AMS mapping when it's missing OR unresolved
  2131. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  2132. # frontend status-load race can persist [-1] (#2589) — and
  2133. # must be recomputed from live trays rather than trusted.
  2134. if await _edited_since_loaded(db, item):
  2135. continue
  2136. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  2137. if unmappable:
  2138. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  2139. continue
  2140. # Filament-deficit pre-dispatch check (#1496). If the
  2141. # assigned spool can't satisfy any required slot grams,
  2142. # promote the item to manual_start so the user must
  2143. # acknowledge via the ▶ button (which re-checks live).
  2144. if await self._block_on_filament_deficit(db, item):
  2145. # Now staged for the user to start by hand, and the row
  2146. # shows the filament-short badge instead. Cleared because
  2147. # a staged item never reaches this branch again.
  2148. await hold_item(item, None)
  2149. continue
  2150. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  2151. # than let the printer pick a substitute for a slot the
  2152. # matcher could not resolve on this printer.
  2153. if await self._block_on_unmatched_filament(db, item):
  2154. continue
  2155. # Hold this item back for the next pass rather than racing
  2156. # another dispatch over the same transient library row. The
  2157. # printer is still marked busy so a later item does not jump
  2158. # its place in this printer's queue.
  2159. if _library_row_conflict(item):
  2160. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2161. await hold_for_printer(
  2162. item,
  2163. item.printer_id,
  2164. "holding its place while another item releases a library row",
  2165. f"Busy: {printer_label(item.printer_id)}",
  2166. )
  2167. continue
  2168. # Print takes priority: stop a cycle Bambuddy armed, now
  2169. # that this item is definitely going out.
  2170. #
  2171. # Placement is the whole point (#2801). This used to sit up
  2172. # with the availability checks, inside the not-idle branch
  2173. # -- so it fired only on the passes where the print was NOT
  2174. # going to start, and never on the ones where it was.
  2175. # Drying is not one of the things `_is_printer_idle` looks
  2176. # at, so a stop could never have unblocked that printer
  2177. # anyway; the cycle was spent for nothing, auto-drying
  2178. # re-armed on the next tick, and a plate left
  2179. # unacknowledged turned that into a loop on the scheduler
  2180. # interval. Every skip between there and here -- a failed
  2181. # previous print, an unmappable item, a filament deficit, a
  2182. # contested library row -- is another way to lose a cycle
  2183. # for a print that never happens, which is why this waits
  2184. # until the decision is actually made.
  2185. if self._drying_in_progress.get(
  2186. item.printer_id
  2187. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2188. await self._stop_drying(item.printer_id)
  2189. # Queue the dispatch instead of running it here — see
  2190. # _dispatch_selected(). busy_printers still gets the printer
  2191. # immediately, so nothing else in this pass can target it.
  2192. #
  2193. # The reason goes first: this item is not waiting for anything
  2194. # any more, and the model-based branch clears its own at the
  2195. # equivalent moment (#3074).
  2196. await hold_item(item, None)
  2197. _claim_library_row(item)
  2198. dispatch_ids.append(item.id)
  2199. claim_printer(item.printer_id)
  2200. # SJF starvation guard: mark items that were jumped
  2201. if sjf_enabled and item.print_time_seconds is not None:
  2202. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2203. for other in items:
  2204. if (
  2205. other.id != item.id
  2206. and other.id not in dispatch_ids
  2207. and other.status == "pending"
  2208. and _could_take_printer(other, item.printer_id, pinned_model)
  2209. and not other.been_jumped
  2210. and other.position < item.position
  2211. and (
  2212. other.print_time_seconds is None
  2213. or other.print_time_seconds > item.print_time_seconds
  2214. )
  2215. ):
  2216. other.been_jumped = True
  2217. await db.commit()
  2218. elif item.target_model or item.variants:
  2219. # Model-based assignment - find any idle printer of matching model.
  2220. # A plain model-based item has exactly one candidate, built from
  2221. # its own columns. A cross-model item (#671) has one per sliced
  2222. # variant and takes the first that matches, walking them in the
  2223. # user's priority order so the pick is reproducible when more
  2224. # than one printer is free in the same pass.
  2225. candidates = _candidates_for(item)
  2226. item_scope = await _creator_scope(item.created_by_id)
  2227. printer_id = None
  2228. chosen: _ModelCandidate | None = None
  2229. per_model_reasons: list[tuple[str | None, str]] = []
  2230. # Candidates that cleared the cross-model gate below. The
  2231. # smart-plug wake step may only consider these — waking a
  2232. # printer for a file that can never legally run on it is
  2233. # worse than not waking at all (#2786).
  2234. wakeable_candidates: list[_ModelCandidate] = []
  2235. # Printers passed over because their last print failed.
  2236. gate_blocked: set[int] = set()
  2237. if not candidates:
  2238. # Every candidate file has been deleted or trashed out from
  2239. # under this item. Hold it with something the user can act
  2240. # on rather than letting it look dispatchable forever.
  2241. per_model_reasons.append(
  2242. (
  2243. item.target_model,
  2244. "Every file for this job has been deleted — add a file back or remove the item",
  2245. )
  2246. )
  2247. for candidate in candidates:
  2248. effective_types, filament_overrides = _filament_constraints(candidate)
  2249. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2250. # for an incompatible model to a printer, no matter how the
  2251. # row got into the DB (old rows, direct API writes). Held
  2252. # as pending with an actionable waiting_reason — the user
  2253. # fixes it by editing the item's target model.
  2254. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2255. per_model_reasons.append(
  2256. (
  2257. candidate.target_model,
  2258. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2259. f"{candidate.target_model} — edit the item and fix its target model",
  2260. )
  2261. )
  2262. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2263. continue
  2264. wakeable_candidates.append(candidate)
  2265. async def is_short(
  2266. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2267. ) -> bool:
  2268. # The check reads the file and plate off the item,
  2269. # so it must hold this candidate's. Resolving is
  2270. # safe to repeat, and the winner is resolved again
  2271. # below.
  2272. self._resolve_variant(item, candidate)
  2273. return await self._filament_short_on(db, item, pid)
  2274. async def unmatched_on(
  2275. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2276. ) -> list[str]:
  2277. self._resolve_variant(item, candidate)
  2278. return await self._unmatched_on(db, item, pid)
  2279. while True:
  2280. match_id, match_reason = await self._find_idle_printer_for_model(
  2281. db,
  2282. candidate.target_model,
  2283. # Sensor-held printers are unavailable to the
  2284. # matcher but stay out of busy_printers itself
  2285. # (#1148) — see where `interlocked` is built.
  2286. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2287. effective_types,
  2288. item.target_location,
  2289. filament_overrides=filament_overrides,
  2290. require_plate_clear=require_plate_clear,
  2291. wakeable_ids=wakeable_printer_ids,
  2292. printer_scope=item_scope,
  2293. is_short=is_short,
  2294. drying_ids=drying_held,
  2295. unmatched_on=unmatched_on,
  2296. refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
  2297. sliced_nozzle=candidate.sliced_nozzle,
  2298. )
  2299. # "Only if the previous print succeeded" is about the
  2300. # printer the job lands on: one whose last print failed
  2301. # is passed over for another of the model.
  2302. if (
  2303. match_id
  2304. and item.require_previous_success
  2305. and not await self._check_previous_success(db, item, printer_id=match_id)
  2306. ):
  2307. gate_blocked.add(match_id)
  2308. continue
  2309. break
  2310. if match_id:
  2311. printer_id = match_id
  2312. chosen = candidate
  2313. break
  2314. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2315. # Nothing is available and nothing has been woken this pass:
  2316. # switch one matching printer on. Assignment is left to the
  2317. # next pass, which sees the booted printer's live state
  2318. # instead of guessing at it seconds after connect (#2786).
  2319. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2320. woken_id, attempted_id = await self._wake_printer_for_model(
  2321. db,
  2322. wakeable_candidates,
  2323. item.target_location,
  2324. busy_printers | interlocked.keys(),
  2325. wakeable_printer_ids,
  2326. require_plate_clear,
  2327. printer_scope=item_scope,
  2328. )
  2329. # An attempt spends the pass's one wake whether or not
  2330. # it worked: it has already blocked the queue loop for
  2331. # the boot wait. A failed printer is held out of later
  2332. # passes by its own cool-off, deliberately NOT by
  2333. # busy_printers — it is off, not busy, and labelling it
  2334. # busy would both misdescribe it in every later item's
  2335. # waiting reason and suppress the notification, since
  2336. # an all-busy reason is treated as needing no action.
  2337. power_on_attempted = attempted_id is not None
  2338. if woken_id is not None:
  2339. # Hold this item back rather than dispatching onto a
  2340. # printer whose AMS has not reported yet.
  2341. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2342. continue
  2343. if printer_id is None and gate_blocked:
  2344. # The matcher reports the printers passed over as busy;
  2345. # what holds the job is their failed last print.
  2346. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2347. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2348. # Fold the winning variant's file and settings onto the item
  2349. # before anything else looks at them — the guards below and
  2350. # every step of the dispatch read the item's own columns.
  2351. if chosen is not None:
  2352. self._resolve_variant(item, chosen)
  2353. # Update waiting_reason if changed and send notification when first waiting
  2354. if item.waiting_reason != waiting_reason:
  2355. was_waiting = item.waiting_reason is not None
  2356. previous_reason = item.waiting_reason
  2357. item.waiting_reason = waiting_reason
  2358. await db.commit()
  2359. # Send waiting notification only when transitioning to waiting state
  2360. # and the reason requires user action (not just "all printers busy")
  2361. # Also when a job that only waited for a busy printer
  2362. # now waits on something the user has to do.
  2363. if (
  2364. waiting_reason
  2365. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2366. and not _asks_nothing_new(waiting_reason)
  2367. ):
  2368. job_name = await self._get_job_name(db, item)
  2369. await notification_service.on_queue_job_waiting(
  2370. job_name=job_name,
  2371. target_model=_candidate_model_label(candidates) or item.target_model,
  2372. waiting_reason=waiting_reason,
  2373. db=db,
  2374. )
  2375. if printer_id:
  2376. # Before claiming the printer: hold back rather than race
  2377. # another dispatch over the same transient library row.
  2378. # Checked here so a held item does not get a printer
  2379. # assigned and then sit on it. See _library_row_conflict().
  2380. #
  2381. # No busy_printers.add() here, unlike the fixed-printer
  2382. # branch above: that one protects its printer's own queue
  2383. # ordering, but this item was never assigned to `printer_id`
  2384. # — the matcher merely offered it. Marking it busy would
  2385. # strand an idle printer for the rest of the pass.
  2386. if _library_row_conflict(item):
  2387. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2388. continue
  2389. if await _edited_since_loaded(db, item):
  2390. continue
  2391. # Assign printer and start - clear waiting reason
  2392. item.printer_id = printer_id
  2393. item.waiting_reason = None
  2394. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2395. # Send assignment notification
  2396. job_name = await self._get_job_name(db, item)
  2397. printer = await self._get_printer(db, printer_id)
  2398. await notification_service.on_queue_job_assigned(
  2399. job_name=job_name,
  2400. printer_id=printer_id,
  2401. printer_name=printer.name if printer else "Unknown",
  2402. target_model=item.target_model,
  2403. db=db,
  2404. )
  2405. # A mapping on this item was not made for the printer just
  2406. # picked: it came with a job moved here from a fixed
  2407. # printer, or from a variant. Its tray IDs can name a
  2408. # tray of the right type in another colour here, which
  2409. # the fit check lets through (#3239). Match afresh, by
  2410. # type and colour.
  2411. if item.ams_mapping:
  2412. logger.info(
  2413. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2414. item.id,
  2415. item.ams_mapping,
  2416. printer_id,
  2417. )
  2418. item.ams_mapping = None
  2419. # On a nozzle-rack printer its own nozzle mapping likewise
  2420. # (set through the API or an order's plate spec): it names
  2421. # rack positions, and the dispatch sends a stored one as-is
  2422. # instead of resolving this printer's rack. Elsewhere it
  2423. # holds extruder indices, the same on every printer of the
  2424. # model (an H2D VP keeps the slicer's for that reason), and
  2425. # one that came with the chosen variant belongs to that
  2426. # variant's file: both stay.
  2427. if (
  2428. (chosen is None or chosen.variant is None)
  2429. and printer is not None
  2430. and is_nozzle_rack_model(printer.model)
  2431. ):
  2432. item.nozzle_mapping = None
  2433. # Resolve the AMS mapping for the assigned printer. It is
  2434. # always missing here, so this computes it, and it also
  2435. # self-heals a bogus stored [-1] (#2589).
  2436. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2437. if unmappable:
  2438. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2439. continue
  2440. # Filament-deficit pre-dispatch check (#1496).
  2441. if await self._block_on_filament_deficit(db, item):
  2442. continue
  2443. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2444. # selection already filters on filament type, so this is a
  2445. # backstop for an AMS that changed between assignment and
  2446. # dispatch, and for a type loaded on the wrong nozzle.
  2447. # The assignment made above is released with the hold —
  2448. # this item asked for a model, not this printer.
  2449. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2450. continue
  2451. # As for a pinned job: drying stops once the print is
  2452. # decided, unless it may run through it.
  2453. if self._drying_in_progress.get(
  2454. printer_id
  2455. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2456. await self._stop_drying(printer_id)
  2457. _claim_library_row(item)
  2458. dispatch_ids.append(item.id)
  2459. claim_printer(printer_id)
  2460. # SJF starvation guard: mark items that were jumped
  2461. if sjf_enabled and item.print_time_seconds is not None:
  2462. for other in items:
  2463. if (
  2464. other.id != item.id
  2465. and other.id not in dispatch_ids
  2466. and other.status == "pending"
  2467. and _could_take_printer(other, printer_id, item.target_model)
  2468. and not other.been_jumped
  2469. and other.position < item.position
  2470. and (
  2471. other.print_time_seconds is None
  2472. or other.print_time_seconds > item.print_time_seconds
  2473. )
  2474. ):
  2475. other.been_jumped = True
  2476. await db.commit()
  2477. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2478. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2479. # skip summary that only lands after the transfers have finished is
  2480. # useless for working out why an item did not go out.
  2481. if skip_reasons:
  2482. logger.info("Queue skip summary: %s", skip_reasons)
  2483. for pid in sorted(busy_printers):
  2484. reason = busy_reasons.get(pid, "no reason recorded")
  2485. if pid in claimed_printers:
  2486. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2487. continue
  2488. # The three live fields stay, because they are what someone
  2489. # reading a bundle wants next -- but they are labelled as read
  2490. # now, not as the state the decision was made on, which is what
  2491. # made the old line contradict itself.
  2492. state = printer_manager.get_status(pid)
  2493. logger.info(
  2494. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2495. pid,
  2496. reason,
  2497. printer_manager.is_connected(pid),
  2498. state.state if state else "NO_STATUS",
  2499. printer_manager.is_awaiting_plate_clear(pid),
  2500. )
  2501. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2502. # selection and `_launch_uploads`, so anything raising here would
  2503. # discard this tick's selections — computed AMS mappings and all —
  2504. # and, on a persistent fault, stop the queue dispatching entirely.
  2505. # Same reasoning as the deficit check's guard below: never let an
  2506. # auxiliary check wedge the queue. The bed simply stays wherever it
  2507. # was, and the next tick tries again.
  2508. try:
  2509. await self._apply_keep_warm(
  2510. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2511. )
  2512. except Exception as e:
  2513. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2514. # Read the concurrency limit BEFORE the commit below, not inside
  2515. # _dispatch_selected(). A SELECT on this session after the commit
  2516. # implicitly opens a fresh transaction that nothing then closes, and
  2517. # it would stay open for the whole dispatch — minutes of "idle in
  2518. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2519. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2520. # checkpointed while every dispatch is writing to it.
  2521. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2522. # Selection is done; every decision above is recorded on `db`
  2523. # (model-based printer assignment, computed ams_mapping). Flush it
  2524. # before the dispatch tasks open their own sessions, or they will
  2525. # read a row that still says printer_id=None. This also releases the
  2526. # connection back to the pool for the duration of the dispatch.
  2527. await db.commit()
  2528. if dispatch_ids:
  2529. item_printers = {it.id: it.printer_id for it in items}
  2530. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2531. # Auto-drying: start drying on idle printers that have no pending queue items
  2532. await self._check_auto_drying(db, items, dispatching_printers)
  2533. # Low filament: alert on assigned spools that have crossed their
  2534. # low-stock threshold (#2913). Runs on both paths out of this method
  2535. # for the same reason auto-drying does — an empty queue does not mean
  2536. # the spools in the printers stopped mattering.
  2537. await self._check_filament_low(db)
  2538. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2539. # is about to run out before a replenishment could arrive (#2955).
  2540. await self._check_stock_forecast(db)
  2541. # Keep the loop on the fast interval while any upload is in flight so
  2542. # a slot freed mid-tick refills within seconds rather than after the
  2543. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2544. # deferred because the pool was full) also counts as productive.
  2545. return bool(dispatch_ids) or bool(self._inflight)
  2546. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2547. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2548. Dispatch used to happen inline in the selection loop: ``await
  2549. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2550. performs the FTP upload, that serialized every printer behind every
  2551. other printer's transfer even though the printers are independent
  2552. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2553. gather was awaited before ``check_queue`` returned, so the run loop
  2554. stayed blocked until the *slowest* upload in the batch finished — a
  2555. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2556. 93-printer farm even as other printers came free (#2602).
  2557. Each upload now runs as an independent background task tracked in
  2558. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2559. `pending` until their upload completes) and their printers from the
  2560. next pass's selection, and this method launches at most
  2561. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2562. the next fast tick instead of waiting out the whole batch. The bound
  2563. exists because the printers are independent but the host is not: each
  2564. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2565. file handle.
  2566. The no-overlapping-dispatch invariant the batch-await used to provide
  2567. is now carried by the in-flight exclusion in check_queue. Everything
  2568. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2569. per-printer hold, and each item's independent failure handling — still
  2570. lives in ``_start_print`` and runs per task exactly as before.
  2571. Synchronous on purpose: it registers every launched task into
  2572. ``self._inflight`` before returning, so the next (sequential) tick sees
  2573. an accurate in-flight count with no interleaving await.
  2574. """
  2575. free = limit - len(self._inflight)
  2576. if free <= 0:
  2577. logger.info(
  2578. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2579. len(self._inflight),
  2580. limit,
  2581. len(item_ids),
  2582. item_ids,
  2583. )
  2584. return
  2585. to_launch = item_ids[:free]
  2586. deferred = item_ids[free:]
  2587. logger.info(
  2588. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2589. len(to_launch),
  2590. len(self._inflight),
  2591. limit,
  2592. f" — deferring {deferred} to a later tick" if deferred else "",
  2593. )
  2594. for item_id in to_launch:
  2595. task = spawn_background_task(
  2596. self._dispatch_one(item_id, item_printers.get(item_id)),
  2597. name=f"queue-upload-{item_id}",
  2598. )
  2599. self._inflight[item_id] = (task, item_printers.get(item_id))
  2600. # Prune on completion so the freed slot is refillable next tick.
  2601. # spawn_background_task already logs any uncaught exception; this
  2602. # only reclaims the pool slot (fires on success, failure, or cancel).
  2603. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2604. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2605. """Upload + start one queue item in its own session (pool worker, #2602).
  2606. Its own session: pool workers run concurrently and an AsyncSession is
  2607. not safe to share across tasks; it also keeps a slow upload from pinning
  2608. the scheduler's session (and, on SQLite, its transaction) open for the
  2609. transfer's duration.
  2610. ``selected_printer_id`` is the printer this item was selected for, taken
  2611. from the same snapshot the caller used. It exists so the preheat pin can
  2612. be unwound on the paths that never reach the ``finally`` below — see the
  2613. claim failure a few lines down. Optional so the direct-call tests keep
  2614. working; when it is absent those paths simply behave as they did before.
  2615. """
  2616. async with async_session() as item_db:
  2617. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2618. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2619. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2620. # routes reject reassignment (409), so printer_id can't change out from
  2621. # under the in-flight upload and split the queue row from the
  2622. # archive/expected-print/physical command.
  2623. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2624. logger.info(
  2625. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2626. item_id,
  2627. )
  2628. # This return is outside the try/finally below, so the rollback
  2629. # has to happen here. Selecting this item already handed any
  2630. # keep-warm hold on its printer over to the preheat pin
  2631. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2632. # unwind it. Bailing without doing so leaves the bed hot with
  2633. # nothing tracking it: the keep-warm entry is gone, so the
  2634. # max-duration cap no longer applies, and if this was the
  2635. # printer's last pending item nothing else will ever turn it
  2636. # off. Reachable whenever a cancel or delete lands between
  2637. # selection and the claim.
  2638. if selected_printer_id is not None:
  2639. self._rollback_preheat_pin(item_id, selected_printer_id)
  2640. return
  2641. # Seeded from the caller's snapshot so the `item vanished` return
  2642. # below still unwinds the pin; overwritten with the row's own
  2643. # printer_id as soon as we have it.
  2644. item_printer_id: int | None = selected_printer_id
  2645. try:
  2646. item = await item_db.get(PrintQueueItem, item_id)
  2647. if not item:
  2648. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2649. return
  2650. item_printer_id = item.printer_id
  2651. await self._start_print(item_db, item)
  2652. finally:
  2653. # Undo an expected-print registration whose print command never
  2654. # went out. One choke point covers every way `_start_print` can
  2655. # end without sending: a raised exception (a DB failure mid-
  2656. # dispatch is the reported case), an early return, a cancel
  2657. # winning the #1853 CAS, or `start_print()` returning False.
  2658. # A confirmed send removes the entry itself, so this is a no-op
  2659. # on the happy path.
  2660. self._rollback_unconfirmed_expected_print(item_id)
  2661. # Likewise the print user it set: the printer's next print is
  2662. # not this item's.
  2663. self._rollback_unconfirmed_print_user(item_id)
  2664. # Its archive is no longer held for it (archive_work).
  2665. self._release_held_archive(item_id)
  2666. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2667. # reservation survives only after start_print() accepted the
  2668. # command. Failure, cancellation, deferral, and exceptions all
  2669. # release it here.
  2670. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2671. # Unwind preheat state (bed/chamber/airduct) if the
  2672. # dispatch aborted before the print's own gcode took over.
  2673. # `_start_print` clears the pin on successful `start_print()`;
  2674. # anything still present here is by definition an aborted
  2675. # dispatch and gets rolled back so the printer isn't left
  2676. # heating for a job that isn't happening.
  2677. if item_printer_id is not None:
  2678. self._rollback_preheat_pin(item_id, item_printer_id)
  2679. # The cancellation flag only has meaning while this dispatch is
  2680. # running; drop it so the set cannot grow without bound and a
  2681. # re-queued item never inherits a stale cancellation.
  2682. self._cancelled_dispatches.discard(item_id)
  2683. # Release the claim on every exit. Once dispatch has finished the
  2684. # row's status carries the lock (printing/failed/cancelled are all
  2685. # != pending), so the token is only needed for the duration of the
  2686. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2687. # dispatchable again on the next tick.
  2688. await self._clear_dispatch_claim(item_db, item_id)
  2689. async def _requeue_after_upload_refused(
  2690. self,
  2691. db: AsyncSession,
  2692. item: PrintQueueItem,
  2693. printer: Printer,
  2694. error_msg: str,
  2695. toast_uid: int | None,
  2696. kind: FtpFailureKind,
  2697. ) -> None:
  2698. """Put an item back in the queue after its file never reached the printer (#3210).
  2699. The printer goes into `_upload_backoff`, which keeps every item away
  2700. from it until the window ends. The window grows with each refusal in a
  2701. row; see ``_upload_backoff_seconds``.
  2702. An item pinned to this printer keeps it, waits there, and is the one
  2703. that knocks again. An item for "Any <model>" goes back to the pool
  2704. instead, so another printer of the model can take it (#3409). Only the
  2705. assignment goes: the next model assignment drops whatever on the row
  2706. was worked out for one printer, as it does for every model job.
  2707. The first refusal in a run sends the one "Job waiting" notification,
  2708. and a later one only if it asks for something else (a card after a
  2709. dropped connection). It cannot wait for the hold the way it used to: a
  2710. released item is not held on this printer, so nothing would say why
  2711. it stopped. A job cancelled or moved during the upload sends none.
  2712. `dispatch_attempts` is not charged: that budget bounds a printer that
  2713. takes the file and then never starts, which this is not.
  2714. """
  2715. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2716. self._upload_refusals[printer.id] = refusals
  2717. self._upload_refusal_kind[printer.id] = kind
  2718. backoff = _upload_backoff_seconds(refusals)
  2719. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2720. released = False
  2721. if item.target_model:
  2722. # Only while it is still pending on this printer: a cancel, or a
  2723. # move the user made during the upload, stands.
  2724. result = cast(
  2725. CursorResult,
  2726. await db.execute(
  2727. update(PrintQueueItem)
  2728. .where(PrintQueueItem.id == item.id)
  2729. .where(PrintQueueItem.status == "pending")
  2730. .where(PrintQueueItem.printer_id == printer.id)
  2731. .values(printer_id=None, error_message=None)
  2732. .execution_options(synchronize_session=False)
  2733. ),
  2734. )
  2735. await db.commit()
  2736. released = result.rowcount > 0
  2737. elif item.error_message:
  2738. # The row is still `pending` -- it only moves to `printing` after a
  2739. # successful upload -- so there is no status to write back. Writing
  2740. # one anyway would undo a cancel that landed during the upload.
  2741. item.error_message = None
  2742. await db.commit()
  2743. logger.warning(
  2744. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue%s; "
  2745. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2746. item.id,
  2747. printer.id,
  2748. printer.name,
  2749. error_msg,
  2750. " and returned to the pool" if released else "",
  2751. refusals,
  2752. backoff,
  2753. )
  2754. reason = _refused_upload_hold_reason(printer.name or f"printer {printer.id}", kind)
  2755. if self._upload_refusal_notified.get(printer.id) != reason and await self._still_waiting_on(
  2756. db, item.id, None if released else printer.id
  2757. ):
  2758. self._upload_refusal_notified[printer.id] = reason
  2759. try:
  2760. await notification_service.on_queue_job_waiting(
  2761. job_name=await self._get_job_name(db, item),
  2762. target_model=item.target_model or printer.model or "",
  2763. waiting_reason=reason,
  2764. db=db,
  2765. printer_id=printer.id,
  2766. )
  2767. except Exception as e:
  2768. # The job is safe in the queue either way.
  2769. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  2770. try:
  2771. # Closes the dispatch toast for this attempt. Without it the toast
  2772. # keeps spinning on an upload that has ended.
  2773. await ws_manager.send_queue_item_failed(
  2774. user_id=toast_uid,
  2775. queue_item_id=item.id,
  2776. printer_id=printer.id,
  2777. reason="upload_failed",
  2778. )
  2779. except Exception:
  2780. pass # toast is best-effort
  2781. @staticmethod
  2782. async def _still_waiting_on(db: AsyncSession, item_id: int, printer_id: int | None) -> bool:
  2783. """Whether the item is still pending, on *printer_id* (None: unassigned)."""
  2784. row = (
  2785. await db.execute(
  2786. select(PrintQueueItem.status, PrintQueueItem.printer_id).where(PrintQueueItem.id == item_id)
  2787. )
  2788. ).one_or_none()
  2789. return row is not None and row.status == "pending" and row.printer_id == printer_id
  2790. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2791. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2792. if printer_id is not None:
  2793. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2794. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2795. """Withdraw the expected print and print user of a sent print that never started.
  2796. Both tell the rest of Bambuddy that the printer's next print is this
  2797. item's: left behind, a print started by hand later is taken for it.
  2798. With ``unless_printing``, a printer that is printing after all keeps
  2799. them, as that print is most likely this one starting late.
  2800. ``keep_expected`` withdraws only the print user, which vouches for any
  2801. print on the printer. The expected print names this item's file, so a
  2802. late start of it is still matched to its archive.
  2803. """
  2804. sent = self._sent_unstarted_print.get(item_id)
  2805. if sent is None:
  2806. return
  2807. printer_id, remote_filename, archive_id = sent
  2808. if unless_printing:
  2809. status = printer_manager.get_status(printer_id)
  2810. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2811. return
  2812. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2813. if keep_expected:
  2814. return
  2815. del self._sent_unstarted_print[item_id]
  2816. if remote_filename is not None and archive_id is not None:
  2817. try:
  2818. from backend.app.main import unregister_expected_print
  2819. unregister_expected_print(printer_id, remote_filename, archive_id)
  2820. except Exception:
  2821. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2822. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2823. """Drop an expectation for a print command that was never sent.
  2824. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2825. where the interesting exception is usually the one already propagating.
  2826. """
  2827. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2828. if pending is None:
  2829. return
  2830. printer_id, remote_filename, archive_id = pending
  2831. try:
  2832. from backend.app.main import unregister_expected_print
  2833. unregister_expected_print(printer_id, remote_filename, archive_id)
  2834. except Exception:
  2835. logger.warning(
  2836. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2837. item_id,
  2838. printer_id,
  2839. remote_filename,
  2840. archive_id,
  2841. exc_info=True,
  2842. )
  2843. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2844. """Release a queue reservation without touching the dispatch session."""
  2845. if item_id not in self._unconfirmed_budget_reservations:
  2846. return
  2847. for attempt in range(1, 4):
  2848. async with async_session() as cleanup_db:
  2849. try:
  2850. await release_budget_reservation(
  2851. cleanup_db,
  2852. source_type="print_queue",
  2853. source_id=item_id,
  2854. status="released",
  2855. )
  2856. await cleanup_db.commit()
  2857. self._unconfirmed_budget_reservations.discard(item_id)
  2858. return
  2859. except Exception as exc:
  2860. try:
  2861. await cleanup_db.rollback()
  2862. except Exception:
  2863. pass
  2864. if attempt == 3:
  2865. logger.error(
  2866. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2867. item_id,
  2868. attempt,
  2869. exc,
  2870. )
  2871. return
  2872. await asyncio.sleep(0.5 * attempt)
  2873. @staticmethod
  2874. def _reported_bed_target(printer_id: int) -> int | None:
  2875. """The bed target firmware currently reports, or None if it can't be read.
  2876. None means "no evidence", not "zero" — callers must not treat it as a
  2877. temperature. Deliberately total: this feeds cleanup paths that run in a
  2878. ``finally``, where a malformed status must not become the exception the
  2879. caller sees.
  2880. """
  2881. try:
  2882. state = printer_manager.get_status(printer_id)
  2883. if state is None:
  2884. return None
  2885. temps = state.temperatures
  2886. if not isinstance(temps, dict):
  2887. return None
  2888. return int(float(temps.get("bed_target", 0) or 0))
  2889. except (TypeError, ValueError, AttributeError):
  2890. return None
  2891. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2892. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2893. Turns the bed heater off, the chamber heater off, and opens the
  2894. airduct flap back to cooling — for whichever of those preheat
  2895. actually applied. `_start_print` clears the pin on successful
  2896. `start_print()`; anything still present when `_dispatch_one` exits
  2897. is by definition an aborted dispatch and gets rolled back here.
  2898. The bed is the one action that can be declined: if firmware has since
  2899. been given a target other than the one we pinned, it belongs to someone
  2900. else and is left alone. See the comment at that branch.
  2901. Also called directly from `_dispatch_one`'s claim-failure return, which
  2902. never reaches the ``finally``.
  2903. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2904. """
  2905. pin = self._preheat_pin.pop(printer_id, set())
  2906. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2907. if not pin:
  2908. return
  2909. client = printer_manager.get_client(printer_id)
  2910. if client is None:
  2911. logger.info(
  2912. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2913. item_id,
  2914. printer_id,
  2915. )
  2916. return
  2917. if "bed" in pin:
  2918. # Only undo our own target. If firmware reports something else, the
  2919. # user or another writer owns the bed now and zeroing it would
  2920. # clobber their choice -- the same guard `_release_keep_warm`
  2921. # applies to a keep-warm hold.
  2922. #
  2923. # Every uncertain case switches the bed off rather than leaving it:
  2924. # no recorded target (a pin written before this bookkeeping, or a
  2925. # setter that raised after pinning) and an unreadable status both
  2926. # fall through. A bed left hot with no owner is the worse failure,
  2927. # and this runs in a `finally` where raising would mask the real
  2928. # exception.
  2929. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2930. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2931. logger.info(
  2932. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2933. item_id,
  2934. printer_id,
  2935. cur_bed_target,
  2936. pinned_bed,
  2937. )
  2938. else:
  2939. try:
  2940. client.set_bed_temperature(0)
  2941. except Exception as exc:
  2942. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2943. if "chamber" in pin:
  2944. try:
  2945. client.set_chamber_temperature(0)
  2946. except Exception as exc:
  2947. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2948. if "airduct" in pin:
  2949. try:
  2950. client.set_airduct_mode("cooling")
  2951. except Exception as exc:
  2952. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2953. logger.info(
  2954. "Dispatch item %s (printer %d): preheat rollback → %s",
  2955. item_id,
  2956. printer_id,
  2957. sorted(pin),
  2958. )
  2959. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2960. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2961. Returns True if this call won the claim, False if the row was already
  2962. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2963. the load-bearing guard against reassign-during-dispatch (#2615).
  2964. ``printer_id`` is the printer the item was selected for: a row moved to
  2965. another printer since is not claimed, and the next pass selects it for
  2966. that one."""
  2967. query = (
  2968. update(PrintQueueItem)
  2969. .where(PrintQueueItem.id == item_id)
  2970. .where(PrintQueueItem.status == "pending")
  2971. .where(PrintQueueItem.dispatching_at.is_(None))
  2972. )
  2973. if printer_id is not None:
  2974. query = query.where(PrintQueueItem.printer_id == printer_id)
  2975. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2976. await db.commit()
  2977. return res.rowcount > 0
  2978. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2979. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2980. mask the dispatch outcome.
  2981. Retried, because the failure mode in practice is transient and narrow: a
  2982. database that is momentarily unreachable — PostgreSQL out of connection
  2983. slots is the observed case — refuses this write for a second or two while
  2984. the dispatch that just ended is still holding the row out of the selection
  2985. query. One attempt was enough to wedge the item; a couple of spaced
  2986. attempts clear it. Each attempt rolls back first, since a failed write
  2987. leaves the session needing it before it can be reused.
  2988. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2989. on the next quiet tick.
  2990. """
  2991. for attempt in range(1, 4):
  2992. try:
  2993. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2994. await db.commit()
  2995. return
  2996. except Exception as exc:
  2997. try:
  2998. await db.rollback()
  2999. except Exception:
  3000. pass
  3001. if attempt == 3:
  3002. logger.warning(
  3003. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  3004. "— a later quiet tick will release it",
  3005. item_id,
  3006. attempt,
  3007. exc,
  3008. )
  3009. return
  3010. await asyncio.sleep(0.5 * attempt)
  3011. async def _printers_for_model(
  3012. self,
  3013. db: AsyncSession,
  3014. model: str,
  3015. target_location: str | None = None,
  3016. printer_scope: PrinterScope = ALL_PRINTERS,
  3017. ) -> list[Printer]:
  3018. """Active printers of *model*, optionally narrowed to one location.
  3019. Shared by the matcher and by the smart-plug wake step (#2786) so both
  3020. answer "which printers can this job run on" from one query — a job can
  3021. only be woken onto a printer the matcher would also have considered.
  3022. ``printer_scope`` is the job creator's (#1727).
  3023. In the order of Settings > Queue > printer order (#2915), fewest print
  3024. hours first by default (#3480): both take the first printer that
  3025. fits, so an "Any" job goes to the least worn machine and a farm's jobs
  3026. spread by wear instead of all landing on the lowest id. The hours are
  3027. the maintenance counter's (runtime plus the baseline offset), which
  3028. counts every print, wherever it was started. Ties (printers still at
  3029. zero) go by id, so the order is stable.
  3030. """
  3031. normalized_model = normalize_printer_model(model) or model
  3032. query = (
  3033. select(Printer)
  3034. .where(func.lower(Printer.model) == normalized_model.lower())
  3035. .where(Printer.is_active == True) # noqa: E712
  3036. )
  3037. if target_location:
  3038. query = query.where(Printer.location == target_location)
  3039. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  3040. query = query.where(clause)
  3041. result = await db.execute(query)
  3042. printers = list(result.scalars().all())
  3043. order = await self._get_model_dispatch_order(db)
  3044. last_finished: dict[int, datetime] | None = None
  3045. if order == "least_recently_used" and printers:
  3046. last_finished = await self._last_finished_by_printer(db, [p.id for p in printers])
  3047. return _order_printers(printers, order, last_finished)
  3048. async def _get_model_dispatch_order(self, db: AsyncSession) -> str:
  3049. """The order setting (#2915); anything unknown reads as the default."""
  3050. result = await db.execute(select(Settings).where(Settings.key == "model_dispatch_order"))
  3051. setting = result.scalar_one_or_none()
  3052. value = (setting.value if setting else "") or ""
  3053. return value if value in ("most_hours", "least_recently_used", "priority") else "fewest_hours"
  3054. async def _last_finished_by_printer(self, db: AsyncSession, printer_ids: list[int]) -> dict[int, datetime]:
  3055. """When each printer last finished a print, from the Print Log; none for one that never has."""
  3056. from backend.app.models.print_log import PrintLogEntry
  3057. result = await db.execute(
  3058. select(PrintLogEntry.printer_id, func.max(PrintLogEntry.completed_at))
  3059. .where(PrintLogEntry.printer_id.in_(printer_ids), PrintLogEntry.completed_at.is_not(None))
  3060. .group_by(PrintLogEntry.printer_id)
  3061. )
  3062. return {
  3063. printer_id: finished
  3064. for printer_id, finished in result.all()
  3065. if printer_id is not None and finished is not None
  3066. }
  3067. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  3068. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  3069. Read once per queue check rather than per printer: it decides both
  3070. whether the wake step has anything to do and how an offline printer is
  3071. worded in the waiting reason — "Offline" and "offline with no Auto On
  3072. plug" are different problems, and the second is the one the user has to
  3073. fix themselves (#2786).
  3074. """
  3075. result = await db.execute(
  3076. select(SmartPlug.printer_id)
  3077. .where(SmartPlug.printer_id.is_not(None))
  3078. .where(SmartPlug.enabled == True) # noqa: E712
  3079. .where(SmartPlug.auto_on == True) # noqa: E712
  3080. )
  3081. return {pid for (pid,) in result.all() if pid is not None}
  3082. def _wake_recently_failed(self, printer_id: int) -> bool:
  3083. """True while this printer's failed power-on is still cooling off (#2786)."""
  3084. deadline = self._wake_failures.get(printer_id)
  3085. if deadline is None:
  3086. return False
  3087. if time.monotonic() >= deadline:
  3088. del self._wake_failures[printer_id]
  3089. return False
  3090. return True
  3091. async def _wake_printer_for_model(
  3092. self,
  3093. db: AsyncSession,
  3094. candidates: list[_ModelCandidate],
  3095. target_location: str | None,
  3096. exclude_ids: set[int],
  3097. wakeable_ids: set[int],
  3098. require_plate_clear: bool,
  3099. printer_scope: PrinterScope = ALL_PRINTERS,
  3100. ) -> tuple[int | None, int | None]:
  3101. """Power on one offline printer a model-based item could run on (#2786).
  3102. The fixed-printer branch has powered a printer on since smart plugs
  3103. existed. The model-based branch never could: its matcher drops an
  3104. offline printer into the "Offline:" waiting reason and nothing looks at
  3105. its plugs, so a class-targeted job with every matching printer switched
  3106. off sat pending forever. The reporter's log is the controlled
  3107. experiment — the same item, same plug, same Auto On setting, dispatched
  3108. the moment they edited it onto a specific printer.
  3109. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  3110. power-on was actually tried, so the caller can tell "nothing here was
  3111. wakeable" (both None — cheap, other items may still find something)
  3112. from "we tried and it did not come up" (only ``attempted_id`` — the
  3113. boot timeout has already been spent).
  3114. A printer whose last known trays cannot satisfy the job is passed over
  3115. rather than woken (#2876): the colours are readable while it is off, so
  3116. switching a farm on one machine at a time to discover them wakes
  3117. printers that could never have taken the job.
  3118. A printer whose last known nozzle cannot print the file is passed over
  3119. the same way (#3536).
  3120. Deliberately does NOT go on to match the job once a printer is up: AMS
  3121. trays arrive with the first status push after connect, so a filament
  3122. check against a printer that booted seconds ago can reject the printer
  3123. we just woke. The next queue pass matches it with live state.
  3124. At most one printer per pass. Each wake blocks the queue loop for the
  3125. boot wait, and a queue of ten class-targeted jobs must not switch on
  3126. ten printers inside one check.
  3127. """
  3128. for candidate in candidates:
  3129. if not candidate.target_model:
  3130. continue
  3131. required_types, filament_overrides = _filament_constraints(candidate)
  3132. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  3133. # Fewest print hours first, as the matcher picks (#3480).
  3134. for printer in printers:
  3135. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  3136. continue
  3137. if printer_manager.is_connected(printer.id):
  3138. continue
  3139. if self._wake_recently_failed(printer.id):
  3140. # Its plug did not bring it back a moment ago. Move on to a
  3141. # sibling instead of spending this pass — and every pass —
  3142. # on the same printer.
  3143. continue
  3144. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  3145. # Waking this one buys nothing: it would boot into IDLE and
  3146. # then be held by the plate-clear gate, which is exactly
  3147. # what the reporter's log shows happening for 80 minutes
  3148. # after a fixed-printer wake. The flag is Bambuddy-side and
  3149. # persisted, so it is readable while the printer is off.
  3150. logger.info(
  3151. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  3152. printer.id,
  3153. candidate.target_model,
  3154. )
  3155. continue
  3156. # #3536: the matcher rejects a printer whose nozzle cannot print
  3157. # the file, so waking one only spends this pass's single wake and
  3158. # the boot wait. A powered-off printer keeps its last status, so
  3159. # the nozzle is readable here. Fail-safe: no status or no reported
  3160. # nozzle means "fits" (None) and the printer is woken as before.
  3161. label = _wrong_nozzle_label(
  3162. printer.name, printer_manager.get_status(printer.id), candidate.sliced_nozzle
  3163. )
  3164. if label:
  3165. logger.info(
  3166. "Not powering on printer %s for a %s job: its nozzle cannot print the file (%s)",
  3167. printer.id,
  3168. candidate.target_model,
  3169. label,
  3170. )
  3171. continue
  3172. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  3173. if shortfall:
  3174. logger.info(
  3175. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  3176. printer.id,
  3177. candidate.target_model,
  3178. ", ".join(shortfall),
  3179. )
  3180. continue
  3181. plugs = await self._get_smart_plugs(db, printer.id)
  3182. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  3183. if not auto_on_plugs:
  3184. # wakeable_ids said otherwise — the plug changed under us
  3185. # mid-pass. Nothing to do but move on.
  3186. continue
  3187. logger.info(
  3188. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  3189. candidate.target_model,
  3190. printer.id,
  3191. )
  3192. primary_plug = self._pick_power_plug(auto_on_plugs)
  3193. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  3194. logger.warning(
  3195. "Could not power on printer %s via smart plug; not trying it again for %ss",
  3196. printer.id,
  3197. self._wake_failure_cooloff,
  3198. )
  3199. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  3200. return None, printer.id
  3201. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  3202. try:
  3203. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  3204. if await service.turn_on(extra_plug):
  3205. await publish_plug_state(
  3206. extra_plug.id,
  3207. extra_plug.name,
  3208. extra_plug.printer_id,
  3209. on=True,
  3210. ha_entity_id=extra_plug.ha_entity_id,
  3211. )
  3212. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  3213. except Exception as e:
  3214. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  3215. return printer.id, printer.id
  3216. return None, None
  3217. async def _find_idle_printer_for_model(
  3218. self,
  3219. db: AsyncSession,
  3220. model: str,
  3221. exclude_ids: set[int],
  3222. required_filament_types: list[str] | None = None,
  3223. target_location: str | None = None,
  3224. filament_overrides: list[dict] | None = None,
  3225. require_plate_clear: bool = True,
  3226. wakeable_ids: set[int] | None = None,
  3227. printer_scope: PrinterScope = ALL_PRINTERS,
  3228. is_short: Callable[[int], Awaitable[bool]] | None = None,
  3229. drying_ids: set[int] | None = None,
  3230. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  3231. refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
  3232. sliced_nozzle: float | None = None,
  3233. ) -> tuple[int | None, str | None]:
  3234. """Find an idle, connected printer matching the model with compatible filaments.
  3235. Args:
  3236. db: Database session
  3237. model: Printer model to match (e.g., "X1C", "P1S")
  3238. exclude_ids: Printer IDs to exclude (already busy)
  3239. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  3240. If provided, only printers with all required types loaded will match.
  3241. target_location: Optional location filter. If provided, only printers in this location are considered.
  3242. filament_overrides: Optional list of override dicts. Each entry may include
  3243. ``force_color_match: true`` to require an exact type+color match
  3244. on the printer for that slot. Without the flag the existing
  3245. colour-preference logic applies.
  3246. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  3247. offline printer is worded: one Bambuddy will switch on reads
  3248. differently from one the user has to go and switch on themselves.
  3249. is_short: Says whether a printer's spools are too light for the job (#3137).
  3250. A printer it flags is passed over while another eligible one
  3251. is not. When every eligible printer is short, the first is
  3252. returned all the same, so the deficit gate holds the job there
  3253. and "Print Anyway" still has a printer to print on.
  3254. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  3255. in the reason, as a pinned job's wait is.
  3256. unmatched_on: Names the filaments the slot matcher would leave without a
  3257. tray on a printer (#3280). A printer it names any for is
  3258. passed over like one missing a filament type: the checks
  3259. above only ask whether each type and forced colour is
  3260. loaded somewhere, not on the right nozzle or once per slot.
  3261. refused_uploads: Excluded printers out of dispatch after a refused upload,
  3262. with why (#3409). Each is named with the reason its own
  3263. queue rows show, not as "Busy".
  3264. sliced_nozzle: Nozzle diameter the file was sliced for (#3536). A printer
  3265. without that nozzle is passed over; None (unknown) passes
  3266. every printer, as before.
  3267. Returns:
  3268. Tuple of (printer_id, waiting_reason):
  3269. - (printer_id, None) if a matching printer was found
  3270. - (None, reason) if no printer is available, with explanation
  3271. """
  3272. normalized_model = normalize_printer_model(model) or model
  3273. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  3274. location_suffix = f" in {target_location}" if target_location else ""
  3275. if not printers:
  3276. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3277. # Separate force-matched overrides from preference-only overrides
  3278. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3279. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3280. # Track reasons for skipping printers
  3281. printers_busy = []
  3282. # Printers out of dispatch after a refused upload, worded as the
  3283. # printer's own queue rows word it: "Busy" would read as printing (#3409).
  3284. printers_refused: list[str] = []
  3285. printers_offline = []
  3286. printers_offline_no_plug = []
  3287. printers_missing_filament: list[tuple[str, list[str]]] = []
  3288. printers_wrong_nozzle: list[str] = []
  3289. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3290. # The first eligible printer that is short on filament, kept in case
  3291. # every eligible printer is (#3137).
  3292. short_fallback: int | None = None
  3293. for printer in printers:
  3294. # #3536: the pick ignored the nozzle, so a job sliced for 0.6 mm went to a
  3295. # 0.4 mm printer and the #1899 guard then failed it in _start_print instead
  3296. # of trying another printer. Fail-safe: no diameter or no reported nozzle
  3297. # fits (_wrong_nozzle_label returns None). Checked first on purpose: a
  3298. # wrong-nozzle printer that is busy, excluded or offline must not read as
  3299. # "Busy"/"Offline", which would hold the job silently forever.
  3300. wrong_nozzle = _wrong_nozzle_label(printer.name, printer_manager.get_status(printer.id), sliced_nozzle)
  3301. if wrong_nozzle:
  3302. printers_wrong_nozzle.append(wrong_nozzle)
  3303. continue
  3304. if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
  3305. printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
  3306. continue
  3307. if printer.id in exclude_ids:
  3308. # Printer is already claimed by another job in this scheduling run.
  3309. # For force-color jobs, still check if the color would match — if not,
  3310. # report it as a color mismatch rather than plain "Busy" so the user
  3311. # knows the job needs a filament change, not just to wait for availability.
  3312. if force_overrides and not pref_overrides:
  3313. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3314. if missing_colors:
  3315. printers_missing_filament.append((printer.name, missing_colors))
  3316. continue
  3317. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3318. continue
  3319. is_connected = printer_manager.is_connected(printer.id)
  3320. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3321. if not is_connected:
  3322. # An offline printer whose last known filament cannot run this
  3323. # job is reported as needing filament rather than as offline
  3324. # (#2876). It is also the printer the smart-plug step will now
  3325. # decline to switch on, and "Offline:" on its own would leave
  3326. # that decision looking like nothing happening at all.
  3327. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3328. if shortfall:
  3329. printers_missing_filament.append((printer.name, shortfall))
  3330. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3331. printers_offline_no_plug.append(printer.name)
  3332. else:
  3333. printers_offline.append(printer.name)
  3334. continue
  3335. if not is_idle:
  3336. # Printer is currently printing. For force-color jobs, check whether the
  3337. # loaded color would satisfy the requirement — if not, surface it as a
  3338. # color-mismatch reason rather than plain "Busy" so the user understands
  3339. # that the job is waiting for a filament change, not just printer availability.
  3340. if force_overrides and not pref_overrides:
  3341. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3342. if missing_colors:
  3343. printers_missing_filament.append((printer.name, missing_colors))
  3344. logger.debug(
  3345. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3346. printer.id,
  3347. printer.name,
  3348. missing_colors,
  3349. )
  3350. continue
  3351. printers_busy.append(printer.name)
  3352. continue
  3353. # Validate filament compatibility if required types are specified
  3354. if required_filament_types:
  3355. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3356. if missing:
  3357. # When force_overrides are present, enrich missing entries with color info
  3358. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3359. if force_overrides:
  3360. force_color_map = {
  3361. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3362. for o in force_overrides
  3363. }
  3364. missing_enriched = [
  3365. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3366. for t in missing
  3367. ]
  3368. printers_missing_filament.append((printer.name, missing_enriched))
  3369. else:
  3370. printers_missing_filament.append((printer.name, missing))
  3371. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3372. continue
  3373. # Force color match: ALL flagged slots must have an exact type+color match
  3374. if force_overrides:
  3375. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3376. if missing_colors:
  3377. printers_missing_filament.append((printer.name, missing_colors))
  3378. logger.debug(
  3379. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3380. printer.id,
  3381. printer.name,
  3382. missing_colors,
  3383. )
  3384. continue
  3385. # The matcher has the last word: a printer it cannot map would be
  3386. # held and given back, then chosen again on the next pass (#3280).
  3387. if unmatched_on is not None:
  3388. unmatched = await unmatched_on(printer.id)
  3389. if unmatched:
  3390. printers_missing_filament.append((printer.name, unmatched))
  3391. logger.debug(
  3392. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3393. printer.id,
  3394. printer.name,
  3395. unmatched,
  3396. )
  3397. continue
  3398. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3399. if pref_overrides:
  3400. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3401. if color_matches > 0:
  3402. candidates.append((printer.id, color_matches))
  3403. else:
  3404. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3405. printers_missing_filament.append((printer.name, override_colors))
  3406. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3407. continue
  3408. else:
  3409. # The first eligible printer wins, which is the one with the
  3410. # fewest print hours (#3480, see _printers_for_model), unless
  3411. # its spools are too light for the job (#3137).
  3412. if is_short is not None and await is_short(printer.id):
  3413. if short_fallback is None:
  3414. short_fallback = printer.id
  3415. logger.info(
  3416. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3417. printer.id,
  3418. printer.name,
  3419. )
  3420. continue
  3421. return printer.id, None
  3422. # If we have candidates from preference override matching, pick the one with most color matches.
  3423. # The sort is stable: among equal matches the fewest print hours still go first (#3480).
  3424. if candidates:
  3425. candidates.sort(key=lambda c: c[1], reverse=True)
  3426. if is_short is not None:
  3427. for candidate_id, _ in candidates:
  3428. if not await is_short(candidate_id):
  3429. return candidate_id, None
  3430. logger.info(
  3431. "Model-based assignment: passing over printer %s, not enough filament",
  3432. candidate_id,
  3433. )
  3434. return candidates[0][0], None
  3435. if short_fallback is not None:
  3436. return short_fallback, None
  3437. # #3536: nothing else is in the way, so the nozzle is the whole reason. Named
  3438. # per printer; when something else also waits, the wrong ones stay out so
  3439. # that reason (e.g. "Busy") is not drowned by a printer that cannot help.
  3440. if printers_wrong_nozzle and not (
  3441. printers_busy
  3442. or printers_refused
  3443. or printers_offline
  3444. or printers_offline_no_plug
  3445. or printers_missing_filament
  3446. ):
  3447. return None, (
  3448. f"No {normalized_model}{location_suffix} has a {sliced_nozzle:g}mm nozzle: "
  3449. f"{', '.join(printers_wrong_nozzle)}"
  3450. )
  3451. # Build waiting reason from what we found
  3452. reasons = []
  3453. if printers_missing_filament:
  3454. # Filament/color mismatch is most actionable - show first
  3455. if force_overrides and not pref_overrides:
  3456. # All mismatches are force-color failures — use descriptive message only;
  3457. # but only if there are no busy printers that DO have the matching color.
  3458. # If a printer has the right color but is busy, surface "Busy" instead so
  3459. # the user knows the job will start automatically once that printer is free.
  3460. # Same for a printer that is merely offline: Bambuddy switches that one on
  3461. # by itself, so the job is not actually waiting on anybody to change a
  3462. # spool (#2876 — offline printers reach this list now that a switched-off
  3463. # printer's own filament is read).
  3464. if not printers_busy and not printers_offline and not printers_refused:
  3465. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3466. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3467. # else: fall through — the self-resolving entries are appended below
  3468. else:
  3469. names_and_missing = [
  3470. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3471. ]
  3472. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3473. reasons.extend(printers_refused)
  3474. if printers_busy:
  3475. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3476. if printers_offline:
  3477. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3478. if printers_offline_no_plug:
  3479. # Named separately because it is the one entry on this list the
  3480. # user has to act on: no enabled Auto On plug means Bambuddy will
  3481. # never power this printer on for the queue (#2786).
  3482. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3483. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3484. @staticmethod
  3485. def _is_busy_only(waiting_reason: str) -> bool:
  3486. """Check if the waiting reason only contains 'Busy' entries.
  3487. When all matching printers are simply busy printing, the queued job
  3488. will start automatically once a printer finishes — no user action
  3489. is required, so we skip the notification.
  3490. """
  3491. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3492. return all(p.startswith("Busy:") for p in parts)
  3493. def _get_missing_force_color_slots(
  3494. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3495. ) -> list[str]:
  3496. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3497. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3498. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3499. with an exact type+color match.
  3500. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3501. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3502. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3503. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3504. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3505. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3506. setups are unaffected.
  3507. Returns:
  3508. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3509. """
  3510. if raw_data is None:
  3511. status = printer_manager.get_status(printer_id)
  3512. if not status:
  3513. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3514. raw_data = status.raw_data
  3515. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3516. loaded: list[tuple[str, str, str]] = []
  3517. for ams_unit in raw_data.get("ams", []):
  3518. for tray in ams_unit.get("tray", []):
  3519. tray_type = tray.get("tray_type")
  3520. if tray_type:
  3521. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3522. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3523. for vt in raw_data.get("vt_tray") or []:
  3524. vt_type = vt.get("tray_type")
  3525. if vt_type:
  3526. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3527. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3528. # One spool per slot, the way the matcher assigns them: two slots asking
  3529. # for the same filament need two spools of it (#3280). Slots naming a
  3530. # variant go first and take that variant before a spool naming none, so
  3531. # a slot open to any variant cannot use up the one a later slot needs.
  3532. missing = []
  3533. taken: set[int] = set()
  3534. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3535. o_type = canonical_filament_type(o.get("type") or "")
  3536. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3537. o_idx = o.get("tray_info_idx") or ""
  3538. fits = [
  3539. i
  3540. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3541. if i not in taken
  3542. and t_type == o_type
  3543. and t_color == o_color
  3544. and (not o_idx or not t_idx or o_idx == t_idx)
  3545. ]
  3546. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3547. if pick is not None:
  3548. taken.add(pick)
  3549. else:
  3550. color_label = o.get("color_name") or o.get("color", "?")
  3551. missing.append(f"{o_type} ({color_label})")
  3552. return missing
  3553. def _get_missing_filament_types(
  3554. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3555. ) -> list[str]:
  3556. """Get the list of required filament types that are not loaded on the printer.
  3557. Args:
  3558. printer_id: The printer ID
  3559. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3560. Returns:
  3561. List of missing filament types (empty if all are loaded)
  3562. """
  3563. if raw_data is None:
  3564. status = printer_manager.get_status(printer_id)
  3565. if not status:
  3566. return required_types # Can't determine, assume all missing
  3567. raw_data = status.raw_data
  3568. # Collect all filament types loaded on this printer (AMS units + external spool)
  3569. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3570. loaded_types: set[str] = set()
  3571. # Check AMS units (stored in raw_data["ams"])
  3572. ams_data = raw_data.get("ams", [])
  3573. if ams_data:
  3574. for ams_unit in ams_data:
  3575. for tray in ams_unit.get("tray", []):
  3576. tray_type = tray.get("tray_type")
  3577. if tray_type:
  3578. loaded_types.add(canonical_filament_type(tray_type))
  3579. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3580. for vt in raw_data.get("vt_tray") or []:
  3581. vt_type = vt.get("tray_type")
  3582. if vt_type:
  3583. loaded_types.add(canonical_filament_type(vt_type))
  3584. # Find which required types are missing (using canonical type for equivalence)
  3585. missing = []
  3586. for req_type in required_types:
  3587. if canonical_filament_type(req_type) not in loaded_types:
  3588. missing.append(req_type)
  3589. return missing
  3590. def _count_override_color_matches(
  3591. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3592. ) -> int:
  3593. """Count how many filament overrides have an exact color match on the printer.
  3594. Used to prefer printers that already have the desired override colors loaded.
  3595. """
  3596. if raw_data is None:
  3597. status = printer_manager.get_status(printer_id)
  3598. if not status:
  3599. return 0
  3600. raw_data = status.raw_data
  3601. # Collect loaded filaments' type+color pairs
  3602. loaded: set[tuple[str, str]] = set()
  3603. for ams_unit in raw_data.get("ams", []):
  3604. for tray in ams_unit.get("tray", []):
  3605. tray_type = tray.get("tray_type")
  3606. # `or ""`, not a dict default: a slot can carry the key with a
  3607. # null value, and this now runs against switched-off printers
  3608. # too, where nobody is watching for the AttributeError.
  3609. tray_color = tray.get("tray_color") or ""
  3610. if tray_type:
  3611. color_norm = tray_color.replace("#", "").lower()[:6]
  3612. loaded.add((canonical_filament_type(tray_type), color_norm))
  3613. for vt in raw_data.get("vt_tray") or []:
  3614. vt_type = vt.get("tray_type")
  3615. if vt_type:
  3616. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3617. loaded.add((canonical_filament_type(vt_type), color_norm))
  3618. # Types compared as the type check compares them: a PA12-CF override
  3619. # is met by PA-CF in its colour.
  3620. matches = 0
  3621. for o in overrides:
  3622. o_type = canonical_filament_type(o.get("type") or "")
  3623. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3624. if (o_type, o_color) in loaded:
  3625. matches += 1
  3626. return matches
  3627. @staticmethod
  3628. def _tray_reading(printer_id: int) -> dict:
  3629. """The best tray reading available for a printer that is not printing.
  3630. Live status first: a printer keeps its last status after the power
  3631. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3632. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3633. for when the client itself has been dropped and taken its status with
  3634. it — which is what every power-on attempt does.
  3635. An empty result means "we have never heard", not "nothing is loaded":
  3636. the two are indistinguishable from here, and only the second would be
  3637. safe to act on.
  3638. """
  3639. status = printer_manager.get_status(printer_id)
  3640. raw = (status.raw_data if status else None) or {}
  3641. for ams_unit in raw.get("ams") or []:
  3642. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3643. return raw
  3644. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3645. return raw
  3646. return printer_manager.last_known_trays(printer_id)
  3647. def _cached_filament_shortfall(
  3648. self,
  3649. printer_id: int,
  3650. required_types: list[str] | None,
  3651. filament_overrides: list[dict] | None,
  3652. ) -> list[str]:
  3653. """What a switched-off printer's last known filament cannot provide (#2876).
  3654. The smart-plug wake step used to consider only the model, so a job for a
  3655. colour loaded on the last printer in ID order switched on every earlier
  3656. one in turn, evaluated it, rejected it on colour and left it running.
  3657. Bambuddy knew those colours the whole time. This asks the same three
  3658. questions the matcher asks a live printer — required types, forced
  3659. colours, preferred colours — of the trays it last reported, and returns
  3660. the answers in the same shape the "Waiting for filament" reason uses.
  3661. Empty means the printer may still be able to take the job.
  3662. Fails open, and deliberately: with no tray reading (never connected
  3663. since Bambuddy started, or the cache dropped by a reconnect) this
  3664. returns nothing to report and the printer is treated as it was before.
  3665. A farm restarted while its printers were off must not conclude that
  3666. none of them can print.
  3667. """
  3668. if not required_types and not filament_overrides:
  3669. return []
  3670. raw_data = self._tray_reading(printer_id)
  3671. if not raw_data:
  3672. return []
  3673. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3674. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3675. if required_types:
  3676. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3677. if missing:
  3678. # Same enrichment the live path applies: a bare "PLA" is not
  3679. # much help when what is missing is a particular PLA.
  3680. force_color_map = {
  3681. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3682. }
  3683. return [
  3684. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3685. for t in missing
  3686. ]
  3687. if force_overrides:
  3688. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3689. if missing_colors:
  3690. return missing_colors
  3691. # Preference overrides read as a preference but the matcher treats zero
  3692. # matches as a skip, so a printer with none of the wanted colours is
  3693. # rejected there too. Waking it would only produce that same rejection.
  3694. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3695. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3696. return []
  3697. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3698. """Fold the winning candidate's file and settings onto the queue row (#671).
  3699. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3700. never escapes the selection loop. By the time the pass commits, the row
  3701. looks exactly like an ordinary single-file model-based item, so the upload,
  3702. archive creation, expected-print registration, print history and reprint
  3703. paths need no knowledge that variants exist.
  3704. No-ops for a non-variant candidate, which is already the item's own columns.
  3705. Safe to run and re-run: the item's file columns are only ever *read* when it
  3706. has no variants, so an item that gets resolved and then skipped (library-row
  3707. conflict, previous-print gate) is simply resolved again on the next pass.
  3708. """
  3709. variant = candidate.variant
  3710. if variant is None:
  3711. return
  3712. item.library_file_id = variant.library_file_id
  3713. item.library_file = variant.library_file
  3714. # The dispatcher checks archive_id first and would print that instead of
  3715. # the file we just picked. Creation refuses to combine the two, so this
  3716. # only ever fires on a hand-written row — clear it rather than silently
  3717. # dispatch something the matcher never considered.
  3718. item.archive_id = None
  3719. item.archive = None
  3720. item.target_model = variant.target_model
  3721. item.plate_id = variant.plate_id
  3722. item.ams_mapping = variant.ams_mapping
  3723. item.nozzle_mapping = variant.nozzle_mapping
  3724. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3725. item.filament_overrides = variant.filament_overrides
  3726. item.required_filament_types = variant.required_filament_types
  3727. if variant.print_time_seconds is not None:
  3728. # The row carried the shortest candidate's estimate so SJF could order
  3729. # it before a printer was known; now that one is chosen, record what is
  3730. # actually going to run so history and the ETA agree with reality.
  3731. item.print_time_seconds = variant.print_time_seconds
  3732. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3733. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3734. Recomputes from live printer status when the stored mapping is missing OR
  3735. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3736. frontend status-load race can serialize [-1] before the printer's AMS
  3737. trays are known (#2589) — and must not be trusted: downstream it would be
  3738. silently downgraded to external-spool mode and print against an empty
  3739. feed. A resolved mapping is re-checked against the target printer's
  3740. live trays before it is trusted (#2799) and recomputed when it does not
  3741. fit. When it does fit, its resolved slots are kept as they are and only
  3742. the slots the plate prints that are still unresolved are matched again;
  3743. all of it is left alone when the user has acknowledged it with "Print
  3744. Anyway".
  3745. When recompute cannot resolve it either (no compatible tray loaded), the
  3746. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3747. external selection. On a printer that reported loaded trays,
  3748. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3749. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3750. and the firmware surfaces a clear AMS-mapping error instead of silently
  3751. printing to the empty external feed.
  3752. Returns an actionable message when that firmware error is the only
  3753. possible outcome — the matcher ran, matched nothing, and the printer has
  3754. no AMS to load a different spool into (#2771). The caller fails the item
  3755. on it instead of spending an upload on a print that cannot start.
  3756. Returns None everywhere else, including every case where we simply lack
  3757. the data to judge, so dispatch is only ever blocked on a positive
  3758. finding.
  3759. """
  3760. stored_mapping: list | None = None
  3761. if item.ams_mapping:
  3762. try:
  3763. stored_mapping = json.loads(item.ams_mapping)
  3764. except (json.JSONDecodeError, TypeError):
  3765. stored_mapping = None
  3766. # Present and resolved. Global tray IDs only mean something relative to
  3767. # the printer they were resolved against, so "resolved" is not the same
  3768. # as "resolved *here*" — check the mapping still fits the printer that
  3769. # is about to run this item before trusting it (#2799). "Print anyway"
  3770. # is the user overriding exactly this judgement, so it short-circuits.
  3771. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3772. if item.skip_filament_check:
  3773. return None
  3774. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3775. if conflict is None:
  3776. # It fits, but a slot the plate prints may still be empty: the
  3777. # spool was missing when it was mapped, and has perhaps been
  3778. # loaded since. Nothing else would ever look at that slot again,
  3779. # so a job held for it would be held again on every Start.
  3780. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3781. if filled is not None:
  3782. item.ams_mapping = json.dumps(filled)
  3783. logger.info(
  3784. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3785. item.id,
  3786. stored_mapping,
  3787. printer_id,
  3788. filled,
  3789. )
  3790. await db.commit()
  3791. return None
  3792. logger.warning(
  3793. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3794. item.id,
  3795. stored_mapping,
  3796. printer_id,
  3797. conflict,
  3798. )
  3799. # Drop it before recomputing so a failed recompute cannot fall back
  3800. # to the mapping we just rejected.
  3801. item.ams_mapping = None
  3802. stored_mapping = None
  3803. await db.commit()
  3804. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3805. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3806. item.ams_mapping = json.dumps(computed_mapping)
  3807. logger.info(
  3808. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3809. item.id,
  3810. printer_id,
  3811. computed_mapping,
  3812. )
  3813. await db.commit()
  3814. return None
  3815. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3816. if external_only is not None:
  3817. item.ams_mapping = json.dumps(external_only)
  3818. logger.info(
  3819. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3820. "mapping every filament to it: %s",
  3821. item.id,
  3822. printer_id,
  3823. external_only,
  3824. )
  3825. await db.commit()
  3826. return None
  3827. if _mapping_is_all_unresolved(stored_mapping):
  3828. logger.warning(
  3829. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3830. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3831. item.id,
  3832. stored_mapping,
  3833. printer_id,
  3834. )
  3835. item.ams_mapping = None
  3836. await db.commit()
  3837. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3838. async def _external_spool_only_mapping(
  3839. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3840. ) -> list[int] | None:
  3841. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3842. A printer without an AMS prints from its external spool, and an external
  3843. spool whose filament was never set reports no type, so the matcher has
  3844. nothing to match. Sent without a mapping, the print goes out with the AMS
  3845. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3846. to carry such a job through; a job placed by model or location no longer
  3847. keeps one, and one queued that way never had one.
  3848. Only on a positive report: the printer has said it has no AMS, it has a
  3849. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3850. is not ours to pick), and no feed has a filament set — with one set, the
  3851. matcher has already given its answer. Not for a job that asked for its
  3852. colours to be matched strictly: a spool without a filament set has no
  3853. colour to check. Returns None otherwise.
  3854. """
  3855. if item.filament_overrides:
  3856. try:
  3857. overrides = json.loads(item.filament_overrides)
  3858. except (json.JSONDecodeError, TypeError):
  3859. return None
  3860. if not isinstance(overrides, list) or any(
  3861. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3862. ):
  3863. return None
  3864. status = printer_manager.get_status(printer_id)
  3865. if status is None or not isinstance(status.raw_data, dict):
  3866. return None
  3867. ams_units = status.raw_data.get("ams")
  3868. if not isinstance(ams_units, list) or ams_units:
  3869. return None
  3870. vt_trays = status.raw_data.get("vt_tray")
  3871. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3872. return None
  3873. if self._build_loaded_filaments(status):
  3874. return None
  3875. printer = await self._get_printer(db, printer_id)
  3876. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3877. return None
  3878. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3879. if external < _EXTERNAL_TRAY_ID_MIN:
  3880. return None
  3881. required = await self._get_filament_requirements(db, item)
  3882. slot_ids = [r.get("slot_id") for r in required or []]
  3883. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3884. if not slot_ids:
  3885. return None
  3886. mapping = [-1] * max(slot_ids)
  3887. for slot_id in slot_ids:
  3888. mapping[slot_id - 1] = external
  3889. return mapping
  3890. async def _fill_unresolved_slots(
  3891. self,
  3892. db: AsyncSession,
  3893. printer_id: int,
  3894. item: PrintQueueItem,
  3895. stored_mapping: list | None,
  3896. ) -> list | None:
  3897. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3898. Every resolved entry is kept, so a tray the user picked by hand stays
  3899. picked. Only the plate's unresolved slots are matched, and only against
  3900. trays the mapping does not already use: the matcher never gives two
  3901. slots one tray, and filling a gap with a tray the user assigned to
  3902. another slot would print that slot's filament twice.
  3903. Returns None when there is nothing to fill or nothing could be filled.
  3904. """
  3905. if not isinstance(stored_mapping, list) or not stored_mapping:
  3906. return None
  3907. required = await self._get_filament_requirements(db, item)
  3908. if not required:
  3909. return None
  3910. self._apply_filament_overrides(item, required)
  3911. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3912. if not gaps:
  3913. return None
  3914. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3915. computed = await self._compute_ams_mapping_for_printer(
  3916. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3917. )
  3918. if not computed:
  3919. return None
  3920. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3921. filled = False
  3922. for slot_id in gaps:
  3923. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3924. if _is_tray_id(tray) and tray >= 0:
  3925. merged[slot_id - 1] = tray
  3926. filled = True
  3927. return merged if filled else None
  3928. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3929. """What a staged item would be held for if it were started now (#2799).
  3930. The Start button asks this before releasing an item, so that a job whose
  3931. filament is still not loaded offers "Print Anyway" instead of being
  3932. released, held again by the scheduler and leaving no way past the hold.
  3933. It reaches the same answer the dispatch path would: a stored mapping
  3934. that fits is kept and only its gaps are matched again, and one that
  3935. does not fit (or is missing) is replaced by a fresh match.
  3936. Returns the missing filaments, described the way the queue row
  3937. describes them, or None when nothing is missing or there is not enough
  3938. evidence to say: no printer yet (a model-based item picks one at
  3939. dispatch), no status, no trays reported, or no readable 3MF.
  3940. """
  3941. if item.skip_filament_check or not item.printer_id:
  3942. return None
  3943. status = printer_manager.get_status(item.printer_id)
  3944. if status is None or not self._build_loaded_filaments(status):
  3945. return None
  3946. # Called from a request, not from a pass: drop whatever the last pass
  3947. # memoised so this reads the file as it is now. A pass running at the
  3948. # same time only loses its cache.
  3949. self._filament_req_memo.clear()
  3950. mapping: list | None = None
  3951. if item.ams_mapping:
  3952. try:
  3953. mapping = json.loads(item.ams_mapping)
  3954. except (json.JSONDecodeError, TypeError):
  3955. mapping = None
  3956. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3957. mapping = None
  3958. if mapping is not None:
  3959. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3960. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3961. else:
  3962. mapping = None
  3963. if mapping is None:
  3964. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3965. required = await self._get_filament_requirements(db, item)
  3966. if required:
  3967. self._apply_filament_overrides(item, required)
  3968. else:
  3969. # The same fallback the hold uses, or Start would release a job the
  3970. # next pass holds again (#3280).
  3971. required = _forced_override_requirements(item)
  3972. if not required:
  3973. return None
  3974. missing = _unresolved_required(required, mapping)
  3975. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3976. async def _stored_mapping_conflict(
  3977. self,
  3978. db: AsyncSession,
  3979. printer_id: int,
  3980. item: PrintQueueItem,
  3981. stored_mapping: list | None,
  3982. ) -> str | None:
  3983. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3984. A mapping is a list of global tray IDs, and those are only meaningful
  3985. relative to the printer they were resolved against — the same rule
  3986. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3987. arrives at a printer it was not resolved for:
  3988. * the print dialog stamps one mapping onto every selected printer, so a
  3989. mapping computed against the first printer is dispatched verbatim to
  3990. the rest, whose AMS slot order differs;
  3991. * a spool is moved between queueing and dispatch.
  3992. Both end the same way: the slot index still resolves, so nothing looks
  3993. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3994. the firmware's own type check, so a PETG slot happily prints in ASA.
  3995. Returns a short reason when the mapping names a tray this printer does
  3996. not have loaded, points a slot at a tray holding a different filament
  3997. type, or points it at an external spool this printer reports empty while
  3998. its AMS holds that slot's filament (#3239). Returns None when the
  3999. mapping fits, and — deliberately — whenever we lack the evidence to
  4000. judge, so a recompute only ever follows a positive finding.
  4001. An unresolved (``-1``) required slot is NOT a conflict: it says the
  4002. matcher had nothing, not that the mapping belongs to another printer,
  4003. and destroying a partially hand-resolved mapping over it would lose the
  4004. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  4005. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  4006. item when that finds nothing.
  4007. """
  4008. if not isinstance(stored_mapping, list) or not stored_mapping:
  4009. return None
  4010. status = printer_manager.get_status(printer_id)
  4011. if status is None:
  4012. return None
  4013. loaded = self._build_loaded_filaments(status)
  4014. if not loaded:
  4015. # Nothing reported yet (reconnect, first push pending). Saying
  4016. # "tray not loaded" here would recompute against an AMS we cannot
  4017. # see, which is how #2589 produced a bogus all-[-1] in the first
  4018. # place.
  4019. return None
  4020. by_tray = {f["global_tray_id"]: f for f in loaded}
  4021. layout = TrayLayout.from_state(status)
  4022. # Cheap pass first, on live status alone: every tray the mapping names
  4023. # has to exist here. This catches a foreign mapping without opening the
  4024. # 3MF, which is worth doing because the parse below is neither cached
  4025. # nor free.
  4026. for index, tray in enumerate(stored_mapping):
  4027. if not _is_tray_id(tray) or tray < 0:
  4028. continue
  4029. if tray in by_tray:
  4030. continue
  4031. if tray >= 254 or layout.is_external(tray):
  4032. # An external feed we have not heard about is absence of
  4033. # evidence about *that slot* — the rest of the mapping is still
  4034. # worth judging, so skip it rather than abandoning the pass.
  4035. continue
  4036. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  4037. # Only now is the 3MF worth opening: the type check needs to know what
  4038. # each slot actually asked for. The external spool is checked the same
  4039. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  4040. # two printers with different filament in the external feed is the same
  4041. # failure this method exists to catch.
  4042. required = await self._get_filament_requirements(db, item)
  4043. if not required:
  4044. return None
  4045. self._apply_filament_overrides(item, required)
  4046. # External feeds the printer reports and reports as empty. That is
  4047. # evidence, unlike an external feed it says nothing about (#3239).
  4048. empty_external: set[int] = set()
  4049. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  4050. for vt in vt_trays if isinstance(vt_trays, list) else []:
  4051. if isinstance(vt, dict) and not vt.get("tray_type"):
  4052. try:
  4053. empty_external.add(int(vt.get("id", 254)))
  4054. except (TypeError, ValueError):
  4055. continue
  4056. for req in required:
  4057. slot_id = req.get("slot_id") or 0
  4058. if slot_id <= 0:
  4059. continue
  4060. if slot_id > len(stored_mapping):
  4061. return f"slot {slot_id} is not covered by the mapping"
  4062. tray = stored_mapping[slot_id - 1]
  4063. if not _is_tray_id(tray) or tray < 0:
  4064. continue
  4065. loaded_tray = by_tray.get(tray)
  4066. if loaded_tray is None:
  4067. # A mapping made for a printer that feeds this slot from its
  4068. # external spool, sent to one whose external spool is empty and
  4069. # whose AMS holds the filament (#3239). Only then: an external
  4070. # spool can be loaded without its filament set, and on a printer
  4071. # with nothing else to offer that job printed before. The colour
  4072. # has to match too: with only another colour in the AMS, the
  4073. # printer asking for the spool beats printing in that colour.
  4074. want = canonical_filament_type(req.get("type"))
  4075. if (tray >= 254 or layout.is_external(tray)) and tray in empty_external and want:
  4076. ams_tray = next(
  4077. (
  4078. f
  4079. for f in loaded
  4080. if not f.get("is_external")
  4081. and canonical_filament_type(f.get("type")) == want
  4082. and self._colors_are_similar(f.get("color"), req.get("color"))
  4083. ),
  4084. None,
  4085. )
  4086. if ams_tray is not None:
  4087. return (
  4088. f"slot {slot_id} points at the external spool, which is empty, "
  4089. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  4090. )
  4091. continue
  4092. want = canonical_filament_type(req.get("type"))
  4093. have = canonical_filament_type(loaded_tray.get("type"))
  4094. if want and have and want != have:
  4095. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  4096. # A forced slot fits only a tray the matcher would give it (#3280).
  4097. if req.get("force_color_match"):
  4098. want_idx = req.get("tray_info_idx") or ""
  4099. have_idx = loaded_tray.get("tray_info_idx") or ""
  4100. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  4101. loaded_tray.get("color")
  4102. ) or (want_idx and have_idx and want_idx != have_idx):
  4103. return (
  4104. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  4105. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  4106. )
  4107. return None
  4108. async def _unmappable_without_ams_message(
  4109. self,
  4110. db: AsyncSession,
  4111. printer_id: int,
  4112. item: PrintQueueItem,
  4113. computed_mapping: list[int] | None,
  4114. ) -> str | None:
  4115. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  4116. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  4117. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  4118. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  4119. uploaded several megabytes and burned its dispatch retries. This method
  4120. speaks only for the AMS-less case: there is nothing to resume into — the
  4121. external spool holder is the whole inventory — so the useful answer is to
  4122. say which filament is missing and stop. With an AMS attached it returns
  4123. None: where live status reported loaded trays,
  4124. ``_block_on_unmatched_filament`` holds the item instead, and where it
  4125. reported none the print goes out and the firmware error is the answer —
  4126. the user can load the right spool and press Resume.
  4127. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  4128. every branch that lacks the evidence to be sure returns None.
  4129. """
  4130. # None means the matcher never ran (no requirements parsed from the 3MF,
  4131. # or nothing loaded at all) rather than "ran and matched nothing". Those
  4132. # dispatch as they always have.
  4133. if not _mapping_is_all_unresolved(computed_mapping):
  4134. return None
  4135. status = printer_manager.get_status(printer_id)
  4136. if status is None:
  4137. return None
  4138. # "No AMS" has to be a fact the printer stated, not the absence of a
  4139. # statement. `raw_data["ams"]` is written only once an AMS push has been
  4140. # handled and is preserved across partial pushes thereafter, so a missing
  4141. # key means we have not heard yet — most likely a reconnect, where the
  4142. # trays of a fully loaded AMS would be invisible for a few seconds. An
  4143. # empty list is the positive report of a printer with no AMS.
  4144. ams_units = status.raw_data.get("ams")
  4145. if not isinstance(ams_units, list) or ams_units:
  4146. return None
  4147. required = await self._get_filament_requirements(db, item)
  4148. loaded = self._build_loaded_filaments(status)
  4149. if not required or not loaded:
  4150. # Both were non-empty moments ago or the matcher could not have run.
  4151. # If the picture changed under us, say nothing rather than fail an
  4152. # item on stale evidence.
  4153. return None
  4154. self._apply_filament_overrides(item, required)
  4155. if any(r.get("force_color_match") for r in required):
  4156. # A forced colour is a spool the user can load on the external
  4157. # holder, so the unmatched hold stages the job instead (#3280).
  4158. return None
  4159. return _unmatched_filament_message(required, loaded)
  4160. async def _fail_unmappable_item(
  4161. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  4162. ) -> None:
  4163. """Fail a queue item whose filament mapping cannot resolve (#2771).
  4164. This replaces a failure, not a success: without it the item is uploaded,
  4165. rejected by the firmware with 0700_8012, retried twice more and failed
  4166. anyway with "never started the print after N dispatch attempts". So this
  4167. applies on the model-based path too. There it is rarely reached: choosing
  4168. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  4169. over one it cannot map, so an "Any <model>" job tries its siblings and
  4170. otherwise waits; this remains for a match that failed at selection time.
  4171. """
  4172. item.status = "failed"
  4173. item.error_message = message
  4174. item.completed_at = datetime.now(timezone.utc)
  4175. item.waiting_reason = None
  4176. await db.commit()
  4177. from backend.app.services.print_batch import refresh_batches_after
  4178. await refresh_batches_after([item.id])
  4179. logger.warning(
  4180. "Queue item %s: no usable AMS mapping on printer %s — %s",
  4181. item.id,
  4182. printer_id,
  4183. message,
  4184. )
  4185. job_name = await self._get_job_name(db, item)
  4186. printer = await self._get_printer(db, printer_id)
  4187. await notification_service.on_queue_job_failed(
  4188. job_name=job_name,
  4189. printer_id=printer_id,
  4190. printer_name=printer.name if printer else "Unknown",
  4191. reason=message,
  4192. db=db,
  4193. )
  4194. try:
  4195. await ws_manager.send_queue_item_failed(
  4196. user_id=item.created_by_id,
  4197. queue_item_id=item.id,
  4198. printer_id=printer_id,
  4199. reason="filament_unmappable",
  4200. )
  4201. except Exception:
  4202. pass
  4203. async def _compute_ams_mapping_for_printer(
  4204. self,
  4205. db: AsyncSession,
  4206. printer_id: int,
  4207. item: PrintQueueItem,
  4208. *,
  4209. only_slots: set[int] | None = None,
  4210. reserved_trays: set[int] | None = None,
  4211. ) -> list[int] | None:
  4212. """Compute AMS mapping for a printer based on filament requirements.
  4213. Called when a queue item has no ams_mapping set — either for model-based
  4214. items after printer assignment, or printer-specific items (e.g. from VP).
  4215. Args:
  4216. db: Database session
  4217. printer_id: The assigned printer ID
  4218. item: The queue item (contains archive_id or library_file_id)
  4219. only_slots: Match only these filament slots; every other slot comes
  4220. back unresolved (-1). Used to fill the gaps of a stored mapping.
  4221. reserved_trays: Global tray IDs to leave out of the match, because
  4222. the stored mapping already gives them to another slot.
  4223. Returns:
  4224. AMS mapping array or None if no mapping needed/possible
  4225. """
  4226. # Get printer status
  4227. status = printer_manager.get_status(printer_id)
  4228. if not status:
  4229. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  4230. return None
  4231. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  4232. # either extruder, so the per-nozzle hard filter below must NOT apply.
  4233. # Otherwise a print on one nozzle can't use a spool physically loaded in
  4234. # an AMS on the *other* nozzle, and the matcher falls through to a
  4235. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  4236. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  4237. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  4238. # Get filament requirements from source file
  4239. filament_reqs = await self._get_filament_requirements(db, item)
  4240. if not filament_reqs:
  4241. # When the 3MF can't be read but force-color overrides are present, build a
  4242. # direct mapping from the overrides so the printer uses the correct AMS slot.
  4243. if item.filament_overrides:
  4244. try:
  4245. overrides = json.loads(item.filament_overrides)
  4246. force_overrides = [o for o in overrides if o.get("force_color_match")]
  4247. if force_overrides:
  4248. logger.info(
  4249. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  4250. "force-color override(s)",
  4251. item.id,
  4252. len(force_overrides),
  4253. )
  4254. return self._build_override_direct_mapping(force_overrides, status)
  4255. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4256. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  4257. logger.debug("No filament requirements found for queue item %s", item.id)
  4258. return None
  4259. self._apply_filament_overrides(item, filament_reqs)
  4260. if only_slots is not None:
  4261. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  4262. if not filament_reqs:
  4263. return None
  4264. # Build loaded filaments from printer status
  4265. loaded_filaments = self._build_loaded_filaments(status)
  4266. if reserved_trays:
  4267. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  4268. if not loaded_filaments:
  4269. logger.debug("No filaments loaded on printer %s", printer_id)
  4270. return None
  4271. # Check if user prefers lowest remaining filament when multiple spools match
  4272. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  4273. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  4274. # Without backup, the printer will not switch to a second spool when the
  4275. # picked one runs out — so sorting toward the lowest leaves the print
  4276. # at risk of running dry mid-job. None (unknown: no status report with
  4277. # cfg or home_flag yet) preserves today's behaviour intentionally.
  4278. if prefer_lowest and status.ams_filament_backup is False:
  4279. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  4280. prefer_lowest = False
  4281. # When the preference is on, surface Bambuddy's inventory-side
  4282. # remaining for each slot that's bound to a tracked spool, so the
  4283. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  4284. # entirely when the preference is off — no behaviour change for
  4285. # users who haven't opted in.
  4286. inventory_remain_overrides: dict[int, float] | None = None
  4287. if prefer_lowest:
  4288. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  4289. # Compute mapping: match required filaments to available slots
  4290. return self._match_filaments_to_slots(
  4291. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  4292. )
  4293. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  4294. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  4295. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  4296. diagnosis (#2771) describes the filament the matcher actually looked
  4297. for, not the one the 3MF was sliced with — naming the pre-override
  4298. filament in a user-facing error would send the user to load the wrong
  4299. spool.
  4300. """
  4301. if not item.filament_overrides:
  4302. return
  4303. try:
  4304. overrides = json.loads(item.filament_overrides)
  4305. override_map = {o["slot_id"]: o for o in overrides}
  4306. for req in filament_reqs:
  4307. if req["slot_id"] in override_map:
  4308. override = override_map[req["slot_id"]]
  4309. req["type"] = override["type"]
  4310. req["color"] = override["color"]
  4311. # A manual/preference override SWAPS the slot's filament, so the
  4312. # 3MF's original tray_info_idx now points at the old spool and must
  4313. # be cleared — matching then falls back to type+colour. A
  4314. # force_color_match override is not a swap: it carries the 3MF's
  4315. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4316. # it here too, letting the matcher pin the correct variant slot on a
  4317. # printer holding two same-colour spools of different variants (#2650).
  4318. # A spool that names no variant still counts; one naming another
  4319. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4320. req["tray_info_idx"] = (
  4321. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4322. )
  4323. # The matcher satisfies a forced slot only the way
  4324. # `_get_missing_force_color_slots` does, never by a similar
  4325. # colour or the type alone (#3280).
  4326. req["force_color_match"] = bool(override.get("force_color_match"))
  4327. logger.debug(
  4328. "Queue item %s: Override slot %d -> %s %s",
  4329. item.id,
  4330. req["slot_id"],
  4331. override["type"],
  4332. override["color"],
  4333. )
  4334. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4335. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4336. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4337. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4338. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4339. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4340. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4341. treated as the filament requirement for that slot and matched against the
  4342. current AMS state of the printer.
  4343. Returns the same format as ``_match_filaments_to_slots``, or None when
  4344. the AMS has no loaded filaments.
  4345. """
  4346. loaded = self._build_loaded_filaments(status)
  4347. if not loaded:
  4348. return None
  4349. reqs = [
  4350. {
  4351. "slot_id": o["slot_id"],
  4352. "type": o.get("type", ""),
  4353. "color": o.get("color", ""),
  4354. # These are all force_color_match overrides, so the idx (when the
  4355. # 3MF carried one) is the intended variant, not a stale swap —
  4356. # keep it so the matcher pins the right variant slot (#2650); a
  4357. # spool naming another variant does not satisfy it (#3280).
  4358. "tray_info_idx": o.get("tray_info_idx", ""),
  4359. "force_color_match": True,
  4360. }
  4361. for o in force_overrides
  4362. ]
  4363. return self._match_filaments_to_slots(reqs, loaded)
  4364. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4365. """Resolve the queue item's source 3MF and parse the per-slot
  4366. filament requirements out of it. Thin DB-resolver wrapper around
  4367. ``filament_requirements.extract_filament_requirements`` so the VP
  4368. queue-mode write path (#1188) can reuse the same parser at upload
  4369. time.
  4370. """
  4371. from backend.app.services.filament_requirements import extract_filament_requirements
  4372. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4373. # so every caller gets its own copy — a shared list would leak one
  4374. # item's overrides into the next item that happens to print the same
  4375. # plate.
  4376. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4377. if memo_key in self._filament_req_memo:
  4378. cached = self._filament_req_memo[memo_key]
  4379. return [dict(r) for r in cached] if cached else None
  4380. file_path: Path | None = None
  4381. if item.archive_id:
  4382. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4383. archive = result.scalar_one_or_none()
  4384. if archive:
  4385. file_path = settings.base_dir / archive.file_path
  4386. elif item.library_file_id:
  4387. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4388. library_file = result.scalar_one_or_none()
  4389. if library_file:
  4390. lib_path = Path(library_file.file_path)
  4391. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4392. if not file_path or not file_path.exists():
  4393. self._filament_req_memo[memo_key] = None
  4394. return None
  4395. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4396. self._filament_req_memo[memo_key] = filaments or None
  4397. return [dict(r) for r in filaments] if filaments else None
  4398. def _build_loaded_filaments(self, status) -> list[dict]:
  4399. """Build list of loaded filaments from printer status.
  4400. Args:
  4401. status: PrinterState from printer_manager
  4402. Returns:
  4403. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4404. """
  4405. filaments = []
  4406. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4407. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4408. # Routes external spools to an extruder (#2771). Mirrors
  4409. # `buildLoadedFilaments` in the frontend.
  4410. vt_trays = status.raw_data.get("vt_tray") or []
  4411. is_dual_nozzle = reports_two_nozzles(status)
  4412. # Parse AMS units from raw_data
  4413. ams_data = status.raw_data.get("ams", [])
  4414. layout = TrayLayout.from_state(status)
  4415. for ams_unit in ams_data:
  4416. ams_id = int(ams_unit.get("id", 0))
  4417. trays = ams_unit.get("tray", [])
  4418. is_ht = is_ams_ht_id(ams_id) # AMS-HT unit ids; a regular AMS may list fewer trays
  4419. for tray in trays:
  4420. tray_type = tray.get("tray_type")
  4421. if tray_type:
  4422. tray_id = int(tray.get("id", 0))
  4423. tray_color = tray.get("tray_color", "")
  4424. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4425. tray_info_idx = tray.get("tray_info_idx", "")
  4426. # Normalize color: remove alpha, add hash
  4427. color = self._normalize_color(tray_color)
  4428. # Calculate global tray ID
  4429. # AMS-HT units have IDs starting at 128 with a single tray
  4430. global_tray_id = layout.global_tray_id(ams_id, tray_id)
  4431. filaments.append(
  4432. {
  4433. "type": tray_type,
  4434. "color": color,
  4435. # `color` reads a missing colour as #808080; this
  4436. # says whether the printer reported one at all.
  4437. "color_known": bool(tray_color),
  4438. "tray_info_idx": tray_info_idx,
  4439. "ams_id": ams_id,
  4440. "tray_id": tray_id,
  4441. "is_ht": is_ht,
  4442. "is_external": False,
  4443. "global_tray_id": global_tray_id,
  4444. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4445. "remain": tray.get("remain", -1),
  4446. }
  4447. )
  4448. # Check external spool(s) (vt_tray is a list)
  4449. for idx, vt in enumerate(vt_trays):
  4450. if vt.get("tray_type"):
  4451. color = self._normalize_color(vt.get("tray_color", ""))
  4452. tray_id = int(vt.get("id", 254))
  4453. filaments.append(
  4454. {
  4455. "type": vt["tray_type"],
  4456. "color": color,
  4457. "color_known": bool(vt.get("tray_color")),
  4458. "tray_info_idx": vt.get("tray_info_idx", ""),
  4459. "ams_id": -1,
  4460. "tray_id": idx,
  4461. "is_ht": False,
  4462. "is_external": True,
  4463. "global_tray_id": tray_id,
  4464. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4465. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4466. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4467. "remain": vt.get("remain", -1),
  4468. }
  4469. )
  4470. return filaments
  4471. def _normalize_color(self, color: str | None) -> str:
  4472. """Normalize color to #RRGGBB format."""
  4473. if not color:
  4474. return "#808080"
  4475. hex_color = color.replace("#", "")[:6]
  4476. return f"#{hex_color}"
  4477. def _normalize_color_for_compare(self, color: str | None) -> str:
  4478. """Normalize color for comparison (lowercase, no hash)."""
  4479. if not color:
  4480. return ""
  4481. return color.replace("#", "").lower()[:6]
  4482. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4483. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4484. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4485. stays the per-channel box that shipped — this only decides which of
  4486. several eligible spools is closest, so nothing becomes usable or
  4487. unusable because of it.
  4488. It ranks by how far apart the colours *look*, not how far apart their
  4489. numbers are. RGB distance overweights blue badly enough to invert the
  4490. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4491. the nearer of two eligible spools by RGB and the further by a factor of
  4492. four once measured perceptually.
  4493. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4494. transparent filament is not a colour the user chose, and counting it
  4495. would stop a transparent filament matching itself.
  4496. """
  4497. return perceptual_color_distance(color1, color2)
  4498. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4499. """Check if two colors are visually similar within a threshold."""
  4500. hex1 = self._normalize_color_for_compare(color1)
  4501. hex2 = self._normalize_color_for_compare(color2)
  4502. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4503. return False
  4504. try:
  4505. r1 = int(hex1[0:2], 16)
  4506. g1 = int(hex1[2:4], 16)
  4507. b1 = int(hex1[4:6], 16)
  4508. r2 = int(hex2[0:2], 16)
  4509. g2 = int(hex2[2:4], 16)
  4510. b2 = int(hex2[4:6], 16)
  4511. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4512. except ValueError:
  4513. return False
  4514. async def _build_inventory_remain_overrides(
  4515. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4516. ) -> dict[int, float]:
  4517. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4518. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4519. The MQTT ``remain`` field on a tray is the printer firmware's
  4520. RFID-decremented value, which has two limitations the "Prefer Lowest
  4521. Remaining Filament" feature has been ignoring (#1508):
  4522. - it's only meaningful for Bambu RFID spools; everything else reports
  4523. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4524. compare equal and the sort collapses to AMS-slot order — the user
  4525. who's curating inventory weights gets the lower-slot pick instead
  4526. of the lower-remaining pick;
  4527. - even when set, it's the *printer's* counter, not Bambuddy's
  4528. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4529. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4530. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4531. When the user has bound a spool to a slot, their own inventory
  4532. tracking is authoritative; this helper surfaces that value so the
  4533. sort can prefer it. Slots without a binding are absent from the
  4534. returned map — the caller then falls back to MQTT ``remain`` for
  4535. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4536. Returns an empty map on any failure (no inventory bindings, DB
  4537. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4538. is a preference, not a guarantee.
  4539. """
  4540. if not loaded:
  4541. return {}
  4542. # External / virtual-tray slots are tracked separately from AMS — skip
  4543. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4544. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4545. # match is fiddly and out of scope for this fix).
  4546. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4547. if not tracked_slots:
  4548. return {}
  4549. is_spoolman = await self._is_spoolman_mode(db)
  4550. overrides: dict[int, float] = {}
  4551. if is_spoolman:
  4552. result = await db.execute(
  4553. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4554. )
  4555. assignments = list(result.scalars().all())
  4556. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4557. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4558. for ams_id, tray_id, gtid in tracked_slots:
  4559. spoolman_id = by_slot.get((ams_id, tray_id))
  4560. if spoolman_id is None:
  4561. continue
  4562. grams = await _spoolman_remaining_grams(spoolman_id)
  4563. if grams is not None:
  4564. overrides[gtid] = grams
  4565. return overrides
  4566. # Internal inventory mode (default). selectinload matches the pattern
  4567. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4568. # plus an eager-loaded relationship rather than an explicit join, so
  4569. # the row-attribute shape is exactly what those routes already rely on.
  4570. result = await db.execute(
  4571. select(SpoolAssignment)
  4572. .options(selectinload(SpoolAssignment.spool))
  4573. .where(SpoolAssignment.printer_id == printer_id)
  4574. )
  4575. assignments = list(result.scalars().all())
  4576. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4577. for ams_id, tray_id, gtid in tracked_slots:
  4578. spool = by_slot.get((ams_id, tray_id))
  4579. if spool is None:
  4580. continue
  4581. label = float(spool.label_weight or 0)
  4582. used = float(spool.weight_used or 0)
  4583. overrides[gtid] = max(0.0, label - used)
  4584. return overrides
  4585. @staticmethod
  4586. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4587. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4588. here to avoid making this module import-dependent on that private
  4589. helper's signature."""
  4590. try:
  4591. from backend.app.api.routes.settings import get_setting
  4592. v = await get_setting(db, "spoolman_enabled")
  4593. return bool(v) and v.lower() == "true"
  4594. except Exception:
  4595. return False
  4596. @staticmethod
  4597. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4598. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4599. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4600. so a tied sort produces the same physical-position order the pre-#1508
  4601. stable sort did (preserves the regression-free baseline):
  4602. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4603. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4604. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4605. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4606. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4607. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4608. """
  4609. if ams_id is None or ams_id < 0:
  4610. return 10_000
  4611. if ams_id >= 128:
  4612. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4613. return ams_id * 4 + (tray_id or 0)
  4614. @staticmethod
  4615. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4616. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4617. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4618. non-tracked spools (the user has told us they care about these
  4619. specifically), then ascending by remaining within each tier, then
  4620. ascending by AMS slot position as the deterministic tie-breaker.
  4621. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4622. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4623. because the tier flag dominates — which is what lets us mix grams
  4624. (inventory) and percent (MQTT) without a unit conversion.
  4625. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4626. spools the printer DOES know something about sort ahead of those
  4627. it knows nothing about — preserves pre-#1508 behaviour for the
  4628. no-inventory-binding case.
  4629. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4630. external on ties, matching the legacy emission-order stable sort.
  4631. """
  4632. gtid = f.get("global_tray_id")
  4633. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4634. if overrides and gtid in overrides:
  4635. return (0, overrides[gtid], slot_order)
  4636. remain = f.get("remain", -1)
  4637. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4638. def _match_filaments_to_slots(
  4639. self,
  4640. required: list[dict],
  4641. loaded: list[dict],
  4642. prefer_lowest: bool = False,
  4643. inventory_remain_overrides: dict[int, float] | None = None,
  4644. fts_installed: bool = False,
  4645. ) -> list[int] | None:
  4646. """Match required filaments to loaded filaments and build AMS mapping.
  4647. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4648. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4649. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4650. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4651. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4652. matching among those trays.
  4653. Args:
  4654. required: List of required filaments with slot_id, type, color, tray_info_idx
  4655. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4656. Returns:
  4657. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4658. """
  4659. if not required:
  4660. return None
  4661. # Track used trays to avoid duplicate assignment
  4662. used_tray_ids: set[int] = set()
  4663. comparisons = []
  4664. # Forced slots first: a slot that would take any tray of its type must
  4665. # not take the one tray a forced slot can use (#3280). The mapping is
  4666. # built by slot_id below, so the order only decides who goes first.
  4667. # Among forced slots, those naming a variant first, as
  4668. # `_get_missing_force_color_slots` counts them.
  4669. for req in sorted(
  4670. required,
  4671. key=lambda r: (
  4672. not r.get("force_color_match"),
  4673. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4674. ),
  4675. ):
  4676. req_type = (req.get("type") or "").upper()
  4677. req_color = req.get("color", "")
  4678. req_tray_info_idx = req.get("tray_info_idx", "")
  4679. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4680. idx_match = None
  4681. exact_match = None
  4682. similar_match = None
  4683. similar_distance = float("inf")
  4684. type_only_match = None
  4685. # Get available trays (not already used)
  4686. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4687. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4688. # Hard filter — cross-nozzle assignment causes print failures
  4689. # ("position of left hotend is abnormal"), so never fall back.
  4690. # Skipped when an FTS is installed: it routes any AMS slot to either
  4691. # extruder, so restricting to one nozzle would wrongly exclude the
  4692. # correct spool sitting in the other nozzle's AMS (#2186).
  4693. req_nozzle_id = req.get("nozzle_id")
  4694. if req_nozzle_id is not None and not fts_installed:
  4695. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4696. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4697. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4698. # _prefer_lowest_sort_key for the full rationale.
  4699. if prefer_lowest:
  4700. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4701. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4702. # One line per filament req so a bug report can be diagnosed
  4703. # without enabling debug logging: shows what the matcher saw
  4704. # (req shape + sorted candidate trays with their remain values
  4705. # and any inventory override that was applied). Mirrored by
  4706. # the picked-match log at the bottom of the loop.
  4707. logger.info(
  4708. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4709. req.get("slot_id"),
  4710. req_type,
  4711. req_color,
  4712. req_tray_info_idx,
  4713. req_nozzle_id,
  4714. [
  4715. {
  4716. "gtid": f.get("global_tray_id"),
  4717. "type": f.get("type"),
  4718. "color": f.get("color"),
  4719. "tii": f.get("tray_info_idx"),
  4720. "remain": f.get("remain"),
  4721. "inv_g": (
  4722. inventory_remain_overrides.get(f.get("global_tray_id"))
  4723. if inventory_remain_overrides
  4724. else None
  4725. ),
  4726. }
  4727. for f in available
  4728. ],
  4729. )
  4730. # A forced slot takes only what `_get_missing_force_color_slots`
  4731. # accepts: same type, exact colour, and the same variant when both
  4732. # sides name one -- preferring the tray that does. Nothing looser:
  4733. # the model-based path holds a job the printer cannot satisfy this
  4734. # way, and a printer-pinned job fell through to type_only and
  4735. # printed in whatever colour came first (#3280).
  4736. forced = bool(req.get("force_color_match"))
  4737. if forced:
  4738. want_type = canonical_filament_type(req_type)
  4739. want_color = self._normalize_color_for_compare(req_color)
  4740. candidates = [
  4741. f
  4742. for f in available
  4743. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4744. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4745. and (
  4746. not req_tray_info_idx
  4747. or not f.get("tray_info_idx")
  4748. or f.get("tray_info_idx") == req_tray_info_idx
  4749. )
  4750. ]
  4751. exact_match = next(
  4752. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4753. candidates[0] if candidates else None,
  4754. )
  4755. # Check if tray_info_idx is unique among available trays
  4756. if req_tray_info_idx and not forced:
  4757. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4758. if len(idx_matches) == 1:
  4759. # Unique tray_info_idx - use it as definitive match
  4760. idx_match = idx_matches[0]
  4761. logger.debug(
  4762. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4763. f"-> tray {idx_match['global_tray_id']}"
  4764. )
  4765. elif len(idx_matches) > 1:
  4766. # Multiple trays with same tray_info_idx - use color matching among them
  4767. logger.debug(
  4768. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4769. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4770. )
  4771. if prefer_lowest:
  4772. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4773. # Use color matching within this subset
  4774. for f in idx_matches:
  4775. f_color = f.get("color", "")
  4776. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4777. if not exact_match:
  4778. exact_match = f
  4779. elif self._colors_are_similar(f_color, req_color):
  4780. distance = self._color_distance(f_color, req_color)
  4781. if distance is not None and distance < similar_distance:
  4782. similar_match = f
  4783. similar_distance = distance
  4784. elif not type_only_match:
  4785. type_only_match = f
  4786. # If no idx_match yet, do standard type/color matching on all available trays
  4787. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4788. for f in available:
  4789. f_type = (f.get("type") or "").upper()
  4790. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4791. continue
  4792. # Type matches - check color
  4793. f_color = f.get("color", "")
  4794. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4795. if not exact_match:
  4796. exact_match = f
  4797. elif self._colors_are_similar(f_color, req_color):
  4798. # Nearest wins, not first-in-tray-order. `available` is
  4799. # already in the caller's order (slot order, or the
  4800. # prefer-lowest sort), and `<` keeps the earliest of
  4801. # equally close spools — so that order survives as the
  4802. # tie-break (#2804).
  4803. distance = self._color_distance(f_color, req_color)
  4804. if distance is not None and distance < similar_distance:
  4805. similar_match = f
  4806. similar_distance = distance
  4807. elif not type_only_match:
  4808. type_only_match = f
  4809. match = idx_match or exact_match or similar_match or type_only_match
  4810. if match:
  4811. used_tray_ids.add(match["global_tray_id"])
  4812. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4813. else:
  4814. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4815. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4816. # "Why did it pick that spool" is the question every wrong-filament
  4817. # report starts with, and a `similar_color` win is now a ranked
  4818. # choice among several eligible spools rather than whichever tray
  4819. # came first, so it is worth being able to see after the fact.
  4820. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4821. # is on (#1766).
  4822. if match:
  4823. bucket = (
  4824. "idx"
  4825. if idx_match is not None
  4826. else "exact_color"
  4827. if exact_match is not None
  4828. else "similar_color"
  4829. if similar_match is not None
  4830. else "type_only"
  4831. )
  4832. logger.info(
  4833. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4834. match["global_tray_id"],
  4835. bucket,
  4836. req.get("slot_id"),
  4837. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4838. )
  4839. else:
  4840. logger.info(
  4841. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4842. req.get("slot_id"),
  4843. req_type,
  4844. req_color,
  4845. req_tray_info_idx,
  4846. ", force color match" if forced else "",
  4847. )
  4848. # Build mapping array
  4849. if not comparisons:
  4850. return None
  4851. max_slot_id = max(c["slot_id"] for c in comparisons)
  4852. if max_slot_id <= 0:
  4853. return None
  4854. mapping = [-1] * max_slot_id
  4855. for c in comparisons:
  4856. slot_id = c["slot_id"]
  4857. if slot_id and slot_id > 0:
  4858. mapping[slot_id - 1] = c["global_tray_id"]
  4859. return mapping
  4860. def _mark_printer_dispatched(
  4861. self,
  4862. printer_id: int,
  4863. pre_state: str | None,
  4864. pre_subtask_id: str | None,
  4865. ) -> None:
  4866. """Record that a print command was just sent to ``printer_id``.
  4867. Held until either the watchdog observes a state/subtask transition
  4868. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4869. """
  4870. if not pre_state:
  4871. # No pre_state means we can't detect a transition — fall back to a
  4872. # pure time-based hold using empty string as a sentinel that won't
  4873. # match any real printer state.
  4874. pre_state = ""
  4875. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4876. def _release_dispatch_hold(self, printer_id: int) -> None:
  4877. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4878. self._dispatch_holds.pop(printer_id, None)
  4879. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4880. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4881. Returns False (and clears the hold) once any of these are true:
  4882. - hard timeout (``_dispatch_max_hold``) has elapsed
  4883. - the printer has transitioned out of pre_state and we're past the
  4884. minimum cooldown
  4885. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4886. past the minimum cooldown
  4887. Otherwise the printer is held — caller should treat it as busy.
  4888. """
  4889. entry = self._dispatch_holds.get(printer_id)
  4890. if not entry:
  4891. return False
  4892. started_at, pre_state, pre_subtask_id = entry
  4893. elapsed = time.monotonic() - started_at
  4894. if elapsed >= self._dispatch_max_hold:
  4895. self._dispatch_holds.pop(printer_id, None)
  4896. return False
  4897. # Without a pre_state we can't detect a transition — fall back to the
  4898. # min cooldown alone, then drop the hold.
  4899. if not pre_state:
  4900. if elapsed >= self._dispatch_min_cooldown:
  4901. self._dispatch_holds.pop(printer_id, None)
  4902. return False
  4903. return True
  4904. status = printer_manager.get_status(printer_id)
  4905. current_state = getattr(status, "state", None) if status else None
  4906. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4907. transitioned = (current_state is not None and current_state != pre_state) or (
  4908. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4909. )
  4910. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4911. self._dispatch_holds.pop(printer_id, None)
  4912. return False
  4913. return True
  4914. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4915. """Check if a printer is connected and idle."""
  4916. if not printer_manager.is_connected(printer_id):
  4917. logger.debug("Printer %d: not connected", printer_id)
  4918. return False
  4919. state = printer_manager.get_status(printer_id)
  4920. if not state:
  4921. logger.debug("Printer %d: no status available", printer_id)
  4922. return False
  4923. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4924. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4925. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4926. # printer, it boots back into IDLE with no memory of the previous finish; without
  4927. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4928. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4929. logger.debug(
  4930. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4931. printer_id,
  4932. state.state,
  4933. )
  4934. return False
  4935. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4936. if not idle:
  4937. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4938. return False
  4939. # A print would run from the SD card the firmware is being written to.
  4940. from backend.app.services.firmware_update import upload_in_progress
  4941. if upload_in_progress(printer_id):
  4942. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4943. return False
  4944. return True
  4945. @staticmethod
  4946. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4947. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4948. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4949. and that the fixed-printer branch has already found connected, so the two
  4950. offline cases answer at their own exits and never arrive here.
  4951. The default is the model-based branch's ``Busy:`` wording, which
  4952. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4953. the right answer for the connected-but-no-telemetry second or two after a
  4954. reconnect: the model-based branch has always reported it that way, and it
  4955. is not something to wake anybody up for.
  4956. A plate nobody has confirmed is the one case here that does not resolve
  4957. itself — somebody has to walk over to the printer — so it is worded as
  4958. itself and allowed to notify.
  4959. """
  4960. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4961. return f"Waiting for plate confirmation: {printer_name}"
  4962. return f"Busy: {printer_name}"
  4963. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4964. """Read a setting value from the database."""
  4965. result = await db.execute(select(Settings).where(Settings.key == key))
  4966. setting = result.scalar_one_or_none()
  4967. return setting.value if setting else None
  4968. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4969. """Read a boolean setting from the database."""
  4970. result = await db.execute(select(Settings).where(Settings.key == key))
  4971. setting = result.scalar_one_or_none()
  4972. if setting:
  4973. return setting.value.lower() == "true"
  4974. return default
  4975. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4976. """Read an int setting; falls back to default on missing/unparseable rows."""
  4977. result = await db.execute(select(Settings).where(Settings.key == key))
  4978. setting = result.scalar_one_or_none()
  4979. if setting and setting.value:
  4980. try:
  4981. return int(setting.value)
  4982. except ValueError:
  4983. pass
  4984. return default
  4985. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4986. """Get drying presets (user-configured or built-in defaults)."""
  4987. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4988. setting = result.scalar_one_or_none()
  4989. if setting and setting.value:
  4990. try:
  4991. presets = json.loads(setting.value)
  4992. if isinstance(presets, dict) and presets:
  4993. return presets
  4994. except json.JSONDecodeError:
  4995. pass
  4996. return self.DEFAULT_DRYING_PRESETS
  4997. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4998. """Per-filament humidity thresholds (#1605).
  4999. Returns the user-configured overrides map keyed by normalized filament
  5000. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  5001. unknown / unmapped types. Empty / unset → empty dict, in which case
  5002. callers fall back to ``ams_humidity_fair``.
  5003. """
  5004. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  5005. setting = result.scalar_one_or_none()
  5006. if not setting or not setting.value:
  5007. return {}
  5008. try:
  5009. data = json.loads(setting.value)
  5010. except json.JSONDecodeError:
  5011. return {}
  5012. if not isinstance(data, dict):
  5013. return {}
  5014. out: dict[str, int] = {}
  5015. for key, value in data.items():
  5016. try:
  5017. out[str(key).upper() if key != "default" else "default"] = int(value)
  5018. except (TypeError, ValueError):
  5019. continue
  5020. return out
  5021. # Materials whose AMS spelling differs from the key the tables above use.
  5022. # Bambu labels nylon "PA" while its own composites spell the family out, so
  5023. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  5024. # good PA row (#3067).
  5025. #
  5026. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  5027. # The drying popover has resolved these correctly since #2774 and the
  5028. # scheduler never did, which is exactly why #3067's reporter could dry a
  5029. # PA6-CF spool by hand while auto-drying skipped it every pass.
  5030. #
  5031. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  5032. # of nylon, so it is the one entry that is a judgement rather than a
  5033. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  5034. # way, and PA's row is the hottest the table has. Drying it there is closer
  5035. # to right than not drying it at all, which is what it got before.
  5036. FILAMENT_KEY_ALIASES: dict[str, str] = {
  5037. "NYLON": "PA",
  5038. "PA6": "PA",
  5039. "PA11": "PA",
  5040. "PA12": "PA",
  5041. "PAHT": "PA",
  5042. "PPA": "PA",
  5043. }
  5044. @classmethod
  5045. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  5046. """The key in *table* that answers for this tray's material, or None.
  5047. The printer reports the material in ``tray_type``, and it spells filled
  5048. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  5049. tables here are keyed by base material, so matching the raw string alone
  5050. found a row for 8 of the 41 types a printer can report and skipped the
  5051. rest -- silently, because every caller reads "no row" as "nothing to do
  5052. for this tray". Auto-drying therefore ignored every composite spool on
  5053. the install (#3067).
  5054. Exact match first, so a table the user has extended with a row of its
  5055. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  5056. base material's. Then the suffix is dropped, then the alias map above
  5057. answers for the polyamide spellings.
  5058. Returns None rather than a default: what to do with an unrecognised
  5059. material differs per caller, and only the caller knows whether "no row"
  5060. means skip the tray or fall back to a catch-all. Nothing here invents a
  5061. temperature for a material the table does not list.
  5062. """
  5063. raw = cls._normalize_filament_type(tray_type or "")
  5064. if not raw:
  5065. return None
  5066. for candidate in (raw, raw.split("-")[0]):
  5067. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  5068. if key in table:
  5069. return key
  5070. return None
  5071. @staticmethod
  5072. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  5073. """Resolve the effective humidity threshold for an AMS unit (#1605).
  5074. For mixed filament types loaded into one AMS, returns the most
  5075. restrictive (lowest) threshold across all loaded tray types — matches
  5076. the conservative-params strategy already used for drying temp/hours.
  5077. Empty / unloaded trays contribute no constraint. Unknown types use the
  5078. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  5079. when no per-type map is configured at all.
  5080. """
  5081. default = thresholds.get("default", fallback)
  5082. if not thresholds:
  5083. return fallback
  5084. candidates: list[int] = []
  5085. for tray in trays:
  5086. tray_type = str(tray.get("tray_type") or "").strip()
  5087. if not tray_type:
  5088. continue
  5089. # A composite carries its base material's threshold when it has no
  5090. # row of its own, the same way it takes its drying preset (#3067).
  5091. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  5092. candidates.append(thresholds[key] if key is not None else default)
  5093. if not candidates:
  5094. return default
  5095. return min(candidates)
  5096. def _get_conservative_drying_params(
  5097. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  5098. ) -> tuple[int, int, str] | None:
  5099. """Get the most conservative drying params for mixed filament types in an AMS unit.
  5100. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  5101. """
  5102. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  5103. hours_key = f"{temp_key}_hours"
  5104. min_temp = None
  5105. max_hours = None
  5106. filament_type = ""
  5107. for tray in trays:
  5108. tray_type = tray.get("tray_type", "")
  5109. if not tray_type:
  5110. continue
  5111. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  5112. # which is what stopped auto-drying on every composite spool (#3067).
  5113. base_type = self._resolve_filament_key(tray_type, presets)
  5114. if base_type is None:
  5115. continue
  5116. # The table is user-editable JSON with no per-row validation, so a
  5117. # row can be present and empty. That has always meant "skip this
  5118. # material", and it has to keep meaning it: the reads below fall
  5119. # back to 55C/12h per missing field, which is a temperature nobody
  5120. # chose and would deform a PLA spool.
  5121. preset = presets[base_type]
  5122. if not preset:
  5123. continue
  5124. temp = preset.get(temp_key, 55)
  5125. hours = preset.get(hours_key, 12)
  5126. # Conservative: lowest temp, longest duration
  5127. if min_temp is None or temp < min_temp:
  5128. min_temp = temp
  5129. if max_hours is None or hours > max_hours:
  5130. max_hours = hours
  5131. if not filament_type:
  5132. filament_type = base_type
  5133. if min_temp is None:
  5134. return None
  5135. return (min_temp, max_hours or 12, filament_type)
  5136. async def _check_filament_low(self, db: AsyncSession) -> None:
  5137. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  5138. ``on_filament_low`` has had a column, a schema field, a route, a template
  5139. and a UI toggle since the notification system was built, and no caller --
  5140. so the toggle could be switched on and could never fire. This is the
  5141. producer.
  5142. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  5143. ``low_stock_threshold_pct`` override is already exactly this decision:
  5144. already configurable, already surfaced, already driving the Inventory
  5145. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  5146. consulted -- it has been measured up to 56 points out against a scale,
  5147. which is not a number to page someone on.
  5148. Only slots with an assigned spool produce an event. A slot Bambuddy
  5149. cannot resolve to a spool has no remaining weight it can stand behind,
  5150. and guessing one is how the remain percentage would have got in.
  5151. """
  5152. from backend.app.models.spool import Spool
  5153. # Time-gated rather than run on every pass. run() sleeps
  5154. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  5155. # early-return path counts as productive while an upload is in flight
  5156. # (#2602), so an unthrottled check would re-read the whole spool
  5157. # collection every 3 seconds for the length of a batch drain. In
  5158. # Spoolman mode that is a request storm against a third-party service,
  5159. # which is the thing this producer's design note argues against; and
  5160. # when Spoolman is down, _get_with_retry burns ~16 s inside
  5161. # check_queue holding the scheduler's session, so the outage would
  5162. # throttle the print queue itself. A low spool is not a 3-second
  5163. # concern -- the idle interval is the natural resolution.
  5164. now = time.monotonic()
  5165. if now < self._filament_low_next_check:
  5166. return
  5167. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  5168. try:
  5169. # on_filament_low defaults to off on every provider, so on most
  5170. # installs nobody wants this alert. Without this the check would
  5171. # still read every assigned spool each interval -- the whole
  5172. # collection over HTTP in Spoolman mode -- for an event that is
  5173. # switched off. One query against the provider table settles it
  5174. # before any spool work, the same guard the bed-cooled waiter uses.
  5175. # No printer_id: this asks whether any provider wants the event at
  5176. # all; per-printer scoping is applied when the event is sent.
  5177. #
  5178. # While nobody wants it, no pass sees a slot go back above its
  5179. # threshold, so nothing can re-arm; a spool refilled under the same
  5180. # id in that time would stay silenced until a restart. Forgetting
  5181. # what was sent is right anyway: whoever switches the event back on
  5182. # is told about the spools that are low now.
  5183. #
  5184. # The MQTT relay publishes the same event, so a connected relay is
  5185. # reason enough to run the check. Its record is forgotten when the
  5186. # relay is switched off, not when the broker drops: a reconnect must
  5187. # not re-send every low slot.
  5188. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  5189. relay = mqtt_relay.enabled and mqtt_relay.connected
  5190. if not notify:
  5191. self._notified_filament_low.clear()
  5192. if not mqtt_relay.enabled:
  5193. self._relayed_filament_low.clear()
  5194. if not notify and not relay:
  5195. return
  5196. global_threshold = await self._get_low_stock_threshold(db)
  5197. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  5198. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  5199. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5200. if spoolman_on:
  5201. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  5202. else:
  5203. rows = (
  5204. await db.execute(
  5205. select(SpoolAssignment, Spool)
  5206. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  5207. # An archived spool is not stock. The Inventory page's
  5208. # Low Stock count skips them (InventoryPage.tsx:1089)
  5209. # and get_all_spools without allow_archived already
  5210. # excludes them in Spoolman mode, so without this the
  5211. # internal path is the only one that alerts on them.
  5212. .where(Spool.archived_at.is_(None))
  5213. )
  5214. ).all()
  5215. for assignment, spool in rows:
  5216. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  5217. if pct is None:
  5218. continue
  5219. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  5220. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  5221. pct,
  5222. threshold,
  5223. spool.color_name,
  5224. )
  5225. if not slots:
  5226. # Nothing resolvable this pass. Deliberately not clearing the
  5227. # notified set: a Spoolman that is briefly unreachable would
  5228. # otherwise re-alert on every spool as soon as it came back.
  5229. return
  5230. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  5231. except Exception as e:
  5232. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  5233. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  5234. """The global low-stock percentage, defaulting to the schema's 20.0."""
  5235. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  5236. if raw is None or raw.value is None:
  5237. return 20.0
  5238. try:
  5239. value = float(raw.value)
  5240. except (TypeError, ValueError):
  5241. return 20.0
  5242. return value if 0 < value <= 100 else 20.0
  5243. async def _filament_low_slots_spoolman(
  5244. self, db: AsyncSession, global_threshold: float
  5245. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  5246. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  5247. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  5248. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  5249. so the global threshold is the only one that applies here. That matches
  5250. what the Inventory page already does in this mode.
  5251. One ``get_all_spools`` call covers every slot rather than a request per
  5252. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  5253. without ``allow_archived`` -- which is the behaviour the internal path
  5254. has to ask for explicitly.
  5255. An unreachable Spoolman returns no slots rather than raising. It is an
  5256. ordinary state for a third-party service, not an error in this pass: the
  5257. caller's "nothing resolvable" branch already leaves the notified set
  5258. alone, which is exactly right here, whereas letting it reach the broad
  5259. ``except`` would write a full traceback every time the check runs.
  5260. """
  5261. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5262. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5263. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  5264. if not assignments:
  5265. return {}
  5266. client = await get_spoolman_client()
  5267. if client is None:
  5268. return {}
  5269. try:
  5270. all_spools = await client.get_all_spools()
  5271. except SpoolmanUnavailableError as e:
  5272. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  5273. return {}
  5274. by_id: dict[int, dict] = {}
  5275. for raw in all_spools:
  5276. raw_id = raw.get("id")
  5277. if isinstance(raw_id, int):
  5278. by_id[raw_id] = raw
  5279. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5280. for assignment in assignments:
  5281. raw = by_id.get(assignment.spoolman_spool_id)
  5282. if raw is None:
  5283. continue
  5284. try:
  5285. mapped = _map_spoolman_spool(raw)
  5286. except ValueError:
  5287. continue
  5288. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  5289. if pct is None:
  5290. continue
  5291. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  5292. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  5293. return slots
  5294. async def _emit_filament_low(
  5295. self,
  5296. db: AsyncSession,
  5297. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  5298. *,
  5299. notify: bool = True,
  5300. relay: bool = False,
  5301. ) -> None:
  5302. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  5303. printers: dict[int, Printer] = {}
  5304. for key, (pct, threshold, color) in slots.items():
  5305. printer_id, ams_id, tray_id, spool_id = key
  5306. if pct >= threshold:
  5307. # Back above the line: re-arm rather than expire on a timer, so a
  5308. # refilled slot can alert again and a spool sitting just under the
  5309. # threshold stays quiet.
  5310. self._notified_filament_low.discard(key)
  5311. self._relayed_filament_low.discard(key)
  5312. continue
  5313. send_notification = notify and key not in self._notified_filament_low
  5314. # Only while connected, so a crossing the relay missed reaches it
  5315. # after the reconnect.
  5316. send_relay = relay and key not in self._relayed_filament_low
  5317. if not send_notification and not send_relay:
  5318. continue
  5319. # Marked before sending, which is a choice rather than the only
  5320. # option, and it is the opposite failure mode from the one the
  5321. # debounce argues against: one transient provider failure loses this
  5322. # alert until the spool goes back above the threshold and crosses it
  5323. # again. Marking after a successful send would trade that for
  5324. # re-alerting on every pass while a provider is down -- which is the
  5325. # repetition the whole debounce exists to prevent, and the louder of
  5326. # the two failures. A spool that is low stays low, so the next real
  5327. # signal is not far away; a provider stuck retrying is a signal that
  5328. # never stops.
  5329. if send_notification:
  5330. self._notified_filament_low.add(key)
  5331. if send_relay:
  5332. self._relayed_filament_low.add(key)
  5333. if printer_id not in printers:
  5334. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5335. if printer is None:
  5336. continue
  5337. printers[printer_id] = printer
  5338. printer = printers[printer_id]
  5339. slot = _ams_slot_label(ams_id, tray_id, printer_tray_layout(printer_id, printer_manager))
  5340. if send_notification:
  5341. try:
  5342. await notification_service.on_filament_low(
  5343. printer_id,
  5344. printer.name,
  5345. slot,
  5346. int(pct),
  5347. db,
  5348. color=color,
  5349. )
  5350. except Exception as e:
  5351. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5352. if send_relay:
  5353. try:
  5354. await mqtt_relay.on_filament_low(
  5355. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5356. )
  5357. except Exception as e:
  5358. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5359. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5360. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5361. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5362. a schema field, a template and a UI toggle, and nothing that computes the
  5363. condition -- the Forecast panel does it in the browser, so with no page
  5364. open nothing could ever alert. This runs the same arithmetic
  5365. (``stock_forecast``) from the scheduler loop.
  5366. An alert is sent when a SKU *moves into* a condition, once, and again
  5367. after the condition has cleared. A SKU that worsens from reorder to break
  5368. alerts again as a break, because the panel treats the two as exclusive; one
  5369. that eases from break back to reorder does not alert again.
  5370. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5371. while it is still low tells you.
  5372. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5373. loop runs every 3 s while an upload is in flight, and the whole spool
  5374. collection is read over HTTP in Spoolman mode. Both events default to off
  5375. on every provider, so nothing is read unless a provider wants one.
  5376. """
  5377. now = time.monotonic()
  5378. if now < self._stock_forecast_next_check:
  5379. return
  5380. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5381. try:
  5382. if self._stock_alerts_persisted is None:
  5383. await self._load_stock_alerts(db)
  5384. wanted = {
  5385. "reorder": bool(
  5386. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5387. ),
  5388. "break": bool(
  5389. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5390. ),
  5391. }
  5392. if not any(wanted.values()):
  5393. # Nobody wants either event. Forget what was sent, so whoever
  5394. # switches one on is told about the SKUs that are low now.
  5395. self._notified_stock_alerts.clear()
  5396. await self._save_stock_alerts(db)
  5397. return
  5398. forecasts = await self._stock_forecasts(db)
  5399. if forecasts is None:
  5400. # Spoolman unreachable. Deliberately not clearing the notified
  5401. # set: a brief outage would otherwise re-alert every SKU when it
  5402. # came back.
  5403. return
  5404. await self._emit_stock_alerts(db, forecasts, wanted)
  5405. await self._save_stock_alerts(db)
  5406. except Exception as e:
  5407. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5408. def _serialize_stock_alerts(self) -> str:
  5409. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5410. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5411. return json.dumps(rows)
  5412. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5413. """Read the notified set saved by the last run, once per process.
  5414. A missing or unreadable row is an empty set: the worst that does is one
  5415. repeat of what a restart used to cause every time.
  5416. """
  5417. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5418. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5419. if raw and raw.value:
  5420. try:
  5421. for key, kind, events in json.loads(raw.value):
  5422. if len(key) == 4 and kind in ("reorder", "break"):
  5423. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5424. except (ValueError, TypeError):
  5425. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5426. loaded = {}
  5427. self._notified_stock_alerts = loaded
  5428. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5429. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5430. """Write the notified set to its settings row if it changed since it was last read or written."""
  5431. serialized = self._serialize_stock_alerts()
  5432. if serialized == self._stock_alerts_persisted:
  5433. return
  5434. from backend.app.core.db_dialect import upsert_setting
  5435. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5436. await db.commit()
  5437. self._stock_alerts_persisted = serialized
  5438. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5439. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5440. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5441. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5442. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5443. sku_settings = {
  5444. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5445. lead_time_days=row.lead_time_days,
  5446. safety_margin_value=row.safety_margin_value,
  5447. safety_margin_unit=row.safety_margin_unit,
  5448. alerts_snoozed=bool(row.alerts_snoozed),
  5449. )
  5450. for row in sku_rows
  5451. }
  5452. if await self._get_bool_setting(db, "spoolman_enabled"):
  5453. spools = await self._stock_spools_spoolman()
  5454. if spools is None:
  5455. return None
  5456. # The Spoolman spools' own rows (#3407), keyed by Spoolman id. Never
  5457. # the built-in ones: a Spoolman id that matches a local spool id
  5458. # (left over from before Spoolman was switched on) would borrow an
  5459. # unrelated spool's history (#3406).
  5460. history = await self._stock_usage_history(db, spoolman=True)
  5461. history = {
  5462. spool.id: stock_forecast.own_records(spool, history[spool.id])
  5463. for spool in spools
  5464. if spool.id in history
  5465. }
  5466. else:
  5467. spools = await self._stock_spools_internal(db)
  5468. history = await self._stock_usage_history(db)
  5469. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5470. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5471. from backend.app.models.spool import Spool
  5472. # Every spool: stock, the recently archived ones that count towards the
  5473. # rate, and the older ones that tell it the SKU was in use before its
  5474. # window (#3407). stock_forecast.forecast_all sorts them.
  5475. rows = (await db.execute(select(Spool))).scalars().all()
  5476. return [
  5477. stock_forecast.StockSpool(
  5478. id=spool.id,
  5479. material=spool.material,
  5480. subtype=spool.subtype,
  5481. brand=spool.brand,
  5482. color_name=spool.color_name,
  5483. label_weight=float(spool.label_weight or 0),
  5484. weight_used=float(spool.weight_used or 0),
  5485. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5486. created_at=spool.created_at,
  5487. archived_at=spool.archived_at,
  5488. last_used_at=spool.last_used,
  5489. )
  5490. for spool in rows
  5491. ]
  5492. async def _stock_usage_history(
  5493. self, db: AsyncSession, *, spoolman: bool = False
  5494. ) -> dict[int, list[stock_forecast.UsageRecord]]:
  5495. """Usage rows by spool id, for one inventory: its own ids, as the forecast
  5496. panel reads them from the usage endpoint."""
  5497. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5498. spool_id = SpoolUsageHistory.spoolman_spool_id if spoolman else SpoolUsageHistory.spool_id
  5499. rows = (
  5500. await db.execute(
  5501. select(spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5502. .where(
  5503. SpoolUsageHistory.spoolman_spool_id.is_not(None)
  5504. if spoolman
  5505. else SpoolUsageHistory.spoolman_spool_id.is_(None)
  5506. )
  5507. .order_by(SpoolUsageHistory.created_at.desc())
  5508. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5509. )
  5510. ).all()
  5511. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5512. for spool_id, created_at, weight_used in rows:
  5513. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5514. # filtered before the limit, so the window matches the forecast panel's.
  5515. if created_at is None or spool_id is None:
  5516. continue
  5517. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5518. return history
  5519. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5520. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5521. Archived ones too: a recently used-up spool counts towards its SKU's
  5522. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5523. page (and so the panel) reads; it dates archiving by the spool's last
  5524. use, as Spoolman records no archive date.
  5525. """
  5526. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5527. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5528. client = await get_spoolman_client()
  5529. if client is None:
  5530. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5531. return None
  5532. try:
  5533. raw_spools = await client.get_all_spools(allow_archived=True)
  5534. except SpoolmanUnavailableError as e:
  5535. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5536. return None
  5537. spools: list[stock_forecast.StockSpool] = []
  5538. for raw in raw_spools:
  5539. try:
  5540. mapped = _map_spoolman_spool(raw)
  5541. except ValueError:
  5542. continue
  5543. created_at = _spoolman_time(mapped.get("created_at"))
  5544. archived_at = None
  5545. if raw.get("archived"):
  5546. # Archived without a date to tell when: not stock, and too old to
  5547. # count towards the rate.
  5548. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5549. spools.append(
  5550. stock_forecast.StockSpool(
  5551. id=mapped["id"],
  5552. material=mapped["material"],
  5553. subtype=mapped.get("subtype"),
  5554. brand=mapped.get("brand"),
  5555. color_name=mapped.get("color_name"),
  5556. label_weight=float(mapped.get("label_weight") or 0),
  5557. weight_used=float(mapped.get("weight_used") or 0),
  5558. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5559. created_at=created_at,
  5560. archived_at=archived_at,
  5561. first_used_at=_spoolman_time(mapped.get("first_used")),
  5562. last_used_at=_spoolman_time(mapped.get("last_used")),
  5563. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5564. )
  5565. )
  5566. return spools
  5567. async def _emit_stock_alerts(
  5568. self,
  5569. db: AsyncSession,
  5570. forecasts: stock_forecast.ForecastMap,
  5571. wanted: dict[str, bool],
  5572. ) -> None:
  5573. """Send the notifications for each SKU that has moved into a stock alert condition.
  5574. A SKU in break has also reached its reorder point, so both events apply to
  5575. it: the break event goes to providers that have it on, and the reorder event
  5576. to the providers that have only that one on. A provider with both on gets the
  5577. break and no second message.
  5578. What is remembered per SKU is the condition and which events had a
  5579. subscriber when it was sent. An event with no subscriber is forgotten, so
  5580. switching it on later reports the SKUs already in that condition.
  5581. """
  5582. active_events = {event for event, on in wanted.items() if on}
  5583. for key, (forecast, spool) in forecasts.items():
  5584. kind: str | None = None
  5585. if not forecast.snoozed:
  5586. if forecast.stock_break_alert:
  5587. kind = "break"
  5588. elif forecast.reorder_alert:
  5589. kind = "reorder"
  5590. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5591. events = applicable & active_events
  5592. if not events:
  5593. self._notified_stock_alerts.pop(key, None)
  5594. continue
  5595. previous = self._notified_stock_alerts.get(key)
  5596. told = (previous[1] & active_events) if previous else frozenset()
  5597. # Trimmed to the events this condition can send. That is what makes easing from
  5598. # break back to reorder silent (the reorder event was told with the break) and
  5599. # worsening again news again (the break event is no longer remembered).
  5600. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5601. # Recorded before sending, for the reason _emit_filament_low gives: a
  5602. # provider that is down should lose this alert, not repeat it every hour.
  5603. to_send = events - told
  5604. # Both flags imply a positive rate and so a day count.
  5605. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5606. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5607. color = None if spool.color_name_is_synthesized else spool.color_name
  5608. try:
  5609. if "break" in to_send:
  5610. await notification_service.on_stock_break_alert(
  5611. spool.material,
  5612. spool.brand,
  5613. forecast.remaining_g,
  5614. rate,
  5615. days_left,
  5616. forecast.effective_lead_time_days,
  5617. db,
  5618. subtype=spool.subtype,
  5619. color=color,
  5620. )
  5621. if "reorder" in to_send:
  5622. await notification_service.on_stock_reorder_alert(
  5623. spool.material,
  5624. spool.brand,
  5625. forecast.remaining_g,
  5626. rate,
  5627. days_left,
  5628. db,
  5629. subtype=spool.subtype,
  5630. color=color,
  5631. skip_break_subscribers=kind == "break",
  5632. )
  5633. except Exception as e:
  5634. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5635. # A SKU with no spools left is no longer alerting.
  5636. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5637. del self._notified_stock_alerts[key]
  5638. @staticmethod
  5639. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5640. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5641. from backend.app.core.auth import is_auth_enabled
  5642. if user_id is None or not await is_auth_enabled(db):
  5643. return ALL_PRINTERS
  5644. return await resolve_user_id_printer_scope(db, user_id)
  5645. async def _model_job_printer_ids(
  5646. self,
  5647. db: AsyncSession,
  5648. item: PrintQueueItem,
  5649. scope: PrinterScope,
  5650. cache: dict[tuple[str, str | None, int | None], set[int]],
  5651. ) -> set[int]:
  5652. """Every printer an "Any <model>" job could land on: the active printers
  5653. of each of its candidate models, in its location, that its creator may use.
  5654. ``cache`` holds one lookup per model, location and creator for the pass,
  5655. so a long queue of model jobs does not query once per job.
  5656. A printer whose last known nozzle cannot print the file is left out
  5657. (#3536): the job stays pending there, so it must not hold drying off."""
  5658. printer_ids: set[int] = set()
  5659. for candidate in _candidates_for(item):
  5660. if not candidate.target_model:
  5661. continue
  5662. key = (candidate.target_model, item.target_location, item.created_by_id)
  5663. if key not in cache:
  5664. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5665. cache[key] = {printer.id for printer in printers}
  5666. # #3536: a job with no fitting nozzle now stays pending instead of
  5667. # failing at once, so it must not count for a printer whose last
  5668. # known nozzle cannot print it (it would block or trigger drying
  5669. # there for good). Unknown nozzle fits (fail-safe). The cache stays
  5670. # per model; the filter runs per candidate, not per cache entry.
  5671. printer_ids |= {
  5672. pid
  5673. for pid in cache[key]
  5674. if _wrong_nozzle_label("", printer_manager.get_status(pid), candidate.sliced_nozzle) is None
  5675. }
  5676. return printer_ids
  5677. async def _check_auto_drying(
  5678. self,
  5679. db: AsyncSession,
  5680. queue_items: list[PrintQueueItem],
  5681. dispatching_printers: set[int],
  5682. ):
  5683. """Start drying on idle printers based on humidity.
  5684. Three modes (can all be enabled independently):
  5685. - queue_drying_enabled: Dry between scheduled queue prints
  5686. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5687. - print_drying_enabled: Also evaluate printers that are currently printing,
  5688. when model+firmware supports "Print While Drying" (gated by
  5689. supports_drying_while_printing). Drying temperature is capped at
  5690. max(40, preset_temp - 5) to protect spools mid-print.
  5691. """
  5692. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5693. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5694. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5695. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5696. # The wait belongs to ambient drying: the settings UI only shows it while
  5697. # ambient drying is on, so a value left behind when ambient is turned off
  5698. # must not keep delaying the one path that still reaches the wait gate
  5699. # without it (a mid-print start under print_drying).
  5700. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5701. # Clear every streak as soon as the wait is inactive. An early return (or
  5702. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5703. # a quick toggle-on inherit an old streak.
  5704. if not sustained_wait_active:
  5705. self._auto_dry_above.clear()
  5706. if not queue_drying_enabled and not ambient_drying_enabled:
  5707. # Stop active drying on all printers if both features disabled
  5708. if self._drying_in_progress:
  5709. for pid in list(self._drying_in_progress):
  5710. if pid in self._scheduled_drying_printer_ids:
  5711. continue
  5712. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5713. await self._stop_drying(pid)
  5714. return
  5715. # Update drying state from printer status (handles backend restart)
  5716. self._sync_drying_state()
  5717. # Find printers with scheduled items (for queue drying mode)
  5718. # An "Any <model>" job counts for every printer it could land on.
  5719. printers_with_scheduled: set[int] = set()
  5720. # Printers with a job that could start now: the ones block mode keeps
  5721. # a new cycle off. A job waiting for its start time is what queue
  5722. # drying dries ahead of.
  5723. printers_with_ready_items: set[int] = set()
  5724. now_utc = datetime.now(timezone.utc)
  5725. creator_scopes: dict[int | None, PrinterScope] = {}
  5726. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5727. for item in queue_items:
  5728. if item.printer_id:
  5729. item_printers = {item.printer_id}
  5730. elif item.target_model or item.variants:
  5731. if item.created_by_id not in creator_scopes:
  5732. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5733. item_printers = await self._model_job_printer_ids(
  5734. db, item, creator_scopes[item.created_by_id], model_printers
  5735. )
  5736. else:
  5737. continue
  5738. if item.scheduled_time and not item.manual_start:
  5739. printers_with_scheduled |= item_printers
  5740. sched = item.scheduled_time
  5741. if sched is not None and sched.tzinfo is None:
  5742. sched = sched.replace(tzinfo=timezone.utc)
  5743. if sched is None or sched <= now_utc:
  5744. printers_with_ready_items |= item_printers
  5745. # If only queue mode is on and no printers have scheduled items, stop drying
  5746. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5747. # may still be eligible for mid-print drying regardless of queue state).
  5748. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5749. for pid in list(self._drying_in_progress):
  5750. if pid in self._scheduled_drying_printer_ids:
  5751. continue
  5752. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5753. await self._stop_drying(pid)
  5754. return
  5755. # Get humidity threshold (global fallback)
  5756. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5757. setting = result.scalar_one_or_none()
  5758. global_humidity_threshold = int(setting.value) if setting else 60
  5759. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5760. # to the global threshold for every AMS unit.
  5761. per_type_thresholds = await self._get_humidity_thresholds(db)
  5762. # Get drying presets
  5763. presets = await self._get_drying_presets(db)
  5764. # Determine if drying should be skipped for printers with pending items
  5765. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5766. # Get all active printers
  5767. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5768. for printer in all_printers.scalars():
  5769. pid = printer.id
  5770. # Resolve model+firmware up front — needed to decide whether this printer
  5771. # qualifies for mid-print drying (busy printer on capable hardware).
  5772. state = printer_manager.get_status(pid)
  5773. if not state:
  5774. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5775. continue
  5776. model = printer_manager.get_model(pid)
  5777. firmware = state.firmware_version
  5778. # "Mid-print" has to mean the printer is actually printing (#2801).
  5779. # It used to be inferred from the dispatch set, which also holds
  5780. # printers that merely could not be dispatched to -- so a printer
  5781. # sitting in FINISH behind an unacknowledged plate was treated as
  5782. # printing, had its drying temperature capped by the mid-print
  5783. # spool protection, and was logged as (mid-print) while idle.
  5784. is_printing = state.state in _ACTIVE_PRINT_STATES
  5785. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5786. # A printer whose print is running or imminent is left alone unless
  5787. # it can dry through it. `dispatching_printers` is deliberately the
  5788. # narrow set: running, held post-dispatch, or mid-upload.
  5789. if (is_printing or pid in dispatching_printers) and not mid_print:
  5790. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5791. continue
  5792. if not mid_print:
  5793. # In queue-only mode, only dry printers that have scheduled prints
  5794. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5795. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5796. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5797. await self._stop_drying(pid)
  5798. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5799. continue
  5800. # When block mode is on, don't START new drying on printers with
  5801. # a job that could start now: the cycle would hold it. One
  5802. # scheduled for later may pre-dry; if the cycle is still running
  5803. # at its time, the hold applies then. Already-drying printers go
  5804. # through so humidity auto-stop logic still runs.
  5805. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5806. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5807. continue
  5808. if not printer_manager.is_connected(pid):
  5809. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5810. continue
  5811. # Plate-clear is deliberately ignored here (#2801). It answers
  5812. # "is the bed ready for the next job", which says nothing about
  5813. # whether the AMS may heat -- and the gap between a finished print
  5814. # and the acknowledgment is exactly when drying is most useful,
  5815. # because the printer is free and nobody is waiting on it. Leaving
  5816. # the plate unacknowledged is also how people hold the queue by
  5817. # hand, and that hold should not cost them their drying.
  5818. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5819. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5820. continue
  5821. # Check drying capability. For mid-print path, supports_drying_while_printing
  5822. # was already verified when computing mid_print above.
  5823. if not mid_print and not supports_drying(model, firmware):
  5824. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5825. continue
  5826. # Check each AMS unit from raw_data
  5827. ams_list = state.raw_data.get("ams", [])
  5828. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5829. for ams_data in ams_list:
  5830. module_type = str(ams_data.get("module_type") or "")
  5831. ams_id = int(ams_data.get("id", 0))
  5832. # Only n3f/n3s support drying
  5833. if module_type not in ("n3f", "n3s"):
  5834. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5835. continue
  5836. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5837. # Most-restrictive of all loaded tray types; falls back to the
  5838. # global threshold when no overrides are configured.
  5839. trays = ams_data.get("tray", []) or []
  5840. humidity_threshold = self.resolve_humidity_threshold(
  5841. trays, per_type_thresholds, global_humidity_threshold
  5842. )
  5843. dry_time = int(ams_data.get("dry_time") or 0)
  5844. # Read humidity as a percentage. The 1-5 index is never
  5845. # substituted: it is inverted, and being unable to exceed any
  5846. # threshold it would read as "dry" forever (#3140). ``None``
  5847. # already means "skip this unit" everywhere below.
  5848. humidity_pct = ams_humidity_percent(ams_data)
  5849. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5850. unit_key = (pid, ams_id)
  5851. unit_state = self._auto_dry_units.get(unit_key)
  5852. # Already drying — let it run to its configured duration (#1892).
  5853. #
  5854. # We deliberately do NOT stop drying from a humidity re-check here.
  5855. # Relative humidity drops steeply in heated air, so the AMS sensor
  5856. # reads ~15-20% within minutes of the dryer starting even while the
  5857. # filament is still saturated. A humidity-based early-stop therefore
  5858. # always fires at the minimum-time floor, truncating both user-started
  5859. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5860. # The firmware stops when the configured duration elapses; scheduling
  5861. # stops (print takes priority, queue no longer needs drying) are
  5862. # handled separately via _stop_drying().
  5863. #
  5864. # A parked countdown is not a running cycle (#3478): the firmware
  5865. # took the command and left the heater off, so dry_time sits at
  5866. # its full duration and never reaches 0 on its own. Treating it
  5867. # as running blocked auto-drying on that unit for days. A sample
  5868. # the stall detector has not classified yet (its first 150 s)
  5869. # still counts as running.
  5870. parked = is_countdown_parked(ams_data)
  5871. if dry_time > 0 and not parked:
  5872. if pid not in self._drying_in_progress:
  5873. # Drying we didn't start (manual or from before restart) —
  5874. # track it so scheduling stops still apply; never auto-stop it.
  5875. self._drying_in_progress[pid] = time.monotonic()
  5876. if unit_state is not None:
  5877. unit_state["running"] = True
  5878. logger.debug(
  5879. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5880. pid,
  5881. ams_id,
  5882. dry_time,
  5883. humidity,
  5884. )
  5885. continue
  5886. # Nothing is drying. Close out a cycle we armed ourselves and
  5887. # judge whether it achieved anything (#2770).
  5888. #
  5889. # "Achieved anything" is measured against the LOWEST reading any
  5890. # cycle on this unit has ended at, not against the threshold and
  5891. # not against the previous cycle. A spool that is genuinely wet
  5892. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5893. # allowed to keep going for as long as it is still coming down,
  5894. # however far it still is from the threshold. What must not
  5895. # continue is a cycle that ends exactly where the last one did,
  5896. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5897. # Comparing against the running minimum rather than the previous
  5898. # end is what stops a sensor oscillating by one point between two
  5899. # values from reading as progress every other cycle.
  5900. if unit_state is not None and unit_state.pop("running", False):
  5901. unit_state["ended_at"] = time.monotonic()
  5902. # The streak that armed this cycle is spent; the next one
  5903. # starts fresh (and accumulates through the re-arm cooldown
  5904. # below, so the wait overlaps the cooldown, never stacks on
  5905. # top of it).
  5906. self._auto_dry_above.pop(unit_key, None)
  5907. if parked:
  5908. # The timer stood still (never started, or paused by the
  5909. # power limit or the print), so the cycle says nothing
  5910. # about humidity: count it apart from the unproductive
  5911. # cycles below (#3478).
  5912. never_heated = _never_heated(unit_state) + 1
  5913. unit_state["never_heated"] = never_heated
  5914. logger.warning(
  5915. "Auto-drying: printer %d AMS %d — drying cycle not running: the timer stands "
  5916. "still at %dm with the status Off, %d in a row",
  5917. pid,
  5918. ams_id,
  5919. dry_time,
  5920. never_heated,
  5921. )
  5922. else:
  5923. # A cycle that counted down ran; the parked streak is over.
  5924. unit_state.pop("never_heated", None)
  5925. if not parked and humidity is not None and humidity > humidity_threshold:
  5926. best = unit_state.get("best_end_humidity")
  5927. if isinstance(best, int) and humidity < best:
  5928. # Still coming down. Keep going, however far the
  5929. # threshold still is.
  5930. unproductive = 0
  5931. else:
  5932. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5933. if not isinstance(best, int) or humidity < best:
  5934. unit_state["best_end_humidity"] = humidity
  5935. unit_state["unproductive"] = unproductive
  5936. logger.info(
  5937. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5938. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5939. pid,
  5940. ams_id,
  5941. humidity,
  5942. humidity_threshold,
  5943. unit_state.get("best_end_humidity"),
  5944. unproductive,
  5945. )
  5946. # A cycle that ended at or below the threshold needs no
  5947. # counter reset here: the branch below drops the whole entry.
  5948. # Humidity below threshold — no need to start drying. This is
  5949. # also the only thing that lifts a suspension: the reading we
  5950. # gave up on has come down, so auto-drying works again and the
  5951. # unit goes back to having no history at all.
  5952. if humidity is None or humidity <= humidity_threshold:
  5953. if unit_state is not None and unit_state.get("suspended"):
  5954. logger.info(
  5955. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5956. "threshold, resuming automatic drying",
  5957. pid,
  5958. ams_id,
  5959. humidity,
  5960. humidity_threshold,
  5961. )
  5962. # Clear the judgement, keep the clock (#2801). Dropping the
  5963. # whole entry also dropped `ended_at`, and with it the
  5964. # 30-minute cooldown -- so a reading that dips to the
  5965. # threshold as the AMS cools and comes back above it once
  5966. # warm wiped its own history and re-armed immediately. That
  5967. # oscillation is the very thing #2770's cooldown exists to
  5968. # ride out, and it is worst at exactly the margin that makes
  5969. # a unit dry repeatedly: a point or two above the threshold.
  5970. if unit_state is not None:
  5971. unit_state.pop("suspended", None)
  5972. unit_state.pop("unproductive", None)
  5973. unit_state.pop("best_end_humidity", None)
  5974. unit_state.pop("never_heated", None)
  5975. # A real below-threshold reading ends any sustained-wait
  5976. # streak (#2518) -- "continuously above" means exactly that.
  5977. # An absent reading (humidity is None) is no-information and
  5978. # leaves the streak alone; the observation-gap guard handles
  5979. # a prolonged sensor silence.
  5980. if humidity is not None:
  5981. _above = self._auto_dry_above.pop(unit_key, None)
  5982. if _above is not None and sustained_wait_active:
  5983. logger.info(
  5984. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5985. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5986. pid,
  5987. ams_id,
  5988. humidity,
  5989. time.monotonic() - _above["since"],
  5990. sustained_minutes,
  5991. humidity_threshold,
  5992. )
  5993. logger.debug(
  5994. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5995. pid,
  5996. ams_id,
  5997. humidity,
  5998. humidity_threshold,
  5999. )
  6000. continue
  6001. # Sustained-humidity streak (#2518): updated on every pass that
  6002. # observes the reading above the threshold, BEFORE the
  6003. # suspension/cooldown gates below -- a suspended or cooling-down
  6004. # unit still accumulates streak time, so the wait overlaps those
  6005. # gates instead of stacking after them. Inert when the feature
  6006. # is off: no entries are written, and an entry left over from a
  6007. # toggle-off is dropped so it cannot seed a stale streak later.
  6008. if sustained_wait_active:
  6009. _now = time.monotonic()
  6010. # Four missed scheduler passes, floored: a single slow pass
  6011. # must not void a streak, but the ceiling has to scale with
  6012. # the cadence or a slow loop silently restarts every streak.
  6013. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  6014. _above = self._auto_dry_above.get(unit_key)
  6015. if _above is None:
  6016. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  6017. elif _now - _above["last"] > _gap_ceiling:
  6018. # Restart, and say so at the same level as the dip
  6019. # reset: a silent restart voids the streak invisibly,
  6020. # and a user who set a long wait and never gets a dry
  6021. # has no way to see why.
  6022. logger.info(
  6023. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  6024. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  6025. pid,
  6026. ams_id,
  6027. _now - _above["last"],
  6028. _gap_ceiling,
  6029. sustained_minutes,
  6030. )
  6031. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  6032. else:
  6033. _above["last"] = _now
  6034. else:
  6035. self._auto_dry_above.pop(unit_key, None)
  6036. if unit_state is not None:
  6037. if unit_state.get("suspended"):
  6038. logger.debug(
  6039. "Auto-drying: printer %d AMS %d skipped — suspended until humidity is back at "
  6040. "or below the %d%% threshold",
  6041. pid,
  6042. ams_id,
  6043. humidity_threshold,
  6044. )
  6045. continue
  6046. never_heated = _never_heated(unit_state)
  6047. if never_heated >= AUTO_DRY_MAX_NEVER_HEATED_CYCLES:
  6048. unit_state["suspended"] = True
  6049. logger.warning(
  6050. "Auto-drying: printer %d AMS %d — suspending automatic drying. The printer "
  6051. "accepted %d drying commands in a row, but each time the timer stood still and "
  6052. "the unit did not heat. Clear the timer with Stop on the printer card and check "
  6053. "the AMS power; automatic drying resumes once humidity is back at or below the "
  6054. "%d%% threshold.",
  6055. pid,
  6056. ams_id,
  6057. never_heated,
  6058. humidity_threshold,
  6059. )
  6060. await self._notify_auto_drying_suspended(
  6061. db, printer, ams_id, humidity, humidity_threshold, never_heated, never_heated=True
  6062. )
  6063. continue
  6064. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  6065. unit_state["suspended"] = True
  6066. logger.warning(
  6067. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  6068. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  6069. "higher while it is warm, so a threshold in that range can never be reached and "
  6070. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  6071. pid,
  6072. ams_id,
  6073. int(unit_state.get("unproductive", 0)),
  6074. humidity,
  6075. humidity_threshold,
  6076. )
  6077. await self._notify_auto_drying_suspended(
  6078. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  6079. )
  6080. continue
  6081. ended_at = unit_state.get("ended_at")
  6082. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  6083. logger.debug(
  6084. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  6085. "cycle before the humidity reading is worth acting on",
  6086. pid,
  6087. ams_id,
  6088. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  6089. )
  6090. continue
  6091. # Check cannot-dry reasons (power constraints etc.). Sits
  6092. # ahead of the sustained wait so a unit the firmware refuses
  6093. # to dry never logs a wait it was never going to cash in.
  6094. sf_reasons = ams_data.get("dry_sf_reason", [])
  6095. if sf_reasons:
  6096. logger.debug(
  6097. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  6098. pid,
  6099. ams_id,
  6100. sf_reasons,
  6101. )
  6102. continue
  6103. # Sustained-humidity wait (#2518): ambient-triggered starts
  6104. # wait; only a printer with a scheduled queue item pending
  6105. # keeps the instant behavior, because that drying has a real
  6106. # deadline. Mid-print is deliberately NOT exempt while ambient
  6107. # drying is on: a humidity start on a printer that happens to be
  6108. # printing is as vulnerable to a lid-open spike as one on an idle
  6109. # printer (proven live: a 2-point threshold crossing mid-print
  6110. # bought a parked 12h command). Inactive when ambient drying is
  6111. # off: print_drying then still starts mid-print cycles on its own
  6112. # (#1816, "regardless of queue state"), and those stay instant.
  6113. if sustained_wait_active and pid not in printers_with_scheduled:
  6114. _above = self._auto_dry_above.get(unit_key)
  6115. _waited = time.monotonic() - _above["since"] if _above else 0.0
  6116. if _waited < sustained_minutes * 60:
  6117. logger.debug(
  6118. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  6119. "threshold for %.0fs of the required %dm",
  6120. pid,
  6121. ams_id,
  6122. humidity,
  6123. humidity_threshold,
  6124. _waited,
  6125. sustained_minutes,
  6126. )
  6127. continue
  6128. # Get conservative drying params for mixed filaments
  6129. params = self._get_conservative_drying_params(trays, module_type, presets)
  6130. if not params:
  6131. logger.debug(
  6132. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  6133. )
  6134. continue
  6135. temp, duration_hours, filament_type = params
  6136. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  6137. # "drying temperature must not exceed the filament's softening temperature"
  6138. # for Print While Drying). Floor at 40 degC — below that the dryer is
  6139. # ineffective and firmware will reject anyway.
  6140. if mid_print:
  6141. temp = max(40, temp - 5)
  6142. # Start drying
  6143. logger.info(
  6144. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  6145. "starting %s drying at %d°C for %dh%s",
  6146. pid,
  6147. ams_id,
  6148. humidity,
  6149. humidity_threshold,
  6150. filament_type,
  6151. temp,
  6152. duration_hours,
  6153. " (mid-print)" if mid_print else "",
  6154. )
  6155. success = printer_manager.send_drying_command(
  6156. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  6157. )
  6158. if success:
  6159. self._drying_in_progress[pid] = time.monotonic()
  6160. armed = self._auto_dry_units.setdefault(
  6161. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  6162. )
  6163. armed["running"] = True
  6164. async def _notify_auto_drying_suspended(
  6165. self,
  6166. db: AsyncSession,
  6167. printer: Printer,
  6168. ams_id: int,
  6169. humidity: int,
  6170. threshold: int,
  6171. cycles: int,
  6172. *,
  6173. never_heated: bool = False,
  6174. ) -> None:
  6175. """Tell the user auto-drying has given up on one AMS unit (#2770).
  6176. ``never_heated`` picks the message for cycles the printer accepted but
  6177. never ran (#3478) instead of cycles that left humidity high.
  6178. Fires once per suspension — the caller sets ``suspended`` before calling
  6179. and every later pass short-circuits on it — because the whole point is
  6180. that Bambuddy has stopped acting. Somebody whose printer sits in another
  6181. building needs that to reach them, and the hourly humidity alarm they
  6182. are already getting says the opposite of what happened here.
  6183. Never raises: a notification provider being down must not stop the
  6184. suspension itself from taking effect.
  6185. """
  6186. ams_label = unit_label(ams_id, printer_tray_layout(printer.id, printer_manager).ams_type(ams_id))
  6187. try:
  6188. await notification_service.on_ams_drying_suspended(
  6189. printer.id,
  6190. printer.name,
  6191. ams_label,
  6192. float(humidity),
  6193. float(threshold),
  6194. cycles,
  6195. db,
  6196. never_heated=never_heated,
  6197. )
  6198. except Exception as e:
  6199. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  6200. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  6201. """Stop judging the drying cycle currently on this AMS unit (#2770).
  6202. The unproductive-cycle counter exists to notice that *drying* is not
  6203. moving the humidity reading. A cycle that ended because somebody sent a
  6204. stop says nothing about that — it was cut short before it had a chance —
  6205. so counting it would suspend auto-drying for a reason that has nothing to
  6206. do with the loop the counter is there to break.
  6207. Two callers, both of them a stop Bambuddy is responsible for: the
  6208. print-takes-priority stop below, and the manual Stop button. Left
  6209. uncalled, an install that dries between queue jobs would suspend its own
  6210. auto-drying after two prints interrupted a dry — exactly the install
  6211. queue-drying exists for.
  6212. The rest of the unit's history is kept: the cooldown before re-arming
  6213. still applies, and an earlier count still stands.
  6214. """
  6215. state = self._auto_dry_units.get((printer_id, ams_id))
  6216. if state is not None:
  6217. state.pop("running", None)
  6218. state["ended_at"] = time.monotonic()
  6219. # A stopped cycle spends the streak that armed it, same as a completed
  6220. # one (#2518).
  6221. self._auto_dry_above.pop((printer_id, ams_id), None)
  6222. def _sync_drying_state(self):
  6223. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  6224. One direction only: it prunes, it never adds. A printer drying without an
  6225. entry here — because the user started the cycle from Studio, the printer's
  6226. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  6227. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  6228. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  6229. That is deliberate for now rather than an oversight: populating this from
  6230. telemetry would hand the scheduler authority to stop drying a user started
  6231. by hand. It also means the backend-restart case this used to claim to
  6232. handle is not handled.
  6233. """
  6234. to_remove = []
  6235. for pid in self._drying_in_progress:
  6236. state = printer_manager.get_status(pid)
  6237. if not state:
  6238. to_remove.append(pid)
  6239. continue
  6240. # Check if any AMS unit is still drying
  6241. ams_list = state.raw_data.get("ams", [])
  6242. # A parked timer is not drying (#3478): it never ends on its own,
  6243. # so it would keep the printer in here for good.
  6244. any_drying = any(int(a.get("dry_time") or 0) > 0 and not is_countdown_parked(a) for a in ams_list)
  6245. if not any_drying:
  6246. to_remove.append(pid)
  6247. for pid in to_remove:
  6248. self._drying_in_progress.pop(pid, None)
  6249. # A printer that has gone away entirely takes its per-AMS auto-drying
  6250. # history with it (#2770), so a printer deleted and re-added does not
  6251. # inherit a suspension it never earned.
  6252. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  6253. self._auto_dry_units.pop(key, None)
  6254. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  6255. # printer starts a fresh wait, and vanished printers do not leak
  6256. # entries.
  6257. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  6258. self._auto_dry_above.pop(key, None)
  6259. @staticmethod
  6260. def _drying_is_only_parked(printer_id: int) -> bool:
  6261. """True when every AMS unit with a drying timer on this printer is parked.
  6262. A parked timer (#2896: the command was taken but the countdown never
  6263. runs) does not end on its own, so nothing may wait on it. False when no
  6264. unit reports a timer yet -- a command just sent that the firmware has not
  6265. reported back is real drying about to begin.
  6266. """
  6267. state = printer_manager.get_status(printer_id)
  6268. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  6269. timed = []
  6270. for unit in units:
  6271. try:
  6272. if int(unit.get("dry_time") or 0) > 0:
  6273. timed.append(unit)
  6274. except (TypeError, ValueError):
  6275. continue
  6276. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  6277. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  6278. """True when a running cycle can be left alone while the next print runs.
  6279. Some hardware dries happily through a print and #2758 settled that we
  6280. should not tear those cycles down: the X2D there was refusing to
  6281. *start* a job, which is a different problem, and stopping drying before
  6282. every dispatch would throw away cycles the printer was content to run.
  6283. Where the model cannot do it, or the user has not enabled it, the print
  6284. takes priority and the cycle stops -- which is what the queue_drying_block
  6285. setting has always promised in its off position.
  6286. """
  6287. if not await self._get_bool_setting(db, "print_drying_enabled"):
  6288. return False
  6289. status = printer_manager.get_status(printer_id)
  6290. return supports_drying_while_printing(
  6291. printer_manager.get_model(printer_id),
  6292. status.firmware_version if status else None,
  6293. )
  6294. async def _stop_drying(self, printer_id: int):
  6295. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  6296. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  6297. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  6298. enough to kill a cycle the user had started by hand on a *different*
  6299. unit of the same printer (#2801). That contradicted the contract
  6300. ``_sync_drying_state`` already documents -- the entry gate deliberately
  6301. only knows about cycles Bambuddy began, so the action must not reach
  6302. past them either.
  6303. """
  6304. state = printer_manager.get_status(printer_id)
  6305. if not state:
  6306. self._drying_in_progress.pop(printer_id, None)
  6307. return
  6308. ams_list = state.raw_data.get("ams", [])
  6309. for ams_data in ams_list:
  6310. dry_time = int(ams_data.get("dry_time") or 0)
  6311. if dry_time > 0:
  6312. ams_id = int(ams_data.get("id", 0))
  6313. if (printer_id, ams_id) not in self._auto_dry_units:
  6314. logger.debug(
  6315. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  6316. printer_id,
  6317. ams_id,
  6318. )
  6319. continue
  6320. logger.info(
  6321. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  6322. printer_id,
  6323. ams_id,
  6324. )
  6325. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  6326. self.forget_auto_dry_cycle(printer_id, ams_id)
  6327. self._drying_in_progress.pop(printer_id, None)
  6328. # Scheduled manual drying (#2638) -----------------------------------
  6329. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  6330. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  6331. async def _check_scheduled_dryings(self, db: AsyncSession):
  6332. """Dispatch due scheduled drying runs and track running ones."""
  6333. now = utcnow_naive()
  6334. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  6335. # Monotonic, so a clock adjustment cannot park the prune for hours.
  6336. since_prune = time.monotonic()
  6337. if (
  6338. self._last_scheduled_drying_prune is None
  6339. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  6340. ):
  6341. self._last_scheduled_drying_prune = since_prune
  6342. await db.execute(
  6343. delete(ScheduledDrying).where(
  6344. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  6345. ScheduledDrying.completed_at.is_not(None),
  6346. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  6347. )
  6348. )
  6349. # Same order as the list route: with two rows due on one printer the
  6350. # earliest scheduled wins rather than whatever the DB hands back first.
  6351. result = await db.execute(
  6352. select(ScheduledDrying)
  6353. .where(ScheduledDrying.status.in_(("pending", "running")))
  6354. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  6355. )
  6356. rows = list(result.scalars().all())
  6357. # Rebuild from the DB every tick so route-side cancels and completions
  6358. # show up. Auto-drying's stop-all branches check this set before
  6359. # stopping anything (#2638).
  6360. # Kept from the previous pass so a run that ended between passes — a
  6361. # cancel through the route, say — can still be released below.
  6362. previously_running = self._scheduled_drying_printer_ids
  6363. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6364. running_printer_ids = set(self._scheduled_drying_printer_ids)
  6365. # Model and firmware come from the printer row, not the live state.
  6366. printer_ids = {row.printer_id for row in rows}
  6367. printers_by_id: dict[int, Printer] = {}
  6368. if printer_ids:
  6369. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  6370. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  6371. for row in rows:
  6372. if row.status == "running":
  6373. self._update_running_scheduled_drying(row, now)
  6374. continue
  6375. if row.start_after is not None and row.start_after > now:
  6376. continue
  6377. state = printer_manager.get_status(row.printer_id)
  6378. if not state:
  6379. row.waiting_reason = "printer_offline"
  6380. continue
  6381. # Same preflight the immediate endpoint runs. Without it the publish
  6382. # succeeds, the row goes to running, the printer ignores the command
  6383. # and the run silently cancels itself after the grace window.
  6384. printer = printers_by_id.get(row.printer_id)
  6385. unsupported = drying_preflight.check_drying_supported(
  6386. printer.model if printer else None, state.firmware_version
  6387. )
  6388. if unsupported:
  6389. row.status = "failed"
  6390. row.error_message = unsupported
  6391. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6392. row.completed_at = now
  6393. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6394. continue
  6395. if (
  6396. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6397. ) or row.printer_id in running_printer_ids:
  6398. row.waiting_reason = "already_drying"
  6399. continue
  6400. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6401. row.waiting_reason = "printer_busy"
  6402. continue
  6403. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6404. if target is None:
  6405. row.waiting_reason = "ams_not_found"
  6406. continue
  6407. blocking = drying_preflight.blocking_reason_codes(target)
  6408. if blocking:
  6409. # Keep the power case distinct; it needs the user to act, so the
  6410. # card can say so instead of waiting silently.
  6411. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6412. continue
  6413. filament = drying_preflight.resolve_filament(target, row.filament)
  6414. logger.info(
  6415. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6416. row.id,
  6417. row.printer_id,
  6418. row.ams_id,
  6419. row.temp,
  6420. row.duration_hours,
  6421. )
  6422. success = printer_manager.send_drying_command(
  6423. row.printer_id,
  6424. row.ams_id,
  6425. row.temp,
  6426. row.duration_hours,
  6427. mode=1,
  6428. filament=filament,
  6429. rotate_tray=row.rotate_tray,
  6430. )
  6431. if success:
  6432. row.status = "running"
  6433. row.started_at = now
  6434. row.waiting_reason = None
  6435. row.filament = filament
  6436. self._drying_in_progress[row.printer_id] = time.monotonic()
  6437. self._scheduled_drying_printer_ids.add(row.printer_id)
  6438. running_printer_ids.add(row.printer_id)
  6439. else:
  6440. row.waiting_reason = "printer_offline"
  6441. # Release the printers whose run has ended. `_drying_in_progress` is
  6442. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6443. # but that call sits behind the auto-drying enabled check, and this
  6444. # method is the one writer that runs whether auto-drying is on or not.
  6445. # With it off, nothing would ever drop the entry short of a print being
  6446. # dispatched to the same printer, so the next scheduled run would wait
  6447. # on "already_drying" forever and `queue_drying_block` would hold the
  6448. # printer's prints too. Covers a run that ended during this pass and one
  6449. # cancelled through the route between passes.
  6450. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6451. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6452. self._drying_in_progress.pop(printer_id, None)
  6453. await db.commit()
  6454. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6455. """Detect completion or interruption of a running scheduled drying.
  6456. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6457. drying. Within the grace window after start we ignore dry_time==0
  6458. (the status lags the command). After that, dry_time==0 near the end
  6459. of the configured duration means completed. Much earlier means the
  6460. run was stopped: re-queue it if a print preempted the dryer, but a
  6461. stop while the printer is idle was deliberate, so cancel the row
  6462. rather than restart drying the user just stopped.
  6463. """
  6464. if row.started_at is None:
  6465. row.started_at = now
  6466. return
  6467. elapsed = (now - row.started_at).total_seconds()
  6468. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6469. return
  6470. state = printer_manager.get_status(row.printer_id)
  6471. if not state:
  6472. return # offline mid-dry; resolve when it reconnects
  6473. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6474. # throw on a malformed id would cost the whole pass including print
  6475. # dispatch, every tick.
  6476. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6477. try:
  6478. dry_time = int(target.get("dry_time") or 0) if target else 0
  6479. except (TypeError, ValueError):
  6480. dry_time = 0
  6481. if dry_time > 0 and is_countdown_parked(target):
  6482. # The printer took the command but the countdown is not running
  6483. # (#2896) and will never reach 0, so the run would stay "running"
  6484. # forever. A print in progress is the likely cause (the power budget
  6485. # is spent), so re-queue it like any interruption; the next start
  6486. # waits for the printer to be idle. Parked on an idle printer is a
  6487. # refusal, not something a retry fixes. The timer itself is left on
  6488. # the printer: it may yet start once power frees up.
  6489. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6490. logger.info(
  6491. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6492. row.id,
  6493. row.ams_id,
  6494. )
  6495. row.status = "pending"
  6496. row.started_at = None
  6497. row.waiting_reason = "interrupted"
  6498. else:
  6499. logger.warning(
  6500. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6501. row.id,
  6502. row.ams_id,
  6503. )
  6504. row.status = "failed"
  6505. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6506. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6507. row.completed_at = now
  6508. return
  6509. if dry_time > 0:
  6510. return
  6511. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6512. row.status = "completed"
  6513. row.completed_at = now
  6514. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6515. row.status = "pending"
  6516. row.started_at = None
  6517. row.waiting_reason = "interrupted"
  6518. else:
  6519. row.status = "cancelled"
  6520. row.completed_at = now
  6521. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6522. """Get all smart plugs associated with a printer."""
  6523. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6524. return list(result.scalars().all())
  6525. @staticmethod
  6526. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6527. """Pick the plug to power-cycle a printer back online with (#2629).
  6528. Only a plug flagged ``controls_printer_power`` can actually bring the
  6529. printer back; waiting for a boot on an accessory (filter fan, lights)
  6530. just burns the power-on timeout and fails the dispatch. Falls back to
  6531. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6532. Callers must pass a non-empty list.
  6533. """
  6534. for plug in auto_on_plugs:
  6535. if plug.controls_printer_power:
  6536. return plug
  6537. return auto_on_plugs[0]
  6538. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6539. # chamber-temperature recommendations BambuStudio ships for the matching
  6540. # filament profile; users can override via Settings → Workflow → Preheat
  6541. # card. "default" applies when a loaded tray's normalised type isn't in
  6542. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6543. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6544. "PLA": 0,
  6545. "PETG": 0,
  6546. "PETG-CF": 40,
  6547. "ABS": 45,
  6548. "ASA": 45,
  6549. "PA": 50,
  6550. "PA-CF": 55,
  6551. "PC": 50,
  6552. "PC-FR": 50,
  6553. "TPU": 0,
  6554. "PVA": 0,
  6555. "default": 0,
  6556. }
  6557. @classmethod
  6558. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6559. """The bundled map under the same key casing a parsed one gets.
  6560. The constant is declared with a lowercase ``default`` because that is
  6561. the key the Settings editor writes and displays. Every read of the map
  6562. happens after ``str(key).upper()``, so handing the constant back as
  6563. declared broke the contract the parser documents: an install that had
  6564. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6565. and the resolution loop's fallback silently found nothing. It read the
  6566. right number only because the bundled default happens to be 0 -- change
  6567. that constant and every unconfigured install would keep preheating to
  6568. zero with no way to tell why.
  6569. """
  6570. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6571. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6572. """Parse the user-configured filament→chamber-target map, falling back
  6573. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6574. are uppercased and the 'default' fallback is always present in the
  6575. returned dict so the resolution loop can index it unconditionally."""
  6576. raw = await self._get_setting(db, "preheat_filament_targets")
  6577. if not raw:
  6578. return self._bundled_preheat_targets()
  6579. try:
  6580. parsed = json.loads(raw)
  6581. if not isinstance(parsed, dict):
  6582. raise ValueError("not an object")
  6583. except (json.JSONDecodeError, ValueError) as exc:
  6584. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6585. return self._bundled_preheat_targets()
  6586. # Coerce values to int; drop unparseable rows so a stray string
  6587. # doesn't crash the loop.
  6588. out: dict[str, int] = {}
  6589. for key, value in parsed.items():
  6590. try:
  6591. out[str(key).upper()] = int(value)
  6592. except (TypeError, ValueError):
  6593. continue
  6594. if "DEFAULT" not in out:
  6595. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6596. return out
  6597. @staticmethod
  6598. def _normalize_filament_type(tray_type: str) -> str:
  6599. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6600. existing drying-preset normalisation (split-at-space, upper-case) so
  6601. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6602. "PA-CF" (no space to split on).
  6603. This is the first stage of ``_resolve_filament_key``, which goes on to
  6604. drop the suffix and consult the alias map; on its own it only decides
  6605. what the tray is called, not which row answers for it.
  6606. Indexing the split rather than testing the input: a tray_type of spaces
  6607. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6608. it through to an IndexError.
  6609. """
  6610. words = (tray_type or "").split()
  6611. return words[0].upper() if words else ""
  6612. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6613. """Per-filament chamber target for one tray's reported type, or 0 when
  6614. the tray is empty / RFID-less and reports no type at all.
  6615. A filled or foamed variant wants its base material's chamber when the
  6616. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6617. not the 0 an unknown type falls to. The specific type is still tried
  6618. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6619. (#2902).
  6620. That lookup is now the shared one, which adds the polyamide aliases on
  6621. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6622. too, rather than the catch-all it was landing on (#3067).
  6623. """
  6624. if not self._normalize_filament_type(tray_type or ""):
  6625. return 0
  6626. key = self._resolve_filament_key(tray_type, targets)
  6627. if key is not None:
  6628. return targets[key]
  6629. # A type the map does not list at all, which is not the same as a tray
  6630. # with nothing in it -- that already returned 0 above.
  6631. return targets.get("DEFAULT", 0)
  6632. def _derive_chamber_target(
  6633. self,
  6634. printer: Printer,
  6635. targets: dict[str, int],
  6636. item: PrintQueueItem | None = None,
  6637. ) -> int:
  6638. """Chamber target for the trays this print actually loads: the max of
  6639. their per-filament targets. Returns 0 when there is nothing to read (no
  6640. status, no AMS telemetry — e.g. external-spool prints) or when every
  6641. tray considered maps to 0, and the chamber phase then short-circuits in
  6642. the main loop.
  6643. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6644. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6645. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6646. plus soak burned ahead of each upload, on a printer whose chamber never
  6647. reaches the target anyway (#2886). An item with no usable mapping falls
  6648. back to scanning every loaded tray: that is the only signal left, and
  6649. narrowing to nothing would skip preheat on prints that genuinely need
  6650. it.
  6651. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6652. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6653. less slots have empty `tray_type` and contribute nothing. The external
  6654. spool is consulted only when the mapping names it (>= 254); it stays
  6655. out of the unnarrowed scan, so an item without a mapping derives from
  6656. the AMS alone exactly as before.
  6657. """
  6658. state = printer_manager.get_status(printer.id)
  6659. if state is None:
  6660. return 0
  6661. raw_data = state.raw_data or {}
  6662. used = _used_global_tray_ids(item)
  6663. ams_list = raw_data.get("ams")
  6664. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6665. if isinstance(ams_list, dict):
  6666. ams_list = ams_list.get("ams") or []
  6667. if not isinstance(ams_list, list):
  6668. ams_list = []
  6669. best = 0
  6670. layout = TrayLayout.from_state(state)
  6671. for ams in ams_list:
  6672. if not isinstance(ams, dict):
  6673. continue
  6674. ams_id = _int_or(ams.get("id"), 0)
  6675. for tray in ams.get("tray") or []:
  6676. # A non-dict entry has never been seen from real firmware, but
  6677. # `.get` on one raises, and nothing between here and
  6678. # `_dispatch_one`'s try/finally catches it — the item would be
  6679. # left holding its dispatch claim. Preheat is best-effort by
  6680. # contract, so step over it instead.
  6681. if not isinstance(tray, dict):
  6682. continue
  6683. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0), layout) not in used:
  6684. continue
  6685. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6686. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN or layout.is_external(t) for t in used):
  6687. for vt in raw_data.get("vt_tray") or []:
  6688. if not isinstance(vt, dict):
  6689. continue
  6690. # `_build_loaded_filaments` addresses external feeds by the id
  6691. # the firmware reports — 255 main, 254 deputy — defaulting to
  6692. # 254 when the field is absent. Same expression here so the two
  6693. # agree on which entry a mapping's 254/255 refers to.
  6694. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6695. continue
  6696. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6697. return best
  6698. def _release_keep_warm(self, pid: int) -> None:
  6699. """Release keep-warm on a printer that left the candidate set.
  6700. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6701. reports the target we set (``entry.held_target``), so a user or
  6702. subsequent print that changed the bed target since is not clobbered.
  6703. Best-effort, never raises.
  6704. The entry is kept, not dropped, when the printer cannot be reached
  6705. right now: a printer that is briefly offline still has a hot bed, and
  6706. holding the entry is what keeps the max-duration timeout applying and
  6707. lets a later tick retry the release. Only a printer that has left the
  6708. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6709. """
  6710. entry = self._keep_warm.get(pid)
  6711. if entry is None:
  6712. return
  6713. state = printer_manager.get_status(pid)
  6714. client = printer_manager.get_client(pid)
  6715. if state is None or client is None:
  6716. logger.debug(
  6717. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6718. pid,
  6719. )
  6720. return
  6721. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6722. if int(cur_bed_target) != entry.held_target:
  6723. # Someone else owns the bed now, so there is nothing of ours to
  6724. # undo and nothing left to track.
  6725. logger.info(
  6726. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6727. pid,
  6728. int(cur_bed_target),
  6729. entry.held_target,
  6730. )
  6731. self._keep_warm.pop(pid, None)
  6732. return
  6733. try:
  6734. client.set_bed_temperature(0)
  6735. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6736. self._keep_warm.pop(pid, None)
  6737. except Exception as exc:
  6738. # Keep the entry so the next tick tries again rather than leaving
  6739. # the bed hot with nothing tracking it.
  6740. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6741. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6742. """Release printers that dropped out of the keep-warm candidate set.
  6743. Called from ``_apply_keep_warm`` on every tick (with the current
  6744. candidate set), and from ``check_queue``'s no-pending-items early
  6745. return (with an empty candidate set) so orphaned holds still get
  6746. released when the queue empties. Also called with an empty candidate
  6747. set when any of the three gate settings toggles off, so a printer
  6748. whose feature was disabled mid-hold gets its bed released.
  6749. Printers being dispatched this tick are excluded from the bed-off
  6750. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6751. transient 0 in between would just churn against preheat. Ownership of
  6752. the hot bed transfers to the preheat rollback pin instead — if the
  6753. dispatch aborts before the print starts (failed upload, cancelled
  6754. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6755. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6756. is the ONLY thing standing between an aborted dispatch and a bed
  6757. left hot with no owner. A successful print start clears the pin and
  6758. the print's own gcode takes over, as usual.
  6759. """
  6760. for _pid in list(self._keep_warm):
  6761. if _pid in active_candidates:
  6762. continue
  6763. if _pid in dispatched:
  6764. handed_over = self._keep_warm.pop(_pid, None)
  6765. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6766. if handed_over is not None:
  6767. self._preheat_pin_bed[_pid] = handed_over.held_target
  6768. continue
  6769. self._release_keep_warm(_pid)
  6770. async def _apply_keep_warm(
  6771. self,
  6772. db: AsyncSession,
  6773. items: list[PrintQueueItem],
  6774. dispatch_ids: list[int] | set[int],
  6775. busy_printers: set[int],
  6776. require_plate_clear: bool,
  6777. ) -> None:
  6778. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6779. When a printer just finished a job (FINISH state) and the next queued
  6780. item needs chamber heating, hold the bed hot so the chamber stays warm
  6781. during the bed-clearing window. The bed is the chamber's heating
  6782. element here, not a print surface — nothing is printing during the
  6783. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6784. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6785. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6786. aftermarket chamber heaters), raised to the item's own parsed
  6787. bed_temperature when that is higher. Items whose archive metadata has
  6788. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6789. get a hold — chamber need is what gates the feature, not metadata.
  6790. Skips entirely for filaments that map to a 0°C chamber target
  6791. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6792. names, so a hot-chamber spool it never touches does not hold the bed of
  6793. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6794. whole unit, as every item was before. Printers being dispatched this
  6795. cycle are excluded:
  6796. ``_preheat_and_soak`` already handles their bed temperature.
  6797. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6798. released to 0 and the entry is latched ``expired=True`` so
  6799. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6800. MQTT: publish is skipped when firmware already has the target.
  6801. The release sweep runs BEFORE the engagement gate so a printer that
  6802. was owned by keep-warm still gets its bed released when any of the
  6803. three gate settings is toggled off mid-hold. The
  6804. ``check_queue`` early-return-when-no-items path also calls
  6805. ``_sweep_keep_warm`` directly to release orphaned holds.
  6806. """
  6807. dispatch_set = set(dispatch_ids)
  6808. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6809. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6810. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6811. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6812. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6813. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6814. # Release sweep first — must run even when gate_open is False so a
  6815. # printer owned by keep-warm when a gate toggles off gets released.
  6816. self._sweep_keep_warm(
  6817. active_candidates=warm_candidates if gate_open else set(),
  6818. dispatched=dispatched_printers,
  6819. )
  6820. if not gate_open:
  6821. return
  6822. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6823. max_hold_seconds = (
  6824. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6825. )
  6826. now_mono = time.monotonic()
  6827. filament_targets: dict[str, int] | None = None
  6828. for pid in warm_candidates:
  6829. entry = self._keep_warm.get(pid)
  6830. # Latched-expired: max-duration timeout already fired for this
  6831. # printer. Skip until the release sweep drops the entry (i.e.
  6832. # until the printer leaves the candidate set).
  6833. if entry is not None and entry.expired:
  6834. continue
  6835. # These two guards sit ahead of the max-duration check below, so an
  6836. # engaged hold only ages out while its printer is still reachable
  6837. # and still in FINISH. That is deliberate rather than a hole: with
  6838. # no status or no client there is no M140 to send anyway, and the
  6839. # elapsed check runs off `entry.started` so it fires on the first
  6840. # tick after the printer comes back. Leaving FINISH means the plate
  6841. # was cleared, which drops the printer out of `warm_candidates` and
  6842. # hands it to `_release_keep_warm` instead. The invariant worth
  6843. # preserving if this is ever reordered: every path out of an
  6844. # engaged hold ends in a bed-off, whether by timeout or release.
  6845. state = printer_manager.get_status(pid)
  6846. if state is None or state.state != "FINISH":
  6847. continue
  6848. client = printer_manager.get_client(pid)
  6849. if client is None:
  6850. continue
  6851. next_item = next((it for it in items if it.printer_id == pid), None)
  6852. if next_item is None:
  6853. continue
  6854. # Hold temperature: the configured keep-warm temp, raised to the
  6855. # item's own bed temp when the metadata reports a higher one. A
  6856. # missing bed_temperature (Orca gcode.3mf exports parse without
  6857. # one) does NOT skip the hold — chamber need gates the feature.
  6858. archive = next_item.archive
  6859. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6860. bed_target = max(item_bed, hold_temp)
  6861. if bed_target <= 0:
  6862. continue
  6863. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6864. if explicit is not None:
  6865. chamber_needed = int(explicit) > 0
  6866. else:
  6867. if filament_targets is None:
  6868. filament_targets = await self._get_preheat_filament_targets(db)
  6869. printer_obj = await self._get_printer(db, pid)
  6870. chamber_needed = (
  6871. printer_obj is not None
  6872. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6873. )
  6874. if not chamber_needed:
  6875. continue
  6876. # Seed the timer on first engagement; keep it on subsequent ticks
  6877. # (never re-seed — that would defeat the max-duration cap).
  6878. if entry is None:
  6879. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6880. self._keep_warm[pid] = entry
  6881. elapsed = now_mono - entry.started
  6882. if elapsed > max_hold_seconds:
  6883. # Timeout: publish bed → 0 once (if firmware still holds our
  6884. # target) and latch expired. The entry stays until the release
  6885. # sweep drops it, preventing the next tick from re-seeding.
  6886. logger.warning(
  6887. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6888. pid,
  6889. elapsed,
  6890. )
  6891. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6892. if int(cur_bed_target) == entry.held_target:
  6893. try:
  6894. client.set_bed_temperature(0)
  6895. except Exception as exc:
  6896. logger.warning(
  6897. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6898. pid,
  6899. exc,
  6900. )
  6901. else:
  6902. logger.info(
  6903. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6904. pid,
  6905. int(cur_bed_target),
  6906. entry.held_target,
  6907. )
  6908. entry.expired = True
  6909. continue
  6910. # Idempotence: skip publish when firmware already has our target.
  6911. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6912. if int(cur_bed_target) == bed_target:
  6913. entry.held_target = bed_target
  6914. continue
  6915. try:
  6916. client.set_bed_temperature(bed_target)
  6917. entry.held_target = bed_target
  6918. logger.info(
  6919. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6920. bed_target,
  6921. pid,
  6922. )
  6923. except Exception as exc:
  6924. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6925. def _sample_chamber_temps(self) -> None:
  6926. """Record a chamber temperature sample for every connected printer.
  6927. Called once per scheduler tick (every 3–30 s). Entries older than
  6928. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6929. Also evicts per-printer state whose printer_id is no longer registered
  6930. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6931. """
  6932. now = time.monotonic()
  6933. cutoff = now - self._chamber_history_ttl
  6934. statuses = printer_manager.get_all_statuses()
  6935. known_pids = set(statuses.keys())
  6936. for pid, status in statuses.items():
  6937. if status is None or not status.connected:
  6938. continue
  6939. temps = status.temperatures or {}
  6940. chamber = temps.get("chamber")
  6941. if chamber is None:
  6942. continue
  6943. hist = self._chamber_history.setdefault(pid, deque())
  6944. hist.append((now, float(chamber)))
  6945. while hist and hist[0][0] < cutoff:
  6946. hist.popleft()
  6947. # Evict state for printers that are no longer registered with the manager.
  6948. # This is the one place a keep-warm entry is dropped without releasing
  6949. # the bed: the printer is gone from the manager, so there is no client
  6950. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6951. # for printers that are merely unreachable, which is what makes this
  6952. # the terminal case rather than a silent leak.
  6953. for pid in list(self._chamber_history):
  6954. if pid not in known_pids:
  6955. self._chamber_history.pop(pid, None)
  6956. for pid in list(self._keep_warm):
  6957. if pid not in known_pids:
  6958. logger.info(
  6959. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6960. pid,
  6961. )
  6962. self._keep_warm.pop(pid, None)
  6963. for pid in list(self._preheat_pin):
  6964. if pid not in known_pids:
  6965. self._preheat_pin.pop(pid, None)
  6966. self._preheat_pin_bed.pop(pid, None)
  6967. def _chamber_soak_remaining(
  6968. self,
  6969. printer_id: int,
  6970. chamber_target: float,
  6971. soak_seconds: int,
  6972. tolerance: float = 2.0,
  6973. ) -> int:
  6974. """Return how many seconds of soak time are still needed.
  6975. Credits the time the chamber has already spent at temperature against
  6976. the configured soak. The credit may not start earlier than any of:
  6977. * **The newest sample.** Nothing recent means the printer stopped
  6978. reporting mid-observation and the chamber may have cooled unseen, so
  6979. the full soak is required. (A 2 h history whose last reading is half
  6980. an hour old is not evidence of anything — the measured cooling rate
  6981. is fast enough to cross the threshold in that time.)
  6982. * **The most recent contiguous run of samples.** A gap wider than
  6983. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6984. far side is not evidence of temperature.
  6985. * **The end of the most recent real dip below the threshold.**
  6986. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6987. — see that constant for the thermal reasoning. A stray low reading is
  6988. an artifact, and treating it as cooling would discard a soak that
  6989. actually happened.
  6990. Returns ``soak_seconds`` when nothing can be credited (no history,
  6991. stale history, or the chamber is below the threshold right now) and 0
  6992. once the credited time covers the whole soak.
  6993. """
  6994. hist = self._chamber_history.get(printer_id)
  6995. if not hist:
  6996. return soak_seconds
  6997. now = time.monotonic()
  6998. newest_ts, newest_temp = hist[-1]
  6999. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  7000. return soak_seconds # stale — no fresh evidence to credit
  7001. threshold = chamber_target - tolerance
  7002. if newest_temp < threshold:
  7003. return soak_seconds # below target right now; nothing is soaked
  7004. samples = list(hist)
  7005. # Earliest point we have unbroken observations for.
  7006. credit_from = samples[-1][0]
  7007. for i in range(len(samples) - 1, 0, -1):
  7008. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  7009. break
  7010. credit_from = samples[i - 1][0]
  7011. # Pull the credit forward to the end of the last significant dip. Each
  7012. # excursion is measured between the in-range readings that bracket it,
  7013. # so a lone stray sample is charged one sampling interval rather than
  7014. # zero, and the comparison errs towards calling a dip real.
  7015. i = 0
  7016. while i < len(samples):
  7017. if samples[i][1] >= threshold:
  7018. i += 1
  7019. continue
  7020. j = i
  7021. while j < len(samples) and samples[j][1] < threshold:
  7022. j += 1
  7023. # `newest_temp >= threshold` was checked above, so j is in range.
  7024. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  7025. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  7026. # Credit resumes at the last below-threshold sample rather than
  7027. # the first good one after it, so a recovered dip over-credits
  7028. # by up to one sampling interval — the opposite lean to the
  7029. # bracketing above. Both are bounded by the sample cadence and
  7030. # dwarfed by the grace period, so neither is worth the extra
  7031. # arithmetic to remove.
  7032. credit_from = max(credit_from, samples[j - 1][0])
  7033. i = j
  7034. return max(0, soak_seconds - int(now - credit_from))
  7035. def notify_dispatch_cancelled(self, item_id: int) -> None:
  7036. """Tell an in-flight dispatch that its item no longer wants to print.
  7037. Called by the queue's cancel and delete routes. Those only write to the
  7038. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  7039. observe — so preheat would keep heating for the rest of max_wait + soak
  7040. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  7041. blocking every other queued item behind a print that is not happening.
  7042. Signalling in memory rather than re-reading the row keeps this off the
  7043. database entirely: no second session, no transaction held across a long
  7044. sleep, and no snapshot staleness deciding whether a print goes ahead.
  7045. Bambuddy serves from a single uvicorn process with one scheduler task,
  7046. so the route and the dispatch always share this object. The flag is
  7047. advisory — dropping it (e.g. after a restart) only costs a wasted
  7048. preheat, never a wrongly-abandoned print.
  7049. Only ids with a dispatch actually in flight are recorded, so the set
  7050. stays bounded by the upload pool rather than growing once per cancelled
  7051. item for the life of the process. Skipping the rest loses nothing: an
  7052. item that is not in flight cannot start heating later either, because
  7053. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  7054. the caller has already committed a terminal status (or deleted the row)
  7055. before calling this.
  7056. """
  7057. if item_id in self._inflight:
  7058. self._cancelled_dispatches.add(item_id)
  7059. # A print sent for it earlier that never started is not one any more.
  7060. self._forget_unstarted_print(item_id, unless_printing=False)
  7061. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  7062. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  7063. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  7064. while it is parked, so the wait is chopped into
  7065. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  7066. """
  7067. remaining = float(seconds)
  7068. while remaining > 0:
  7069. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  7070. await asyncio.sleep(slice_secs)
  7071. remaining -= slice_secs
  7072. if item_id in self._cancelled_dispatches:
  7073. return False
  7074. return True
  7075. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  7076. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  7077. The full preheat stage does this as part of its own dispatch: an H2D
  7078. left in heating mode by the ABS job before it would otherwise cook the
  7079. PLA that follows. The skip path never reaches that code, so it calls
  7080. this instead -- one idempotent MQTT command, no waiting, and nothing to
  7081. add to the rollback pin, because a flap set to cooling for a print that
  7082. needs no heat is where it should have been either way.
  7083. Best-effort like everything else in the stage: a refused command logs
  7084. and the dispatch carries on.
  7085. """
  7086. model = printer.model or ""
  7087. if not supports_airduct(model):
  7088. return
  7089. state = printer_manager.get_status(printer.id)
  7090. current = getattr(state, "airduct_mode", None) if state else None
  7091. if current == _AIRDUCT_MODE_COOLING:
  7092. return
  7093. client = printer_manager.get_client(printer.id)
  7094. if client is None:
  7095. return
  7096. try:
  7097. client.set_airduct_mode("cooling")
  7098. except Exception as exc:
  7099. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  7100. async def _preheat_and_soak(
  7101. self,
  7102. db: AsyncSession,
  7103. item: PrintQueueItem,
  7104. printer: Printer,
  7105. archive: PrintArchive | None,
  7106. ) -> bool:
  7107. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  7108. Returns True when the dispatch should carry on to the upload — including
  7109. every case where preheat is skipped, since a skipped preheat is not a
  7110. reason to abandon the print. Returns False only when the item stopped
  7111. wanting to be printed while the stage was waiting (cancelled or
  7112. deleted); the caller must then abandon the dispatch, and
  7113. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  7114. Resolution order:
  7115. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  7116. to the global `preheat_enabled` setting; 'on' forces the stage on
  7117. even if the global is off.
  7118. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  7119. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  7120. across the trays `item.ams_mapping` names (every loaded slot when
  7121. it names none).
  7122. 3. A target of 0 off the filament map skips the whole stage: the
  7123. materials this print loads want no chamber, so there is nothing to
  7124. soak for and the bed phase would only delay the upload (#3041).
  7125. An explicit 0 typed into the per-item override, or a per-item
  7126. 'on', still runs the bed phase and the soak — both are the user
  7127. asking for a warm bed in so many words.
  7128. 4. Three hardware tiers branch the wait loop:
  7129. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  7130. send M141 to the resolved target, then wait for the chamber sensor
  7131. to reach it (or the max-wait timeout to elapse).
  7132. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  7133. no M141; the bed is the only heat source, so we wait for the chamber
  7134. sensor to rise via bed radiation OR fall through on timeout.
  7135. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  7136. temperature; the function just heats the bed and holds for the
  7137. configured soak duration.
  7138. The bed target comes from the archive's parsed metadata
  7139. (`bed_temperature`); if missing the preheat stage logs and returns
  7140. without dispatching anything, rather than guessing at a default that
  7141. might wreck filament setup.
  7142. Failures are logged but never re-raised — preheat is best-effort. A
  7143. printer that goes offline mid-soak, a refused gcode command, or a
  7144. missing temperature reading must not turn into a failed queue item; the
  7145. normal upload + start path runs immediately after this method returns.
  7146. """
  7147. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  7148. if override == "off":
  7149. return True
  7150. if override == "inherit":
  7151. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  7152. if not enabled:
  7153. return True
  7154. # override == "on" forces the stage on regardless of the global setting.
  7155. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  7156. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  7157. # Chamber target resolution:
  7158. # 1. Explicit per-item override beats everything (user knows best).
  7159. # 2. Otherwise derive from the filament types this print loads, via
  7160. # the per-filament target map. A PLA-only print derives 0 and the
  7161. # block below skips the stage without the user touching anything,
  7162. # even when an ASA spool is sitting in another slot of the same
  7163. # AMS (#2886).
  7164. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  7165. if explicit_target is not None and explicit_target > 0:
  7166. chamber_target = int(explicit_target)
  7167. chamber_source = "item-override"
  7168. elif explicit_target == 0:
  7169. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  7170. chamber_source = "item-override-zero"
  7171. else:
  7172. targets = await self._get_preheat_filament_targets(db)
  7173. chamber_target = self._derive_chamber_target(printer, targets, item)
  7174. chamber_source = "filament-map"
  7175. # Nothing to preheat *for*. A zero that came out of the filament map is
  7176. # the map saying this print's materials want no chamber conditioning --
  7177. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  7178. # anyway heated the bed and then held it for the full soak, which
  7179. # delayed every PLA dispatch by minutes and bought nothing: the print's
  7180. # own G-code sets the bed the moment it starts, so preheating it here
  7181. # only moves that heating ahead of the upload instead of overlapping
  7182. # with it, and the soak has no chamber to condition (#3041).
  7183. #
  7184. # An explicit statement from the user still runs the stage. Forcing the
  7185. # per-item override to 'on', or typing a chamber target of exactly 0,
  7186. # both mean "preheat the bed for this print" -- the second is
  7187. # documented as doing precisely that. Only the automatic path, the
  7188. # global toggle plus the filament map, short-circuits here.
  7189. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  7190. logger.info(
  7191. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  7192. "target, so there is nothing to soak for (override=%s model=%s)",
  7193. item.id,
  7194. override,
  7195. printer.model or "",
  7196. )
  7197. self._preheat_flap_to_cooling(item.id, printer)
  7198. return True
  7199. bed_target = await _queued_plate_bed_temperature(item, archive)
  7200. if bed_target <= 0:
  7201. # No bed temperature in the slicer metadata. When the print needs a
  7202. # hot chamber the bed is simply how we heat it, so fall back to the
  7203. # configured chamber-heating bed temperature rather than skipping
  7204. # the whole stage — otherwise the print starts with a cold chamber,
  7205. # which is exactly what preheat exists to prevent. Without a chamber
  7206. # requirement there is nothing to preheat *for*, so skip as before
  7207. # rather than guess a bed temperature for the print itself.
  7208. if chamber_target <= 0:
  7209. logger.info(
  7210. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  7211. item.id,
  7212. )
  7213. return True
  7214. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  7215. logger.info(
  7216. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  7217. "%d°C to drive the chamber to %d°C",
  7218. item.id,
  7219. bed_target,
  7220. chamber_target,
  7221. )
  7222. client = printer_manager.get_client(printer.id)
  7223. if client is None:
  7224. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  7225. return True
  7226. model = printer.model or ""
  7227. has_heater = supports_chamber_heater(model)
  7228. has_sensor = supports_chamber_temp(model)
  7229. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  7230. # Fast path: if the chamber has been continuously above target for at
  7231. # least soak_seconds and the bed is already at temperature, skip the
  7232. # entire preheat stage. Typical case: keep-warm held the bed between
  7233. # consecutive same-material prints and the chamber never dropped.
  7234. if do_chamber and has_sensor and soak_seconds > 0:
  7235. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7236. if remaining == 0:
  7237. cur = printer_manager.get_status(printer.id)
  7238. if cur:
  7239. cur_temps = cur.temperatures or {}
  7240. if (
  7241. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  7242. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  7243. ):
  7244. logger.info(
  7245. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  7246. "and bed is already at temperature (chamber history fast-path)",
  7247. item.id,
  7248. chamber_target,
  7249. soak_seconds,
  7250. )
  7251. # Still set targets to prevent cooling during the 3MF upload window.
  7252. # Register each successful set in the preheat pin so `_dispatch_one`
  7253. # unwinds them on any non-success exit.
  7254. pin = self._preheat_pin.setdefault(printer.id, set())
  7255. try:
  7256. client.set_bed_temperature(bed_target)
  7257. pin.add("bed")
  7258. self._preheat_pin_bed[printer.id] = bed_target
  7259. except Exception as exc:
  7260. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  7261. if supports_airduct(model):
  7262. cur_airduct = getattr(cur, "airduct_mode", None)
  7263. if cur_airduct != _AIRDUCT_MODE_HEATING:
  7264. try:
  7265. client.set_airduct_mode("heating")
  7266. # Only undo what we can see we replaced. `None`
  7267. # means no mode has been observed yet, and
  7268. # rolling that back to cooling would assert a
  7269. # state the printer never reported.
  7270. if cur_airduct == _AIRDUCT_MODE_COOLING:
  7271. pin.add("airduct")
  7272. except Exception as exc:
  7273. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  7274. if has_heater:
  7275. try:
  7276. client.set_chamber_temperature(chamber_target)
  7277. pin.add("chamber")
  7278. except Exception as exc:
  7279. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  7280. return True
  7281. logger.info(
  7282. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  7283. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  7284. item.id,
  7285. bed_target,
  7286. chamber_target if do_chamber else 0,
  7287. chamber_source,
  7288. override,
  7289. model,
  7290. has_heater,
  7291. has_sensor,
  7292. max_wait,
  7293. soak_seconds,
  7294. )
  7295. # Preheat rollback registry: everything we set below is recorded here so
  7296. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  7297. # (bed off, chamber off, airduct back to cooling) on any non-success
  7298. # exit. Populated as each command succeeds; consumed and cleared by
  7299. # `_dispatch_one`.
  7300. pin = self._preheat_pin.setdefault(printer.id, set())
  7301. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  7302. # cache the target locally so the polling reads below see consistent
  7303. # state (firmware MQTT echoes lag by ~1s).
  7304. try:
  7305. client.set_bed_temperature(bed_target)
  7306. pin.add("bed")
  7307. self._preheat_pin_bed[printer.id] = bed_target
  7308. except Exception as exc:
  7309. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  7310. return True
  7311. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  7312. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  7313. # left it on, regardless of M141. Default cooling actively vents the
  7314. # chamber, so a `chamber_target > 0` print with the flap stuck in
  7315. # cooling never converges — the heater fights the open exhaust. We
  7316. # flip the flap BEFORE M141 to "heating" when the preheat wants
  7317. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  7318. # on an H2D that was previously running ABS would otherwise stay in
  7319. # heating mode and overheat PLA). The current-state read keeps the
  7320. # command idempotent — no MQTT chatter when the flap is already where
  7321. # we want it.
  7322. if supports_airduct(model):
  7323. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  7324. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  7325. current_state = printer_manager.get_status(printer.id)
  7326. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  7327. if current_airduct != desired_id:
  7328. try:
  7329. client.set_airduct_mode(desired_airduct)
  7330. # As in the fast path: only pin a rollback for a flap we
  7331. # saw in cooling. `current_airduct` of None means no mode
  7332. # has been observed, so there is nothing to restore to.
  7333. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  7334. pin.add("airduct")
  7335. except Exception as exc:
  7336. logger.warning(
  7337. "Queue item %s: preheat airduct %s mode failed: %s",
  7338. item.id,
  7339. desired_airduct,
  7340. exc,
  7341. )
  7342. if do_chamber and has_heater:
  7343. try:
  7344. client.set_chamber_temperature(chamber_target)
  7345. pin.add("chamber")
  7346. except Exception as exc:
  7347. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  7348. # Release the pooled DB connection before the (potentially many-minute)
  7349. # heat-soak wait below (#2572). Every setting this method needs is read
  7350. # above; the wait/soak loop only polls printer_manager state and sleeps —
  7351. # it never touches the DB. Without this the caller's transaction sat
  7352. # "idle in transaction" for the whole soak, pinning one pooled connection
  7353. # per preheating printer. expire_on_commit=False keeps item/printer
  7354. # readable afterwards; there are no pending writes to lose here.
  7355. await db.commit()
  7356. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  7357. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  7358. # Poll every 3s — frequent enough for responsive logging without
  7359. # spamming the MQTT state stream. The "converged" predicate is:
  7360. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  7361. # AND
  7362. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  7363. BED_TOLERANCE = 2.0
  7364. CHAMBER_TOLERANCE = 2.0
  7365. POLL_INTERVAL = 3.0
  7366. deadline = asyncio.get_event_loop().time() + max_wait
  7367. while True:
  7368. state = printer_manager.get_status(printer.id)
  7369. if state is None:
  7370. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  7371. break
  7372. temps = state.temperatures or {}
  7373. bed_now = float(temps.get("bed", 0) or 0)
  7374. chamber_now = float(temps.get("chamber", 0) or 0)
  7375. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  7376. if not do_chamber:
  7377. chamber_ok = True # phase disabled or model has neither sensor nor heater
  7378. elif not has_sensor:
  7379. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  7380. else:
  7381. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  7382. if bed_ok and chamber_ok:
  7383. logger.info(
  7384. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  7385. item.id,
  7386. bed_now,
  7387. chamber_now,
  7388. )
  7389. break
  7390. if asyncio.get_event_loop().time() >= deadline:
  7391. logger.info(
  7392. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7393. item.id,
  7394. bed_now,
  7395. bed_target,
  7396. chamber_now,
  7397. chamber_target if do_chamber else 0,
  7398. )
  7399. break
  7400. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7401. logger.info(
  7402. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7403. item.id,
  7404. )
  7405. return False
  7406. if soak_seconds > 0:
  7407. if do_chamber and has_sensor:
  7408. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7409. else:
  7410. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7411. if remaining > 0:
  7412. logger.info(
  7413. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7414. "has been above target for ~%ds already)",
  7415. item.id,
  7416. remaining,
  7417. soak_seconds,
  7418. soak_seconds - remaining,
  7419. )
  7420. if not await self._preheat_sleep(item.id, remaining):
  7421. logger.info(
  7422. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7423. item.id,
  7424. )
  7425. return False
  7426. else:
  7427. logger.info(
  7428. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7429. item.id,
  7430. chamber_target,
  7431. soak_seconds,
  7432. )
  7433. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7434. return True
  7435. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7436. """Turn on smart plug and wait for printer to connect.
  7437. Returns True if printer connected successfully within timeout.
  7438. """
  7439. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7440. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7441. # Check current plug state
  7442. status = await service.get_status(plug)
  7443. if not status.get("reachable"):
  7444. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7445. return False
  7446. # Turn on if not already on
  7447. if status.get("state") != "ON":
  7448. success = await service.turn_on(plug)
  7449. if not success:
  7450. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7451. return False
  7452. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7453. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7454. # Get printer from database for connection
  7455. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7456. printer = result.scalar_one_or_none()
  7457. if not printer:
  7458. logger.error("Printer %s not found in database", printer_id)
  7459. return False
  7460. # End the pass's transaction before waiting up to minutes for the boot:
  7461. # held open, it pins a pooled connection idle in transaction
  7462. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7463. # through it.
  7464. await db.commit()
  7465. # Wait for printer to boot (give it some time before trying to connect)
  7466. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7467. await asyncio.sleep(30)
  7468. # Try to connect to the printer periodically
  7469. elapsed = 30 # Already waited 30s
  7470. while elapsed < self._power_on_wait_time:
  7471. # Try to connect
  7472. logger.info("Attempting to connect to printer %s...", printer_id)
  7473. try:
  7474. connected = await printer_manager.connect_printer(printer)
  7475. if connected:
  7476. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7477. # Give it a moment to stabilize and get status
  7478. await asyncio.sleep(5)
  7479. return True
  7480. except Exception as e:
  7481. logger.debug("Connection attempt failed: %s", e)
  7482. await asyncio.sleep(self._power_on_check_interval)
  7483. elapsed += self._power_on_check_interval
  7484. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7485. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7486. return False
  7487. async def _check_previous_success(
  7488. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7489. ) -> bool:
  7490. """Check if the previous print on this printer succeeded.
  7491. ``printer_id`` names the printer to look at when the item has none yet
  7492. (a job for any printer of a model, checked against the one offered).
  7493. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7494. deliberate action, not a failure, so subsequent items should still
  7495. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7496. a skip isn't an actual print attempt, so it must not gate downstream
  7497. items — counting it as a failed predecessor was the cascade bug that
  7498. let a single cancellation block 18 items over 3 days for the reporter.
  7499. Only `failed` and `aborted` — real print-attempt failures — block.
  7500. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7501. action — #1818) are also excluded from the lookback so the user can
  7502. clear the gate after fixing the physical issue without having to
  7503. re-queue every downstream job.
  7504. """
  7505. result = await db.execute(
  7506. select(PrintQueueItem)
  7507. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7508. .where(PrintQueueItem.id != item.id)
  7509. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7510. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7511. # A row ended without a completion time must not count as the
  7512. # latest: PostgreSQL sorts NULL first in a descending order.
  7513. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7514. .limit(1)
  7515. )
  7516. prev_item = result.scalar_one_or_none()
  7517. # If no previous item, assume success (first in queue)
  7518. if not prev_item:
  7519. return True
  7520. return prev_item.status in ("completed", "cancelled")
  7521. def _hold_archive(self, item_id: int, archive_id: int) -> None:
  7522. """Hold the archive a dispatch prints into until it ends (archive_work)."""
  7523. from backend.app.services import archive_work
  7524. self._release_held_archive(item_id)
  7525. archive_work.hold(archive_id)
  7526. self._held_archives[item_id] = archive_id
  7527. def _release_held_archive(self, item_id: int) -> None:
  7528. from backend.app.services import archive_work
  7529. if (archive_id := self._held_archives.pop(item_id, None)) is not None:
  7530. archive_work.release(archive_id)
  7531. @staticmethod
  7532. async def _printing_elsewhere(db: AsyncSession, archive_id: int) -> bool:
  7533. """Whether a print of the archive is running (its run open)."""
  7534. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7535. return (
  7536. await db.scalar(
  7537. select(PrintLogEntry.id)
  7538. .where(PrintLogEntry.archive_id == archive_id, PrintLogEntry.status == RUN_OPEN)
  7539. .limit(1)
  7540. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7541. )
  7542. is not None
  7543. )
  7544. async def _claim_reusable_archive(
  7545. self, db: AsyncSession, item: PrintQueueItem, file_path: Path
  7546. ) -> PrintArchive | None:
  7547. """The archive a library dispatch adds its run to, or None for a new one.
  7548. The same file of the same owner, in the same project, archived from
  7549. this library file or from none (one since deleted, or a print started
  7550. elsewhere), with its copy of the file still on disk. Also while it is
  7551. printing, queued or finishing elsewhere: each print of an archive is
  7552. its own run, with its own start, end, charge, energy, outcome,
  7553. timelapse and photos (archive redesign), as for the copies of a batch.
  7554. """
  7555. from backend.app.services.archive import ArchiveService
  7556. # Off the file as it is now: the stored hash is not refreshed when the
  7557. # file changes on disk (an external folder, overwritten in place).
  7558. content_hash = await asyncio.to_thread(ArchiveService.compute_file_hash, file_path)
  7559. owner = (
  7560. PrintArchive.created_by_id.is_(None)
  7561. if item.created_by_id is None
  7562. else PrintArchive.created_by_id == item.created_by_id
  7563. )
  7564. project = (
  7565. PrintArchive.project_id.is_(None) if item.project_id is None else PrintArchive.project_id == item.project_id
  7566. )
  7567. candidates = (
  7568. await db.scalars(
  7569. select(PrintArchive)
  7570. .where(
  7571. PrintArchive.content_hash == content_hash,
  7572. owner,
  7573. project,
  7574. or_(PrintArchive.library_file_id == item.library_file_id, PrintArchive.library_file_id.is_(None)),
  7575. PrintArchive.deleted_at.is_(None),
  7576. )
  7577. .order_by(PrintArchive.id.desc())
  7578. )
  7579. ).all()
  7580. from backend.app.services import archive_work
  7581. for candidate in candidates:
  7582. # Not one a merge is moving into another archive right now; held
  7583. # from here, with no await between, until the dispatch ends.
  7584. if archive_work.is_merging(candidate.id):
  7585. continue
  7586. if candidate.file_path and (settings.base_dir / candidate.file_path).is_file():
  7587. self._hold_archive(item.id, candidate.id)
  7588. return candidate
  7589. return None
  7590. async def _repoint_siblings_at_archive(
  7591. self,
  7592. db: AsyncSession,
  7593. *,
  7594. consumed_library_file_id: int,
  7595. archive_id: int,
  7596. dispatched_item_id: int,
  7597. ) -> int:
  7598. """Move the other queue items off a library row that is about to be deleted (#2819).
  7599. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7600. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7601. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7602. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7603. clones, so the first dispatch could pull the file out from under rows that
  7604. had not run yet. What those rows did next depended on the database, and
  7605. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7606. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7607. they were left pointing at a row that no longer existed, failing with
  7608. "Library file not found" whenever someone started them -- or sitting
  7609. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7610. constraint, so there the rows were deleted outright and the queued copies
  7611. simply vanished, with no error and no history.
  7612. The archive holds its own copy of the 3MF, so the remaining copies can print
  7613. from it instead. Two things happen here, and both must happen *before* the
  7614. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7615. * every row still naming the file has ``library_file_id`` cleared, which is
  7616. what takes it out of the cascade's reach. That covers rows this cannot
  7617. re-point as well -- a copy already printing from its own archive, and the
  7618. finished ones, which are not spare parts but the record a batch order
  7619. counts its progress from.
  7620. * the rows that still need something to print are pointed at the archive.
  7621. Returns how many items were re-pointed.
  7622. """
  7623. variant_item_ids = (
  7624. (
  7625. await db.execute(
  7626. select(PrintQueueVariant.queue_item_id).where(
  7627. PrintQueueVariant.library_file_id == consumed_library_file_id
  7628. )
  7629. )
  7630. )
  7631. .scalars()
  7632. .all()
  7633. )
  7634. # Candidate rows naming the consumed file have to go rather than be
  7635. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7636. # one out of the cascade. This is what PostgreSQL already does, and
  7637. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7638. # outcome changes -- the two backends simply stop disagreeing about
  7639. # whether the row is still there.
  7640. #
  7641. # It also has to happen before the re-point below: a cross-model item
  7642. # (#671) picks a variant every pass and folds it onto the row, and
  7643. # _resolve_variant clears archive_id as it does so, which would undo the
  7644. # re-point on the very next lap.
  7645. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7646. # An item left with other candidates still has somewhere to go, and those
  7647. # carry their own target model -- pointing it at this archive would print a
  7648. # file the matcher never chose. It is excluded from the re-point and simply
  7649. # re-resolves against what is left.
  7650. surviving_variant_item_ids = set(
  7651. (
  7652. await db.execute(
  7653. select(PrintQueueVariant.queue_item_id).where(
  7654. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7655. )
  7656. )
  7657. )
  7658. .scalars()
  7659. .all()
  7660. )
  7661. repoint_ids = set(
  7662. (
  7663. await db.execute(
  7664. select(PrintQueueItem.id)
  7665. .where(PrintQueueItem.id != dispatched_item_id)
  7666. .where(PrintQueueItem.archive_id.is_(None))
  7667. # "skipped" belongs here with the two live states: it is not
  7668. # terminal. Clearing a printer's previous-success gate puts
  7669. # every item skipped by it back to "pending"
  7670. # (resume_after_failure), and one restored onto a deleted
  7671. # file is the same orphan by a slower route. "failed",
  7672. # "cancelled", "aborted" and "completed" never return.
  7673. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7674. .where(
  7675. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7676. )
  7677. .where(
  7678. or_(
  7679. PrintQueueItem.library_file_id == consumed_library_file_id,
  7680. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7681. )
  7682. )
  7683. )
  7684. )
  7685. .scalars()
  7686. .all()
  7687. )
  7688. if repoint_ids:
  7689. await db.execute(
  7690. update(PrintQueueItem)
  7691. .where(PrintQueueItem.id.in_(repoint_ids))
  7692. .values(
  7693. archive_id=archive_id,
  7694. library_file_id=None,
  7695. # The file this flag named is already consumed. Leaving it set
  7696. # would arm every re-pointed copy to delete whatever library
  7697. # row it is next given.
  7698. cleanup_library_after_dispatch=False,
  7699. )
  7700. )
  7701. logger.info(
  7702. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7703. sorted(repoint_ids),
  7704. archive_id,
  7705. consumed_library_file_id,
  7706. dispatched_item_id,
  7707. )
  7708. # Everything else that still names the file: taken out of the cascade's
  7709. # reach without touching what it prints. The file is gone either way; what
  7710. # this preserves is the row.
  7711. await db.execute(
  7712. update(PrintQueueItem)
  7713. .where(PrintQueueItem.id != dispatched_item_id)
  7714. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7715. .values(library_file_id=None)
  7716. )
  7717. return len(repoint_ids)
  7718. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7719. """Schedule power-off if the queue item enabled auto_off_after.
  7720. Delegates to the smart-plug manager so the off honours each plug's
  7721. configured strategy (time delay or temperature threshold), is cancelled
  7722. if the printer starts printing again, and never cuts power on a loaded
  7723. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7724. powered off on the timeout regardless of print state.
  7725. """
  7726. if not item.auto_off_after:
  7727. return
  7728. try:
  7729. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7730. except Exception as e:
  7731. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7732. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7733. """Get a human-readable name for a queue item."""
  7734. if item.archive_id:
  7735. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7736. archive = result.scalar_one_or_none()
  7737. if archive:
  7738. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7739. if item.library_file_id:
  7740. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7741. library_file = result.scalar_one_or_none()
  7742. if library_file:
  7743. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7744. # A cross-model item (#671) holds no file of its own until a printer is
  7745. # picked, so name it after its first candidate — otherwise every waiting
  7746. # notification for one reads "Job #12". Queried rather than read off
  7747. # item.variants because callers outside the selection loop have not
  7748. # eager-loaded them, and a lazy load raises in async.
  7749. first_variant_name = (
  7750. await db.execute(
  7751. select(LibraryFile.filename)
  7752. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7753. .where(PrintQueueVariant.queue_item_id == item.id)
  7754. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7755. .limit(1)
  7756. )
  7757. ).scalar_one_or_none()
  7758. if first_variant_name:
  7759. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7760. return f"Job #{item.id}"
  7761. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7762. """Get printer by ID."""
  7763. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7764. return result.scalar_one_or_none()
  7765. async def _notify_dispatch_gave_up(
  7766. self,
  7767. queue_item_id: int,
  7768. printer_id: int,
  7769. created_by_id: int | None,
  7770. reason: str = "Printer accepted the file but never started printing",
  7771. ) -> None:
  7772. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7773. Called from the watchdog, which is a background task with no session of
  7774. its own — hence the fresh one here. Best-effort throughout: the row is
  7775. already marked failed and that is the load-bearing part; a notification
  7776. provider being down must not resurrect the retry loop we just stopped.
  7777. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7778. path passes its own, because "accepted the file but never started" is the
  7779. opposite of what happened there — the printer refused it outright (#2732).
  7780. """
  7781. try:
  7782. async with async_session() as db:
  7783. item = await db.get(PrintQueueItem, queue_item_id)
  7784. if not item:
  7785. return
  7786. job_name = await self._get_job_name(db, item)
  7787. printer = await self._get_printer(db, printer_id)
  7788. await notification_service.on_queue_job_failed(
  7789. job_name=job_name,
  7790. printer_id=printer_id,
  7791. printer_name=printer.name if printer else "Unknown",
  7792. reason=reason,
  7793. db=db,
  7794. )
  7795. except Exception as e:
  7796. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7797. try:
  7798. await ws_manager.send_queue_item_failed(
  7799. user_id=created_by_id,
  7800. queue_item_id=queue_item_id,
  7801. printer_id=printer_id,
  7802. reason="never_started",
  7803. )
  7804. except Exception:
  7805. pass # toast is best-effort
  7806. async def _filament_short_on(
  7807. self,
  7808. db: AsyncSession,
  7809. item: PrintQueueItem,
  7810. printer_id: int,
  7811. *,
  7812. require_known: bool = False,
  7813. ) -> bool:
  7814. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7815. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7816. assigned there, with the mapping the item would get there, but changes
  7817. nothing. The model-based matcher uses it to prefer a printer whose
  7818. spools can finish the job.
  7819. False whenever the gate would let the item through: "Print Anyway",
  7820. no mapping, or a check that fails. With ``require_known`` all three of
  7821. those, and any printed slot whose remaining amount is unknown, count
  7822. as short instead: releasing a held job starts it with nobody asked, so
  7823. it needs the amount on record, not merely nothing against it.
  7824. """
  7825. if item.skip_filament_check:
  7826. return False
  7827. try:
  7828. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7829. if not mapping:
  7830. return require_known
  7831. deficit = await compute_deficit_for_queue_item(
  7832. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7833. )
  7834. except Exception as e:
  7835. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7836. return require_known
  7837. return bool(deficit)
  7838. async def _release_short_model_hold(
  7839. self,
  7840. db: AsyncSession,
  7841. item: PrintQueueItem,
  7842. unavailable: set[int],
  7843. require_plate_clear: bool,
  7844. printer_scope: PrinterScope,
  7845. ) -> bool:
  7846. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7847. The deficit gate holds a model-based job on the printer the matcher
  7848. gave it, because "Print Anyway" needs a printer to print on. When
  7849. another idle printer of the job's model has the filament, the job is
  7850. moved to that printer and its hold lifted, and the fixed-printer
  7851. branch dispatches it in this same pass, through the same checks a
  7852. held job meets when the user presses Start. It is moved rather than
  7853. put back in the pool because the model-based branch would pick again
  7854. without requiring the amounts on record (below), and could pick a
  7855. different printer. Only the deficit gate sets ``filament_short``, so a
  7856. job held for any other reason stays held.
  7857. The printer it is held on is left out: a spool loaded there is started
  7858. with Start, as before, rather than while someone may still be loading
  7859. the next one. Each job is checked at most every
  7860. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7861. on each idle printer again.
  7862. Cross-model jobs (#671) stay held: checking a variant writes its file
  7863. onto the item, which would leave a job that is not moved holding
  7864. another variant's file for the printer it waits on.
  7865. A printer qualifies only on a positive finding: every slot the plate
  7866. prints mapped to a spool whose remaining amount is on record and
  7867. enough. A printer whose spools Bambuddy does not track is not one.
  7868. Returns True when the job was moved. A check that fails keeps the hold
  7869. rather than stopping the queue pass.
  7870. """
  7871. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7872. return False
  7873. if not item.target_model or item.variants:
  7874. return False
  7875. now = time.monotonic()
  7876. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7877. return False
  7878. self._short_hold_checked_at[item.id] = now
  7879. try:
  7880. candidates = _candidates_for(item)
  7881. if not candidates:
  7882. return False
  7883. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7884. async def is_short(pid: int) -> bool:
  7885. return await self._filament_short_on(db, item, pid, require_known=True)
  7886. async def unmatched_on(pid: int) -> list[str]:
  7887. return await self._unmatched_on(db, item, pid)
  7888. match_id, _ = await self._find_idle_printer_for_model(
  7889. db,
  7890. item.target_model,
  7891. unavailable | {item.printer_id},
  7892. effective_types,
  7893. item.target_location,
  7894. filament_overrides=filament_overrides,
  7895. require_plate_clear=require_plate_clear,
  7896. printer_scope=printer_scope,
  7897. is_short=is_short,
  7898. unmatched_on=unmatched_on,
  7899. sliced_nozzle=candidates[0].sliced_nozzle,
  7900. )
  7901. # Every idle printer short comes back as the first of them.
  7902. if match_id is None or await is_short(match_id):
  7903. return False
  7904. except Exception as e:
  7905. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7906. return False
  7907. logger.info(
  7908. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7909. item.id,
  7910. match_id,
  7911. item.printer_id,
  7912. )
  7913. self._short_hold_checked_at.pop(item.id, None)
  7914. item.printer_id = match_id
  7915. # Resolved against the printer it leaves (#3239): the tray mapping and
  7916. # the nozzle positions.
  7917. drop_printer_resolved(item)
  7918. item.manual_start = False
  7919. item.filament_short = False
  7920. item.waiting_reason = None
  7921. await db.commit()
  7922. try:
  7923. printer = await self._get_printer(db, match_id)
  7924. await notification_service.on_queue_job_assigned(
  7925. job_name=await self._get_job_name(db, item),
  7926. printer_id=match_id,
  7927. printer_name=printer.name if printer else "Unknown",
  7928. target_model=item.target_model,
  7929. db=db,
  7930. )
  7931. except Exception as e:
  7932. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7933. return True
  7934. async def _block_on_filament_deficit(
  7935. self,
  7936. db: AsyncSession,
  7937. item: PrintQueueItem,
  7938. ) -> bool:
  7939. """Promote the item to manual_start when the assigned spool is short (#1496).
  7940. Returns True when this dispatch attempt was blocked, False when the
  7941. item is clear to start. A previously-flagged item whose spool has
  7942. since been swapped to one with enough material clears the flag here
  7943. so the next scheduler tick dispatches it.
  7944. """
  7945. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7946. # don't re-flag, don't even compute. Without this short-circuit the
  7947. # scheduler bounces between "user said anyway" (route clears
  7948. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7949. # on identical spool state) (#1698-followup).
  7950. if item.skip_filament_check:
  7951. # #1762 diagnostic: surface the short-circuit at INFO so a
  7952. # future "Print Anyway didn't work" report (e.g. issue #1762
  7953. # comment 3) has actionable evidence in the support bundle
  7954. # without needing DEBUG enabled.
  7955. logger.info(
  7956. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7957. item.id,
  7958. )
  7959. return False
  7960. try:
  7961. deficit = await compute_deficit_for_queue_item(db, item)
  7962. except Exception as e:
  7963. # Never let a flaky deficit check wedge the queue — log and let
  7964. # dispatch proceed. The PrintModal-side check still runs on the
  7965. # manual paths.
  7966. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7967. return False
  7968. if deficit:
  7969. item.filament_short = True
  7970. item.manual_start = True
  7971. await db.commit()
  7972. job_name = await self._get_job_name(db, item)
  7973. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7974. logger.info(
  7975. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7976. item.id,
  7977. len(deficit),
  7978. )
  7979. try:
  7980. await notification_service.on_queue_job_waiting(
  7981. job_name=job_name,
  7982. target_model=(printer.model if printer else "") or "",
  7983. waiting_reason="filament_short",
  7984. db=db,
  7985. printer_id=item.printer_id,
  7986. )
  7987. except Exception as e:
  7988. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7989. return True
  7990. # No deficit — clear any stale flag from a previous tick.
  7991. if item.filament_short:
  7992. item.filament_short = False
  7993. await db.commit()
  7994. return False
  7995. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7996. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7997. Compared the way the matcher compares, so the same hex or a similar one
  7998. is a match. Only slots the plate prints, mapped to a tray the printer
  7999. reports, with a colour on both sides: anything else is not a colour the
  8000. job printed in.
  8001. """
  8002. by_tray = {f["global_tray_id"]: f for f in loaded}
  8003. found = []
  8004. for req in required:
  8005. slot_id = req.get("slot_id") or 0
  8006. if slot_id <= 0 or slot_id > len(mapping):
  8007. continue
  8008. tray_id = mapping[slot_id - 1]
  8009. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  8010. if tray is not None and tray.get("color_known") is False:
  8011. # A spool without a colour set is not a different colour.
  8012. continue
  8013. wanted = self._normalize_color_for_compare(req.get("color"))
  8014. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  8015. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  8016. continue
  8017. found.append(
  8018. {
  8019. "slot_id": slot_id,
  8020. "type": req.get("type") or "",
  8021. "wanted": f"#{wanted.upper()}",
  8022. "got": f"#{got.upper()}",
  8023. "tray": tray_id,
  8024. }
  8025. )
  8026. return found
  8027. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  8028. """``item``'s colour substitutions as stored on the row, or None (#3279).
  8029. Read from the mapping the job is about to be sent with, whoever made
  8030. it: the matcher's same-material fallback, a preset match in another
  8031. colour, or a slot picked by hand. The file's colour is the one after
  8032. overrides, so a colour swapped on purpose is not one. None whenever
  8033. there is nothing to compare, and on any failure: a missing note must
  8034. never stop a print.
  8035. """
  8036. try:
  8037. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  8038. if not isinstance(mapping, list) or not item.printer_id:
  8039. return None
  8040. status = printer_manager.get_status(item.printer_id)
  8041. if status is None:
  8042. return None
  8043. required = await self._get_filament_requirements(db, item)
  8044. if not required:
  8045. return None
  8046. self._apply_filament_overrides(item, required)
  8047. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  8048. except Exception as e:
  8049. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  8050. return None
  8051. if found:
  8052. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  8053. return json.dumps(found) if found else None
  8054. async def _unmatched_requirements(
  8055. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  8056. ) -> list[dict]:
  8057. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  8058. ``None`` is a mapping that resolved nothing. Only a printer that reported
  8059. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  8060. on why an empty list is not one.
  8061. """
  8062. if mapping is None:
  8063. status = printer_manager.get_status(printer_id)
  8064. if status is None or not self._build_loaded_filaments(status):
  8065. return []
  8066. # Every required slot reads unresolved against an empty mapping.
  8067. mapping = []
  8068. required = await self._get_filament_requirements(db, item)
  8069. if required:
  8070. self._apply_filament_overrides(item, required)
  8071. else:
  8072. # An unreadable 3MF still has its forced colours to go by: they are
  8073. # what the mapping was built from (#3280).
  8074. required = _forced_override_requirements(item)
  8075. return _unresolved_required(required, mapping) if required else []
  8076. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  8077. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  8078. Asks the matcher and the unmatched-filament hold, but changes nothing.
  8079. Choosing a printer for an "any model" job only checked that each type
  8080. and forced colour was loaded somewhere, which a dual-nozzle printer with
  8081. the spool on the other nozzle, or one spool asked for twice, passes. The
  8082. hold then gave the printer back, and the next pass chose it again.
  8083. Empty when the hold would let the item through, including "Print
  8084. Anyway" and a match that fails: the printer is then chosen as before.
  8085. """
  8086. if item.skip_filament_check:
  8087. return []
  8088. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  8089. if key in self._unmatched_memo:
  8090. return list(self._unmatched_memo[key])
  8091. try:
  8092. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  8093. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  8094. except Exception as e:
  8095. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  8096. return []
  8097. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  8098. self._unmatched_memo[key] = described
  8099. return list(described)
  8100. async def _block_on_unmatched_filament(
  8101. self,
  8102. db: AsyncSession,
  8103. item: PrintQueueItem,
  8104. release_assignment: bool = False,
  8105. ) -> bool:
  8106. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  8107. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  8108. goes ahead, letting the printer choose — which is how a job prints in the
  8109. wrong material without anyone being asked. Holding is the same answer the
  8110. deficit gate already gives for "the spool is too light", so it reuses the
  8111. same promote-and-notify machinery.
  8112. Keyed off unresolved slots in the *computed* mapping intersected with the
  8113. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  8114. read: on its own it also pads slots this plate does not print, so the
  8115. array alone would hold perfectly good jobs. Reading the mapping rather
  8116. than the printer's loaded filament types also inherits the matcher's
  8117. per-nozzle restriction for free — a dual-nozzle printer carrying the
  8118. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  8119. type-only scan would wave that through.
  8120. A mapping that resolved *nothing* is the same finding arriving as an
  8121. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  8122. could not replace, and dispatch then goes out as ``use_ams`` with no
  8123. table at all — several megabytes uploaded for an 0700_8012 rejection.
  8124. That is held too, but only once live status positively reports loaded
  8125. trays: #2589's mapping is bogus precisely because the AMS was not known
  8126. yet, and its empty loaded list is that ignorance rather than a miss.
  8127. ``release_assignment`` is for the model-based path, which commits its
  8128. printer choice before the gates run. Holding an "any P2S" job would
  8129. otherwise pin it to the one P2S that could not run it.
  8130. Returns True when this dispatch attempt was blocked.
  8131. """
  8132. if item.skip_filament_check or not item.printer_id:
  8133. return False
  8134. mapping: list | None = None
  8135. if item.ams_mapping:
  8136. try:
  8137. mapping = json.loads(item.ams_mapping)
  8138. except (json.JSONDecodeError, TypeError):
  8139. return False
  8140. if not isinstance(mapping, list):
  8141. return False
  8142. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  8143. if not unmatched:
  8144. # No cleanup needed here: once start is pressed the item is no
  8145. # longer staged, and whichever exit runs next overwrites the reason
  8146. # (`hold_item` on the fixed-printer branch, the assignment on the
  8147. # model-based one), as does dispatch.
  8148. return False
  8149. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  8150. held_by = item.printer_id
  8151. item.manual_start = True
  8152. # Human-readable: this renders on the queue row.
  8153. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  8154. if release_assignment:
  8155. # "Any P2S" means any, so the job returns to the pool rather than
  8156. # waiting on the printer that could not take it. The mapping goes
  8157. # with the assignment: its tray IDs were resolved against the
  8158. # printer being released and mean nothing on the next one (#2799),
  8159. # and keeping them would hold the job again even on a printer that
  8160. # has the filament, since an unresolved slot is deliberately not a
  8161. # conflict worth recomputing over.
  8162. item.printer_id = None
  8163. drop_printer_resolved(item)
  8164. await db.commit()
  8165. job_name = await self._get_job_name(db, item)
  8166. printer = await self._get_printer(db, held_by)
  8167. logger.info(
  8168. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  8169. item.id,
  8170. held_by,
  8171. wanted,
  8172. )
  8173. try:
  8174. await notification_service.on_queue_job_waiting(
  8175. job_name=job_name,
  8176. target_model=(printer.model if printer else "") or "",
  8177. waiting_reason=f"needs {wanted}",
  8178. db=db,
  8179. # Released to the pool: no printer holds it any more.
  8180. printer_id=None if release_assignment else held_by,
  8181. )
  8182. except Exception as e:
  8183. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  8184. return True
  8185. @staticmethod
  8186. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  8187. """The queue item's owner as the row has it now.
  8188. item.created_by_id was read before preheat and upload, which can take
  8189. minutes; deleting the user clears the row, not this session's copy.
  8190. """
  8191. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  8192. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  8193. """Hand the queue item's owner to printer_manager so the
  8194. print-complete callback can credit the user in PrintLogEntry (#1670).
  8195. No-ops when the item has no `created_by_id` or the referenced user
  8196. row is missing (e.g. user deleted between queue-add and dispatch —
  8197. in that case the print log row falls back to the existing un-credited
  8198. behaviour rather than crashing the dispatch).
  8199. """
  8200. from backend.app.models.user import User
  8201. # Read from the row, not item.created_by_id or db.get: both can still
  8202. # hold a user deleted during the upload, after delete_user forgot them
  8203. # (on SQLite the id may be someone new's by the time the print ends).
  8204. # Joined with the printer too: one deleted during the upload was
  8205. # forgotten as well, and this would write the owner back under its id.
  8206. owner = (
  8207. await db.execute(
  8208. select(User.id, User.username)
  8209. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  8210. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  8211. .where(PrintQueueItem.id == item.id)
  8212. )
  8213. ).first()
  8214. if owner:
  8215. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  8216. if item.printer_id is not None:
  8217. self._unconfirmed_print_user[item.id] = item.printer_id
  8218. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  8219. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  8220. A cancel lands in another session while the upload runs (the edit route
  8221. even tells users to cancel a job that is being sent). An unconditional
  8222. write here would turn that cancellation into a failure, with a failure
  8223. notification, and block the next job that needs the previous print to
  8224. have succeeded. Returns whether the item was marked failed.
  8225. """
  8226. result = cast(
  8227. CursorResult,
  8228. await db.execute(
  8229. update(PrintQueueItem)
  8230. .where(PrintQueueItem.id == item.id)
  8231. .where(PrintQueueItem.status.in_(("pending", "printing")))
  8232. # Failed before the print started: no slot printed in any colour (#3279).
  8233. .values(
  8234. status="failed",
  8235. error_message=message,
  8236. completed_at=datetime.now(timezone.utc),
  8237. color_substitutions=None,
  8238. )
  8239. .execution_options(synchronize_session=False)
  8240. ),
  8241. )
  8242. await db.commit()
  8243. if result.rowcount == 0:
  8244. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  8245. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  8246. return False
  8247. await db.refresh(item)
  8248. from backend.app.services.print_batch import refresh_batches_after
  8249. await refresh_batches_after([item.id])
  8250. return True
  8251. @staticmethod
  8252. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  8253. """Put a job whose printer turned busy before the start back in the queue.
  8254. Only if it is still printing: a stop that landed meanwhile stands.
  8255. """
  8256. await db.execute(
  8257. update(PrintQueueItem)
  8258. .where(PrintQueueItem.id == item.id)
  8259. .where(PrintQueueItem.status == "printing")
  8260. .values(status="pending", started_at=None, color_substitutions=None)
  8261. .execution_options(synchronize_session=False)
  8262. )
  8263. await db.commit()
  8264. @staticmethod
  8265. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  8266. """Close the dispatch toast of an item the user cancelled while it was sent."""
  8267. try:
  8268. await ws_manager.send_queue_item_failed(
  8269. user_id=toast_uid,
  8270. queue_item_id=item.id,
  8271. printer_id=item.printer_id,
  8272. reason="cancelled_mid_dispatch",
  8273. )
  8274. except Exception:
  8275. pass # toast is best-effort
  8276. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  8277. """Upload file and start print for a queue item.
  8278. Supports two sources:
  8279. - archive_id: Print from an existing archive
  8280. - library_file_id: Print from a library file (file manager)
  8281. """
  8282. logger.info("Starting queue item %s", item.id)
  8283. # Also covers a reservation left active by a process interruption
  8284. # during an earlier attempt. `_dispatch_one` releases this marker on
  8285. # every exit unless start_print() confirms that the command was sent.
  8286. self._unconfirmed_budget_reservations.add(item.id)
  8287. try:
  8288. from backend.app.models.user import User
  8289. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  8290. # Recompute at the final authorization boundary as well as enqueue
  8291. # time. This covers rows created before the server-side estimate
  8292. # migration and prevents any alternate write path from weakening
  8293. # the budget reservation.
  8294. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  8295. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  8296. item.estimated_cost = await estimate_queue_source_cost(
  8297. db,
  8298. archive=archive,
  8299. library_file=library_file,
  8300. plate_id=item.plate_id,
  8301. ams_mapping=item.ams_mapping,
  8302. printer_id=item.printer_id,
  8303. )
  8304. await validate_print_budget(
  8305. db,
  8306. cost_center_id=item.cost_center_id,
  8307. estimated_cost=item.estimated_cost,
  8308. current_user=queue_user,
  8309. exclude_queue_item_id=item.id,
  8310. exclude_reservation_source_type="print_queue",
  8311. exclude_reservation_source_id=item.id,
  8312. )
  8313. budget_reservation = await create_budget_reservation(
  8314. db,
  8315. cost_center_id=item.cost_center_id,
  8316. estimated_cost=item.estimated_cost,
  8317. current_user=queue_user,
  8318. source_type="print_queue",
  8319. source_id=item.id,
  8320. print_archive_id=item.archive_id,
  8321. exclude_queue_item_id=item.id,
  8322. )
  8323. await db.commit()
  8324. except HTTPException as exc:
  8325. if not await self._fail_dispatch(db, item, str(exc.detail)):
  8326. return
  8327. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  8328. await self._power_off_if_needed(db, item)
  8329. return
  8330. # Get printer first (needed for both paths)
  8331. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  8332. printer = result.scalar_one_or_none()
  8333. if not printer:
  8334. if not await self._fail_dispatch(db, item, "Printer not found"):
  8335. return
  8336. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  8337. await self._power_off_if_needed(db, item)
  8338. return
  8339. # Check printer is connected
  8340. if not printer_manager.is_connected(item.printer_id):
  8341. if not await self._fail_dispatch(db, item, "Printer not connected"):
  8342. return
  8343. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  8344. await self._power_off_if_needed(db, item)
  8345. return
  8346. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  8347. # `items` was taken at the top of check_queue, but the user can /cancel
  8348. # any pending row in the gap before we reach this point. Re-read the
  8349. # row and bail out cleanly instead of starting an FTP upload for a row
  8350. # that's already cancelled. The atomic CAS at the pending→printing
  8351. # transition (below, before start_print) is the load-bearing guard;
  8352. # this is the early-exit optimisation that avoids wasted FTP I/O.
  8353. await db.refresh(item)
  8354. if item.status != "pending":
  8355. logger.info(
  8356. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  8357. item.id,
  8358. item.status,
  8359. )
  8360. return
  8361. # Busy-printer guard (#2598). check_queue gates dispatch on
  8362. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  8363. # keep reporting FINISH for tens of seconds *after* it accepted a
  8364. # project_file (see the watchdog's phase-B note). A watchdog revert
  8365. # (#2555) also releases the dispatch hold, so a re-selected item can
  8366. # reach here while its printer has actually started printing. Uploading
  8367. # and dispatching then collides with the live job — the firmware answers
  8368. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  8369. # live state right before the expensive FTP upload: if the printer is
  8370. # busy, leave the item pending and let a later tick dispatch it once the
  8371. # printer is genuinely idle. No wasted upload, no collision.
  8372. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8373. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  8374. logger.info(
  8375. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  8376. "leaving item pending for a later tick (#2598)",
  8377. item.id,
  8378. item.printer_id,
  8379. pre_dispatch_state,
  8380. )
  8381. return
  8382. # Determine source: archive or library file
  8383. archive = None
  8384. library_file = None
  8385. file_path = None
  8386. filename = None
  8387. cleanup_disk_paths: list[Path] = []
  8388. # Set when a dispatch consumes its library file, so the photos can be
  8389. # carried over after the commit that removes the row (#3077).
  8390. consumed_library_file_id: int | None = None
  8391. consumed_photos: list[str] = []
  8392. if item.archive_id:
  8393. # Print from archive
  8394. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  8395. archive = result.scalar_one_or_none()
  8396. if archive is not None and archive.deleted_at is not None:
  8397. # Merged into another archive since it was queued (archive
  8398. # redesign P2): print that one, whose file it now holds.
  8399. from backend.app.services.archive_merge import resolve_alias
  8400. if (into := await resolve_alias(db, archive.id)) is not None:
  8401. archive = await db.get(PrintArchive, into)
  8402. if archive is not None:
  8403. item.archive_id = archive.id
  8404. if not archive:
  8405. if not await self._fail_dispatch(db, item, "Archive not found"):
  8406. return
  8407. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  8408. await self._power_off_if_needed(db, item)
  8409. return
  8410. # Persist the queue item's selected plate onto the archive so Print
  8411. # History can show the actual plate after cancel/fail/complete (#2603).
  8412. # The archive shows its latest run's plate; each run keeps its own
  8413. # on its print log entry.
  8414. if item.plate_id is not None:
  8415. archive.plate_id = item.plate_id
  8416. # Ask-for-outcome opt-in rides from the queue item to the archive
  8417. # the same way (#1898); never cleared here so a reprint of an
  8418. # archive that already asked keeps asking.
  8419. if item.confirm_outcome:
  8420. archive.confirm_requested = True
  8421. file_path = settings.base_dir / archive.file_path
  8422. filename = archive.filename
  8423. elif item.library_file_id:
  8424. # Print from library file (file manager)
  8425. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  8426. library_file = result.scalar_one_or_none()
  8427. if not library_file:
  8428. # "Not found" covers two different situations and only one of
  8429. # them is recoverable, so say which. A trashed file is still
  8430. # there and restoring it makes a re-queued job work; a file that
  8431. # is really gone needs a different one. Neither is knowable from
  8432. # the queue, which is the whole complaint about this message.
  8433. trashed = (
  8434. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  8435. ).scalar_one_or_none()
  8436. if not await self._fail_dispatch(
  8437. db,
  8438. item,
  8439. (
  8440. f"'{trashed}' is in the library trash — restore it and queue the print again"
  8441. if trashed
  8442. else "Library file not found — it was deleted after this job was queued"
  8443. ),
  8444. ):
  8445. return
  8446. logger.error(
  8447. "Queue item %s: library file %s is %s",
  8448. item.id,
  8449. item.library_file_id,
  8450. "in the trash" if trashed else "gone",
  8451. )
  8452. await self._power_off_if_needed(db, item)
  8453. return
  8454. # Library files store absolute paths
  8455. lib_path = Path(library_file.file_path)
  8456. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  8457. filename = library_file.filename
  8458. # Create archive from library file so usage tracking has access to the 3MF
  8459. queue_item_id = item.id
  8460. # Held separately: a cleanup dispatch clears item.library_file_id
  8461. # below, and the log line at the end of this block reported that
  8462. # cleared field -- so every consumed print logged "from library
  8463. # file None", which is the one case worth being able to trace.
  8464. source_library_file_id = item.library_file_id
  8465. reused_archive = False
  8466. try:
  8467. from backend.app.services.archive import ArchiveService
  8468. # The file printed before: this run joins its archive rather
  8469. # than archiving the same file a second time.
  8470. archive = await self._claim_reusable_archive(db, item, file_path)
  8471. if archive is not None:
  8472. reused_archive = True
  8473. if archive.library_file_id is None:
  8474. archive.library_file_id = item.library_file_id
  8475. # This run's, as a new archive would have them: the
  8476. # archive shows its latest run's plate, and a print
  8477. # without a queue item falls back to the archive's plate
  8478. # and cost centre. Not while another print of it runs: they
  8479. # are that print's (this one's run has its own, from the
  8480. # dispatch), and the archive takes the latest run's plate
  8481. # once none prints (print_log.mirror_latest_run).
  8482. if not await self._printing_elsewhere(db, archive.id):
  8483. if item.plate_id is not None:
  8484. archive.plate_id = item.plate_id
  8485. archive.cost_center_id = item.cost_center_id
  8486. else:
  8487. archive_service = ArchiveService(db)
  8488. archive = await archive_service.archive_print(
  8489. printer_id=item.printer_id,
  8490. source_file=file_path,
  8491. original_filename=filename,
  8492. created_by_id=item.created_by_id,
  8493. project_id=item.project_id,
  8494. cost_center_id=item.cost_center_id,
  8495. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8496. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8497. )
  8498. if archive:
  8499. self._hold_archive(item.id, archive.id)
  8500. item.archive_id = archive.id
  8501. if item.confirm_outcome:
  8502. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8503. if budget_reservation is not None:
  8504. budget_reservation.print_archive_id = archive.id
  8505. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8506. consumed_library_file_id = library_file.id
  8507. item.library_file_id = None
  8508. cleanup_disk_paths.append(file_path)
  8509. if library_file.thumbnail_path:
  8510. thumb_path = Path(library_file.thumbnail_path)
  8511. if not thumb_path.is_absolute():
  8512. thumb_path = settings.base_dir / library_file.thumbnail_path
  8513. cleanup_disk_paths.append(thumb_path)
  8514. # Before the delete, not after: on PostgreSQL the FK
  8515. # cascade would already have taken these rows (#2819).
  8516. await self._repoint_siblings_at_archive(
  8517. db,
  8518. consumed_library_file_id=consumed_library_file_id,
  8519. archive_id=archive.id,
  8520. dispatched_item_id=item.id,
  8521. )
  8522. # Read while the row is still here; the photos move
  8523. # below, once the delete has actually committed.
  8524. consumed_photos = list(library_file.photos or [])
  8525. # The delete clears the link on the earlier archives of
  8526. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8527. # SQLite). This one is loaded, so set it here too, or it
  8528. # keeps the stale id in the session.
  8529. archive.library_file_id = None
  8530. await db.delete(library_file)
  8531. file_path = settings.base_dir / archive.file_path
  8532. filename = archive.filename
  8533. # Commit, not flush — flush opens the SQLite write
  8534. # transaction (item.archive_id update + library_file
  8535. # delete) and would hold the WAL writer lock through the
  8536. # FTP upload below, causing "database is locked" cascades
  8537. # for sensor history + concurrent cancels (#1853).
  8538. await db.commit()
  8539. logger.info(
  8540. "Queue item %s: %s archive %s from library file %s",
  8541. item.id,
  8542. "Reused" if reused_archive else "Created",
  8543. archive.id,
  8544. source_library_file_id,
  8545. )
  8546. except Exception as e:
  8547. logger.warning(
  8548. "Queue item %s: Failed to create archive from library file: %s",
  8549. queue_item_id,
  8550. e,
  8551. exc_info=True,
  8552. )
  8553. await db.rollback()
  8554. item = await db.get(PrintQueueItem, queue_item_id)
  8555. if item:
  8556. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8557. return
  8558. await self._power_off_if_needed(db, item)
  8559. return
  8560. if not archive:
  8561. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8562. return
  8563. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8564. await self._power_off_if_needed(db, item)
  8565. return
  8566. # The photos follow the file into the archive that replaces it, for
  8567. # the same reason the siblings do (#3077). After the commit above,
  8568. # never before it: that commit can fail ("database is locked",
  8569. # #1853) and roll the library row back, and photos already moved
  8570. # would leave it naming a directory that no longer exists. The
  8571. # file and thumbnail unlinks are deferred for the same reason.
  8572. if consumed_library_file_id is not None and consumed_photos:
  8573. # Held as a plain int, read here while the session is still
  8574. # healthy, because the handler below may not touch an ORM
  8575. # instance at all. The commit it exists for fails inside the
  8576. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8577. # first DML statement, so a busy writer surfaces as "database
  8578. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8579. # internally through safe_reraise before re-raising, which
  8580. # expires every loaded instance and leaves the session in
  8581. # pending-rollback state -- so `archive.id` inside the except
  8582. # would itself raise PendingRollbackError and the rollback
  8583. # below would never be reached.
  8584. archive_id = archive.id
  8585. try:
  8586. carried_photos = move_library_photos(
  8587. consumed_library_file_id,
  8588. consumed_photos,
  8589. archive_photos_dir(archive),
  8590. )
  8591. if carried_photos:
  8592. archive.photos = list(archive.photos or []) + carried_photos
  8593. await db.commit()
  8594. except Exception as e:
  8595. # The archive and the delete are already committed; the
  8596. # print goes ahead either way. Worst case the pictures sit
  8597. # unnamed in the archive's own directory.
  8598. #
  8599. # Ints only until the rollback has run, per the note above,
  8600. # which is why this logs queue_item_id and not item.id --
  8601. # the sibling handler forty lines up does the same.
  8602. logger.warning(
  8603. "Queue item %s: failed to carry library photos into archive %s: %s",
  8604. queue_item_id,
  8605. archive_id,
  8606. e,
  8607. )
  8608. await db.rollback()
  8609. # rollback() expires every loaded instance, and in async
  8610. # SQLAlchemy the next plain attribute read is lazy IO
  8611. # outside the greenlet -- MissingGreenlet, which would turn
  8612. # this cosmetic failure into a dispatch crash in exactly the
  8613. # "database is locked" case the block exists for (#1853).
  8614. # The nozzle guard, the upload and the start all keep
  8615. # reading item, archive and printer, so all three go back
  8616. # into the session before falling through.
  8617. item = await db.get(PrintQueueItem, queue_item_id)
  8618. archive = await db.get(PrintArchive, archive_id)
  8619. printer = await db.get(Printer, item.printer_id) if item else None
  8620. if not item or not archive or not printer:
  8621. logger.error(
  8622. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8623. queue_item_id,
  8624. archive_id,
  8625. )
  8626. return
  8627. else:
  8628. # Neither archive nor library file specified
  8629. if not await self._fail_dispatch(db, item, "No source file specified"):
  8630. return
  8631. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8632. await self._power_off_if_needed(db, item)
  8633. return
  8634. # Check file exists on disk
  8635. if not file_path.exists():
  8636. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8637. return
  8638. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8639. await self._power_off_if_needed(db, item)
  8640. return
  8641. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8642. # size dispatched to a printer with a different nozzle installed is
  8643. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8644. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8645. # gives the user no idea what went wrong. Catch it here, before we spend
  8646. # time preheating and uploading, and fail with an actionable message.
  8647. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8648. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8649. # the printer hasn't reported its nozzles yet, we fall through and let the
  8650. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8651. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8652. # as one of the two hotends is a 0.6.
  8653. #
  8654. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8655. # (#2885): the printer fetches one as part of starting the print, so the
  8656. # set to test against is "reachable", not "currently mounted". This runs
  8657. # well before the rack picker at the bottom of this method, so without
  8658. # the rack in scope here that picker never got the chance to run.
  8659. sliced_nozzle = archive.nozzle_diameter if archive else None
  8660. if sliced_nozzle:
  8661. nozzle_status = printer_manager.get_status(item.printer_id)
  8662. installed = _installed_nozzle_diameters(nozzle_status)
  8663. rack = _rack_nozzle_diameters(nozzle_status)
  8664. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8665. if mismatch_msg:
  8666. if not await self._fail_dispatch(db, item, mismatch_msg):
  8667. return
  8668. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8669. await notification_service.on_queue_job_failed(
  8670. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8671. printer_id=printer.id,
  8672. printer_name=printer.name,
  8673. reason=mismatch_msg,
  8674. db=db,
  8675. )
  8676. try:
  8677. await ws_manager.send_queue_item_failed(
  8678. user_id=item.created_by_id,
  8679. queue_item_id=item.id,
  8680. printer_id=item.printer_id,
  8681. reason="nozzle_mismatch",
  8682. )
  8683. except Exception:
  8684. pass
  8685. await self._power_off_if_needed(db, item)
  8686. return
  8687. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8688. # bed (and chamber, if applicable) is at temperature when the firmware
  8689. # starts the actual print routine. Best-effort: any failure logs and
  8690. # falls through to the normal upload+start path rather than turning a
  8691. # configuration issue into a failed queue item.
  8692. # Returns False only when the item was cancelled or deleted while the
  8693. # stage was holding at temperature. Uploading and starting it anyway
  8694. # would print a job the user has already called off, so abandon the
  8695. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8696. if not await self._preheat_and_soak(db, item, printer, archive):
  8697. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8698. return
  8699. # See `_effective_plate_id` for why this is resolved once here rather
  8700. # than each site below repeating `item.plate_id or 1`.
  8701. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8702. # G-code injection for auto-print systems (#422)
  8703. injected_path = None
  8704. # #2547: tracked separately from `injected_path`, which is also set when
  8705. # only a START snippet was injected. Only an END snippet changes what the
  8706. # camera sees at print completion.
  8707. end_gcode_injected = False
  8708. if item.gcode_injection:
  8709. try:
  8710. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8711. if snippets_raw:
  8712. snippets = json.loads(snippets_raw)
  8713. model_snippets = snippets.get(printer.model, {})
  8714. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8715. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8716. if start_gc or end_gc:
  8717. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8718. injected_path = inject_gcode_into_3mf(
  8719. file_path, effective_plate_id, start_gc or None, end_gc or None
  8720. )
  8721. if injected_path:
  8722. file_path = injected_path
  8723. end_gcode_injected = bool(end_gc)
  8724. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8725. else:
  8726. logger.warning(
  8727. "Queue item %s: G-code injection returned no result, using original", item.id
  8728. )
  8729. except Exception as e:
  8730. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8731. # #2547: the finish-photo path can't learn from telemetry that this print
  8732. # ends with user End G-code — which means the plate may be gone by the
  8733. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8734. # the print once the printer confirms it running.
  8735. if end_gcode_injected:
  8736. print_dispatch_context.mark_pending(printer.id)
  8737. # Upload to root directory (not /cache/) - the start_print command references
  8738. # files by name only (ftp://{filename}), so they must be in the root
  8739. remote_filename = derive_remote_filename(filename)
  8740. remote_path = f"/{remote_filename}"
  8741. # Get FTP retry settings
  8742. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8743. logger.info(
  8744. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8745. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8746. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8747. )
  8748. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8749. # Every read this method needs (printer, archive/library, preheat) is
  8750. # done, and the library-file branch already committed its archive
  8751. # creation. Without this the transaction opened by the first SELECT above
  8752. # stays "idle in transaction" for the entire upload — multiple seconds
  8753. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8754. # a farm dispatching many jobs at once then exhausts the pool. This was
  8755. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8756. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8757. # readable; the status writes below (upload-failure path and the
  8758. # pending->printing CAS) transparently open a fresh transaction.
  8759. # The owner is read here, after preheat, so the commit releases this read too.
  8760. toast_uid = await self._queue_owner_id(db, item)
  8761. await db.commit()
  8762. # Delete existing file if present (avoids 553 error on overwrite)
  8763. try:
  8764. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8765. delete_result = await delete_file_async(
  8766. printer.ip_address,
  8767. printer.access_code,
  8768. remote_path,
  8769. socket_timeout=ftp_timeout,
  8770. printer_model=printer.model,
  8771. # This delete and the upload below are one bounded, user-initiated
  8772. # unit -- at most nine connections -- so neither skips on the
  8773. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8774. # trace this delete took the TLS failure and armed the cool-off,
  8775. # and the upload's four attempts were then spent against it
  8776. # without a socket being opened.
  8777. respect_handshake_cooloff=False,
  8778. )
  8779. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8780. except Exception as e:
  8781. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8782. # Dispatch toast — announce the upload start with the total byte
  8783. # count so the frontend can render an honest progress bar.
  8784. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8785. try:
  8786. total_bytes = file_path.stat().st_size
  8787. except OSError:
  8788. total_bytes = 0
  8789. try:
  8790. await ws_manager.send_queue_item_uploading(
  8791. user_id=toast_uid,
  8792. queue_item_id=item.id,
  8793. printer_id=item.printer_id,
  8794. printer_name=printer.name,
  8795. file_name=toast_file_name,
  8796. total_bytes=total_bytes,
  8797. )
  8798. except Exception:
  8799. pass # toast is best-effort
  8800. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8801. # A deadline expiry gets its own message: "check your SD card" is the
  8802. # wrong advice for a link that was simply too slow to finish (#2529).
  8803. upload_error: str | None = None
  8804. # Why the upload failed, straight from the client rather than inferred.
  8805. # Owned here, so a background fetch for another print cannot overwrite
  8806. # it between the failure and the sentence built from it (#2899).
  8807. upload_failure = FtpFailureReport()
  8808. try:
  8809. # The printer's MQTT goes quiet while it receives the file; the
  8810. # stale check must not reconnect it under the print command (#3538).
  8811. with printer_manager.uploading(item.printer_id):
  8812. if ftp_retry_enabled:
  8813. uploaded = await with_ftp_retry(
  8814. upload_file_async,
  8815. printer.ip_address,
  8816. printer.access_code,
  8817. file_path,
  8818. remote_path,
  8819. socket_timeout=ftp_timeout,
  8820. printer_model=printer.model,
  8821. progress_callback=progress_bridge,
  8822. respect_handshake_cooloff=False,
  8823. failure=upload_failure,
  8824. max_retries=ftp_retry_count,
  8825. retry_delay=ftp_retry_delay,
  8826. operation_name=f"Upload print to {printer.name}",
  8827. )
  8828. else:
  8829. uploaded = await upload_file_async(
  8830. printer.ip_address,
  8831. printer.access_code,
  8832. file_path,
  8833. remote_path,
  8834. socket_timeout=ftp_timeout,
  8835. printer_model=printer.model,
  8836. progress_callback=progress_bridge,
  8837. respect_handshake_cooloff=False,
  8838. failure=upload_failure,
  8839. )
  8840. except UploadCancelled as e:
  8841. uploaded = False
  8842. upload_error = (
  8843. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8844. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8845. )
  8846. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8847. except Exception as e:
  8848. uploaded = False
  8849. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8850. # Clean up injected temp file after upload attempt
  8851. if injected_path and injected_path.exists():
  8852. injected_path.unlink(missing_ok=True)
  8853. # Again after the upload, which can take minutes: an owner deleted
  8854. # meanwhile gets no more toasts, and neither does whoever has their id.
  8855. toast_uid = await self._queue_owner_id(db, item)
  8856. # The printer's copy at this path was replaced (or deleted above): the
  8857. # file browser's previews must not show the old one.
  8858. from backend.app.services.printer_file_cache import printer_file_cache
  8859. printer_file_cache.forget(printer.id, remote_path)
  8860. if not uploaded:
  8861. # This used to be one string for every upload failure, telling
  8862. # everyone to check the SD card. The client knows which of seven
  8863. # things went wrong and logs each one differently; it just had no
  8864. # way to say so here, so the card got named even for a TLS
  8865. # handshake that never reached the printer's filesystem (#2899).
  8866. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8867. failure = upload_failure.failure
  8868. if failure is not None and failure.kind is FtpFailureKind.STORAGE:
  8869. try:
  8870. validate_print_filename(remote_filename)
  8871. except InvalidFilenameError as e:
  8872. # This 553 is the file's name, which no card can hold, not
  8873. # the printer's storage: it would be refused on every retry
  8874. # and every printer, so this item fails and the queue goes on.
  8875. upload_error = f"The printer could not create the file {remote_filename!r}: {e}. Rename the file."
  8876. error_msg = upload_error
  8877. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8878. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid, failure.kind)
  8879. return
  8880. if not await self._fail_dispatch(db, item, error_msg):
  8881. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8882. return
  8883. logger.error(
  8884. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8885. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8886. )
  8887. # Send failure notification
  8888. await notification_service.on_queue_job_failed(
  8889. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8890. printer_id=printer.id,
  8891. printer_name=printer.name,
  8892. # The same sentence the queue shows. A push notification saying
  8893. # something different from the UI is its own small bug (#2899).
  8894. reason=error_msg,
  8895. db=db,
  8896. )
  8897. try:
  8898. await ws_manager.send_queue_item_failed(
  8899. user_id=toast_uid,
  8900. queue_item_id=item.id,
  8901. printer_id=item.printer_id,
  8902. reason="upload_failed",
  8903. )
  8904. except Exception:
  8905. pass
  8906. await self._power_off_if_needed(db, item)
  8907. return
  8908. # The printer took a file, so any run of refused uploads is over: the
  8909. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8910. self._upload_refusals.pop(printer.id, None)
  8911. self._upload_refusal_kind.pop(printer.id, None)
  8912. self._upload_refusal_notified.pop(printer.id, None)
  8913. # Parse AMS mapping if stored
  8914. ams_mapping = None
  8915. if item.ams_mapping:
  8916. try:
  8917. ams_mapping = json.loads(item.ams_mapping)
  8918. except json.JSONDecodeError:
  8919. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8920. # Register as expected print so we don't create a duplicate archive
  8921. # Only applicable for archive-based prints
  8922. if archive:
  8923. from backend.app.main import register_expected_print
  8924. register_expected_print(
  8925. item.printer_id,
  8926. remote_filename,
  8927. archive.id,
  8928. ams_mapping=ams_mapping,
  8929. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8930. # no print-start email, and neither does whoever has their id.
  8931. created_by_id=toast_uid,
  8932. cost_center_id=item.cost_center_id,
  8933. # The plate actually dispatched, not the queue item's raw
  8934. # column: on None, `register_expected_print` stores nothing,
  8935. # and `extract_filament_usage_from_3mf` then books every
  8936. # filament in the file rather than the one plate that printed.
  8937. plate_id=effective_plate_id,
  8938. )
  8939. # Registration happens before the print command by necessity (the
  8940. # printer can report the print before the send returns), so record
  8941. # what to undo if we never get as far as sending. `_dispatch_one`
  8942. # rolls back anything still pending here on every exit — exception,
  8943. # early return, or cancel winning the CAS below.
  8944. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8945. # Propagate the queue item's owner into printer_manager so the
  8946. # print-complete callback can credit the user in the PrintLogEntry
  8947. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8948. # items) or when the user clicks the manual-start button.
  8949. await self._propagate_owner_to_printer_manager(db, item)
  8950. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8951. # This prevents phantom reprints if the backend crashes/restarts after the
  8952. # print command is sent but before the status update is committed.
  8953. # If we crash after this commit but before start_print(), the item will be
  8954. # in "printing" status without actually printing - but that's safer than
  8955. # accidentally reprinting the same file hours later.
  8956. #
  8957. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8958. # initial pending read at the top of check_queue and this point) flips
  8959. # the row to "cancelled" in a separate session. Without the WHERE
  8960. # status='pending' clause, the unconditional update here would silently
  8961. # overwrite that cancellation and we'd ship the MQTT start_print below
  8962. # — printer obeys, user sees "I pressed cancel and the print started".
  8963. # rowcount==0 means the user won the race; bail out, best-effort delete
  8964. # the file we just uploaded, do NOT send start_print.
  8965. now_utc = datetime.now(timezone.utc)
  8966. billing_run_id = str(uuid.uuid4())
  8967. # Written with the move to printing, so a retried send replaces the
  8968. # last answer and a cancelled one leaves the row alone (#3279).
  8969. color_substitutions = await self._color_substitutions_for(db, item)
  8970. cas = await db.execute(
  8971. update(PrintQueueItem)
  8972. .where(PrintQueueItem.id == item.id)
  8973. .where(PrintQueueItem.status == "pending")
  8974. .values(
  8975. status="printing",
  8976. started_at=now_utc,
  8977. billing_run_id=billing_run_id,
  8978. color_substitutions=color_substitutions,
  8979. )
  8980. )
  8981. await db.commit()
  8982. if cas.rowcount == 0:
  8983. logger.info(
  8984. "Queue item %s no longer pending at print-command time "
  8985. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8986. item.id,
  8987. )
  8988. try:
  8989. await delete_file_async(
  8990. printer.ip_address,
  8991. printer.access_code,
  8992. remote_path,
  8993. socket_timeout=ftp_timeout,
  8994. printer_model=printer.model,
  8995. )
  8996. except Exception as cleanup_err:
  8997. logger.debug(
  8998. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8999. item.id,
  9000. cleanup_err,
  9001. )
  9002. try:
  9003. await ws_manager.send_queue_item_failed(
  9004. user_id=toast_uid,
  9005. queue_item_id=item.id,
  9006. printer_id=item.printer_id,
  9007. reason="cancelled_mid_dispatch",
  9008. )
  9009. except Exception:
  9010. pass
  9011. return
  9012. # Sync the in-memory item so subsequent code that reads item.status /
  9013. # item.started_at sees the values we just persisted.
  9014. item.status = "printing"
  9015. item.started_at = now_utc
  9016. item.billing_run_id = billing_run_id
  9017. if archive is not None:
  9018. archive.billing_run_id = billing_run_id
  9019. # Legacy transaction deletion used an archive-wide skip flag.
  9020. # A newly dispatched run has its own UUID/tombstone, so it must be
  9021. # billable independently of any older deleted run on this archive.
  9022. archive.wallet_charge_skipped = False
  9023. # Persist before MQTT send so completion and restart recovery can
  9024. # always recover the internal billing identity.
  9025. await db.commit()
  9026. for cleanup_path in cleanup_disk_paths:
  9027. try:
  9028. if cleanup_path.exists():
  9029. cleanup_path.unlink()
  9030. except OSError as cleanup_err:
  9031. logger.warning(
  9032. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  9033. json.dumps(
  9034. {
  9035. "queue_item_id": item.id,
  9036. "path": str(cleanup_path),
  9037. "error": str(cleanup_err),
  9038. },
  9039. sort_keys=True,
  9040. ),
  9041. )
  9042. # Clear the awaiting-plate-clear flag now that we're starting a new print
  9043. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  9044. # #1898: with the opt-in default-good setting, moving on to the next
  9045. # print resolves the previous print's unanswered outcome prompt as
  9046. # "good" — this path also covers the camera-based plate detection,
  9047. # which releases the gate by allowing dispatch rather than by an
  9048. # explicit acknowledgment. Rides on the dispatch transaction.
  9049. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  9050. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  9051. await resolve_pending_confirmation_as_good(db, item.printer_id)
  9052. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  9053. # Capture state before dispatch so the watchdog can detect whether the
  9054. # printer actually transitioned (#967). Also capture subtask_id so the
  9055. # watchdog can recognise "command landed but state hasn't flipped yet"
  9056. # on slow H2D transitions (#1078).
  9057. pre_status = printer_manager.get_status(item.printer_id)
  9058. pre_state = getattr(pre_status, "state", None) if pre_status else None
  9059. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  9060. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  9061. # #1721: respect the user's explicit timelapse choice. The #1397
  9062. # force-on at dispatch was removed because it caused per-layer nozzle
  9063. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  9064. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  9065. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  9066. # FINISH-state fallback — no need to force a video.
  9067. effective_timelapse = bool(item.timelapse)
  9068. # Nozzle-rack fallback (#2800). A job that never passed through the
  9069. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  9070. # dispatches with no nozzle field at all and chooses for itself — which
  9071. # is how a print levelled on one hotend and then printed on another,
  9072. # millimetres above the plate. Derive the per-slot extruder assignment
  9073. # from the file being dispatched.
  9074. #
  9075. # Done here rather than at queue time because this is the first point
  9076. # that knows both the actual printer and the actual file: an item can
  9077. # be created without a printer (model-based assignment), reassigned
  9078. # afterwards, or have its file swapped for a G-code-injected copy just
  9079. # above. Every queue-creation path — the print dialog, a bulk library
  9080. # add, the webhook, a pipeline run — is covered by the one call.
  9081. # Skipped when the item already carries a Bambu Studio capture: that
  9082. # one wins downstream anyway, so reading the 3MF again would be work
  9083. # thrown away on every dispatch.
  9084. # Rack position resolution (#1784), tried before the #2800 fallback
  9085. # below because it can express what that one cannot: a plate wanting a
  9086. # *different* hotend off the rack per filament group. The position per
  9087. # group is the operator's pick — the 3MF states it nowhere, proven by
  9088. # sending one plate twice with different picks and finding the two
  9089. # files identical bar float noise — so it is resolved here against the
  9090. # rack as it stands right now, after the upload, not at queue time.
  9091. resolved_nozzle_mapping = None
  9092. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  9093. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  9094. if rack_plan is not None:
  9095. try:
  9096. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  9097. except (json.JSONDecodeError, TypeError):
  9098. stored_choice = {}
  9099. logger.warning(
  9100. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  9101. item.id,
  9102. item.nozzle_rack_choice,
  9103. )
  9104. # JSON object keys are strings; the groups are ints.
  9105. choice: dict[int, int] = {}
  9106. for key, value in (stored_choice or {}).items():
  9107. try:
  9108. choice[int(key)] = int(value)
  9109. except (TypeError, ValueError):
  9110. continue
  9111. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  9112. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  9113. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  9114. )
  9115. if resolved_nozzle_mapping is None and choice:
  9116. # An explicit pick that no longer holds stops the print. The
  9117. # operator named a hotend; printing from a different one is
  9118. # how a plate gets levelled on one nozzle and drawn with
  9119. # another, millimetres above the bed. Nothing has been sent
  9120. # to the printer yet, so failing here costs only the upload.
  9121. # The file is already on the SD card by this point, and a
  9122. # 3MF left there is a phantom print waiting to be started
  9123. # from the touchscreen. Same cleanup the start_print
  9124. # failure path below does, for the same reason.
  9125. try:
  9126. await delete_file_async(
  9127. printer.ip_address,
  9128. printer.access_code,
  9129. remote_path,
  9130. printer_model=printer.model,
  9131. )
  9132. except Exception:
  9133. pass # Best-effort — don't fail the error handler
  9134. if not await self._fail_dispatch(
  9135. db,
  9136. item,
  9137. (
  9138. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  9139. "Edit the item to choose another position."
  9140. ),
  9141. ):
  9142. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9143. return
  9144. logger.warning(
  9145. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  9146. item.id,
  9147. printer.name,
  9148. rack_error,
  9149. choice,
  9150. [slot.get("id") for slot in live_rack],
  9151. )
  9152. await notification_service.on_queue_job_failed(
  9153. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9154. printer_id=printer.id,
  9155. printer_name=printer.name,
  9156. reason=item.error_message,
  9157. db=db,
  9158. )
  9159. try:
  9160. await ws_manager.send_queue_item_failed(
  9161. user_id=toast_uid,
  9162. queue_item_id=item.id,
  9163. printer_id=item.printer_id,
  9164. reason="nozzle_rack_pick_stale",
  9165. )
  9166. except Exception:
  9167. pass # Best-effort — don't fail the error handler
  9168. return
  9169. if resolved_nozzle_mapping is None:
  9170. # Nothing was picked and nothing could be assigned. Falls
  9171. # through to the #2800 path, which is what ran before this
  9172. # existed — strictly not worse than today.
  9173. logger.info(
  9174. "Queue item %s: no rack positions assignable (%s); falling back",
  9175. item.id,
  9176. rack_error,
  9177. )
  9178. else:
  9179. logger.info(
  9180. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  9181. item.id,
  9182. resolved_nozzle_mapping,
  9183. rack_plan.slot_groups,
  9184. choice or "auto",
  9185. )
  9186. nozzle_slot_extruders = None
  9187. if (
  9188. not item.nozzle_mapping
  9189. and resolved_nozzle_mapping is None
  9190. and file_path is not None
  9191. and is_nozzle_rack_model(printer.model)
  9192. ):
  9193. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  9194. if slot_extruders:
  9195. nozzle_slot_extruders = json.dumps(slot_extruders)
  9196. # Every filament this plate prints is on the external spool -> the print
  9197. # must go out with use_ams=False. The firmware answers use_ams=true plus
  9198. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  9199. # table", which is what held the reporter's P1S at Heatbed preheating
  9200. # for ten minutes before it gave up (#3087). The MQTT command builder
  9201. # already downgrades a mapping that is *only* external ([254]), but a
  9202. # multi-filament project pads the slots this plate does not print with
  9203. # -1 — BambuStudio's own convention — and down there a -1 is
  9204. # indistinguishable from a slot that never resolved, which must never be
  9205. # sent to the spool holder (#2589). Here the plate's filament list says
  9206. # which is which, so the answer is exact rather than a guess.
  9207. #
  9208. # Deliberately narrow: this fires only when every consumed slot is an
  9209. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  9210. # alone and the firmware still rejects the print, exactly as today. And
  9211. # only for single-nozzle printers, mirroring the builder's own reconcile
  9212. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  9213. # whether to use the AMS, so it is not ours to rewrite.
  9214. effective_use_ams = item.use_ams
  9215. plate_uses_only_external = False
  9216. if (
  9217. ams_mapping
  9218. and file_path is not None
  9219. # Cheap gate before opening the file: with nothing on the spool
  9220. # holder anywhere in the mapping, no subset of it can be all
  9221. # external, so most dispatches never pay for the parse. The
  9222. # isinstance also keeps a malformed stored mapping (a bare number
  9223. # from a hand-edited row) failing where it always failed, in the
  9224. # command builder, rather than here.
  9225. and isinstance(ams_mapping, list)
  9226. and any(_is_external_tray(t, TrayLayout.from_state(pre_status).rack) for t in ams_mapping)
  9227. and not _might_be_dual_nozzle(printer.model, pre_status)
  9228. ):
  9229. from backend.app.services.filament_requirements import extract_filament_requirements
  9230. consumed = _consumed_mapping_entries(
  9231. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  9232. )
  9233. if consumed and all(_is_external_tray(t, TrayLayout.from_state(pre_status).rack) for t in consumed):
  9234. # Exact for this plate: the command builder must not turn the
  9235. # AMS back on for a real tray another plate of the file uses,
  9236. # whether the job asked for the AMS or already had it off.
  9237. plate_uses_only_external = True
  9238. if plate_uses_only_external and effective_use_ams:
  9239. effective_use_ams = False
  9240. logger.info(
  9241. "Queue item %s: every filament plate %s prints is on the external spool "
  9242. "(mapping %s) — dispatching with use_ams=False (#3087)",
  9243. item.id,
  9244. effective_plate_id,
  9245. ams_mapping,
  9246. )
  9247. # A slot that lost its K-profile selection (a power cycle resets every
  9248. # slot to the default K) would print on the default. The idle check in
  9249. # the status handler normally restores it first, but nothing guarantees
  9250. # it ran before this dispatch (#3219). Unthrottled: once per job.
  9251. # Never allowed to stop the print it is protecting.
  9252. try:
  9253. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  9254. except Exception:
  9255. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  9256. # Start the print with AMS mapping, plate_id and print options.
  9257. # nozzle_mapping rides through verbatim — JSON string captured from
  9258. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  9259. # parses + injects it only for dual-nozzle models so a null on every
  9260. # other model is a transparent pass-through. The rack fallback is
  9261. # resolved down there too, where the live rack position is known.
  9262. started = printer_manager.start_print(
  9263. item.printer_id,
  9264. remote_filename,
  9265. plate_id=effective_plate_id,
  9266. ams_mapping=ams_mapping,
  9267. bed_levelling=item.bed_levelling,
  9268. flow_cali=item.flow_cali,
  9269. vibration_cali=item.vibration_cali,
  9270. layer_inspect=item.layer_inspect,
  9271. timelapse=effective_timelapse,
  9272. use_ams=effective_use_ams,
  9273. plate_uses_only_external=plate_uses_only_external,
  9274. nozzle_offset_cali=item.nozzle_offset_cali,
  9275. nozzle_mapping=item.nozzle_mapping
  9276. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  9277. nozzle_slot_extruders=nozzle_slot_extruders,
  9278. )
  9279. if started:
  9280. # The command is away, so the expectation is now legitimate and must
  9281. # survive. Anything still in this dict when _dispatch_one exits gets
  9282. # rolled back.
  9283. self._unconfirmed_expected_print.pop(item.id, None)
  9284. self._unconfirmed_budget_reservations.discard(item.id)
  9285. self._unconfirmed_print_user.pop(item.id, None)
  9286. if item.printer_id is not None:
  9287. self._sent_unstarted_print[item.id] = (
  9288. item.printer_id,
  9289. remote_filename if archive else None,
  9290. archive.id if archive else None,
  9291. )
  9292. # Handoff to the print's own gcode: keep whatever preheat set (bed
  9293. # target, chamber target, airduct heating) — the gcode owns
  9294. # heater/flap control from here. Clearing the pin prevents
  9295. # `_dispatch_one`'s finally from unwinding a live print.
  9296. self._preheat_pin.pop(item.printer_id, None)
  9297. self._preheat_pin_bed.pop(item.printer_id, None)
  9298. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  9299. # No dispatch-toast event here: the legacy bg-dispatch path kept
  9300. # status='processing' from upload start until the printer acked
  9301. # (or timed out). The frontend derives "Awaiting printer…" purely
  9302. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  9303. # event would push the status chip out of 'PROCESSING' prematurely
  9304. # — which is exactly what the screenshot at #1625-followup
  9305. # complained about.
  9306. # Register the local 3MF in the cover-cache so /cover skips FTP
  9307. # (#1166 follow-up). file_path was resolved earlier from either the
  9308. # archive or the library file row.
  9309. if file_path is not None:
  9310. cache_3mf_download(item.printer_id, remote_filename, file_path)
  9311. # Hold the printer against further dispatches until the watchdog
  9312. # confirms the printer transitioned (or until the hard timeout).
  9313. # Prevents multi-plate batches from triple-dispatching onto the
  9314. # same H2D Pro while it digests the first project_file (#1157).
  9315. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  9316. # Watchdog: if the printer never transitions out of pre_state AND
  9317. # never advances subtask_id, the MQTT publish was accepted locally but
  9318. # didn't reach the printer (half-broken session — same shape as
  9319. # #887/#936). Revert the queue item so the next dispatch can pick it
  9320. # up instead of leaving it stuck in "printing" (#967). subtask_id
  9321. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  9322. # that would otherwise cause the item to re-dispatch as a reprint
  9323. # of the just-finished job (#1078).
  9324. if pre_state:
  9325. spawn_background_task(
  9326. self._watchdog_print_start(
  9327. item.id,
  9328. item.printer_id,
  9329. pre_state,
  9330. pre_subtask_id,
  9331. pre_gcode_file,
  9332. created_by_id=toast_uid,
  9333. ),
  9334. name=f"watchdog-print-start-{item.id}",
  9335. )
  9336. # Get estimated time for notification.
  9337. #
  9338. # This used to fall back to `library_file.print_time_seconds`, a column
  9339. # LibraryFile does not have — the print time it knows about lives in
  9340. # `file_metadata`. So a library print whose archive carried no parseable
  9341. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  9342. # AttributeError right here, *after* the printer had already been sent
  9343. # the job: the started-notification never fired, and the exception
  9344. # unwound the whole queue pass, so every other printer still waiting to
  9345. # be dispatched on that tick silently missed its turn.
  9346. #
  9347. # The queue item caches the print time at creation ("Cached from
  9348. # archive/library"), which is the value this was reaching for.
  9349. # The item's is its plate's; the archive's adds every plate of the
  9350. # file up (#3375).
  9351. estimated_time = None
  9352. if item.print_time_seconds:
  9353. estimated_time = item.print_time_seconds
  9354. elif archive and archive.print_time_seconds:
  9355. estimated_time = archive.print_time_seconds
  9356. # Send job started notification
  9357. await notification_service.on_queue_job_started(
  9358. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9359. printer_id=printer.id,
  9360. printer_name=printer.name,
  9361. db=db,
  9362. estimated_time=estimated_time,
  9363. )
  9364. # MQTT relay - publish queue job started
  9365. try:
  9366. await mqtt_relay.on_queue_job_started(
  9367. job_id=item.id,
  9368. filename=filename,
  9369. printer_id=printer.id,
  9370. printer_name=printer.name,
  9371. printer_serial=printer.serial_number,
  9372. )
  9373. except Exception:
  9374. pass # Don't fail if MQTT fails
  9375. else:
  9376. # Clean up uploaded file from SD card to prevent phantom prints
  9377. try:
  9378. await delete_file_async(
  9379. printer.ip_address,
  9380. printer.access_code,
  9381. remote_path,
  9382. printer_model=printer.model,
  9383. )
  9384. except Exception:
  9385. pass # Best-effort — don't fail the error handler
  9386. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  9387. # state can flip from idle to active in the window between the
  9388. # pre-dispatch check above and this publish (the FTP upload takes
  9389. # seconds); start_print() then refuses to send project_file to the
  9390. # now-busy printer and returns False. Failing the item here would be
  9391. # wrong — the printer is fine, it is simply busy — so revert to
  9392. # pending and let a later tick dispatch it once the printer is idle,
  9393. # exactly like the pre-dispatch guard. Only a start_print() False on
  9394. # an idle/unknown printer is a genuine command failure.
  9395. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  9396. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  9397. logger.info(
  9398. "Queue item %s: printer %s became busy (state=%s) before the start "
  9399. "command was sent — deferring, reverting item to pending (#2598)",
  9400. item.id,
  9401. item.printer_id,
  9402. post_dispatch_state,
  9403. )
  9404. await self._defer_until_printer_idle(db, item)
  9405. return
  9406. # Print command failed - revert status
  9407. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  9408. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9409. return
  9410. logger.error(
  9411. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  9412. f"printer_manager.start_print() returned False. "
  9413. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  9414. f"Check printer status and backend logs for details."
  9415. )
  9416. # Send failure notification
  9417. await notification_service.on_queue_job_failed(
  9418. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9419. printer_id=printer.id,
  9420. printer_name=printer.name,
  9421. reason="Failed to send print command to printer - check printer connection and status",
  9422. db=db,
  9423. )
  9424. try:
  9425. await ws_manager.send_queue_item_failed(
  9426. user_id=toast_uid,
  9427. queue_item_id=item.id,
  9428. printer_id=item.printer_id,
  9429. reason="start_command_failed",
  9430. )
  9431. except Exception:
  9432. pass
  9433. await self._power_off_if_needed(db, item)
  9434. @staticmethod
  9435. async def _watchdog_print_start(
  9436. queue_item_id: int,
  9437. printer_id: int,
  9438. pre_state: str,
  9439. pre_subtask_id: str | None = None,
  9440. pre_gcode_file: str | None = None,
  9441. timeout: float = 90.0,
  9442. phase_b_timeout: float = 180.0,
  9443. poll_interval: float = 3.0,
  9444. created_by_id: int | None = None,
  9445. ) -> None:
  9446. """Revert a queue item if the printer never acknowledges the start command.
  9447. Bambuddy optimistically marks the queue item as "printing" right after the
  9448. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  9449. Phase A (up to ``timeout``): wait for either an active-state transition
  9450. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  9451. primary signal; subtask_id advance handles the H2D case where state can
  9452. sit at FINISH for ~50 s after the printer accepted ``project_file``
  9453. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  9454. was lost on a half-broken session (#887/#936) — revert and force
  9455. reconnect (the #967 recovery path).
  9456. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  9457. alone): keep watching for the active-state transition. subtask_id alone
  9458. proves the file landed but not that the printer started — and a printer
  9459. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  9460. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  9461. used to leave the queue item stuck in 'printing' forever because the
  9462. old watchdog returned success as soon as subtask_id advanced. If Phase
  9463. B times out, revert the queue item so the user can retry without
  9464. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  9465. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9466. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  9467. transitions that also don't emit an early subtask_id tick.
  9468. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  9469. refuses to verify our commands will never start this job or any other,
  9470. so waiting out the full 270 s and re-uploading the 3MF twice more only
  9471. burns an upload slot the rest of the farm is queued behind — that path
  9472. is for a printer that might still come good, which this one cannot
  9473. (#2732). It fails the item on the spot with the actual reason instead.
  9474. """
  9475. last_status = None
  9476. landed_on_subtask = False
  9477. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  9478. # every push carrying an `hms` key, so the fault can come and go between
  9479. # 3-second polls. Seeing it once inside the dispatch window is enough.
  9480. command_rejected = False
  9481. # Latched for the same reason as command_rejected: drying can finish, or
  9482. # be stopped by the user, part-way through the dispatch window. Seeing it
  9483. # once is what matters — it is the state the printer was in when it
  9484. # declined to start (#2758).
  9485. drying_ams_ids: list[int] = []
  9486. # The printer answered the start with a refusal: nothing will start,
  9487. # and the command was not lost, so no reconnect either.
  9488. start_refusal: tuple[str, str | None] | None = None
  9489. deadline = time.monotonic() + timeout
  9490. while time.monotonic() < deadline:
  9491. await asyncio.sleep(poll_interval)
  9492. status = printer_manager.get_status(printer_id)
  9493. if not status:
  9494. # Printer disconnected — don't mess with the DB. Drop the
  9495. # in-memory dispatch hold too so a fresh dispatch can retry
  9496. # once the printer comes back; the hard timeout would
  9497. # otherwise hold the printer unnecessarily.
  9498. scheduler._release_dispatch_hold(printer_id)
  9499. return
  9500. last_status = status
  9501. if status.state in _ACTIVE_PRINT_STATES:
  9502. # Printer is actively processing the job — release the
  9503. # post-dispatch hold so the next pending item for this printer
  9504. # can be evaluated normally. We do NOT accept arbitrary state
  9505. # transitions: a printer going FINISH -> IDLE (user dismissed
  9506. # the post-print prompt without accepting our project_file)
  9507. # would otherwise look like "command landed" and leave the
  9508. # queue item stuck in 'printing' forever (#1370).
  9509. scheduler._release_dispatch_hold(printer_id)
  9510. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9511. try:
  9512. await ws_manager.send_queue_item_acked(
  9513. user_id=created_by_id,
  9514. queue_item_id=queue_item_id,
  9515. printer_id=printer_id,
  9516. )
  9517. except Exception:
  9518. pass
  9519. return
  9520. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9521. # Checked only after the active-state exit above: a stale HMS left
  9522. # over from an earlier job must never abort a print that is visibly
  9523. # running. An actually-refused command leaves the printer idle, so
  9524. # this ordering costs the detection nothing.
  9525. if _mqtt_commands_rejected(status):
  9526. command_rejected = True
  9527. break
  9528. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9529. if isinstance(refusal, tuple):
  9530. start_refusal = refusal
  9531. break
  9532. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9533. # Phase A exit — printer accepted the file (subtask_id flipped
  9534. # to our submission id). Don't return yet: the printer may
  9535. # have accepted the command but never actually start (e.g.
  9536. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9537. # B watches for the active-state transition.
  9538. landed_on_subtask = True
  9539. break
  9540. if landed_on_subtask and not command_rejected:
  9541. phase_b_deadline = time.monotonic() + phase_b_timeout
  9542. while time.monotonic() < phase_b_deadline:
  9543. await asyncio.sleep(poll_interval)
  9544. status = printer_manager.get_status(printer_id)
  9545. if not status:
  9546. scheduler._release_dispatch_hold(printer_id)
  9547. return
  9548. last_status = status
  9549. if status.state in _ACTIVE_PRINT_STATES:
  9550. scheduler._release_dispatch_hold(printer_id)
  9551. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9552. try:
  9553. await ws_manager.send_queue_item_acked(
  9554. user_id=created_by_id,
  9555. queue_item_id=queue_item_id,
  9556. printer_id=printer_id,
  9557. )
  9558. except Exception:
  9559. pass
  9560. return
  9561. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9562. # Same ordering rule as Phase A: a running print wins over a
  9563. # lingering HMS.
  9564. if _mqtt_commands_rejected(status):
  9565. command_rejected = True
  9566. break
  9567. # No active-state transition. Revert the item so the scheduler can retry.
  9568. # Drop the in-memory hold so the retry isn't blocked by it.
  9569. scheduler._release_dispatch_hold(printer_id)
  9570. # Logged on every failed dispatch window, not just the last one, so a
  9571. # support bundle shows the correlation from the first attempt rather than
  9572. # only after the retry budget is spent (#2758).
  9573. if drying_ams_ids:
  9574. logger.info(
  9575. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9576. queue_item_id,
  9577. printer_id,
  9578. ", ".join(str(i) for i in drying_ams_ids),
  9579. )
  9580. # Four outcomes from the revert attempt, each routed differently:
  9581. # "reverted": row flipped from printing -> pending, run recovery
  9582. # "gave_up": same, but the retry budget is spent — row failed
  9583. # rather than pending, so it stops going round again
  9584. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9585. # on_print_complete or user). Skip recovery entirely
  9586. # — the print clearly landed somewhere even if the
  9587. # watchdog didn't see the active-state transition.
  9588. # "revert_failed": SQLite contention exhausted retries. Still run
  9589. # recovery so the MQTT session gets a fresh client_id
  9590. # on the half-broken-session path.
  9591. #
  9592. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9593. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9594. # the watchdog again. For a printer that is genuinely wedged that loop never
  9595. # ends — the reporter had one printer "since this morning still not launch"
  9596. # — and each lap also consumes an upload slot that the other printers in the
  9597. # farm are waiting on. Retrying is right; retrying forever is not.
  9598. async def _do_revert(db):
  9599. item = await db.get(PrintQueueItem, queue_item_id)
  9600. if not item or item.status != "printing":
  9601. return "already_moved_on"
  9602. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9603. item.started_at = None
  9604. # The print never started: no slot printed in any colour (#3279).
  9605. item.color_substitutions = None
  9606. # Charge the attempt to the candidate that was actually dispatched, so
  9607. # a cross-model item (#671) reaches for its other file next lap instead
  9608. # of retrying the printer that just failed to start. Matched by file
  9609. # because that is what the resolver copied onto the row.
  9610. if item.library_file_id is not None:
  9611. await db.execute(
  9612. update(PrintQueueVariant)
  9613. .where(PrintQueueVariant.queue_item_id == item.id)
  9614. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9615. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9616. )
  9617. if command_rejected:
  9618. # No retry budget for this one: the printer refused to verify the
  9619. # command, and re-uploading the same 3MF to the same printer will
  9620. # be refused the same way. Fail now with the fix rather than after
  9621. # three laps of a message about SD cards (#2732).
  9622. item.status = "failed"
  9623. item.error_message = (
  9624. "The printer rejected the print command: MQTT command verification failed "
  9625. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9626. "then start the job again."
  9627. )
  9628. item.completed_at = datetime.now(timezone.utc)
  9629. await db.commit()
  9630. return "command_rejected"
  9631. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9632. item.status = "failed"
  9633. if drying_ams_ids:
  9634. # #2758: the generic message below sent the reporter looking
  9635. # at the SD card while the actual obstacle — AMS units in a
  9636. # drying cycle — was on screen the whole time. Name what we
  9637. # observed and let the user judge it; Bambuddy does not stop
  9638. # the cycle itself, because on this hardware drying can run
  9639. # alongside a print and stopping it may not be the fix.
  9640. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9641. item.error_message = (
  9642. f"The printer accepted the file but never started printing, after "
  9643. f"{item.dispatch_attempts} attempts. {units} "
  9644. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9645. f"some printers refuse to begin a print while an AMS is in a drying "
  9646. f"cycle, and an AMS drying without its external power supply can also "
  9647. f"leave too little power for the start-of-print calibration. Stop the "
  9648. f"drying, or connect the AMS power supply, and start the job again."
  9649. )
  9650. else:
  9651. item.error_message = (
  9652. f"The printer accepted the file but never started printing, after "
  9653. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9654. f"prompt or error, confirm its SD card is readable, and start the job again."
  9655. )
  9656. item.completed_at = datetime.now(timezone.utc)
  9657. await release_budget_reservation(
  9658. db,
  9659. source_type="print_queue",
  9660. source_id=item.id,
  9661. status="released",
  9662. )
  9663. await db.commit()
  9664. return "gave_up"
  9665. item.status = "pending"
  9666. await db.commit()
  9667. return "reverted"
  9668. try:
  9669. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9670. except Exception as e:
  9671. logger.warning(
  9672. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9673. "scheduler may keep treating this item as in-flight",
  9674. queue_item_id,
  9675. printer_id,
  9676. e,
  9677. )
  9678. revert_outcome = "revert_failed"
  9679. if revert_outcome in ("command_rejected", "gave_up"):
  9680. # The item is failed: its print user and expected print must not
  9681. # pass the printer's next print off as Bambuddy's.
  9682. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9683. from backend.app.services.print_batch import refresh_batches_after
  9684. await refresh_batches_after([queue_item_id])
  9685. elif revert_outcome == "reverted":
  9686. # Another try claims the printer again. Until then no print on it
  9687. # is vouched for as this item's, except a late start of its file.
  9688. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9689. elif revert_outcome == "already_moved_on":
  9690. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9691. if revert_outcome == "already_moved_on":
  9692. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9693. # other path) already moved the item past 'printing', don't run the
  9694. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9695. # session breaks ongoing prints on the same printer.
  9696. return
  9697. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9698. if revert_outcome == "command_rejected":
  9699. logger.error(
  9700. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9701. "failed) — the print command was rejected, not lost. Failing the item "
  9702. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9703. queue_item_id,
  9704. printer_id,
  9705. HMS_MQTT_VERIFY_FAILED,
  9706. )
  9707. await scheduler._notify_dispatch_gave_up(
  9708. queue_item_id,
  9709. printer_id,
  9710. created_by_id,
  9711. reason="Printer rejected the print command (MQTT command verification failed)",
  9712. )
  9713. # Same reasoning as the landed_on_subtask path below: the file is on
  9714. # the printer and a forced reconnect would only add 0500_4003 to a
  9715. # problem that has nothing to do with the MQTT session (#1150).
  9716. return
  9717. if revert_outcome == "gave_up":
  9718. logger.error(
  9719. "Queue item %s: printer %d never started the print after %d dispatch "
  9720. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9721. "re-uploading it again (#2555)",
  9722. queue_item_id,
  9723. printer_id,
  9724. DISPATCH_MAX_ATTEMPTS,
  9725. total_timeout,
  9726. )
  9727. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9728. elif revert_outcome == "reverted":
  9729. if start_refusal is not None:
  9730. logger.warning(
  9731. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9732. "reverted to 'pending' for retry",
  9733. queue_item_id,
  9734. printer_id,
  9735. start_refusal[0],
  9736. start_refusal[1],
  9737. )
  9738. elif landed_on_subtask:
  9739. logger.warning(
  9740. "Queue item %s: printer %d accepted project_file (subtask_id "
  9741. "advanced) but never transitioned to an active state within "
  9742. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9743. "for retry (#1678)",
  9744. queue_item_id,
  9745. printer_id,
  9746. total_timeout,
  9747. )
  9748. else:
  9749. logger.warning(
  9750. "Queue item %s: printer %d did not respond to print command within "
  9751. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9752. "for retry (#967)",
  9753. queue_item_id,
  9754. printer_id,
  9755. timeout,
  9756. pre_state,
  9757. pre_subtask_id,
  9758. )
  9759. # Phase B was entered iff subtask_id advanced, which means the
  9760. # project_file landed on the printer. A forced reconnect at this point
  9761. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9762. # skip the recovery entirely.
  9763. if landed_on_subtask or start_refusal is not None:
  9764. return
  9765. # Phase A timeout path: if the printer's gcode_file changed since
  9766. # pre-dispatch, the project_file command landed and the printer is
  9767. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9768. # If gcode_file is unchanged, the publish was silently swallowed
  9769. # (#887/#936) and force_reconnect recovery is what we want.
  9770. client = printer_manager.get_client(printer_id)
  9771. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9772. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9773. if publish_landed:
  9774. logger.warning(
  9775. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9776. "received the command and is parsing slowly. Skipping forced "
  9777. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9778. queue_item_id,
  9779. current_gcode_file,
  9780. pre_gcode_file,
  9781. )
  9782. elif client and hasattr(client, "force_reconnect_stale_session"):
  9783. client.force_reconnect_stale_session(
  9784. f"queue print command unacknowledged after {timeout:.0f}s "
  9785. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9786. )
  9787. # Global scheduler instance
  9788. scheduler = PrintScheduler()