print_scheduler.py 517 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import derive_remote_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. plate_bed_temperature,
  90. select_plate_gcode_name,
  91. )
  92. logger = logging.getLogger(__name__)
  93. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  94. """Human slot name for an assignment tuple, in the spelling already in use.
  95. Composed from the notification side's own pair rather than spelled out again
  96. here. The hand-rolled version this replaces got three real slot kinds wrong:
  97. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  98. ``chr(191)``; both externals collapsed to one label, because an external
  99. assignment stores ams_id 255 with tray_id picking left or right
  100. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  101. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  102. Naming the same slot two ways is its own defect once an alert and the
  103. Inventory page are meant to be talking about the same tray, so this defers
  104. rather than adding a fifth spelling.
  105. """
  106. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  107. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  108. # interval: the fast path runs every 3 s while an upload is in flight, and a
  109. # low spool does not need answering at that resolution (#2913).
  110. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  111. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  112. # days, so a finer check would only repeat the same answer.
  113. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  114. # The settings row that holds which stock alerts have already been sent (#2955).
  115. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  116. # The Inventory page asks for this many usage records and the forecast panel
  117. # builds its rates from them; the alert reads the same window so the two agree.
  118. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  119. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  120. """Remaining filament as a percentage of the label weight.
  121. The same arithmetic the Inventory page's Low Stock count uses, and it works
  122. unchanged in both inventory modes: internal spools store ``weight_used``
  123. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  124. ``remaining_weight`` so the shape matches. Returns None when there is no
  125. label weight to be a percentage of -- a spool that cannot say how full it
  126. started cannot say how empty it is.
  127. """
  128. if not label_weight or label_weight <= 0:
  129. return None
  130. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  131. return remaining / float(label_weight) * 100.0
  132. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  133. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  134. # byte gate) from before the scheduler unification. Time gate keeps small
  135. # files from going silent (a single 8 KB chunk fires once and that's it);
  136. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  137. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  138. # sub-200 ms files.
  139. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  140. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  141. # How far back chamber temperature samples are retained. 2h comfortably spans
  142. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  143. # before the next print.
  144. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  145. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  146. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  147. # who clear plates promptly will want far less than this; it is deliberately
  148. # the cautious end, since the cost of it being too short is only a re-soak.
  149. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  150. # Max acceptable gap between two consecutive chamber samples before we treat
  151. # the older one as belonging to a separate observation run (printer went
  152. # offline and came back). Above ~30s cadence with a safety margin.
  153. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  154. # How long the chamber must read below target before we accept that it really
  155. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  156. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  157. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  158. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  159. # sub-target readings are therefore a door opening or noise, not lost soak,
  160. # and a plate swap (exactly when keep-warm is running) produces one. Six
  161. # minutes clears the longest such artifact observed (~5 min once bracketed by
  162. # its neighbouring samples) and still sits far below the 23-minute floor for
  163. # real cooling.
  164. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  165. # How often the preheat stage re-checks that the item it is heating for still
  166. # wants to be printed. Cancelling only writes `status` to the database — it
  167. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  168. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  169. # and the printer stays in `busy_printers`, blocking every other queued item
  170. # behind a print that is not happening.
  171. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  172. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  173. _AIRDUCT_MODE_COOLING = 0
  174. _AIRDUCT_MODE_HEATING = 1
  175. # How long a queue row may stay 'printing' while its printer sits in a terminal
  176. # state before the scheduler closes it itself (#2829).
  177. #
  178. # A real completion arrives within seconds of the printer going terminal, so
  179. # five minutes is far outside the normal path — this only ever sees a row whose
  180. # completion was refused or never delivered. It is the whole cost of the
  181. # failure to the user, though: a stranded row blocks every later job for that
  182. # printer, so it should not be raised without reason.
  183. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  184. # gcode_state values that mean the print is over, mapped to the queue status
  185. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  186. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  187. # which the queue calls cancelled) so a recovered row cannot disagree with one
  188. # closed by the normal path.
  189. _TERMINAL_STATE_QUEUE_STATUS = {
  190. "FINISH": "completed",
  191. "FAILED": "failed",
  192. "IDLE": "cancelled",
  193. }
  194. def _terminal_queue_status(state) -> str | None:
  195. """Queue status implied by *state*, or None if the print is not over.
  196. None for a disconnected printer as well as a busy one: a printer we are not
  197. talking to has a stale ``state`` field that proves nothing about what it is
  198. doing now.
  199. """
  200. if state is None or not getattr(state, "connected", False):
  201. return None
  202. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  203. @dataclass
  204. class _KeepWarmEntry:
  205. """Per-printer keep-warm state.
  206. - ``started``: monotonic time when keep-warm first fired for this printer.
  207. Used by the max-duration timeout.
  208. - ``held_target``: last bed target we successfully published. On release
  209. we only send bed-off when firmware still reports this value, so a user
  210. or subsequent print that changed the target isn't clobbered.
  211. - ``expired``: latched True when the max-duration timeout fires. Prevents
  212. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  213. release sweep drops the entry entirely once the printer leaves the
  214. candidate set.
  215. """
  216. started: float
  217. held_target: int
  218. expired: bool = False
  219. # Auto-drying re-arm guards (#2770).
  220. #
  221. # An AMS reports HIGHER relative humidity while it is warm than once it has
  222. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  223. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  224. # threshold set inside that band therefore cannot be satisfied while the box is
  225. # hot, and the firmware is free to end a cycle whenever it decides the filament
  226. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  227. # the threshold and arms another cycle. The reporter's log has five 12-hour
  228. # cycles armed inside four hours, one of them six seconds after the previous
  229. # ended.
  230. #
  231. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  232. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  233. # manual or firmware-run dry is untouched.
  234. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  235. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  236. # Sustained-humidity wait (#2518): an above-threshold streak is only
  237. # "continuous" if some pass observed it within the gap ceiling. A unit that
  238. # goes unobserved longer (print running, printer disconnected, sensor silent)
  239. # restarts its streak rather than inheriting a stale one. The ceiling is
  240. # derived from the scheduler cadence — four missed passes — with this floor so
  241. # a fast-polling configuration does not void streaks on a single hiccup.
  242. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  243. # How long a finished scheduled drying row is kept before it is pruned.
  244. SCHEDULED_DRYING_RETENTION_DAYS = 7
  245. # How often that prune actually runs. The check itself is called on every queue
  246. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  247. # write transaction, which SQLite serialises against every other writer. Rows
  248. # only become prunable a week after they finish, so anything short of hourly is
  249. # paying that cost for nothing.
  250. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  251. class _UploadProgressBridge:
  252. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  253. ``upload_file_async`` runs the FTP transfer in an executor thread and
  254. invokes its ``progress_callback`` from that thread, so the callback
  255. body cannot ``await`` directly. This bridge captures the asyncio loop
  256. at construction (on the scheduler thread) and uses
  257. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  258. matches the legacy background_dispatch.py path 1:1 so the toast feels
  259. identical to the pre-#1625 experience.
  260. Failures inside the emit are swallowed — progress is a UX nicety, the
  261. upload itself must not fail because of a WS hiccup.
  262. """
  263. def __init__(self, user_id: int | None, queue_item_id: int):
  264. self._user_id = user_id
  265. self._queue_item_id = queue_item_id
  266. try:
  267. self._loop = asyncio.get_running_loop()
  268. except RuntimeError:
  269. self._loop = None
  270. self._last_emit_bytes = 0
  271. self._last_emit_monotonic = 0.0
  272. self._has_emitted = False
  273. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  274. if self._loop is None or total_bytes <= 0:
  275. return
  276. now = time.monotonic()
  277. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  278. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  279. # the four matter most: first-call so the user sees something even
  280. # for sub-chunk-size files; uploaded >= total so the bar locks at
  281. # 100% even when the throttle would otherwise eat it.
  282. should_emit = (
  283. not self._has_emitted
  284. or bytes_transferred >= total_bytes
  285. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  286. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  287. )
  288. if not should_emit:
  289. return
  290. self._has_emitted = True
  291. self._last_emit_bytes = bytes_transferred
  292. self._last_emit_monotonic = now
  293. try:
  294. asyncio.run_coroutine_threadsafe(
  295. ws_manager.send_queue_item_upload_progress(
  296. user_id=self._user_id,
  297. queue_item_id=self._queue_item_id,
  298. bytes_transferred=bytes_transferred,
  299. total_bytes=total_bytes,
  300. ),
  301. self._loop,
  302. )
  303. except Exception:
  304. pass # progress is best-effort, never block the upload
  305. # Bambu firmware states that mean the project_file has actually been accepted
  306. # and the printer is now processing / running / paused mid-print. Used by the
  307. # dispatch watchdog (#1370): a transition into one of these states means the
  308. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  309. # a post-print prompt) is NOT a valid "command landed" signal even though the
  310. # state value did change. SLICING is included because some firmwares park
  311. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  312. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  313. # How many times the start-watchdog may revert an item to 'pending' before it
  314. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  315. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  316. # both never recovers and starves the other printers of dispatch slots. Three
  317. # is chosen to clear the transient causes the watchdog already recovers from —
  318. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  319. # force-reconnect on the very next attempt — while still bounding the loop.
  320. DISPATCH_MAX_ATTEMPTS = 3
  321. # Upload failures that mean the file never reached the printer's storage: the
  322. # file service refused or never answered (#3210). These put the item back in
  323. # the queue instead of failing it, because nothing about the job is wrong --
  324. # and failing it left the printer idle, so the next pass handed it the next
  325. # item, which failed the same way. One P2S whose file service was out of
  326. # connection slots ate 43 queued jobs in ten minutes that way.
  327. #
  328. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  329. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  330. # and an upload that overran its deadline -- each of those would fail the same
  331. # way on every retry.
  332. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  333. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  334. )
  335. # How long a printer whose upload was put back stays out of dispatch (#3210).
  336. # The first window matches the FTP client's own handshake cool-off, so the
  337. # retry lands after the client would talk to the printer again anyway. Each
  338. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  339. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  340. # five connection attempts and a page of log. A successful upload resets it.
  341. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  342. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  343. def _upload_backoff_seconds(refusals: int) -> int:
  344. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  345. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  346. @dataclass(slots=True)
  347. class _ModelCandidate:
  348. """One (file, printer model) pair the model-based matcher may try.
  349. Model-based assignment used to have exactly one of these per item, held
  350. directly in the item's own columns. Cross-model queue items (#671) have
  351. several, held in ``print_queue_variants``. Both shapes are normalised into
  352. this so the matching, the cross-model gate and the waiting-reason handling
  353. are written once and an item without variants provably takes the same path
  354. it took before variants existed.
  355. ``variant`` is None for the item's own columns and set for a real variant
  356. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  357. item once that candidate wins.
  358. """
  359. target_model: str | None
  360. sliced_for: str | None
  361. required_filament_types: str | None
  362. filament_overrides: str | None
  363. variant: "PrintQueueVariant | None" = None
  364. def _sliced_for_model(archive, library_file) -> str | None:
  365. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  366. if archive is not None:
  367. return archive.sliced_for_model
  368. if library_file is not None and library_file.file_metadata:
  369. return library_file.file_metadata.get("sliced_for_model")
  370. return None
  371. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  372. """The filament a candidate needs, as ``(types, overrides)``.
  373. Both columns are JSON text written by the slicer step. Malformed content is
  374. treated as no constraint rather than as an error: a job whose overrides
  375. cannot be parsed still prints, it just gets no filament-based narrowing.
  376. Overrides carry their own types, so the returned type list is the union of
  377. the two — an override on one slot must not drop the requirements of the
  378. slots it says nothing about.
  379. Shared by the matcher and by the smart-plug wake step so both ask a printer
  380. for the same filament (#2876). Waking a printer the matcher would then
  381. reject on colour is the bug this exists to prevent.
  382. """
  383. required_types = None
  384. if candidate.required_filament_types:
  385. try:
  386. required_types = json.loads(candidate.required_filament_types)
  387. except json.JSONDecodeError:
  388. pass
  389. filament_overrides = None
  390. if candidate.filament_overrides:
  391. try:
  392. filament_overrides = json.loads(candidate.filament_overrides)
  393. except json.JSONDecodeError:
  394. pass
  395. effective_types = required_types
  396. if filament_overrides:
  397. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  398. if override_types:
  399. effective_types = sorted(set(required_types or []) | set(override_types))
  400. return effective_types, filament_overrides
  401. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  402. """Whether ``item`` was competing for the printer another item just took.
  403. The SJF starvation guard marks a job as jumped when a shorter one lower in
  404. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  405. compete for the same printer, so the guard has to look across both lanes
  406. (#3200); looking only inside the dispatched item's own lane let a stream of
  407. short model-based jobs hold a longer pinned job back indefinitely.
  408. Location filters are not checked: over-marking only lifts an item that was
  409. going to wait anyway, while under-marking is the starvation this prevents.
  410. """
  411. if item.printer_id is not None:
  412. return item.printer_id == printer_id
  413. if not printer_model:
  414. return False
  415. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  416. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  417. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  418. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  419. """Candidate files for ``item``, best first.
  420. An item with no variant rows yields exactly one candidate built from its own
  421. columns — the pre-#671 behaviour, unchanged.
  422. Variants come back least-attempted first, ties broken by the user's
  423. ``position``. On the first pass every count is zero, so this is purely the
  424. user's priority order. After a start-watchdog bounce the printer that failed
  425. drops behind, so the next lap tries the other machine rather than spending the
  426. item's whole retry budget on the one that is wedged. Once every candidate has
  427. been tried equally often they cycle again, which keeps the item-level
  428. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  429. still gives up, it just does not give up without trying them.
  430. """
  431. if not item.variants:
  432. if not item.archive_id and not item.library_file_id:
  433. # Nothing to print at all. Dispatching would fail deep in the upload
  434. # on "No archive_id or library_file_id"; the caller holds the item
  435. # with an explanation instead.
  436. return []
  437. return [
  438. _ModelCandidate(
  439. target_model=item.target_model,
  440. sliced_for=_sliced_for_model(item.archive, item.library_file),
  441. required_filament_types=item.required_filament_types,
  442. filament_overrides=item.filament_overrides,
  443. )
  444. ]
  445. # Drop candidates whose file is gone or in the trash. Both are reachable and
  446. # neither is covered by the schema: library deletes are soft (the row lives
  447. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  448. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  449. # fires there and a hard delete leaves the variant row pointing at nothing.
  450. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  451. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  452. return [
  453. _ModelCandidate(
  454. target_model=v.target_model,
  455. sliced_for=_sliced_for_model(None, v.library_file),
  456. required_filament_types=v.required_filament_types,
  457. filament_overrides=v.filament_overrides,
  458. variant=v,
  459. )
  460. for v in ordered
  461. ]
  462. # Why a job for any printer of a model waits when every free one's last print
  463. # failed. The queue page matches it to offer Resume for the model.
  464. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  465. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  466. """Fold one waiting reason per candidate into a single line for the item.
  467. A cross-model item produces a reason per candidate, and pasting them
  468. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  469. — on which machine?). Each reason is prefixed with its model, except in the
  470. single-candidate case where the item already displays its target model and
  471. the prefix would be noise.
  472. Identical reasons collapse rather than repeat, so three idle-less models
  473. read as one clause.
  474. When *every* candidate is merely busy the parts are joined with the ``" | "``
  475. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  476. unprefixed. That case must keep testing busy-only: a fleet that is simply
  477. printing needs no user action, and labelling the clauses would turn each pass
  478. over a two-model item into a "job waiting" notification.
  479. """
  480. reasons = [(model, reason) for model, reason in per_model if reason]
  481. if not reasons:
  482. return None
  483. if len(reasons) == 1:
  484. return reasons[0][1]
  485. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  486. if len(distinct) == 1:
  487. return distinct[0]
  488. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  489. return " | ".join(distinct)
  490. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  491. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  492. """Human label for the models an item is waiting on ("H2S or H2C").
  493. Notifications take a single target model. For a cross-model item the item's
  494. own ``target_model`` is whichever variant happens to be first, which reads as
  495. a lie once it is the H2C that actually runs — so name all of them.
  496. """
  497. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  498. if not models:
  499. return None
  500. return " or ".join(models)
  501. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  502. """True if ``mapping`` is a non-empty list whose every entry is the
  503. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  504. Such a mapping is a bug artifact: a frontend status-load race can serialize
  505. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  506. recomputed from live status at dispatch rather than trusted, otherwise it
  507. reaches the print command and is silently downgraded to external-spool mode.
  508. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  509. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  510. explicit external selection (``>= 254``) is NOT unresolved either — those
  511. keep their meaning.
  512. """
  513. if not isinstance(mapping, list) or not mapping:
  514. return False
  515. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  516. def _is_tray_id(value: object) -> bool:
  517. """True when ``value`` can be read as a global tray ID.
  518. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  519. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  520. against whatever happens to be loaded there.
  521. """
  522. return isinstance(value, int) and not isinstance(value, bool)
  523. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  524. # stages an item (#2799). The manual_start branch clears every other reason on
  525. # a staged item (#3074); this one is the reason it was staged, so it stays.
  526. _UNMATCHED_HOLD_PREFIX = "Needs "
  527. # How often an "any model" job held for low filament looks for another printer
  528. # of its model that has enough (#3137). Each look matches its filament on every
  529. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  530. _SHORT_HOLD_RECHECK_SECONDS = 120
  531. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  532. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  533. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  534. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  535. """The item's force_color_match overrides as filament requirements (#3280).
  536. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  537. read, so the checks after it judge the same list.
  538. """
  539. try:
  540. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  541. except (json.JSONDecodeError, TypeError):
  542. return []
  543. if not isinstance(overrides, list):
  544. return []
  545. return [
  546. {
  547. "slot_id": o.get("slot_id"),
  548. "type": o.get("type", ""),
  549. "color": o.get("color", ""),
  550. "tray_info_idx": o.get("tray_info_idx", ""),
  551. "force_color_match": True,
  552. }
  553. for o in overrides
  554. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  555. ]
  556. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  557. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  558. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  559. for a filament this plate does not use. A slot past the end of the mapping
  560. is unresolved too.
  561. """
  562. unresolved = []
  563. for req in required:
  564. slot_id = req.get("slot_id") or 0
  565. if slot_id <= 0:
  566. continue
  567. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  568. if not _is_tray_id(tray) or tray < 0:
  569. unresolved.append(req)
  570. return unresolved
  571. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  572. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  573. # on `_mapping_is_all_unresolved`.
  574. _EXTERNAL_TRAY_ID_MIN = 254
  575. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  576. """The ``mapping`` entries for the slots this plate actually prints.
  577. ``required`` comes from ``extract_filament_requirements``, which drops any
  578. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  579. consumes, and one absent from it is padding. That distinction is why this
  580. decision lives here and not in the MQTT command builder: a ``-1`` in the
  581. mapping means either "this plate does not print filament N" or "we never
  582. worked out which tray", and only the plate's own filament list separates
  583. them. The builder sees both as the same byte, which is how a plate whose one
  584. printed filament sat on the external spool went out as `use_ams=true` with a
  585. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  586. with 07FF_8012 (#3087).
  587. Returns None whenever the two cannot be lined up — no mapping, no parsed
  588. requirements, or a requirement the mapping is too short to cover — so every
  589. caller falls back to existing behaviour rather than acting on a guess.
  590. """
  591. if not isinstance(mapping, list) or not mapping or not required:
  592. return None
  593. entries = []
  594. for filament in required:
  595. slot_id = filament.get("slot_id")
  596. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  597. # The mapping and the requirements disagree about how many filaments
  598. # the file has. They came from different reads, so judge nothing.
  599. return None
  600. entries.append(mapping[slot_id - 1])
  601. return entries or None
  602. def _is_external_tray(tray_id) -> bool:
  603. """True for an explicit external-spool selection (254/255), not for an
  604. unresolved slot and not for an AMS tray."""
  605. if tray_id is None:
  606. return False
  607. try:
  608. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  609. except (TypeError, ValueError):
  610. return False
  611. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  612. """Whether this printer could have two extruders, judged generously.
  613. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  614. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  615. why the MQTT command builder skips its own use_ams reconcile there. Anything
  616. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  617. with, external spools or not.
  618. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  619. behaviour it has always had, while a wrong "no" would rewrite a field that
  620. steers which nozzle prints. The model name is the first answer (it is what
  621. the command builder falls back to as well), then the same live evidence the
  622. dispatcher's extruder annotation uses — a second nozzle reporting a
  623. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  624. since a single-nozzle printer has exactly one.
  625. """
  626. if is_dual_nozzle_model(printer_model):
  627. return True
  628. nozzles = getattr(status, "nozzles", None) or []
  629. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  630. return True
  631. raw = getattr(status, "raw_data", None) or {}
  632. if raw.get("ams_extruder_map"):
  633. return True
  634. vt_trays = raw.get("vt_tray") or []
  635. return isinstance(vt_trays, list) and len(vt_trays) > 1
  636. def _int_or(value, default: int) -> int:
  637. """``int(value)``, or ``default`` when the field is missing or junk.
  638. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  639. the next — and a tray id that fails to parse must not take the whole
  640. derivation down with it.
  641. """
  642. try:
  643. return int(value)
  644. except (TypeError, ValueError):
  645. return default
  646. # What a queue job's dispatch is worked out from, and an edit can change.
  647. _DISPATCH_INPUTS = (
  648. "printer_id",
  649. "status",
  650. "ams_mapping",
  651. "plate_id",
  652. "filament_overrides",
  653. "skip_filament_check",
  654. "target_model",
  655. "target_location",
  656. )
  657. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  658. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  659. The pass works on the jobs as loaded at its start, and it may have waited
  660. since: a plug powering a printer on takes minutes. A job edited meanwhile
  661. (moved to another printer, given a mapping or another plate, cancelled)
  662. is left to the next pass, which reads it fresh: deciding from the stale
  663. copy would overwrite the edit, or send the job where it no longer goes.
  664. The query flushes the pass's own pending changes first, so those don't
  665. count as edits.
  666. """
  667. row = (
  668. await db.execute(
  669. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  670. )
  671. ).one_or_none()
  672. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  673. return False
  674. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  675. return True
  676. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  677. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  678. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  679. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  680. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  681. agree or a mapping cannot be read back against live tray telemetry.
  682. """
  683. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  684. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  685. """The global tray ids ``item`` actually prints from, or None if unknown.
  686. ``ams_mapping`` is the array the print command carries: position = filament
  687. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  688. not use. None means "no usable statement" — no mapping, unparseable JSON,
  689. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  690. documents), or one that resolves to no tray at all. Callers must treat None
  691. as "consider every loaded tray" rather than "consider none": narrowing on
  692. an absent mapping would silently drop requirements the print really has.
  693. """
  694. raw = getattr(item, "ams_mapping", None)
  695. if not raw:
  696. return None
  697. if isinstance(raw, str):
  698. try:
  699. mapping = json.loads(raw)
  700. except (json.JSONDecodeError, TypeError):
  701. return None
  702. else:
  703. mapping = raw
  704. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  705. return None
  706. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  707. return used or None
  708. def _mqtt_commands_rejected(status) -> bool:
  709. """True when the printer is currently reporting that it refused a command.
  710. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  711. a control command it could not verify. Queries still answer, so the printer
  712. looks connected and idle while project_file, gcode_line and
  713. ams_change_filament are all dropped — no amount of waiting or re-uploading
  714. changes that (#2732).
  715. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  716. ``print_error`` path builds HMSError differently), so this is safe to call on
  717. every watchdog poll.
  718. """
  719. for err in getattr(status, "hms_errors", None) or []:
  720. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  721. return True
  722. return False
  723. def _drying_ams_ids(status) -> list[int]:
  724. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  725. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  726. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  727. started (#2758) — it is a diagnostic, not a gate.
  728. Deliberately not used to block or stop drying before dispatch. This printer
  729. class supports drying concurrently with an active print
  730. (``supports_drying_while_printing``), so drying is not incompatible with
  731. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  732. while two AMS units were drying, one of them without its external PSU. Until
  733. it is known whether the blocker is drying itself or the power budget
  734. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  735. hardware is perfectly happy to continue.
  736. """
  737. ids: list[int] = []
  738. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  739. if not isinstance(unit, dict):
  740. continue
  741. try:
  742. if int(unit.get("dry_time") or 0) > 0:
  743. ids.append(int(unit.get("id", 0)))
  744. except (TypeError, ValueError):
  745. continue
  746. return ids
  747. def _parse_diameter(raw) -> float | None:
  748. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  749. try:
  750. value = float(raw)
  751. except (TypeError, ValueError):
  752. return None
  753. return value if value > 0 else None
  754. def _nozzle_info_by_id(status) -> dict[int, dict]:
  755. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  756. The field name is historical: on the H2 series ``nozzle_info`` carries an
  757. entry for *every* nozzle the printer knows about — the L/R hotends under
  758. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  759. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  760. :func:`_installed_nozzle_diameters` each take the half they need.
  761. """
  762. by_id: dict[int, dict] = {}
  763. for entry in getattr(status, "nozzle_rack", None) or []:
  764. if not isinstance(entry, dict):
  765. continue
  766. try:
  767. by_id[int(entry.get("id"))] = entry
  768. except (TypeError, ValueError):
  769. continue
  770. return by_id
  771. # What the firmware puts in a nozzle's serial number when the carriage or dock
  772. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  773. # its nozzle back in the rack (#2885).
  774. _EMPTY_NOZZLE_SERIAL = "N/A"
  775. def _nozzle_is_mounted(entry: dict | None) -> bool:
  776. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  777. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  778. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  779. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  780. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  781. the dock. So the diameter is not a presence signal (#2885).
  782. Emptiness has to be stated, not merely unstated. The serial must be the
  783. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  784. absent — an empty serial only means the printer didn't say, and a firmware
  785. that reports neither field normalises to exactly that. Treating "didn't
  786. say" as "empty" would silently switch the #1899 guard off on any such
  787. machine, so everything we cannot positively call empty counts as mounted.
  788. """
  789. if entry is None:
  790. return True
  791. serial = str(entry.get("serial_number") or "").strip().upper()
  792. if serial != _EMPTY_NOZZLE_SERIAL:
  793. return True
  794. try:
  795. max_temp = float(entry.get("max_temp") or 0)
  796. except (TypeError, ValueError):
  797. return True
  798. return max_temp > 0
  799. def _installed_nozzle_diameters(status) -> list[float]:
  800. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  801. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  802. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  803. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  804. told us its nozzle hardware" — callers must treat that as unknown, not as a
  805. mismatch, so we never block a print on missing data.
  806. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  807. though ``nozzles`` still carries a diameter for it: that value is stale, and
  808. counting it would let a slice match a nozzle the machine does not have
  809. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  810. """
  811. info = _nozzle_info_by_id(status)
  812. diameters: list[float] = []
  813. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  814. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  815. try:
  816. value = float(raw)
  817. except (TypeError, ValueError):
  818. continue
  819. if value > 0 and _nozzle_is_mounted(info.get(index)):
  820. diameters.append(value)
  821. return diameters
  822. def _rack_nozzle_diameters(status) -> list[float]:
  823. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  824. Keyed off the nozzle ids themselves rather than the printer model: only a
  825. rack machine ever reports ids 16-21, so there is no model registry to keep
  826. in sync. An empty dock is simply absent from the payload — measured on an
  827. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  828. present — so appearing here already means "a nozzle is in that dock".
  829. ``stat`` is deliberately not interpreted: its values aren't known, and
  830. reading it wrongly could hide a nozzle the printer would happily fetch.
  831. """
  832. diameters: list[float] = []
  833. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  834. if nozzle_id not in _RACK_NOZZLE_IDS:
  835. continue
  836. # PrinterState spells it "diameter"; the REST schema renames it to
  837. # "nozzle_diameter". Accept either so a caller holding the serialised
  838. # shape gets the same answer.
  839. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  840. if value is not None:
  841. diameters.append(value)
  842. return diameters
  843. def _format_diameters(diameters: list[float]) -> str:
  844. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  845. Deduplicated because a loaded rack holds several nozzles of the same size,
  846. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  847. short form doesn't. Matching still runs over the full list.
  848. """
  849. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  850. def _nozzle_mismatch_message(
  851. sliced_nozzle: float | None,
  852. installed: list[float],
  853. rack: list[float] | None = None,
  854. ) -> str | None:
  855. """Return an actionable error message when the sliced nozzle can't be
  856. printed on any nozzle the machine can reach, else None (#1899).
  857. Fail-safe: returns None whenever we lack the data to judge — no sliced
  858. diameter, or the printer reported no nozzles — so a print is only ever
  859. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  860. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  861. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  862. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  863. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  864. as reachable: the printer fetches one as part of starting the print, so a
  865. slice that matches a docked nozzle is not a mismatch. Without this the
  866. guard blocked every job whose nozzle happened not to be on a hotend at
  867. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  868. diameter already mounted could ever print, and the user had to fetch the
  869. nozzle by hand on the printer's own UI first (#2885).
  870. """
  871. reachable = [*installed, *(rack or [])]
  872. if not sliced_nozzle or not reachable:
  873. return None
  874. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  875. return None
  876. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  877. if rack:
  878. where += f" and {_format_diameters(rack)} in the nozzle rack"
  879. return (
  880. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  881. f"{where}. Re-slice for an available nozzle, or fit the matching "
  882. f"nozzle before printing."
  883. )
  884. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  885. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  886. Shared by the required and loaded sides, which name their extruder
  887. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  888. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  889. 1 the left/deputy — and both are absent on single-nozzle printers, where
  890. naming a nozzle would be noise.
  891. """
  892. parts = [(entry.get("type") or "filament").upper()]
  893. if entry.get("color"):
  894. parts.append(str(entry["color"]))
  895. nozzle = entry.get(nozzle_key)
  896. if nozzle == 0:
  897. parts.append("(right nozzle)")
  898. elif nozzle == 1:
  899. parts.append("(left nozzle)")
  900. return " ".join(parts)
  901. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  902. """Explain that nothing loaded matches what the file needs (#2771).
  903. Only ever built for a printer with no AMS, where the loaded list is short
  904. enough to quote in full and there is no "load another spool and hit Resume"
  905. recovery — the external spool holder is all there is, so the user needs to
  906. be told which filament to put on it.
  907. """
  908. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  909. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  910. return (
  911. f"No filament loaded on this printer matches the file. It needs {want}; "
  912. f"the printer has {have} and no AMS. Load the required filament on the "
  913. f"external spool holder, or send this job to a printer that has it."
  914. )
  915. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  916. """Bed temperature for the plate a queued job prints, 0 when unknown.
  917. The archive stores the highest bed temperature of any filament in the
  918. project, while the job may print another plate than the one archived: a
  919. PLA plate of a project that also holds PETG is heated for PLA. Read from
  920. the archive's file for the job's own plate, falling back to the stored
  921. value when the file can't be read.
  922. """
  923. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  924. if archive is None or not archive.file_path:
  925. return stored
  926. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  927. return temperature or stored
  928. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  929. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  930. every call site below it: G-code injection, usage registration, rack-plan
  931. lookup, slot-extruder lookup, the external-spool check, and the actual
  932. print command.
  933. A positive explicit ``plate_id`` on the queue item always wins. A
  934. non-positive one is treated as "not set" and resolved from the archive,
  935. the way the rest of the queue code already reads it (``if item.plate_id:``
  936. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  937. field, and passing a 0 straight through would build a print command for
  938. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  939. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  940. Falling back to a bare ``1`` instead of reading the archive assumes a
  941. single-plate file's one G-code is numbered 1, which only holds for a
  942. plate exported on its own: one cut out of a larger project keeps its
  943. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  944. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  945. the file, throws an HMS error, and sits wedged in IDLE until
  946. power-cycled (#2947).
  947. The call sites agreed on a fallback only by accident before this:
  948. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  949. the archive's own default plate internally whenever the plate id it's
  950. handed isn't in the file, so it could silently inject into a different
  951. plate than the one the print command itself asked for.
  952. Falls back to 1 when the archive can't be read, holds no G-code member at
  953. all, or its default member doesn't follow the ``plate_N`` naming
  954. convention (a slicer that doesn't use it has no number to dispatch).
  955. An explicit plate the archive doesn't hold is logged and then sent
  956. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  957. to a plate that is in the file would print a model nobody asked for,
  958. which is the worse of the two.
  959. """
  960. try:
  961. with zipfile.ZipFile(file_path, "r") as zf:
  962. names = zf.namelist()
  963. except (OSError, zipfile.BadZipFile) as exc:
  964. logger.warning(
  965. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  966. "is unavailable; dispatching plate %s",
  967. file_path,
  968. exc,
  969. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  970. )
  971. names = None
  972. if explicit_plate_id is not None and explicit_plate_id > 0:
  973. if (
  974. names is not None
  975. and default_plate_number(names) is not None
  976. and select_plate_gcode_name(names, explicit_plate_id) is None
  977. ):
  978. logger.warning(
  979. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  980. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  981. "file, since printing a different plate would print the wrong model (#2947)",
  982. file_path,
  983. explicit_plate_id,
  984. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  985. explicit_plate_id,
  986. )
  987. return explicit_plate_id
  988. resolved = default_plate_number(names) if names is not None else None
  989. return resolved if resolved is not None else 1
  990. class PrintScheduler:
  991. """Background scheduler that processes the print queue."""
  992. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  993. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  994. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  995. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  996. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  997. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  998. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  999. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1000. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1001. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1002. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1003. }
  1004. def __init__(self):
  1005. self._running = False
  1006. self._check_interval = 30 # seconds
  1007. # After a pass that actually dispatched something, loop again almost
  1008. # immediately instead of sleeping the full interval (#2555). A dispatch
  1009. # changes printer state — a batch launch fans out over several passes as
  1010. # printers free up, a wedged head-of-line job reverts to pending, an
  1011. # upload slot opens — and the next batch of ready work should not have to
  1012. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1013. # pending items are behind printers that are genuinely busy printing),
  1014. # there is nothing to react to, so we fall back to the normal interval;
  1015. # that also means this can never tight-loop, since fast ticks only
  1016. # continue while dispatches keep happening and the queue is draining.
  1017. self._fast_check_interval = 3 # seconds
  1018. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1019. self._power_on_check_interval = 10 # seconds between connection checks
  1020. # Printers whose class-target power-on failed, mapped to the monotonic
  1021. # time their cool-off expires (#2786).
  1022. #
  1023. # Without this, one printer with an unreachable plug starves every
  1024. # sibling of its model forever: the wake step walks candidates in id
  1025. # order, spends the pass's single attempt on the same broken printer
  1026. # every time, and the healthy one two slots down is never reached. It
  1027. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1028. # which delays the whole queue, not just this job.
  1029. #
  1030. # Entries expire on read rather than being cleared on success: a printer
  1031. # inside its cool-off is skipped before the power-on is reached, so a
  1032. # live entry can never be overwritten by a success anyway. A printer
  1033. # that comes back by any other route stops being a wake candidate the
  1034. # moment it connects.
  1035. self._wake_failures: dict[int, float] = {}
  1036. self._wake_failure_cooloff = 600 # seconds
  1037. # Printers whose last upload never reached them, mapped to the monotonic
  1038. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1039. # as `_wake_failures`. Without it, a printer that cannot take files is
  1040. # idle on every pass, so it is picked on every pass.
  1041. self._upload_backoff: dict[int, float] = {}
  1042. # Refused uploads in a row per printer, which sets the next backoff
  1043. # window. Cleared by a successful upload to that printer.
  1044. self._upload_refusals: dict[int, int] = {}
  1045. # Printers whose current run of refusals has already sent its one
  1046. # "job waiting" notification. Each retry clears the item's waiting
  1047. # reason and the next refusal sets it again, which `hold_item` reads as
  1048. # a new reason; without this, every retry would notify. Cleared with
  1049. # `_upload_refusals`.
  1050. self._upload_refusal_notified: set[int] = set()
  1051. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1052. self._drying_in_progress: dict[int, float] = {}
  1053. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1054. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1055. # cycle and the humidity finally coming down, so the normal steady
  1056. # state is an empty dict. Fields:
  1057. # running — a cycle we armed is (or should be) on the firmware
  1058. # ended_at — monotonic when we observed that cycle end
  1059. # unproductive — consecutive armed cycles that ended with the reading
  1060. # still above the threshold
  1061. # suspended — we have stopped arming this unit and said so
  1062. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1063. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1064. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1065. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1066. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1067. # arming setdefault all act on that meaning -- a unit that is merely
  1068. # waiting out its streak must not become stoppable or judgeable.
  1069. # since -- monotonic stamp when the current continuous above-threshold
  1070. # streak began
  1071. # last -- monotonic stamp of the last pass that observed the streak
  1072. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1073. # Slots already notified as low on filament:
  1074. # {(printer_id, ams_id, tray_id, spool_id)}.
  1075. # Cleared when the slot goes back above its threshold rather than on a
  1076. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1077. # boundary must not produce an alert on every pass, and a slot that has
  1078. # been refilled has to be able to alert again. See #2913.
  1079. #
  1080. # The spool id is part of the key because the slot alone cannot clear
  1081. # itself. Pull a low spool and put a different part-used one in the same
  1082. # slot: the key survives the pass where the slot resolves to nothing --
  1083. # deliberately, so a brief Spoolman outage does not re-alert everything
  1084. # when it returns -- and the replacement never goes above the threshold,
  1085. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1086. # different key and the stale one is inert.
  1087. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1088. # The same, for the MQTT relay's filament/low event: its own record, so
  1089. # one channel having been told never silences the other.
  1090. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1091. # Earliest monotonic time the next low-filament check may run (#2913).
  1092. self._filament_low_next_check: float = 0.0
  1093. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1094. # condition is "reorder" or "break", the events are those that had a
  1095. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1096. # condition clears, so it can alert again, and when nobody wants either
  1097. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1098. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1099. # re-send one message per SKU that is still low.
  1100. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1101. # The JSON last read from or written to that row; None until it has been read.
  1102. self._stock_alerts_persisted: str | None = None
  1103. # Earliest monotonic time the next stock forecast check may run (#2955).
  1104. self._stock_forecast_next_check: float = 0.0
  1105. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1106. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1107. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1108. # both features share _drying_in_progress.
  1109. self._scheduled_drying_printer_ids: set[int] = set()
  1110. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1111. # the first pass after a restart reaps anything left behind.
  1112. self._last_scheduled_drying_prune: float | None = None
  1113. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1114. # a project_file command must not get a second dispatch until either it
  1115. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1116. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1117. # during that window the DB busy_printers seed is empirically unreliable
  1118. # (multi-plate batches double-/triple-dispatched onto the same printer
  1119. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1120. # or revert.
  1121. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1122. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1123. # Minimum cooldown between dispatches to the same printer (covers the
  1124. # H2D's project_file digestion window).
  1125. self._dispatch_min_cooldown = 60.0
  1126. # Hard timeout — drop the hold even if we never observed a transition,
  1127. # so a lost MQTT session can't lock a printer out of the queue forever.
  1128. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1129. # watchdog runs first on the unhappy path.
  1130. self._dispatch_max_hold = 180.0
  1131. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1132. # an earlier pass and is still running. `_start_print` flips the row
  1133. # pending -> printing only *after* the upload completes, so until then
  1134. # the row stays `pending`: each tick, check_queue excludes these
  1135. # item_ids from re-selection and their printers from new dispatch /
  1136. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1137. # freed slots refill on the next fast tick. check_queue is the sole,
  1138. # sequential caller and the prune done-callbacks run in the same
  1139. # event-loop thread, so this dict needs no lock.
  1140. # item_id -> (task, printer_id)
  1141. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1142. # Expected prints registered by `_start_print` that have not yet had a
  1143. # print command sent. Populated at registration, dropped once
  1144. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1145. # other exit. Same threading argument as `_inflight` above: one
  1146. # sequential caller, callbacks on the same loop, so no lock.
  1147. # item_id -> (printer_id, remote_filename, archive_id)
  1148. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1149. # Budget reservations created for a dispatch whose print command has
  1150. # not been confirmed yet. `_dispatch_one` releases these on every
  1151. # unsuccessful exit; a successful start removes the item id and leaves
  1152. # the reservation for finance_billing to consume with the archive.
  1153. self._unconfirmed_budget_reservations: set[int] = set()
  1154. # The print user `_start_print` handed to printer_manager for an item
  1155. # whose print command has not been sent yet (item_id -> printer_id).
  1156. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1157. # expected print above: it marks the printer's next print as Bambuddy's.
  1158. self._unconfirmed_print_user: dict[int, int] = {}
  1159. # Prints whose command went out but which the printer has not been
  1160. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1161. # the file and archive None for a library print. The watchdog drops the
  1162. # entry once the print runs, and withdraws what it stands for when the
  1163. # print never starts (see `_forget_unstarted_print`).
  1164. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1165. # Chamber temperature history for smart soak-time reduction.
  1166. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1167. # Entries older than _chamber_history_ttl are pruned on write.
  1168. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1169. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1170. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1171. # Populated on engagement in `_apply_keep_warm`, cleared by
  1172. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1173. # when a gate setting toggles off mid-hold — the release publishes
  1174. # bed → 0 first).
  1175. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1176. # Preheat rollback registry: printer_id -> subset of
  1177. # {"bed", "chamber", "airduct"} listing which preheat commands
  1178. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1179. # every entry still present at exit unless the print successfully
  1180. # started, so a failed upload / cancel / exception never leaves the
  1181. # printer heating for a job that isn't happening.
  1182. self._preheat_pin: dict[int, set[str]] = {}
  1183. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1184. # rollback can tell its own target from one someone else has since
  1185. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1186. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1187. self._preheat_pin_bed: dict[int, int] = {}
  1188. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1189. # its preheat was still holding at temperature. Set by
  1190. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1191. # `_preheat_sleep`, and cleared when the dispatch exits.
  1192. self._cancelled_dispatches: set[int] = set()
  1193. # printer_id -> monotonic time it was first seen terminal while one of
  1194. # its queue rows was still 'printing'. Reset by any non-terminal
  1195. # observation, so it measures an unbroken run rather than a total.
  1196. # In-memory on purpose: a restart re-arms the grace period, which only
  1197. # delays a recovery that is already the exceptional path (#2829).
  1198. self._terminal_since: dict[int, float] = {}
  1199. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1200. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1201. # across idle printers repeats that for every one of them in a single
  1202. # pass. Cleared at the top of each pass so a re-sliced file is never
  1203. # served from a previous tick.
  1204. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1205. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1206. # matcher about every idle candidate, and a pass can ask again for the
  1207. # same job and printer (another variant, a previous-print retry, the
  1208. # low-filament move). Cleared with the requirement memo.
  1209. self._unmatched_memo: dict[tuple, list[str]] = {}
  1210. # When each "any model" job held for low filament last looked for
  1211. # another printer (#3137), by queue item id.
  1212. self._short_hold_checked_at: dict[int, float] = {}
  1213. async def run(self):
  1214. """Main loop - check queue every interval."""
  1215. self._running = True
  1216. logger.info("Print scheduler started")
  1217. await self._clear_stale_dispatch_claims(at_startup=True)
  1218. while self._running:
  1219. dispatched = False
  1220. try:
  1221. self._sample_chamber_temps()
  1222. # No-op while any upload is in flight; on a quiet tick it releases
  1223. # a claim whose best-effort clear failed (e.g. the database was
  1224. # briefly unreachable), instead of leaving the row wedged until
  1225. # the next restart.
  1226. await self._clear_stale_dispatch_claims()
  1227. await self._close_stranded_printing_items()
  1228. dispatched = await self.check_queue()
  1229. except Exception as e:
  1230. logger.error("Scheduler error: %s", e)
  1231. # Re-check quickly after a productive pass so a draining batch does
  1232. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1233. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1234. async def _close_stranded_printing_items(self) -> None:
  1235. """Close a ``printing`` row the completion event never closed (#2829).
  1236. ``on_print_complete`` refuses to close a row when the completion's
  1237. subtask name disagrees with the file the row was dispatched with, so a
  1238. completion meant for something else (the printer's own
  1239. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1240. The refusal has no way back, though: nothing else ever closes the row,
  1241. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1242. one bad comparison wedges that printer's queue until a human presses
  1243. cancel. That is what #2829's reporters hit, and the guard's own
  1244. docstring already called stranding the worse of the two failures.
  1245. This is the way back. When a row has been ``printing`` while its
  1246. printer sat in a terminal state for the whole grace period, the print
  1247. is over however the event was read, and the row is closed with the
  1248. status the printer's own state implies.
  1249. Deliberately conservative:
  1250. * Only a connected printer counts. A disconnected one has a stale
  1251. ``state`` and proves nothing.
  1252. * The clock is reset by any non-terminal observation, so this cannot
  1253. fire on a printer that is merely between stages.
  1254. * The grace period is far longer than the gap between a printer
  1255. finishing and its completion arriving, so the normal path always
  1256. wins the race and this only ever sees genuine strandings.
  1257. What it does *not* do is replay the completion's side effects --
  1258. notifications, billing, auto-off. It restores the queue, which is the
  1259. harm being undone; the archive was updated by the normal path
  1260. regardless, since only the queue block refuses. A recovery that
  1261. silently re-fired notifications minutes late would be its own bug.
  1262. """
  1263. try:
  1264. async with async_session() as db:
  1265. result = await db.execute(
  1266. select(PrintQueueItem)
  1267. .where(PrintQueueItem.status == "printing")
  1268. .where(PrintQueueItem.printer_id.is_not(None))
  1269. )
  1270. items = list(result.scalars().all())
  1271. if not items:
  1272. self._terminal_since.clear()
  1273. return
  1274. now = time.monotonic()
  1275. seen_printers: set[int] = set()
  1276. closed = False
  1277. for item in items:
  1278. printer_id = item.printer_id
  1279. seen_printers.add(printer_id)
  1280. state = printer_manager.get_status(printer_id)
  1281. status = _terminal_queue_status(state)
  1282. if status is None:
  1283. self._terminal_since.pop(printer_id, None)
  1284. continue
  1285. since = self._terminal_since.setdefault(printer_id, now)
  1286. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1287. continue
  1288. item.status = status
  1289. item.completed_at = datetime.now(timezone.utc)
  1290. closed = True
  1291. # The printer is idle: nothing it prints next is this item's.
  1292. self._forget_unstarted_print(item.id, unless_printing=True)
  1293. logger.warning(
  1294. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1295. "closing it as %s. Its completion event was never matched to it, which blocks "
  1296. "every later job for this printer (#2829).",
  1297. item.id,
  1298. printer_id,
  1299. getattr(state, "state", None),
  1300. now - since,
  1301. status,
  1302. )
  1303. if closed:
  1304. await db.commit()
  1305. from backend.app.services.print_batch import refresh_batches_after
  1306. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1307. for printer_id in list(self._terminal_since):
  1308. if printer_id not in seen_printers:
  1309. del self._terminal_since[printer_id]
  1310. except Exception as e:
  1311. # Best-effort, same as the claim sweep beside it: a recovery path
  1312. # that can itself break the scheduler loop is worse than the strand.
  1313. logger.error("Stranded-item sweep failed: %s", e)
  1314. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1315. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1316. A claim is only ever held by a live dispatch coroutine, so when this
  1317. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1318. is stale. At startup that is trivially true — no coroutine survives a
  1319. restart. It is equally true on any later tick where no upload is running,
  1320. which is what makes this safe to repeat rather than only run once.
  1321. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1322. the database is briefly unreachable at exactly the moment dispatch ends,
  1323. the claim survives and the row is wedged out of the selection query. That
  1324. used to last until the next restart (#2702 follow-up, seen when
  1325. PostgreSQL refused a connection mid-dispatch).
  1326. ``_inflight`` is populated when the task is spawned, before the coroutine
  1327. claims its row, and pruned by a done-callback that cannot run before the
  1328. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1329. race window and needs no age threshold. A size-derived upload deadline
  1330. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1331. """
  1332. if self._inflight:
  1333. return
  1334. try:
  1335. async with async_session() as db:
  1336. res = await db.execute(
  1337. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1338. )
  1339. await db.commit()
  1340. if res.rowcount:
  1341. logger.info(
  1342. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1343. res.rowcount,
  1344. " at startup" if at_startup else "",
  1345. )
  1346. except Exception as exc:
  1347. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1348. def stop(self):
  1349. """Stop the scheduler."""
  1350. self._running = False
  1351. logger.info("Print scheduler stopped")
  1352. def forget_printer(self, printer_id: int) -> None:
  1353. """Drop what is kept for a deleted printer, so the next printer given its
  1354. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1355. would keep it out of dispatch for up to an hour.
  1356. A dispatch already in flight keeps its own state (_inflight, the preheat
  1357. pins, unconfirmed prints): it unwinds that when it ends.
  1358. """
  1359. for keyed in (
  1360. self._upload_backoff,
  1361. self._upload_refusals,
  1362. self._wake_failures,
  1363. self._drying_in_progress,
  1364. self._dispatch_holds,
  1365. self._chamber_history,
  1366. self._keep_warm,
  1367. self._terminal_since,
  1368. ):
  1369. keyed.pop(printer_id, None)
  1370. self._upload_refusal_notified.discard(printer_id)
  1371. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1372. for key in [key for key in keyed if key[0] == printer_id]:
  1373. del keyed[key]
  1374. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1375. del self._sent_unstarted_print[item_id]
  1376. async def check_queue(self) -> bool:
  1377. """Check for prints ready to start.
  1378. Returns True if this pass dispatched at least one item, so the caller
  1379. can loop again quickly instead of sleeping the full interval (#2555).
  1380. """
  1381. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1382. self._filament_req_memo.clear()
  1383. self._unmatched_memo.clear()
  1384. async with async_session() as db:
  1385. # Check if shortest-job-first scheduling is enabled
  1386. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1387. # Get all pending items in the one order the queue page shows them
  1388. # in (#3200). The first eligible item takes a printer, so this order
  1389. # decides who wins a printer that a pinned job and an "Any <model>"
  1390. # job both want. It used to start with ``printer_id``, which made the
  1391. # lane outrank the position: SQLite sorts NULL first, so model-based
  1392. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1393. # Neither is what the user dragged into place.
  1394. if sjf_enabled:
  1395. # SJF: items already jumped get top priority (starvation guard),
  1396. # then sort by print_time ascending. Items with no print time go
  1397. # last, and position breaks ties.
  1398. result = await db.execute(
  1399. select(PrintQueueItem)
  1400. .where(PrintQueueItem.status == "pending")
  1401. # Never re-select a row a dispatch worker has already claimed
  1402. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1403. # below, and the guard that lets an orphaned claim be ignored
  1404. # until startup reconciliation clears it.
  1405. .where(PrintQueueItem.dispatching_at.is_(None))
  1406. # archive/library_file are read by the cross-model gate
  1407. # (#2578); eager-load once per pass instead of a lazy-load
  1408. # (which would raise in async) per item.
  1409. .options(
  1410. selectinload(PrintQueueItem.archive),
  1411. selectinload(PrintQueueItem.library_file),
  1412. # Cross-model candidates (#671), plus each candidate's file
  1413. # for the same cross-model gate. Lazy-loading either would
  1414. # raise in async.
  1415. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1416. )
  1417. .order_by(
  1418. PrintQueueItem.been_jumped.desc(),
  1419. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1420. PrintQueueItem.position,
  1421. PrintQueueItem.id,
  1422. )
  1423. )
  1424. else:
  1425. result = await db.execute(
  1426. select(PrintQueueItem)
  1427. .where(PrintQueueItem.status == "pending")
  1428. # Skip rows already claimed by a dispatch worker (#2615).
  1429. .where(PrintQueueItem.dispatching_at.is_(None))
  1430. .options(
  1431. selectinload(PrintQueueItem.archive),
  1432. selectinload(PrintQueueItem.library_file),
  1433. # Cross-model candidates (#671), plus each candidate's file
  1434. # for the same cross-model gate. Lazy-loading either would
  1435. # raise in async.
  1436. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1437. )
  1438. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1439. )
  1440. items = list(result.scalars().all())
  1441. # Drop rows whose upload is still in flight from an earlier pass
  1442. # (#2602). They stay `pending` until the upload finishes, so without
  1443. # this a fast tick would re-select and re-dispatch the same row.
  1444. # Belt-and-suspenders with the printer exclusion below.
  1445. if self._inflight:
  1446. inflight_ids = set(self._inflight)
  1447. items = [it for it in items if it.id not in inflight_ids]
  1448. # Read plate-clear setting once per queue check. Default MUST be
  1449. # False to match the schema (SettingsSchema.require_plate_clear
  1450. # defaults False) and the frontend (toggle + card badge both treat a
  1451. # missing value as off). When no settings row exists, a True default
  1452. # here re-enabled the plate-clear gate the UI showed as disabled,
  1453. # blocking dispatch to FINISH-state printers forever with no UI path
  1454. # to clear it (#1865).
  1455. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1456. # Dispatch and track scheduled drying runs (#2638)
  1457. await self._check_scheduled_dryings(db)
  1458. if not items:
  1459. # No dispatchable pending items — still check auto-drying on idle
  1460. # printers, but keep any printer with an upload still in flight
  1461. # from an earlier pass out of it (#2602): its print is imminent,
  1462. # so it must not be auto-dried in the gap before the row flips to
  1463. # printing. Report the pass as productive while uploads run so the
  1464. # loop stays on the fast interval.
  1465. #
  1466. # Also release any keep-warm holds that got orphaned by the queue
  1467. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1468. # this early return, so call it directly with an empty candidate
  1469. # set. Without this, a printer whose queued item was cancelled or
  1470. # deleted would keep its bed at target until the max-duration
  1471. # timeout expired.
  1472. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1473. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1474. await self._check_auto_drying(db, [], inflight_printers)
  1475. await self._check_filament_low(db)
  1476. await self._check_stock_forecast(db)
  1477. return bool(self._inflight)
  1478. logger.info(
  1479. "Queue check: found %d pending items: %s",
  1480. len(items),
  1481. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1482. )
  1483. # Forget jobs that left the queue since they were last checked.
  1484. pending_ids = {i.id for i in items}
  1485. self._short_hold_checked_at = {
  1486. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1487. }
  1488. # Seed busy_printers with printers that already have an item in 'printing'
  1489. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1490. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1491. # lag several seconds behind the print command, so the next check_queue
  1492. # tick still sees IDLE and would double-dispatch onto the same printer.
  1493. # Without this guard, two pending items targeting the same printer
  1494. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1495. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1496. busy_result = await db.execute(
  1497. select(PrintQueueItem.printer_id)
  1498. .where(PrintQueueItem.status == "printing")
  1499. .where(PrintQueueItem.printer_id.is_not(None))
  1500. )
  1501. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1502. # Why each printer left this pass, recorded where the decision is
  1503. # made rather than re-derived when the summary is logged. #3018's
  1504. # bundle shows what the old summary produced: "printer 1 not
  1505. # available -- connected=True, state=IDLE" immediately followed by a
  1506. # dispatch to printer 1. Two things went wrong at once. The line read
  1507. # live state at log time, which by then no longer matched the state
  1508. # the decision was made on; and `busy_printers` holds both printers
  1509. # that cannot take work and printers this pass has claimed for it,
  1510. # which are opposite facts. It is the first line anyone greps for
  1511. # "why did my item not go out", so it has to say which.
  1512. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1513. # Printers this pass is dispatching to. They are in busy_printers so
  1514. # nothing else in the pass targets them -- that is a reservation, not
  1515. # an obstruction, and the summary says so.
  1516. claimed_printers: set[int] = set()
  1517. def mark_busy(printer_id: int, reason: str) -> None:
  1518. """Take ``printer_id`` out of this pass, recording why.
  1519. First reason wins: a printer already excluded by a stronger fact
  1520. -- a print running on it -- must not be relabelled by a weaker
  1521. check that ran later and would have excluded it anyway.
  1522. """
  1523. busy_printers.add(printer_id)
  1524. busy_reasons.setdefault(printer_id, reason)
  1525. def claim_printer(printer_id: int) -> None:
  1526. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1527. claimed_printers.add(printer_id)
  1528. mark_busy(printer_id, "selected for dispatch in this pass")
  1529. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1530. # worded for a different audience: the log wants "still inside its
  1531. # post-dispatch hold window", the queue row wants to know the printer
  1532. # is taken and nothing is broken. Only the cases that would read wrong
  1533. # as a plain "Busy" are recorded here; the rest fall back to it.
  1534. item_hold_reasons: dict[int, str] = {}
  1535. # Names and models for the printers this pass may have to write a
  1536. # waiting reason about, read once rather than per skip per tick. The
  1537. # model-based branch already has its names from `_printers_for_model`.
  1538. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1539. pinned_printers: dict[int, tuple[str, str]] = {}
  1540. if pinned_printer_ids:
  1541. pinned_rows = await db.execute(
  1542. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1543. )
  1544. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1545. def printer_label(printer_id: int) -> str:
  1546. """What to call this printer in a queue row."""
  1547. entry = pinned_printers.get(printer_id)
  1548. return (entry[0] if entry else "") or f"printer {printer_id}"
  1549. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1550. """Record why *item* is not going out, in the words the queue row shows.
  1551. The fixed-printer branch's single writer for ``waiting_reason``
  1552. (#3074). Before this, the sensor interlock was the only thing that
  1553. wrote the field there, so an item pinned to a printer that was
  1554. merely printing sat at `pending` with nothing to show for it —
  1555. indistinguishable from a queue that had stopped working — while
  1556. the same job queued as "Any <model>" explained itself.
  1557. Every exit from that branch now calls this, which is also what
  1558. replaced the interlock's old habit of clearing the field up front:
  1559. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1560. because whichever exit runs next overwrites it and the dispatch
  1561. path clears it.
  1562. A notification goes out when this item starts asking for
  1563. something, and only then: the new reason needs the user, and what
  1564. it replaced did not. "What it replaced did not" has to include a
  1565. busy-only reason, not just an empty one. The sequence this branch
  1566. actually produces is a print running (``Busy: X1C-01``) and then
  1567. the plate it left behind (``Waiting for plate confirmation``), and
  1568. testing "was the field empty" would call that no transition at all
  1569. and stay quiet through the one case worth saying out loud.
  1570. The cost is that a printer dropping offline, coming back busy and
  1571. dropping again asks twice rather than once. That is the honest
  1572. reading — it went wrong twice — and the alternative was a rule
  1573. that never fired for the case this was built for.
  1574. *notify* is how a caller opts out. The sensor interlock does: it
  1575. has never sent this notification, and a change about what the
  1576. queue *displays* is not the place to start (#1148).
  1577. """
  1578. if item.waiting_reason == reason:
  1579. return
  1580. # Busy-only and empty are the same thing here: neither is the
  1581. # queue asking the user for anything.
  1582. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1583. item.waiting_reason = reason
  1584. await db.commit()
  1585. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1586. return
  1587. try:
  1588. job_name = await self._get_job_name(db, item)
  1589. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1590. await notification_service.on_queue_job_waiting(
  1591. job_name=job_name,
  1592. target_model=(entry[1] if entry else "") or "",
  1593. waiting_reason=reason,
  1594. db=db,
  1595. printer_id=item.printer_id,
  1596. )
  1597. except Exception as e:
  1598. # A queue that cannot say why it is waiting is the bug being
  1599. # fixed here; a queue that stops dispatching because a
  1600. # notification provider is down would be a worse one.
  1601. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1602. async def hold_for_printer(
  1603. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1604. ) -> None:
  1605. """Take *printer_id* out of this pass and tell the item's owner why."""
  1606. mark_busy(printer_id, log_reason)
  1607. item_hold_reasons.setdefault(printer_id, item_reason)
  1608. await hold_item(item, item_reason)
  1609. # Defense-in-depth (#1157): augment busy_printers with any printer
  1610. # still in its post-dispatch hold window. Empirically, the DB seed
  1611. # above can miss in-flight items in a multi-plate batch — same-file
  1612. # plates were being dispatched 30 s apart while the H2D was still
  1613. # digesting the first project_file. The hold is keyed in-memory and
  1614. # released by the watchdog on the success path, so it adds a layer
  1615. # that doesn't depend on DB row visibility or completion-callback
  1616. # timing.
  1617. for held_printer_id in list(self._dispatch_holds.keys()):
  1618. if self._printer_in_dispatch_hold(held_printer_id):
  1619. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1620. # Exclude printers whose upload is still in flight from an earlier
  1621. # pass (#2602). The row is `pending` until the upload finishes and
  1622. # the printing-state seed / dispatch hold above only arm once the
  1623. # upload completes, so this is what holds the printer (and, via
  1624. # busy_printers, its auto-drying) out of the pass during the upload.
  1625. for _task, inflight_pid in self._inflight.values():
  1626. if inflight_pid is not None:
  1627. mark_busy(inflight_pid, "an upload to it is still in flight")
  1628. # Snapshot taken here, before the item loop adds anything (#2801).
  1629. #
  1630. # The three sources above all mean the same thing: a print on this
  1631. # printer is running or imminent. Everything the loop adds below
  1632. # means only "the queue could not dispatch to it this pass", which
  1633. # is a different statement -- a printer waiting on a plate-clear
  1634. # acknowledgment, an offline printer, one with no matching file.
  1635. #
  1636. # Auto-drying must only see the first kind. Reading the whole set
  1637. # as "is currently printing" is what put a plate-held printer down
  1638. # the mid-print path: it capped the drying temperature, logged the
  1639. # cycle as (mid-print), and skipped the very gate that was supposed
  1640. # to hold it. The interlock block below already documents the same
  1641. # hazard and works around it by staying out of busy_printers; this
  1642. # generalises that workaround instead of repeating it per case.
  1643. dispatching_printers: set[int] = set(busy_printers)
  1644. # Printers whose last upload never reached them (#3210). After the
  1645. # snapshot above on purpose: such a printer is idle, not about to
  1646. # print, and auto-drying must keep treating it as idle.
  1647. now_mono = time.monotonic()
  1648. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1649. # can leave them out: there is no print to keep a bed warm for.
  1650. backoff_printers: set[int] = set()
  1651. # In backoff, and the "job waiting" notification for this run of
  1652. # refusals has gone out already. Their holds are written silently.
  1653. silent_hold_printers: set[int] = set()
  1654. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1655. if now_mono >= retry_at:
  1656. del self._upload_backoff[backoff_pid]
  1657. continue
  1658. backoff_printers.add(backoff_pid)
  1659. if backoff_pid in self._upload_refusal_notified:
  1660. silent_hold_printers.add(backoff_pid)
  1661. else:
  1662. self._upload_refusal_notified.add(backoff_pid)
  1663. mark_busy(
  1664. backoff_pid,
  1665. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1666. )
  1667. item_hold_reasons.setdefault(
  1668. backoff_pid,
  1669. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1670. )
  1671. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1672. # enclosure door left open, say. The fixed-printer branch turns
  1673. # this into a waiting_reason the user can act on; the model-based
  1674. # branch hides these printers from the matcher so an "Any <model>"
  1675. # job runs on a sibling instead of queueing behind the held one.
  1676. #
  1677. # Deliberately NOT merged into busy_printers, even though that set
  1678. # already means "unavailable this pass". _check_auto_drying reads
  1679. # it as "is currently printing" and would put an idle-but-held
  1680. # printer down the mid-print drying path, which caps the drying
  1681. # temperature and skips the queue-only gating. A held printer is
  1682. # idle; it should dry exactly as it did before.
  1683. #
  1684. # Only sensors we actually read and found alerting appear here; see
  1685. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1686. # holds nothing.
  1687. interlocked: dict[int, str] = {}
  1688. try:
  1689. interlocked = await ha_sensor_manager.blocked_printers(db)
  1690. except Exception as e:
  1691. # Never let the interlock stop the queue running. A broken
  1692. # lookup means no holds, not no dispatches.
  1693. logger.warning("Home Assistant interlock check failed: %s", e)
  1694. interlocked = {}
  1695. # Printers a smart plug can bring back, read once for the whole pass
  1696. # (#2786). Used by the model-based branch both to word "Offline" in
  1697. # the waiting reason and to decide what the wake step may switch on.
  1698. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1699. # At most one power-on per queue check. Each one blocks this loop
  1700. # for the boot wait, so a queue of ten class-targeted jobs must not
  1701. # switch on ten printers inside a single pass — the next pass wakes
  1702. # the next one (#2786).
  1703. power_on_attempted = False
  1704. # Log skip reasons once per queue check (not per item)
  1705. skip_reasons: dict[str, int] = {}
  1706. # Items selected for dispatch in this pass, one per printer. The
  1707. # loop below only *decides* — the uploads happen afterwards, in
  1708. # parallel (#2555). See _dispatch_selected().
  1709. dispatch_ids: list[int] = []
  1710. # Library rows queued with `cleanup_library_after_dispatch` (the
  1711. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1712. # that prints them: the row is deleted and the 3MF is unlinked from
  1713. # disk. That was safe only because dispatch was serial. Run two of
  1714. # them against the same row at once and the second DELETE matches no
  1715. # row (StaleDataError), and the winner's unlink can pull the file out
  1716. # from under the loser's in-flight upload.
  1717. #
  1718. # Only the cleanup flag mutates the row. An ordinary library print
  1719. # just reads it, so the common fan-out — one file, many printers,
  1720. # which is exactly the reporter's workload — still goes out fully in
  1721. # parallel. Narrow the guard to the mutating case; do not serialise
  1722. # the case the whole fix exists for.
  1723. dispatch_libs: set[int] = set()
  1724. consumed_libs: set[int] = set()
  1725. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1726. """True if dispatching `candidate` now would race another item's cleanup."""
  1727. lib_id = candidate.library_file_id
  1728. if lib_id is None:
  1729. return False
  1730. if candidate.cleanup_library_after_dispatch:
  1731. # We would delete a row someone else in this pass is reading.
  1732. return lib_id in dispatch_libs
  1733. # Someone else in this pass will delete the row out from under us.
  1734. return lib_id in consumed_libs
  1735. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1736. lib_id = candidate.library_file_id
  1737. if lib_id is None:
  1738. return
  1739. dispatch_libs.add(lib_id)
  1740. if candidate.cleanup_library_after_dispatch:
  1741. consumed_libs.add(lib_id)
  1742. # Printer scope of each job's creator (#1727), so an "any <model>"
  1743. # job only lands on a printer its creator may use. Loaded lazily,
  1744. # once per creator per pass.
  1745. from backend.app.core.auth import is_auth_enabled
  1746. scope_auth_enabled = await is_auth_enabled(db)
  1747. creator_scopes: dict[int, PrinterScope] = {}
  1748. # Printers a model job passes over while drying blocks the queue,
  1749. # as a pinned job waits for its own. A parked timer never ends,
  1750. # so it does not hold (#2896).
  1751. drying_held: set[int] = (
  1752. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1753. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1754. else set()
  1755. )
  1756. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1757. if not scope_auth_enabled or user_id is None:
  1758. return ALL_PRINTERS
  1759. if user_id not in creator_scopes:
  1760. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1761. return creator_scopes[user_id]
  1762. for item in items:
  1763. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1764. if item.scheduled_time:
  1765. sched = item.scheduled_time
  1766. if sched.tzinfo is None:
  1767. sched = sched.replace(tzinfo=timezone.utc)
  1768. if sched > datetime.now(timezone.utc):
  1769. # Waiting on the clock, not on a printer.
  1770. await hold_item(item, None)
  1771. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1772. continue
  1773. # Skip items that require manual start, except an "any model"
  1774. # job held for low filament that another idle printer can now
  1775. # run: that one is moved there and carries on below (#3137).
  1776. if item.manual_start and not (
  1777. item.filament_short
  1778. and await self._release_short_model_hold(
  1779. db,
  1780. item,
  1781. busy_printers | interlocked.keys() | drying_held,
  1782. require_plate_clear,
  1783. await _creator_scope(item.created_by_id),
  1784. )
  1785. ):
  1786. # Waiting on the user, not on a printer. Cleared here because
  1787. # this is the last pass that will look at the row: a staged
  1788. # item never reaches the branches below again, so a reason
  1789. # left from before it was staged would stand forever (#3074).
  1790. # The one exception is the unmatched-filament hold, whose
  1791. # reason was written at staging and is why the item waits:
  1792. # it names the filament to load (#2799). Pressing start
  1793. # clears manual_start, and the branches below overwrite it.
  1794. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1795. await hold_item(item, keep)
  1796. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1797. continue
  1798. if item.printer_id and item.printer_id not in pinned_printers:
  1799. # Moved by the release above to a printer no row named when
  1800. # the labels were read.
  1801. moved_to = await self._get_printer(db, item.printer_id)
  1802. if moved_to is not None:
  1803. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1804. if item.printer_id:
  1805. # Its creator may no longer use this printer (#1727): an
  1806. # admin took it away from their group after the job was
  1807. # queued, say to keep it free for a training session. Held,
  1808. # not failed, so it starts if access comes back or the user
  1809. # moves it to a printer they still have.
  1810. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1811. await hold_item(
  1812. item,
  1813. "Its owner no longer has access to this printer — move it to another printer",
  1814. notify=False,
  1815. )
  1816. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1817. continue
  1818. # Held by a sensor interlock (#1148). Checked before the
  1819. # busy_printers test that would otherwise swallow it
  1820. # silently — "waiting for a printer" and "waiting for you
  1821. # to shut the enclosure" need to read differently, and only
  1822. # one of them is something the user can fix.
  1823. #
  1824. # It used to be the only thing that wrote a waiting_reason on
  1825. # this branch, and it cleared the field up front so a lifted
  1826. # hold could not leave a shut door reading "Waiting on
  1827. # Enclosure Door". `hold_item` carries that guarantee now —
  1828. # every exit below writes — so the clear is gone and the
  1829. # interlock is an ordinary hold like the rest (#3074).
  1830. interlock_reason = interlocked.get(item.printer_id)
  1831. if interlock_reason:
  1832. # Silent, exactly as it has always been. #1148 built this
  1833. # as a hold that shows on the row, never as an alert, and
  1834. # routing it through the shared writer must not quietly
  1835. # turn every open door into a notification.
  1836. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1837. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1838. continue
  1839. # Specific printer assignment (existing behavior)
  1840. if item.printer_id in busy_printers:
  1841. # Whatever took the printer out of this pass — a print
  1842. # already running on it, a post-dispatch hold, an upload
  1843. # still in flight, an item ahead of this one in the same
  1844. # pass — reads the same way from the queue: the printer is
  1845. # taken and this item is in line for it. The exceptions
  1846. # that do not (an offline printer, say) recorded their own
  1847. # wording in `item_hold_reasons` when they held it.
  1848. await hold_item(
  1849. item,
  1850. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1851. notify=item.printer_id not in silent_hold_printers,
  1852. )
  1853. continue
  1854. # Check if printer is idle
  1855. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1856. printer_connected = printer_manager.is_connected(item.printer_id)
  1857. # If printer not connected, try to power on via smart plug
  1858. if not printer_connected:
  1859. plugs = await self._get_smart_plugs(db, item.printer_id)
  1860. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1861. if auto_on_plugs:
  1862. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1863. # Power on using the plug that actually feeds the printer, and
  1864. # wait for it to boot on that one only (#2629).
  1865. primary_plug = self._pick_power_plug(auto_on_plugs)
  1866. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1867. if powered_on:
  1868. # Also turn on any remaining auto_on plugs (e.g., filter)
  1869. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1870. try:
  1871. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1872. if await service.turn_on(extra_plug):
  1873. await publish_plug_state(
  1874. extra_plug.id,
  1875. extra_plug.name,
  1876. extra_plug.printer_id,
  1877. on=True,
  1878. ha_entity_id=extra_plug.ha_entity_id,
  1879. )
  1880. logger.info(
  1881. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1882. )
  1883. except Exception as e:
  1884. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1885. printer_connected = True
  1886. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1887. else:
  1888. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1889. await hold_for_printer(
  1890. item,
  1891. item.printer_id,
  1892. "smart-plug power-on failed",
  1893. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1894. )
  1895. continue
  1896. else:
  1897. # No plug or auto_on disabled. Worded exactly as the
  1898. # model-based branch words it (#2786): this is the one
  1899. # entry on that list the user has to act on, because
  1900. # Bambuddy will never switch this printer on itself.
  1901. await hold_for_printer(
  1902. item,
  1903. item.printer_id,
  1904. "offline, with no smart plug to power it on",
  1905. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1906. )
  1907. continue
  1908. # Check if printer is idle (busy with another print)
  1909. if not printer_idle:
  1910. await hold_for_printer(
  1911. item,
  1912. item.printer_id,
  1913. "not idle",
  1914. self._pinned_hold_reason(
  1915. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1916. ),
  1917. )
  1918. continue
  1919. # Drying blocks the queue, if the user asked it to. A hold
  1920. # is a skip like any other, so it belongs here with the
  1921. # rest of the availability checks.
  1922. # A parked timer (#2896) never ends, so it must not hold the
  1923. # queue; it stays tracked so the stop paths still reach it.
  1924. if (
  1925. self._drying_in_progress.get(item.printer_id)
  1926. and not self._drying_is_only_parked(item.printer_id)
  1927. and await self._get_bool_setting(db, "queue_drying_block")
  1928. ):
  1929. # Busy-shaped on purpose: the cycle ends on its own and
  1930. # the job goes out, so there is nothing to alert about.
  1931. await hold_for_printer(
  1932. item,
  1933. item.printer_id,
  1934. "drying, and drying is set to block the queue",
  1935. f"Busy: {printer_label(item.printer_id)} (drying)",
  1936. )
  1937. continue
  1938. # Check condition (previous print success)
  1939. if item.require_previous_success:
  1940. if not await self._check_previous_success(db, item):
  1941. item.status = "skipped"
  1942. item.error_message = "Previous print failed or was aborted"
  1943. item.completed_at = datetime.now(timezone.utc)
  1944. # Not pending any more, so not waiting for anything.
  1945. item.waiting_reason = None
  1946. await db.commit()
  1947. logger.info("Skipped queue item %s - previous print failed", item.id)
  1948. # Send notification
  1949. job_name = await self._get_job_name(db, item)
  1950. printer = await self._get_printer(db, item.printer_id)
  1951. await notification_service.on_queue_job_skipped(
  1952. job_name=job_name,
  1953. printer_id=item.printer_id,
  1954. printer_name=printer.name if printer else "Unknown",
  1955. reason="Previous print failed or was aborted",
  1956. db=db,
  1957. )
  1958. continue
  1959. # Resolve the AMS mapping when it's missing OR unresolved
  1960. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1961. # frontend status-load race can persist [-1] (#2589) — and
  1962. # must be recomputed from live trays rather than trusted.
  1963. if await _edited_since_loaded(db, item):
  1964. continue
  1965. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1966. if unmappable:
  1967. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1968. continue
  1969. # Filament-deficit pre-dispatch check (#1496). If the
  1970. # assigned spool can't satisfy any required slot grams,
  1971. # promote the item to manual_start so the user must
  1972. # acknowledge via the ▶ button (which re-checks live).
  1973. if await self._block_on_filament_deficit(db, item):
  1974. # Now staged for the user to start by hand, and the row
  1975. # shows the filament-short badge instead. Cleared because
  1976. # a staged item never reaches this branch again.
  1977. await hold_item(item, None)
  1978. continue
  1979. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1980. # than let the printer pick a substitute for a slot the
  1981. # matcher could not resolve on this printer.
  1982. if await self._block_on_unmatched_filament(db, item):
  1983. continue
  1984. # Hold this item back for the next pass rather than racing
  1985. # another dispatch over the same transient library row. The
  1986. # printer is still marked busy so a later item does not jump
  1987. # its place in this printer's queue.
  1988. if _library_row_conflict(item):
  1989. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1990. await hold_for_printer(
  1991. item,
  1992. item.printer_id,
  1993. "holding its place while another item releases a library row",
  1994. f"Busy: {printer_label(item.printer_id)}",
  1995. )
  1996. continue
  1997. # Print takes priority: stop a cycle Bambuddy armed, now
  1998. # that this item is definitely going out.
  1999. #
  2000. # Placement is the whole point (#2801). This used to sit up
  2001. # with the availability checks, inside the not-idle branch
  2002. # -- so it fired only on the passes where the print was NOT
  2003. # going to start, and never on the ones where it was.
  2004. # Drying is not one of the things `_is_printer_idle` looks
  2005. # at, so a stop could never have unblocked that printer
  2006. # anyway; the cycle was spent for nothing, auto-drying
  2007. # re-armed on the next tick, and a plate left
  2008. # unacknowledged turned that into a loop on the scheduler
  2009. # interval. Every skip between there and here -- a failed
  2010. # previous print, an unmappable item, a filament deficit, a
  2011. # contested library row -- is another way to lose a cycle
  2012. # for a print that never happens, which is why this waits
  2013. # until the decision is actually made.
  2014. if self._drying_in_progress.get(
  2015. item.printer_id
  2016. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2017. await self._stop_drying(item.printer_id)
  2018. # Queue the dispatch instead of running it here — see
  2019. # _dispatch_selected(). busy_printers still gets the printer
  2020. # immediately, so nothing else in this pass can target it.
  2021. #
  2022. # The reason goes first: this item is not waiting for anything
  2023. # any more, and the model-based branch clears its own at the
  2024. # equivalent moment (#3074).
  2025. await hold_item(item, None)
  2026. _claim_library_row(item)
  2027. dispatch_ids.append(item.id)
  2028. claim_printer(item.printer_id)
  2029. # SJF starvation guard: mark items that were jumped
  2030. if sjf_enabled and item.print_time_seconds is not None:
  2031. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2032. for other in items:
  2033. if (
  2034. other.id != item.id
  2035. and other.id not in dispatch_ids
  2036. and other.status == "pending"
  2037. and _could_take_printer(other, item.printer_id, pinned_model)
  2038. and not other.been_jumped
  2039. and other.position < item.position
  2040. and (
  2041. other.print_time_seconds is None
  2042. or other.print_time_seconds > item.print_time_seconds
  2043. )
  2044. ):
  2045. other.been_jumped = True
  2046. await db.commit()
  2047. elif item.target_model or item.variants:
  2048. # Model-based assignment - find any idle printer of matching model.
  2049. # A plain model-based item has exactly one candidate, built from
  2050. # its own columns. A cross-model item (#671) has one per sliced
  2051. # variant and takes the first that matches, walking them in the
  2052. # user's priority order so the pick is reproducible when more
  2053. # than one printer is free in the same pass.
  2054. candidates = _candidates_for(item)
  2055. item_scope = await _creator_scope(item.created_by_id)
  2056. printer_id = None
  2057. chosen: _ModelCandidate | None = None
  2058. per_model_reasons: list[tuple[str | None, str]] = []
  2059. # Candidates that cleared the cross-model gate below. The
  2060. # smart-plug wake step may only consider these — waking a
  2061. # printer for a file that can never legally run on it is
  2062. # worse than not waking at all (#2786).
  2063. wakeable_candidates: list[_ModelCandidate] = []
  2064. # Printers passed over because their last print failed.
  2065. gate_blocked: set[int] = set()
  2066. if not candidates:
  2067. # Every candidate file has been deleted or trashed out from
  2068. # under this item. Hold it with something the user can act
  2069. # on rather than letting it look dispatchable forever.
  2070. per_model_reasons.append(
  2071. (
  2072. item.target_model,
  2073. "Every file for this job has been deleted — add a file back or remove the item",
  2074. )
  2075. )
  2076. for candidate in candidates:
  2077. effective_types, filament_overrides = _filament_constraints(candidate)
  2078. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2079. # for an incompatible model to a printer, no matter how the
  2080. # row got into the DB (old rows, direct API writes). Held
  2081. # as pending with an actionable waiting_reason — the user
  2082. # fixes it by editing the item's target model.
  2083. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2084. per_model_reasons.append(
  2085. (
  2086. candidate.target_model,
  2087. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2088. f"{candidate.target_model} — edit the item and fix its target model",
  2089. )
  2090. )
  2091. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2092. continue
  2093. wakeable_candidates.append(candidate)
  2094. async def is_short(
  2095. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2096. ) -> bool:
  2097. # The check reads the file and plate off the item,
  2098. # so it must hold this candidate's. Resolving is
  2099. # safe to repeat, and the winner is resolved again
  2100. # below.
  2101. self._resolve_variant(item, candidate)
  2102. return await self._filament_short_on(db, item, pid)
  2103. async def unmatched_on(
  2104. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2105. ) -> list[str]:
  2106. self._resolve_variant(item, candidate)
  2107. return await self._unmatched_on(db, item, pid)
  2108. while True:
  2109. match_id, match_reason = await self._find_idle_printer_for_model(
  2110. db,
  2111. candidate.target_model,
  2112. # Sensor-held printers are unavailable to the
  2113. # matcher but stay out of busy_printers itself
  2114. # (#1148) — see where `interlocked` is built.
  2115. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2116. effective_types,
  2117. item.target_location,
  2118. filament_overrides=filament_overrides,
  2119. require_plate_clear=require_plate_clear,
  2120. wakeable_ids=wakeable_printer_ids,
  2121. printer_scope=item_scope,
  2122. is_short=is_short,
  2123. drying_ids=drying_held,
  2124. unmatched_on=unmatched_on,
  2125. )
  2126. # "Only if the previous print succeeded" is about the
  2127. # printer the job lands on: one whose last print failed
  2128. # is passed over for another of the model.
  2129. if (
  2130. match_id
  2131. and item.require_previous_success
  2132. and not await self._check_previous_success(db, item, printer_id=match_id)
  2133. ):
  2134. gate_blocked.add(match_id)
  2135. continue
  2136. break
  2137. if match_id:
  2138. printer_id = match_id
  2139. chosen = candidate
  2140. break
  2141. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2142. # Nothing is available and nothing has been woken this pass:
  2143. # switch one matching printer on. Assignment is left to the
  2144. # next pass, which sees the booted printer's live state
  2145. # instead of guessing at it seconds after connect (#2786).
  2146. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2147. woken_id, attempted_id = await self._wake_printer_for_model(
  2148. db,
  2149. wakeable_candidates,
  2150. item.target_location,
  2151. busy_printers | interlocked.keys(),
  2152. wakeable_printer_ids,
  2153. require_plate_clear,
  2154. printer_scope=item_scope,
  2155. )
  2156. # An attempt spends the pass's one wake whether or not
  2157. # it worked: it has already blocked the queue loop for
  2158. # the boot wait. A failed printer is held out of later
  2159. # passes by its own cool-off, deliberately NOT by
  2160. # busy_printers — it is off, not busy, and labelling it
  2161. # busy would both misdescribe it in every later item's
  2162. # waiting reason and suppress the notification, since
  2163. # an all-busy reason is treated as needing no action.
  2164. power_on_attempted = attempted_id is not None
  2165. if woken_id is not None:
  2166. # Hold this item back rather than dispatching onto a
  2167. # printer whose AMS has not reported yet.
  2168. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2169. continue
  2170. if printer_id is None and gate_blocked:
  2171. # The matcher reports the printers passed over as busy;
  2172. # what holds the job is their failed last print.
  2173. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2174. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2175. # Fold the winning variant's file and settings onto the item
  2176. # before anything else looks at them — the guards below and
  2177. # every step of the dispatch read the item's own columns.
  2178. if chosen is not None:
  2179. self._resolve_variant(item, chosen)
  2180. # Update waiting_reason if changed and send notification when first waiting
  2181. if item.waiting_reason != waiting_reason:
  2182. was_waiting = item.waiting_reason is not None
  2183. previous_reason = item.waiting_reason
  2184. item.waiting_reason = waiting_reason
  2185. await db.commit()
  2186. # Send waiting notification only when transitioning to waiting state
  2187. # and the reason requires user action (not just "all printers busy")
  2188. # Also when a job that only waited for a busy printer
  2189. # now waits on something the user has to do.
  2190. if (
  2191. waiting_reason
  2192. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2193. and not self._is_busy_only(waiting_reason)
  2194. ):
  2195. job_name = await self._get_job_name(db, item)
  2196. await notification_service.on_queue_job_waiting(
  2197. job_name=job_name,
  2198. target_model=_candidate_model_label(candidates) or item.target_model,
  2199. waiting_reason=waiting_reason,
  2200. db=db,
  2201. )
  2202. if printer_id:
  2203. # Before claiming the printer: hold back rather than race
  2204. # another dispatch over the same transient library row.
  2205. # Checked here so a held item does not get a printer
  2206. # assigned and then sit on it. See _library_row_conflict().
  2207. #
  2208. # No busy_printers.add() here, unlike the fixed-printer
  2209. # branch above: that one protects its printer's own queue
  2210. # ordering, but this item was never assigned to `printer_id`
  2211. # — the matcher merely offered it. Marking it busy would
  2212. # strand an idle printer for the rest of the pass.
  2213. if _library_row_conflict(item):
  2214. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2215. continue
  2216. if await _edited_since_loaded(db, item):
  2217. continue
  2218. # Assign printer and start - clear waiting reason
  2219. item.printer_id = printer_id
  2220. item.waiting_reason = None
  2221. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2222. # Send assignment notification
  2223. job_name = await self._get_job_name(db, item)
  2224. printer = await self._get_printer(db, printer_id)
  2225. await notification_service.on_queue_job_assigned(
  2226. job_name=job_name,
  2227. printer_id=printer_id,
  2228. printer_name=printer.name if printer else "Unknown",
  2229. target_model=item.target_model,
  2230. db=db,
  2231. )
  2232. # A mapping on this item was not made for the printer just
  2233. # picked: it came with a job moved here from a fixed
  2234. # printer, or from a variant. Its tray IDs can name a
  2235. # tray of the right type in another colour here, which
  2236. # the fit check lets through (#3239). Match afresh, by
  2237. # type and colour.
  2238. if item.ams_mapping:
  2239. logger.info(
  2240. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2241. item.id,
  2242. item.ams_mapping,
  2243. printer_id,
  2244. )
  2245. item.ams_mapping = None
  2246. # On a nozzle-rack printer its own nozzle mapping likewise
  2247. # (set through the API or an order's plate spec): it names
  2248. # rack positions, and the dispatch sends a stored one as-is
  2249. # instead of resolving this printer's rack. Elsewhere it
  2250. # holds extruder indices, the same on every printer of the
  2251. # model (an H2D VP keeps the slicer's for that reason), and
  2252. # one that came with the chosen variant belongs to that
  2253. # variant's file: both stay.
  2254. if (
  2255. (chosen is None or chosen.variant is None)
  2256. and printer is not None
  2257. and is_nozzle_rack_model(printer.model)
  2258. ):
  2259. item.nozzle_mapping = None
  2260. # Resolve the AMS mapping for the assigned printer. It is
  2261. # always missing here, so this computes it, and it also
  2262. # self-heals a bogus stored [-1] (#2589).
  2263. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2264. if unmappable:
  2265. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2266. continue
  2267. # Filament-deficit pre-dispatch check (#1496).
  2268. if await self._block_on_filament_deficit(db, item):
  2269. continue
  2270. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2271. # selection already filters on filament type, so this is a
  2272. # backstop for an AMS that changed between assignment and
  2273. # dispatch, and for a type loaded on the wrong nozzle.
  2274. # The assignment made above is released with the hold —
  2275. # this item asked for a model, not this printer.
  2276. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2277. continue
  2278. # As for a pinned job: drying stops once the print is
  2279. # decided, unless it may run through it.
  2280. if self._drying_in_progress.get(
  2281. printer_id
  2282. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2283. await self._stop_drying(printer_id)
  2284. _claim_library_row(item)
  2285. dispatch_ids.append(item.id)
  2286. claim_printer(printer_id)
  2287. # SJF starvation guard: mark items that were jumped
  2288. if sjf_enabled and item.print_time_seconds is not None:
  2289. for other in items:
  2290. if (
  2291. other.id != item.id
  2292. and other.id not in dispatch_ids
  2293. and other.status == "pending"
  2294. and _could_take_printer(other, printer_id, item.target_model)
  2295. and not other.been_jumped
  2296. and other.position < item.position
  2297. and (
  2298. other.print_time_seconds is None
  2299. or other.print_time_seconds > item.print_time_seconds
  2300. )
  2301. ):
  2302. other.been_jumped = True
  2303. await db.commit()
  2304. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2305. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2306. # skip summary that only lands after the transfers have finished is
  2307. # useless for working out why an item did not go out.
  2308. if skip_reasons:
  2309. logger.info("Queue skip summary: %s", skip_reasons)
  2310. for pid in sorted(busy_printers):
  2311. reason = busy_reasons.get(pid, "no reason recorded")
  2312. if pid in claimed_printers:
  2313. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2314. continue
  2315. # The three live fields stay, because they are what someone
  2316. # reading a bundle wants next -- but they are labelled as read
  2317. # now, not as the state the decision was made on, which is what
  2318. # made the old line contradict itself.
  2319. state = printer_manager.get_status(pid)
  2320. logger.info(
  2321. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2322. pid,
  2323. reason,
  2324. printer_manager.is_connected(pid),
  2325. state.state if state else "NO_STATUS",
  2326. printer_manager.is_awaiting_plate_clear(pid),
  2327. )
  2328. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2329. # selection and `_launch_uploads`, so anything raising here would
  2330. # discard this tick's selections — computed AMS mappings and all —
  2331. # and, on a persistent fault, stop the queue dispatching entirely.
  2332. # Same reasoning as the deficit check's guard below: never let an
  2333. # auxiliary check wedge the queue. The bed simply stays wherever it
  2334. # was, and the next tick tries again.
  2335. try:
  2336. await self._apply_keep_warm(
  2337. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2338. )
  2339. except Exception as e:
  2340. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2341. # Read the concurrency limit BEFORE the commit below, not inside
  2342. # _dispatch_selected(). A SELECT on this session after the commit
  2343. # implicitly opens a fresh transaction that nothing then closes, and
  2344. # it would stay open for the whole dispatch — minutes of "idle in
  2345. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2346. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2347. # checkpointed while every dispatch is writing to it.
  2348. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2349. # Selection is done; every decision above is recorded on `db`
  2350. # (model-based printer assignment, computed ams_mapping). Flush it
  2351. # before the dispatch tasks open their own sessions, or they will
  2352. # read a row that still says printer_id=None. This also releases the
  2353. # connection back to the pool for the duration of the dispatch.
  2354. await db.commit()
  2355. if dispatch_ids:
  2356. item_printers = {it.id: it.printer_id for it in items}
  2357. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2358. # Auto-drying: start drying on idle printers that have no pending queue items
  2359. await self._check_auto_drying(db, items, dispatching_printers)
  2360. # Low filament: alert on assigned spools that have crossed their
  2361. # low-stock threshold (#2913). Runs on both paths out of this method
  2362. # for the same reason auto-drying does — an empty queue does not mean
  2363. # the spools in the printers stopped mattering.
  2364. await self._check_filament_low(db)
  2365. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2366. # is about to run out before a replenishment could arrive (#2955).
  2367. await self._check_stock_forecast(db)
  2368. # Keep the loop on the fast interval while any upload is in flight so
  2369. # a slot freed mid-tick refills within seconds rather than after the
  2370. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2371. # deferred because the pool was full) also counts as productive.
  2372. return bool(dispatch_ids) or bool(self._inflight)
  2373. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2374. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2375. Dispatch used to happen inline in the selection loop: ``await
  2376. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2377. performs the FTP upload, that serialized every printer behind every
  2378. other printer's transfer even though the printers are independent
  2379. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2380. gather was awaited before ``check_queue`` returned, so the run loop
  2381. stayed blocked until the *slowest* upload in the batch finished — a
  2382. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2383. 93-printer farm even as other printers came free (#2602).
  2384. Each upload now runs as an independent background task tracked in
  2385. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2386. `pending` until their upload completes) and their printers from the
  2387. next pass's selection, and this method launches at most
  2388. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2389. the next fast tick instead of waiting out the whole batch. The bound
  2390. exists because the printers are independent but the host is not: each
  2391. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2392. file handle.
  2393. The no-overlapping-dispatch invariant the batch-await used to provide
  2394. is now carried by the in-flight exclusion in check_queue. Everything
  2395. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2396. per-printer hold, and each item's independent failure handling — still
  2397. lives in ``_start_print`` and runs per task exactly as before.
  2398. Synchronous on purpose: it registers every launched task into
  2399. ``self._inflight`` before returning, so the next (sequential) tick sees
  2400. an accurate in-flight count with no interleaving await.
  2401. """
  2402. free = limit - len(self._inflight)
  2403. if free <= 0:
  2404. logger.info(
  2405. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2406. len(self._inflight),
  2407. limit,
  2408. len(item_ids),
  2409. item_ids,
  2410. )
  2411. return
  2412. to_launch = item_ids[:free]
  2413. deferred = item_ids[free:]
  2414. logger.info(
  2415. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2416. len(to_launch),
  2417. len(self._inflight),
  2418. limit,
  2419. f" — deferring {deferred} to a later tick" if deferred else "",
  2420. )
  2421. for item_id in to_launch:
  2422. task = spawn_background_task(
  2423. self._dispatch_one(item_id, item_printers.get(item_id)),
  2424. name=f"queue-upload-{item_id}",
  2425. )
  2426. self._inflight[item_id] = (task, item_printers.get(item_id))
  2427. # Prune on completion so the freed slot is refillable next tick.
  2428. # spawn_background_task already logs any uncaught exception; this
  2429. # only reclaims the pool slot (fires on success, failure, or cancel).
  2430. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2431. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2432. """Upload + start one queue item in its own session (pool worker, #2602).
  2433. Its own session: pool workers run concurrently and an AsyncSession is
  2434. not safe to share across tasks; it also keeps a slow upload from pinning
  2435. the scheduler's session (and, on SQLite, its transaction) open for the
  2436. transfer's duration.
  2437. ``selected_printer_id`` is the printer this item was selected for, taken
  2438. from the same snapshot the caller used. It exists so the preheat pin can
  2439. be unwound on the paths that never reach the ``finally`` below — see the
  2440. claim failure a few lines down. Optional so the direct-call tests keep
  2441. working; when it is absent those paths simply behave as they did before.
  2442. """
  2443. async with async_session() as item_db:
  2444. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2445. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2446. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2447. # routes reject reassignment (409), so printer_id can't change out from
  2448. # under the in-flight upload and split the queue row from the
  2449. # archive/expected-print/physical command.
  2450. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2451. logger.info(
  2452. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2453. item_id,
  2454. )
  2455. # This return is outside the try/finally below, so the rollback
  2456. # has to happen here. Selecting this item already handed any
  2457. # keep-warm hold on its printer over to the preheat pin
  2458. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2459. # unwind it. Bailing without doing so leaves the bed hot with
  2460. # nothing tracking it: the keep-warm entry is gone, so the
  2461. # max-duration cap no longer applies, and if this was the
  2462. # printer's last pending item nothing else will ever turn it
  2463. # off. Reachable whenever a cancel or delete lands between
  2464. # selection and the claim.
  2465. if selected_printer_id is not None:
  2466. self._rollback_preheat_pin(item_id, selected_printer_id)
  2467. return
  2468. # Seeded from the caller's snapshot so the `item vanished` return
  2469. # below still unwinds the pin; overwritten with the row's own
  2470. # printer_id as soon as we have it.
  2471. item_printer_id: int | None = selected_printer_id
  2472. try:
  2473. item = await item_db.get(PrintQueueItem, item_id)
  2474. if not item:
  2475. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2476. return
  2477. item_printer_id = item.printer_id
  2478. await self._start_print(item_db, item)
  2479. finally:
  2480. # Undo an expected-print registration whose print command never
  2481. # went out. One choke point covers every way `_start_print` can
  2482. # end without sending: a raised exception (a DB failure mid-
  2483. # dispatch is the reported case), an early return, a cancel
  2484. # winning the #1853 CAS, or `start_print()` returning False.
  2485. # A confirmed send removes the entry itself, so this is a no-op
  2486. # on the happy path.
  2487. self._rollback_unconfirmed_expected_print(item_id)
  2488. # Likewise the print user it set: the printer's next print is
  2489. # not this item's.
  2490. self._rollback_unconfirmed_print_user(item_id)
  2491. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2492. # reservation survives only after start_print() accepted the
  2493. # command. Failure, cancellation, deferral, and exceptions all
  2494. # release it here.
  2495. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2496. # Unwind preheat state (bed/chamber/airduct) if the
  2497. # dispatch aborted before the print's own gcode took over.
  2498. # `_start_print` clears the pin on successful `start_print()`;
  2499. # anything still present here is by definition an aborted
  2500. # dispatch and gets rolled back so the printer isn't left
  2501. # heating for a job that isn't happening.
  2502. if item_printer_id is not None:
  2503. self._rollback_preheat_pin(item_id, item_printer_id)
  2504. # The cancellation flag only has meaning while this dispatch is
  2505. # running; drop it so the set cannot grow without bound and a
  2506. # re-queued item never inherits a stale cancellation.
  2507. self._cancelled_dispatches.discard(item_id)
  2508. # Release the claim on every exit. Once dispatch has finished the
  2509. # row's status carries the lock (printing/failed/cancelled are all
  2510. # != pending), so the token is only needed for the duration of the
  2511. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2512. # dispatchable again on the next tick.
  2513. await self._clear_dispatch_claim(item_db, item_id)
  2514. async def _requeue_after_upload_refused(
  2515. self,
  2516. db: AsyncSession,
  2517. item: PrintQueueItem,
  2518. printer: Printer,
  2519. error_msg: str,
  2520. toast_uid: int | None,
  2521. ) -> None:
  2522. """Put an item back in the queue after its file never reached the printer (#3210).
  2523. The item keeps its printer. Its AMS mapping was computed against that
  2524. printer's trays, and nothing on the row says whether a mapping was
  2525. computed or set by the user, so moving it to a sibling could print from
  2526. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2527. keeps every other item away from it; this one waits there and is the
  2528. only thing that knocks again, once per backoff window. The window
  2529. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2530. `dispatch_attempts` is not charged: that budget bounds a printer that
  2531. takes the file and then never starts, which this is not.
  2532. """
  2533. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2534. self._upload_refusals[printer.id] = refusals
  2535. backoff = _upload_backoff_seconds(refusals)
  2536. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2537. # The row is still `pending` -- it only moves to `printing` after a
  2538. # successful upload -- so there is no status to write back. Writing one
  2539. # anyway would undo a cancel that landed during the upload.
  2540. if item.error_message:
  2541. item.error_message = None
  2542. await db.commit()
  2543. logger.warning(
  2544. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2545. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2546. item.id,
  2547. printer.id,
  2548. printer.name,
  2549. error_msg,
  2550. refusals,
  2551. backoff,
  2552. )
  2553. try:
  2554. # Closes the dispatch toast for this attempt. Without it the toast
  2555. # keeps spinning on an upload that has ended.
  2556. await ws_manager.send_queue_item_failed(
  2557. user_id=toast_uid,
  2558. queue_item_id=item.id,
  2559. printer_id=item.printer_id,
  2560. reason="upload_failed",
  2561. )
  2562. except Exception:
  2563. pass # toast is best-effort
  2564. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2565. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2566. if printer_id is not None:
  2567. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2568. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2569. """Withdraw the expected print and print user of a sent print that never started.
  2570. Both tell the rest of Bambuddy that the printer's next print is this
  2571. item's: left behind, a print started by hand later is taken for it.
  2572. With ``unless_printing``, a printer that is printing after all keeps
  2573. them, as that print is most likely this one starting late.
  2574. ``keep_expected`` withdraws only the print user, which vouches for any
  2575. print on the printer. The expected print names this item's file, so a
  2576. late start of it is still matched to its archive.
  2577. """
  2578. sent = self._sent_unstarted_print.get(item_id)
  2579. if sent is None:
  2580. return
  2581. printer_id, remote_filename, archive_id = sent
  2582. if unless_printing:
  2583. status = printer_manager.get_status(printer_id)
  2584. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2585. return
  2586. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2587. if keep_expected:
  2588. return
  2589. del self._sent_unstarted_print[item_id]
  2590. if remote_filename is not None and archive_id is not None:
  2591. try:
  2592. from backend.app.main import unregister_expected_print
  2593. unregister_expected_print(printer_id, remote_filename, archive_id)
  2594. except Exception:
  2595. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2596. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2597. """Drop an expectation for a print command that was never sent.
  2598. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2599. where the interesting exception is usually the one already propagating.
  2600. """
  2601. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2602. if pending is None:
  2603. return
  2604. printer_id, remote_filename, archive_id = pending
  2605. try:
  2606. from backend.app.main import unregister_expected_print
  2607. unregister_expected_print(printer_id, remote_filename, archive_id)
  2608. except Exception:
  2609. logger.warning(
  2610. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2611. item_id,
  2612. printer_id,
  2613. remote_filename,
  2614. archive_id,
  2615. exc_info=True,
  2616. )
  2617. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2618. """Release a queue reservation without touching the dispatch session."""
  2619. if item_id not in self._unconfirmed_budget_reservations:
  2620. return
  2621. for attempt in range(1, 4):
  2622. async with async_session() as cleanup_db:
  2623. try:
  2624. await release_budget_reservation(
  2625. cleanup_db,
  2626. source_type="print_queue",
  2627. source_id=item_id,
  2628. status="released",
  2629. )
  2630. await cleanup_db.commit()
  2631. self._unconfirmed_budget_reservations.discard(item_id)
  2632. return
  2633. except Exception as exc:
  2634. try:
  2635. await cleanup_db.rollback()
  2636. except Exception:
  2637. pass
  2638. if attempt == 3:
  2639. logger.error(
  2640. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2641. item_id,
  2642. attempt,
  2643. exc,
  2644. )
  2645. return
  2646. await asyncio.sleep(0.5 * attempt)
  2647. @staticmethod
  2648. def _reported_bed_target(printer_id: int) -> int | None:
  2649. """The bed target firmware currently reports, or None if it can't be read.
  2650. None means "no evidence", not "zero" — callers must not treat it as a
  2651. temperature. Deliberately total: this feeds cleanup paths that run in a
  2652. ``finally``, where a malformed status must not become the exception the
  2653. caller sees.
  2654. """
  2655. try:
  2656. state = printer_manager.get_status(printer_id)
  2657. if state is None:
  2658. return None
  2659. temps = state.temperatures
  2660. if not isinstance(temps, dict):
  2661. return None
  2662. return int(float(temps.get("bed_target", 0) or 0))
  2663. except (TypeError, ValueError, AttributeError):
  2664. return None
  2665. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2666. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2667. Turns the bed heater off, the chamber heater off, and opens the
  2668. airduct flap back to cooling — for whichever of those preheat
  2669. actually applied. `_start_print` clears the pin on successful
  2670. `start_print()`; anything still present when `_dispatch_one` exits
  2671. is by definition an aborted dispatch and gets rolled back here.
  2672. The bed is the one action that can be declined: if firmware has since
  2673. been given a target other than the one we pinned, it belongs to someone
  2674. else and is left alone. See the comment at that branch.
  2675. Also called directly from `_dispatch_one`'s claim-failure return, which
  2676. never reaches the ``finally``.
  2677. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2678. """
  2679. pin = self._preheat_pin.pop(printer_id, set())
  2680. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2681. if not pin:
  2682. return
  2683. client = printer_manager.get_client(printer_id)
  2684. if client is None:
  2685. logger.info(
  2686. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2687. item_id,
  2688. printer_id,
  2689. )
  2690. return
  2691. if "bed" in pin:
  2692. # Only undo our own target. If firmware reports something else, the
  2693. # user or another writer owns the bed now and zeroing it would
  2694. # clobber their choice -- the same guard `_release_keep_warm`
  2695. # applies to a keep-warm hold.
  2696. #
  2697. # Every uncertain case switches the bed off rather than leaving it:
  2698. # no recorded target (a pin written before this bookkeeping, or a
  2699. # setter that raised after pinning) and an unreadable status both
  2700. # fall through. A bed left hot with no owner is the worse failure,
  2701. # and this runs in a `finally` where raising would mask the real
  2702. # exception.
  2703. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2704. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2705. logger.info(
  2706. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2707. item_id,
  2708. printer_id,
  2709. cur_bed_target,
  2710. pinned_bed,
  2711. )
  2712. else:
  2713. try:
  2714. client.set_bed_temperature(0)
  2715. except Exception as exc:
  2716. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2717. if "chamber" in pin:
  2718. try:
  2719. client.set_chamber_temperature(0)
  2720. except Exception as exc:
  2721. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2722. if "airduct" in pin:
  2723. try:
  2724. client.set_airduct_mode("cooling")
  2725. except Exception as exc:
  2726. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2727. logger.info(
  2728. "Dispatch item %s (printer %d): preheat rollback → %s",
  2729. item_id,
  2730. printer_id,
  2731. sorted(pin),
  2732. )
  2733. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2734. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2735. Returns True if this call won the claim, False if the row was already
  2736. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2737. the load-bearing guard against reassign-during-dispatch (#2615).
  2738. ``printer_id`` is the printer the item was selected for: a row moved to
  2739. another printer since is not claimed, and the next pass selects it for
  2740. that one."""
  2741. query = (
  2742. update(PrintQueueItem)
  2743. .where(PrintQueueItem.id == item_id)
  2744. .where(PrintQueueItem.status == "pending")
  2745. .where(PrintQueueItem.dispatching_at.is_(None))
  2746. )
  2747. if printer_id is not None:
  2748. query = query.where(PrintQueueItem.printer_id == printer_id)
  2749. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2750. await db.commit()
  2751. return res.rowcount > 0
  2752. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2753. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2754. mask the dispatch outcome.
  2755. Retried, because the failure mode in practice is transient and narrow: a
  2756. database that is momentarily unreachable — PostgreSQL out of connection
  2757. slots is the observed case — refuses this write for a second or two while
  2758. the dispatch that just ended is still holding the row out of the selection
  2759. query. One attempt was enough to wedge the item; a couple of spaced
  2760. attempts clear it. Each attempt rolls back first, since a failed write
  2761. leaves the session needing it before it can be reused.
  2762. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2763. on the next quiet tick.
  2764. """
  2765. for attempt in range(1, 4):
  2766. try:
  2767. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2768. await db.commit()
  2769. return
  2770. except Exception as exc:
  2771. try:
  2772. await db.rollback()
  2773. except Exception:
  2774. pass
  2775. if attempt == 3:
  2776. logger.warning(
  2777. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2778. "— a later quiet tick will release it",
  2779. item_id,
  2780. attempt,
  2781. exc,
  2782. )
  2783. return
  2784. await asyncio.sleep(0.5 * attempt)
  2785. async def _printers_for_model(
  2786. self,
  2787. db: AsyncSession,
  2788. model: str,
  2789. target_location: str | None = None,
  2790. printer_scope: PrinterScope = ALL_PRINTERS,
  2791. ) -> list[Printer]:
  2792. """Active printers of *model*, optionally narrowed to one location.
  2793. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2794. answer "which printers can this job run on" from one query — a job can
  2795. only be woken onto a printer the matcher would also have considered.
  2796. ``printer_scope`` is the job creator's (#1727).
  2797. """
  2798. normalized_model = normalize_printer_model(model) or model
  2799. query = (
  2800. select(Printer)
  2801. .where(func.lower(Printer.model) == normalized_model.lower())
  2802. .where(Printer.is_active == True) # noqa: E712
  2803. )
  2804. if target_location:
  2805. query = query.where(Printer.location == target_location)
  2806. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2807. query = query.where(clause)
  2808. result = await db.execute(query)
  2809. return list(result.scalars().all())
  2810. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2811. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2812. Read once per queue check rather than per printer: it decides both
  2813. whether the wake step has anything to do and how an offline printer is
  2814. worded in the waiting reason — "Offline" and "offline with no Auto On
  2815. plug" are different problems, and the second is the one the user has to
  2816. fix themselves (#2786).
  2817. """
  2818. result = await db.execute(
  2819. select(SmartPlug.printer_id)
  2820. .where(SmartPlug.printer_id.is_not(None))
  2821. .where(SmartPlug.enabled == True) # noqa: E712
  2822. .where(SmartPlug.auto_on == True) # noqa: E712
  2823. )
  2824. return {pid for (pid,) in result.all() if pid is not None}
  2825. def _wake_recently_failed(self, printer_id: int) -> bool:
  2826. """True while this printer's failed power-on is still cooling off (#2786)."""
  2827. deadline = self._wake_failures.get(printer_id)
  2828. if deadline is None:
  2829. return False
  2830. if time.monotonic() >= deadline:
  2831. del self._wake_failures[printer_id]
  2832. return False
  2833. return True
  2834. async def _wake_printer_for_model(
  2835. self,
  2836. db: AsyncSession,
  2837. candidates: list[_ModelCandidate],
  2838. target_location: str | None,
  2839. exclude_ids: set[int],
  2840. wakeable_ids: set[int],
  2841. require_plate_clear: bool,
  2842. printer_scope: PrinterScope = ALL_PRINTERS,
  2843. ) -> tuple[int | None, int | None]:
  2844. """Power on one offline printer a model-based item could run on (#2786).
  2845. The fixed-printer branch has powered a printer on since smart plugs
  2846. existed. The model-based branch never could: its matcher drops an
  2847. offline printer into the "Offline:" waiting reason and nothing looks at
  2848. its plugs, so a class-targeted job with every matching printer switched
  2849. off sat pending forever. The reporter's log is the controlled
  2850. experiment — the same item, same plug, same Auto On setting, dispatched
  2851. the moment they edited it onto a specific printer.
  2852. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2853. power-on was actually tried, so the caller can tell "nothing here was
  2854. wakeable" (both None — cheap, other items may still find something)
  2855. from "we tried and it did not come up" (only ``attempted_id`` — the
  2856. boot timeout has already been spent).
  2857. A printer whose last known trays cannot satisfy the job is passed over
  2858. rather than woken (#2876): the colours are readable while it is off, so
  2859. switching a farm on one machine at a time to discover them wakes
  2860. printers that could never have taken the job.
  2861. Deliberately does NOT go on to match the job once a printer is up: AMS
  2862. trays arrive with the first status push after connect, so a filament
  2863. check against a printer that booted seconds ago can reject the printer
  2864. we just woke. The next queue pass matches it with live state.
  2865. At most one printer per pass. Each wake blocks the queue loop for the
  2866. boot wait, and a queue of ten class-targeted jobs must not switch on
  2867. ten printers inside one check.
  2868. """
  2869. for candidate in candidates:
  2870. if not candidate.target_model:
  2871. continue
  2872. required_types, filament_overrides = _filament_constraints(candidate)
  2873. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2874. for printer in sorted(printers, key=lambda p: p.id):
  2875. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2876. continue
  2877. if printer_manager.is_connected(printer.id):
  2878. continue
  2879. if self._wake_recently_failed(printer.id):
  2880. # Its plug did not bring it back a moment ago. Move on to a
  2881. # sibling instead of spending this pass — and every pass —
  2882. # on the same printer.
  2883. continue
  2884. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2885. # Waking this one buys nothing: it would boot into IDLE and
  2886. # then be held by the plate-clear gate, which is exactly
  2887. # what the reporter's log shows happening for 80 minutes
  2888. # after a fixed-printer wake. The flag is Bambuddy-side and
  2889. # persisted, so it is readable while the printer is off.
  2890. logger.info(
  2891. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2892. printer.id,
  2893. candidate.target_model,
  2894. )
  2895. continue
  2896. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2897. if shortfall:
  2898. logger.info(
  2899. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2900. printer.id,
  2901. candidate.target_model,
  2902. ", ".join(shortfall),
  2903. )
  2904. continue
  2905. plugs = await self._get_smart_plugs(db, printer.id)
  2906. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2907. if not auto_on_plugs:
  2908. # wakeable_ids said otherwise — the plug changed under us
  2909. # mid-pass. Nothing to do but move on.
  2910. continue
  2911. logger.info(
  2912. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2913. candidate.target_model,
  2914. printer.id,
  2915. )
  2916. primary_plug = self._pick_power_plug(auto_on_plugs)
  2917. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2918. logger.warning(
  2919. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2920. printer.id,
  2921. self._wake_failure_cooloff,
  2922. )
  2923. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2924. return None, printer.id
  2925. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2926. try:
  2927. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2928. if await service.turn_on(extra_plug):
  2929. await publish_plug_state(
  2930. extra_plug.id,
  2931. extra_plug.name,
  2932. extra_plug.printer_id,
  2933. on=True,
  2934. ha_entity_id=extra_plug.ha_entity_id,
  2935. )
  2936. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2937. except Exception as e:
  2938. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2939. return printer.id, printer.id
  2940. return None, None
  2941. async def _find_idle_printer_for_model(
  2942. self,
  2943. db: AsyncSession,
  2944. model: str,
  2945. exclude_ids: set[int],
  2946. required_filament_types: list[str] | None = None,
  2947. target_location: str | None = None,
  2948. filament_overrides: list[dict] | None = None,
  2949. require_plate_clear: bool = True,
  2950. wakeable_ids: set[int] | None = None,
  2951. printer_scope: PrinterScope = ALL_PRINTERS,
  2952. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2953. drying_ids: set[int] | None = None,
  2954. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  2955. ) -> tuple[int | None, str | None]:
  2956. """Find an idle, connected printer matching the model with compatible filaments.
  2957. Args:
  2958. db: Database session
  2959. model: Printer model to match (e.g., "X1C", "P1S")
  2960. exclude_ids: Printer IDs to exclude (already busy)
  2961. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2962. If provided, only printers with all required types loaded will match.
  2963. target_location: Optional location filter. If provided, only printers in this location are considered.
  2964. filament_overrides: Optional list of override dicts. Each entry may include
  2965. ``force_color_match: true`` to require an exact type+color match
  2966. on the printer for that slot. Without the flag the existing
  2967. colour-preference logic applies.
  2968. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2969. offline printer is worded: one Bambuddy will switch on reads
  2970. differently from one the user has to go and switch on themselves.
  2971. is_short: Says whether a printer's spools are too light for the job (#3137).
  2972. A printer it flags is passed over while another eligible one
  2973. is not. When every eligible printer is short, the first is
  2974. returned all the same, so the deficit gate holds the job there
  2975. and "Print Anyway" still has a printer to print on.
  2976. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  2977. in the reason, as a pinned job's wait is.
  2978. unmatched_on: Names the filaments the slot matcher would leave without a
  2979. tray on a printer (#3280). A printer it names any for is
  2980. passed over like one missing a filament type: the checks
  2981. above only ask whether each type and forced colour is
  2982. loaded somewhere, not on the right nozzle or once per slot.
  2983. Returns:
  2984. Tuple of (printer_id, waiting_reason):
  2985. - (printer_id, None) if a matching printer was found
  2986. - (None, reason) if no printer is available, with explanation
  2987. """
  2988. normalized_model = normalize_printer_model(model) or model
  2989. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2990. location_suffix = f" in {target_location}" if target_location else ""
  2991. if not printers:
  2992. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2993. # Separate force-matched overrides from preference-only overrides
  2994. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2995. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2996. # Track reasons for skipping printers
  2997. printers_busy = []
  2998. printers_offline = []
  2999. printers_offline_no_plug = []
  3000. printers_missing_filament: list[tuple[str, list[str]]] = []
  3001. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3002. # The first eligible printer that is short on filament, kept in case
  3003. # every eligible printer is (#3137).
  3004. short_fallback: int | None = None
  3005. for printer in printers:
  3006. if printer.id in exclude_ids:
  3007. # Printer is already claimed by another job in this scheduling run.
  3008. # For force-color jobs, still check if the color would match — if not,
  3009. # report it as a color mismatch rather than plain "Busy" so the user
  3010. # knows the job needs a filament change, not just to wait for availability.
  3011. if force_overrides and not pref_overrides:
  3012. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3013. if missing_colors:
  3014. printers_missing_filament.append((printer.name, missing_colors))
  3015. continue
  3016. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3017. continue
  3018. is_connected = printer_manager.is_connected(printer.id)
  3019. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3020. if not is_connected:
  3021. # An offline printer whose last known filament cannot run this
  3022. # job is reported as needing filament rather than as offline
  3023. # (#2876). It is also the printer the smart-plug step will now
  3024. # decline to switch on, and "Offline:" on its own would leave
  3025. # that decision looking like nothing happening at all.
  3026. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3027. if shortfall:
  3028. printers_missing_filament.append((printer.name, shortfall))
  3029. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3030. printers_offline_no_plug.append(printer.name)
  3031. else:
  3032. printers_offline.append(printer.name)
  3033. continue
  3034. if not is_idle:
  3035. # Printer is currently printing. For force-color jobs, check whether the
  3036. # loaded color would satisfy the requirement — if not, surface it as a
  3037. # color-mismatch reason rather than plain "Busy" so the user understands
  3038. # that the job is waiting for a filament change, not just printer availability.
  3039. if force_overrides and not pref_overrides:
  3040. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3041. if missing_colors:
  3042. printers_missing_filament.append((printer.name, missing_colors))
  3043. logger.debug(
  3044. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3045. printer.id,
  3046. printer.name,
  3047. missing_colors,
  3048. )
  3049. continue
  3050. printers_busy.append(printer.name)
  3051. continue
  3052. # Validate filament compatibility if required types are specified
  3053. if required_filament_types:
  3054. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3055. if missing:
  3056. # When force_overrides are present, enrich missing entries with color info
  3057. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3058. if force_overrides:
  3059. force_color_map = {
  3060. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3061. for o in force_overrides
  3062. }
  3063. missing_enriched = [
  3064. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3065. for t in missing
  3066. ]
  3067. printers_missing_filament.append((printer.name, missing_enriched))
  3068. else:
  3069. printers_missing_filament.append((printer.name, missing))
  3070. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3071. continue
  3072. # Force color match: ALL flagged slots must have an exact type+color match
  3073. if force_overrides:
  3074. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3075. if missing_colors:
  3076. printers_missing_filament.append((printer.name, missing_colors))
  3077. logger.debug(
  3078. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3079. printer.id,
  3080. printer.name,
  3081. missing_colors,
  3082. )
  3083. continue
  3084. # The matcher has the last word: a printer it cannot map would be
  3085. # held and given back, then chosen again on the next pass (#3280).
  3086. if unmatched_on is not None:
  3087. unmatched = await unmatched_on(printer.id)
  3088. if unmatched:
  3089. printers_missing_filament.append((printer.name, unmatched))
  3090. logger.debug(
  3091. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3092. printer.id,
  3093. printer.name,
  3094. unmatched,
  3095. )
  3096. continue
  3097. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3098. if pref_overrides:
  3099. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3100. if color_matches > 0:
  3101. candidates.append((printer.id, color_matches))
  3102. else:
  3103. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3104. printers_missing_filament.append((printer.name, override_colors))
  3105. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3106. continue
  3107. else:
  3108. # No preference ordering needed: the first eligible printer
  3109. # wins, unless its spools are too light for the job (#3137).
  3110. if is_short is not None and await is_short(printer.id):
  3111. if short_fallback is None:
  3112. short_fallback = printer.id
  3113. logger.info(
  3114. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3115. printer.id,
  3116. printer.name,
  3117. )
  3118. continue
  3119. return printer.id, None
  3120. # If we have candidates from preference override matching, pick the one with most color matches
  3121. if candidates:
  3122. candidates.sort(key=lambda c: c[1], reverse=True)
  3123. if is_short is not None:
  3124. for candidate_id, _ in candidates:
  3125. if not await is_short(candidate_id):
  3126. return candidate_id, None
  3127. logger.info(
  3128. "Model-based assignment: passing over printer %s, not enough filament",
  3129. candidate_id,
  3130. )
  3131. return candidates[0][0], None
  3132. if short_fallback is not None:
  3133. return short_fallback, None
  3134. # Build waiting reason from what we found
  3135. reasons = []
  3136. if printers_missing_filament:
  3137. # Filament/color mismatch is most actionable - show first
  3138. if force_overrides and not pref_overrides:
  3139. # All mismatches are force-color failures — use descriptive message only;
  3140. # but only if there are no busy printers that DO have the matching color.
  3141. # If a printer has the right color but is busy, surface "Busy" instead so
  3142. # the user knows the job will start automatically once that printer is free.
  3143. # Same for a printer that is merely offline: Bambuddy switches that one on
  3144. # by itself, so the job is not actually waiting on anybody to change a
  3145. # spool (#2876 — offline printers reach this list now that a switched-off
  3146. # printer's own filament is read).
  3147. if not printers_busy and not printers_offline:
  3148. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3149. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3150. # else: fall through — the self-resolving entries are appended below
  3151. else:
  3152. names_and_missing = [
  3153. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3154. ]
  3155. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3156. if printers_busy:
  3157. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3158. if printers_offline:
  3159. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3160. if printers_offline_no_plug:
  3161. # Named separately because it is the one entry on this list the
  3162. # user has to act on: no enabled Auto On plug means Bambuddy will
  3163. # never power this printer on for the queue (#2786).
  3164. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3165. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3166. @staticmethod
  3167. def _is_busy_only(waiting_reason: str) -> bool:
  3168. """Check if the waiting reason only contains 'Busy' entries.
  3169. When all matching printers are simply busy printing, the queued job
  3170. will start automatically once a printer finishes — no user action
  3171. is required, so we skip the notification.
  3172. """
  3173. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3174. return all(p.startswith("Busy:") for p in parts)
  3175. def _get_missing_force_color_slots(
  3176. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3177. ) -> list[str]:
  3178. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3179. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3180. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3181. with an exact type+color match.
  3182. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3183. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3184. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3185. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3186. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3187. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3188. setups are unaffected.
  3189. Returns:
  3190. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3191. """
  3192. if raw_data is None:
  3193. status = printer_manager.get_status(printer_id)
  3194. if not status:
  3195. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3196. raw_data = status.raw_data
  3197. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3198. loaded: list[tuple[str, str, str]] = []
  3199. for ams_unit in raw_data.get("ams", []):
  3200. for tray in ams_unit.get("tray", []):
  3201. tray_type = tray.get("tray_type")
  3202. if tray_type:
  3203. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3204. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3205. for vt in raw_data.get("vt_tray") or []:
  3206. vt_type = vt.get("tray_type")
  3207. if vt_type:
  3208. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3209. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3210. # One spool per slot, the way the matcher assigns them: two slots asking
  3211. # for the same filament need two spools of it (#3280). Slots naming a
  3212. # variant go first and take that variant before a spool naming none, so
  3213. # a slot open to any variant cannot use up the one a later slot needs.
  3214. missing = []
  3215. taken: set[int] = set()
  3216. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3217. o_type = canonical_filament_type(o.get("type") or "")
  3218. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3219. o_idx = o.get("tray_info_idx") or ""
  3220. fits = [
  3221. i
  3222. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3223. if i not in taken
  3224. and t_type == o_type
  3225. and t_color == o_color
  3226. and (not o_idx or not t_idx or o_idx == t_idx)
  3227. ]
  3228. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3229. if pick is not None:
  3230. taken.add(pick)
  3231. else:
  3232. color_label = o.get("color_name") or o.get("color", "?")
  3233. missing.append(f"{o_type} ({color_label})")
  3234. return missing
  3235. def _get_missing_filament_types(
  3236. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3237. ) -> list[str]:
  3238. """Get the list of required filament types that are not loaded on the printer.
  3239. Args:
  3240. printer_id: The printer ID
  3241. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3242. Returns:
  3243. List of missing filament types (empty if all are loaded)
  3244. """
  3245. if raw_data is None:
  3246. status = printer_manager.get_status(printer_id)
  3247. if not status:
  3248. return required_types # Can't determine, assume all missing
  3249. raw_data = status.raw_data
  3250. # Collect all filament types loaded on this printer (AMS units + external spool)
  3251. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3252. loaded_types: set[str] = set()
  3253. # Check AMS units (stored in raw_data["ams"])
  3254. ams_data = raw_data.get("ams", [])
  3255. if ams_data:
  3256. for ams_unit in ams_data:
  3257. for tray in ams_unit.get("tray", []):
  3258. tray_type = tray.get("tray_type")
  3259. if tray_type:
  3260. loaded_types.add(canonical_filament_type(tray_type))
  3261. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3262. for vt in raw_data.get("vt_tray") or []:
  3263. vt_type = vt.get("tray_type")
  3264. if vt_type:
  3265. loaded_types.add(canonical_filament_type(vt_type))
  3266. # Find which required types are missing (using canonical type for equivalence)
  3267. missing = []
  3268. for req_type in required_types:
  3269. if canonical_filament_type(req_type) not in loaded_types:
  3270. missing.append(req_type)
  3271. return missing
  3272. def _count_override_color_matches(
  3273. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3274. ) -> int:
  3275. """Count how many filament overrides have an exact color match on the printer.
  3276. Used to prefer printers that already have the desired override colors loaded.
  3277. """
  3278. if raw_data is None:
  3279. status = printer_manager.get_status(printer_id)
  3280. if not status:
  3281. return 0
  3282. raw_data = status.raw_data
  3283. # Collect loaded filaments' type+color pairs
  3284. loaded: set[tuple[str, str]] = set()
  3285. for ams_unit in raw_data.get("ams", []):
  3286. for tray in ams_unit.get("tray", []):
  3287. tray_type = tray.get("tray_type")
  3288. # `or ""`, not a dict default: a slot can carry the key with a
  3289. # null value, and this now runs against switched-off printers
  3290. # too, where nobody is watching for the AttributeError.
  3291. tray_color = tray.get("tray_color") or ""
  3292. if tray_type:
  3293. color_norm = tray_color.replace("#", "").lower()[:6]
  3294. loaded.add((canonical_filament_type(tray_type), color_norm))
  3295. for vt in raw_data.get("vt_tray") or []:
  3296. vt_type = vt.get("tray_type")
  3297. if vt_type:
  3298. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3299. loaded.add((canonical_filament_type(vt_type), color_norm))
  3300. # Types compared as the type check compares them: a PA12-CF override
  3301. # is met by PA-CF in its colour.
  3302. matches = 0
  3303. for o in overrides:
  3304. o_type = canonical_filament_type(o.get("type") or "")
  3305. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3306. if (o_type, o_color) in loaded:
  3307. matches += 1
  3308. return matches
  3309. @staticmethod
  3310. def _tray_reading(printer_id: int) -> dict:
  3311. """The best tray reading available for a printer that is not printing.
  3312. Live status first: a printer keeps its last status after the power
  3313. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3314. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3315. for when the client itself has been dropped and taken its status with
  3316. it — which is what every power-on attempt does.
  3317. An empty result means "we have never heard", not "nothing is loaded":
  3318. the two are indistinguishable from here, and only the second would be
  3319. safe to act on.
  3320. """
  3321. status = printer_manager.get_status(printer_id)
  3322. raw = (status.raw_data if status else None) or {}
  3323. for ams_unit in raw.get("ams") or []:
  3324. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3325. return raw
  3326. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3327. return raw
  3328. return printer_manager.last_known_trays(printer_id)
  3329. def _cached_filament_shortfall(
  3330. self,
  3331. printer_id: int,
  3332. required_types: list[str] | None,
  3333. filament_overrides: list[dict] | None,
  3334. ) -> list[str]:
  3335. """What a switched-off printer's last known filament cannot provide (#2876).
  3336. The smart-plug wake step used to consider only the model, so a job for a
  3337. colour loaded on the last printer in ID order switched on every earlier
  3338. one in turn, evaluated it, rejected it on colour and left it running.
  3339. Bambuddy knew those colours the whole time. This asks the same three
  3340. questions the matcher asks a live printer — required types, forced
  3341. colours, preferred colours — of the trays it last reported, and returns
  3342. the answers in the same shape the "Waiting for filament" reason uses.
  3343. Empty means the printer may still be able to take the job.
  3344. Fails open, and deliberately: with no tray reading (never connected
  3345. since Bambuddy started, or the cache dropped by a reconnect) this
  3346. returns nothing to report and the printer is treated as it was before.
  3347. A farm restarted while its printers were off must not conclude that
  3348. none of them can print.
  3349. """
  3350. if not required_types and not filament_overrides:
  3351. return []
  3352. raw_data = self._tray_reading(printer_id)
  3353. if not raw_data:
  3354. return []
  3355. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3356. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3357. if required_types:
  3358. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3359. if missing:
  3360. # Same enrichment the live path applies: a bare "PLA" is not
  3361. # much help when what is missing is a particular PLA.
  3362. force_color_map = {
  3363. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3364. }
  3365. return [
  3366. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3367. for t in missing
  3368. ]
  3369. if force_overrides:
  3370. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3371. if missing_colors:
  3372. return missing_colors
  3373. # Preference overrides read as a preference but the matcher treats zero
  3374. # matches as a skip, so a printer with none of the wanted colours is
  3375. # rejected there too. Waking it would only produce that same rejection.
  3376. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3377. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3378. return []
  3379. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3380. """Fold the winning candidate's file and settings onto the queue row (#671).
  3381. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3382. never escapes the selection loop. By the time the pass commits, the row
  3383. looks exactly like an ordinary single-file model-based item, so the upload,
  3384. archive creation, expected-print registration, print history and reprint
  3385. paths need no knowledge that variants exist.
  3386. No-ops for a non-variant candidate, which is already the item's own columns.
  3387. Safe to run and re-run: the item's file columns are only ever *read* when it
  3388. has no variants, so an item that gets resolved and then skipped (library-row
  3389. conflict, previous-print gate) is simply resolved again on the next pass.
  3390. """
  3391. variant = candidate.variant
  3392. if variant is None:
  3393. return
  3394. item.library_file_id = variant.library_file_id
  3395. item.library_file = variant.library_file
  3396. # The dispatcher checks archive_id first and would print that instead of
  3397. # the file we just picked. Creation refuses to combine the two, so this
  3398. # only ever fires on a hand-written row — clear it rather than silently
  3399. # dispatch something the matcher never considered.
  3400. item.archive_id = None
  3401. item.archive = None
  3402. item.target_model = variant.target_model
  3403. item.plate_id = variant.plate_id
  3404. item.ams_mapping = variant.ams_mapping
  3405. item.nozzle_mapping = variant.nozzle_mapping
  3406. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3407. item.filament_overrides = variant.filament_overrides
  3408. item.required_filament_types = variant.required_filament_types
  3409. if variant.print_time_seconds is not None:
  3410. # The row carried the shortest candidate's estimate so SJF could order
  3411. # it before a printer was known; now that one is chosen, record what is
  3412. # actually going to run so history and the ETA agree with reality.
  3413. item.print_time_seconds = variant.print_time_seconds
  3414. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3415. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3416. Recomputes from live printer status when the stored mapping is missing OR
  3417. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3418. frontend status-load race can serialize [-1] before the printer's AMS
  3419. trays are known (#2589) — and must not be trusted: downstream it would be
  3420. silently downgraded to external-spool mode and print against an empty
  3421. feed. A resolved mapping is re-checked against the target printer's
  3422. live trays before it is trusted (#2799) and recomputed when it does not
  3423. fit. When it does fit, its resolved slots are kept as they are and only
  3424. the slots the plate prints that are still unresolved are matched again;
  3425. all of it is left alone when the user has acknowledged it with "Print
  3426. Anyway".
  3427. When recompute cannot resolve it either (no compatible tray loaded), the
  3428. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3429. external selection. On a printer that reported loaded trays,
  3430. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3431. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3432. and the firmware surfaces a clear AMS-mapping error instead of silently
  3433. printing to the empty external feed.
  3434. Returns an actionable message when that firmware error is the only
  3435. possible outcome — the matcher ran, matched nothing, and the printer has
  3436. no AMS to load a different spool into (#2771). The caller fails the item
  3437. on it instead of spending an upload on a print that cannot start.
  3438. Returns None everywhere else, including every case where we simply lack
  3439. the data to judge, so dispatch is only ever blocked on a positive
  3440. finding.
  3441. """
  3442. stored_mapping: list | None = None
  3443. if item.ams_mapping:
  3444. try:
  3445. stored_mapping = json.loads(item.ams_mapping)
  3446. except (json.JSONDecodeError, TypeError):
  3447. stored_mapping = None
  3448. # Present and resolved. Global tray IDs only mean something relative to
  3449. # the printer they were resolved against, so "resolved" is not the same
  3450. # as "resolved *here*" — check the mapping still fits the printer that
  3451. # is about to run this item before trusting it (#2799). "Print anyway"
  3452. # is the user overriding exactly this judgement, so it short-circuits.
  3453. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3454. if item.skip_filament_check:
  3455. return None
  3456. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3457. if conflict is None:
  3458. # It fits, but a slot the plate prints may still be empty: the
  3459. # spool was missing when it was mapped, and has perhaps been
  3460. # loaded since. Nothing else would ever look at that slot again,
  3461. # so a job held for it would be held again on every Start.
  3462. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3463. if filled is not None:
  3464. item.ams_mapping = json.dumps(filled)
  3465. logger.info(
  3466. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3467. item.id,
  3468. stored_mapping,
  3469. printer_id,
  3470. filled,
  3471. )
  3472. await db.commit()
  3473. return None
  3474. logger.warning(
  3475. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3476. item.id,
  3477. stored_mapping,
  3478. printer_id,
  3479. conflict,
  3480. )
  3481. # Drop it before recomputing so a failed recompute cannot fall back
  3482. # to the mapping we just rejected.
  3483. item.ams_mapping = None
  3484. stored_mapping = None
  3485. await db.commit()
  3486. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3487. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3488. item.ams_mapping = json.dumps(computed_mapping)
  3489. logger.info(
  3490. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3491. item.id,
  3492. printer_id,
  3493. computed_mapping,
  3494. )
  3495. await db.commit()
  3496. return None
  3497. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3498. if external_only is not None:
  3499. item.ams_mapping = json.dumps(external_only)
  3500. logger.info(
  3501. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3502. "mapping every filament to it: %s",
  3503. item.id,
  3504. printer_id,
  3505. external_only,
  3506. )
  3507. await db.commit()
  3508. return None
  3509. if _mapping_is_all_unresolved(stored_mapping):
  3510. logger.warning(
  3511. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3512. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3513. item.id,
  3514. stored_mapping,
  3515. printer_id,
  3516. )
  3517. item.ams_mapping = None
  3518. await db.commit()
  3519. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3520. async def _external_spool_only_mapping(
  3521. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3522. ) -> list[int] | None:
  3523. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3524. A printer without an AMS prints from its external spool, and an external
  3525. spool whose filament was never set reports no type, so the matcher has
  3526. nothing to match. Sent without a mapping, the print goes out with the AMS
  3527. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3528. to carry such a job through; a job placed by model or location no longer
  3529. keeps one, and one queued that way never had one.
  3530. Only on a positive report: the printer has said it has no AMS, it has a
  3531. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3532. is not ours to pick), and no feed has a filament set — with one set, the
  3533. matcher has already given its answer. Not for a job that asked for its
  3534. colours to be matched strictly: a spool without a filament set has no
  3535. colour to check. Returns None otherwise.
  3536. """
  3537. if item.filament_overrides:
  3538. try:
  3539. overrides = json.loads(item.filament_overrides)
  3540. except (json.JSONDecodeError, TypeError):
  3541. return None
  3542. if not isinstance(overrides, list) or any(
  3543. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3544. ):
  3545. return None
  3546. status = printer_manager.get_status(printer_id)
  3547. if status is None or not isinstance(status.raw_data, dict):
  3548. return None
  3549. ams_units = status.raw_data.get("ams")
  3550. if not isinstance(ams_units, list) or ams_units:
  3551. return None
  3552. vt_trays = status.raw_data.get("vt_tray")
  3553. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3554. return None
  3555. if self._build_loaded_filaments(status):
  3556. return None
  3557. printer = await self._get_printer(db, printer_id)
  3558. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3559. return None
  3560. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3561. if external < _EXTERNAL_TRAY_ID_MIN:
  3562. return None
  3563. required = await self._get_filament_requirements(db, item)
  3564. slot_ids = [r.get("slot_id") for r in required or []]
  3565. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3566. if not slot_ids:
  3567. return None
  3568. mapping = [-1] * max(slot_ids)
  3569. for slot_id in slot_ids:
  3570. mapping[slot_id - 1] = external
  3571. return mapping
  3572. async def _fill_unresolved_slots(
  3573. self,
  3574. db: AsyncSession,
  3575. printer_id: int,
  3576. item: PrintQueueItem,
  3577. stored_mapping: list | None,
  3578. ) -> list | None:
  3579. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3580. Every resolved entry is kept, so a tray the user picked by hand stays
  3581. picked. Only the plate's unresolved slots are matched, and only against
  3582. trays the mapping does not already use: the matcher never gives two
  3583. slots one tray, and filling a gap with a tray the user assigned to
  3584. another slot would print that slot's filament twice.
  3585. Returns None when there is nothing to fill or nothing could be filled.
  3586. """
  3587. if not isinstance(stored_mapping, list) or not stored_mapping:
  3588. return None
  3589. required = await self._get_filament_requirements(db, item)
  3590. if not required:
  3591. return None
  3592. self._apply_filament_overrides(item, required)
  3593. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3594. if not gaps:
  3595. return None
  3596. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3597. computed = await self._compute_ams_mapping_for_printer(
  3598. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3599. )
  3600. if not computed:
  3601. return None
  3602. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3603. filled = False
  3604. for slot_id in gaps:
  3605. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3606. if _is_tray_id(tray) and tray >= 0:
  3607. merged[slot_id - 1] = tray
  3608. filled = True
  3609. return merged if filled else None
  3610. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3611. """What a staged item would be held for if it were started now (#2799).
  3612. The Start button asks this before releasing an item, so that a job whose
  3613. filament is still not loaded offers "Print Anyway" instead of being
  3614. released, held again by the scheduler and leaving no way past the hold.
  3615. It reaches the same answer the dispatch path would: a stored mapping
  3616. that fits is kept and only its gaps are matched again, and one that
  3617. does not fit (or is missing) is replaced by a fresh match.
  3618. Returns the missing filaments, described the way the queue row
  3619. describes them, or None when nothing is missing or there is not enough
  3620. evidence to say: no printer yet (a model-based item picks one at
  3621. dispatch), no status, no trays reported, or no readable 3MF.
  3622. """
  3623. if item.skip_filament_check or not item.printer_id:
  3624. return None
  3625. status = printer_manager.get_status(item.printer_id)
  3626. if status is None or not self._build_loaded_filaments(status):
  3627. return None
  3628. # Called from a request, not from a pass: drop whatever the last pass
  3629. # memoised so this reads the file as it is now. A pass running at the
  3630. # same time only loses its cache.
  3631. self._filament_req_memo.clear()
  3632. mapping: list | None = None
  3633. if item.ams_mapping:
  3634. try:
  3635. mapping = json.loads(item.ams_mapping)
  3636. except (json.JSONDecodeError, TypeError):
  3637. mapping = None
  3638. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3639. mapping = None
  3640. if mapping is not None:
  3641. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3642. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3643. else:
  3644. mapping = None
  3645. if mapping is None:
  3646. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3647. required = await self._get_filament_requirements(db, item)
  3648. if required:
  3649. self._apply_filament_overrides(item, required)
  3650. else:
  3651. # The same fallback the hold uses, or Start would release a job the
  3652. # next pass holds again (#3280).
  3653. required = _forced_override_requirements(item)
  3654. if not required:
  3655. return None
  3656. missing = _unresolved_required(required, mapping)
  3657. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3658. async def _stored_mapping_conflict(
  3659. self,
  3660. db: AsyncSession,
  3661. printer_id: int,
  3662. item: PrintQueueItem,
  3663. stored_mapping: list | None,
  3664. ) -> str | None:
  3665. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3666. A mapping is a list of global tray IDs, and those are only meaningful
  3667. relative to the printer they were resolved against — the same rule
  3668. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3669. arrives at a printer it was not resolved for:
  3670. * the print dialog stamps one mapping onto every selected printer, so a
  3671. mapping computed against the first printer is dispatched verbatim to
  3672. the rest, whose AMS slot order differs;
  3673. * a spool is moved between queueing and dispatch.
  3674. Both end the same way: the slot index still resolves, so nothing looks
  3675. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3676. the firmware's own type check, so a PETG slot happily prints in ASA.
  3677. Returns a short reason when the mapping names a tray this printer does
  3678. not have loaded, points a slot at a tray holding a different filament
  3679. type, or points it at an external spool this printer reports empty while
  3680. its AMS holds that slot's filament (#3239). Returns None when the
  3681. mapping fits, and — deliberately — whenever we lack the evidence to
  3682. judge, so a recompute only ever follows a positive finding.
  3683. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3684. matcher had nothing, not that the mapping belongs to another printer,
  3685. and destroying a partially hand-resolved mapping over it would lose the
  3686. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3687. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3688. item when that finds nothing.
  3689. """
  3690. if not isinstance(stored_mapping, list) or not stored_mapping:
  3691. return None
  3692. status = printer_manager.get_status(printer_id)
  3693. if status is None:
  3694. return None
  3695. loaded = self._build_loaded_filaments(status)
  3696. if not loaded:
  3697. # Nothing reported yet (reconnect, first push pending). Saying
  3698. # "tray not loaded" here would recompute against an AMS we cannot
  3699. # see, which is how #2589 produced a bogus all-[-1] in the first
  3700. # place.
  3701. return None
  3702. by_tray = {f["global_tray_id"]: f for f in loaded}
  3703. # Cheap pass first, on live status alone: every tray the mapping names
  3704. # has to exist here. This catches a foreign mapping without opening the
  3705. # 3MF, which is worth doing because the parse below is neither cached
  3706. # nor free.
  3707. for index, tray in enumerate(stored_mapping):
  3708. if not _is_tray_id(tray) or tray < 0:
  3709. continue
  3710. if tray in by_tray:
  3711. continue
  3712. if tray >= 254:
  3713. # An external feed we have not heard about is absence of
  3714. # evidence about *that slot* — the rest of the mapping is still
  3715. # worth judging, so skip it rather than abandoning the pass.
  3716. continue
  3717. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3718. # Only now is the 3MF worth opening: the type check needs to know what
  3719. # each slot actually asked for. The external spool is checked the same
  3720. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3721. # two printers with different filament in the external feed is the same
  3722. # failure this method exists to catch.
  3723. required = await self._get_filament_requirements(db, item)
  3724. if not required:
  3725. return None
  3726. self._apply_filament_overrides(item, required)
  3727. # External feeds the printer reports and reports as empty. That is
  3728. # evidence, unlike an external feed it says nothing about (#3239).
  3729. empty_external: set[int] = set()
  3730. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3731. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3732. if isinstance(vt, dict) and not vt.get("tray_type"):
  3733. try:
  3734. empty_external.add(int(vt.get("id", 254)))
  3735. except (TypeError, ValueError):
  3736. continue
  3737. for req in required:
  3738. slot_id = req.get("slot_id") or 0
  3739. if slot_id <= 0:
  3740. continue
  3741. if slot_id > len(stored_mapping):
  3742. return f"slot {slot_id} is not covered by the mapping"
  3743. tray = stored_mapping[slot_id - 1]
  3744. if not _is_tray_id(tray) or tray < 0:
  3745. continue
  3746. loaded_tray = by_tray.get(tray)
  3747. if loaded_tray is None:
  3748. # A mapping made for a printer that feeds this slot from its
  3749. # external spool, sent to one whose external spool is empty and
  3750. # whose AMS holds the filament (#3239). Only then: an external
  3751. # spool can be loaded without its filament set, and on a printer
  3752. # with nothing else to offer that job printed before. The colour
  3753. # has to match too: with only another colour in the AMS, the
  3754. # printer asking for the spool beats printing in that colour.
  3755. want = canonical_filament_type(req.get("type"))
  3756. if tray >= 254 and tray in empty_external and want:
  3757. ams_tray = next(
  3758. (
  3759. f
  3760. for f in loaded
  3761. if not f.get("is_external")
  3762. and canonical_filament_type(f.get("type")) == want
  3763. and self._colors_are_similar(f.get("color"), req.get("color"))
  3764. ),
  3765. None,
  3766. )
  3767. if ams_tray is not None:
  3768. return (
  3769. f"slot {slot_id} points at the external spool, which is empty, "
  3770. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3771. )
  3772. continue
  3773. want = canonical_filament_type(req.get("type"))
  3774. have = canonical_filament_type(loaded_tray.get("type"))
  3775. if want and have and want != have:
  3776. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3777. # A forced slot fits only a tray the matcher would give it (#3280).
  3778. if req.get("force_color_match"):
  3779. want_idx = req.get("tray_info_idx") or ""
  3780. have_idx = loaded_tray.get("tray_info_idx") or ""
  3781. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3782. loaded_tray.get("color")
  3783. ) or (want_idx and have_idx and want_idx != have_idx):
  3784. return (
  3785. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3786. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3787. )
  3788. return None
  3789. async def _unmappable_without_ams_message(
  3790. self,
  3791. db: AsyncSession,
  3792. printer_id: int,
  3793. item: PrintQueueItem,
  3794. computed_mapping: list[int] | None,
  3795. ) -> str | None:
  3796. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3797. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3798. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3799. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3800. uploaded several megabytes and burned its dispatch retries. This method
  3801. speaks only for the AMS-less case: there is nothing to resume into — the
  3802. external spool holder is the whole inventory — so the useful answer is to
  3803. say which filament is missing and stop. With an AMS attached it returns
  3804. None: where live status reported loaded trays,
  3805. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3806. reported none the print goes out and the firmware error is the answer —
  3807. the user can load the right spool and press Resume.
  3808. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3809. every branch that lacks the evidence to be sure returns None.
  3810. """
  3811. # None means the matcher never ran (no requirements parsed from the 3MF,
  3812. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3813. # dispatch as they always have.
  3814. if not _mapping_is_all_unresolved(computed_mapping):
  3815. return None
  3816. status = printer_manager.get_status(printer_id)
  3817. if status is None:
  3818. return None
  3819. # "No AMS" has to be a fact the printer stated, not the absence of a
  3820. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3821. # handled and is preserved across partial pushes thereafter, so a missing
  3822. # key means we have not heard yet — most likely a reconnect, where the
  3823. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3824. # empty list is the positive report of a printer with no AMS.
  3825. ams_units = status.raw_data.get("ams")
  3826. if not isinstance(ams_units, list) or ams_units:
  3827. return None
  3828. required = await self._get_filament_requirements(db, item)
  3829. loaded = self._build_loaded_filaments(status)
  3830. if not required or not loaded:
  3831. # Both were non-empty moments ago or the matcher could not have run.
  3832. # If the picture changed under us, say nothing rather than fail an
  3833. # item on stale evidence.
  3834. return None
  3835. self._apply_filament_overrides(item, required)
  3836. if any(r.get("force_color_match") for r in required):
  3837. # A forced colour is a spool the user can load on the external
  3838. # holder, so the unmatched hold stages the job instead (#3280).
  3839. return None
  3840. return _unmatched_filament_message(required, loaded)
  3841. async def _fail_unmappable_item(
  3842. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3843. ) -> None:
  3844. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3845. This replaces a failure, not a success: without it the item is uploaded,
  3846. rejected by the firmware with 0700_8012, retried twice more and failed
  3847. anyway with "never started the print after N dispatch attempts". So this
  3848. applies on the model-based path too. There it is rarely reached: choosing
  3849. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  3850. over one it cannot map, so an "Any <model>" job tries its siblings and
  3851. otherwise waits; this remains for a match that failed at selection time.
  3852. """
  3853. item.status = "failed"
  3854. item.error_message = message
  3855. item.completed_at = datetime.now(timezone.utc)
  3856. item.waiting_reason = None
  3857. await db.commit()
  3858. from backend.app.services.print_batch import refresh_batches_after
  3859. await refresh_batches_after([item.id])
  3860. logger.warning(
  3861. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3862. item.id,
  3863. printer_id,
  3864. message,
  3865. )
  3866. job_name = await self._get_job_name(db, item)
  3867. printer = await self._get_printer(db, printer_id)
  3868. await notification_service.on_queue_job_failed(
  3869. job_name=job_name,
  3870. printer_id=printer_id,
  3871. printer_name=printer.name if printer else "Unknown",
  3872. reason=message,
  3873. db=db,
  3874. )
  3875. try:
  3876. await ws_manager.send_queue_item_failed(
  3877. user_id=item.created_by_id,
  3878. queue_item_id=item.id,
  3879. printer_id=printer_id,
  3880. reason="filament_unmappable",
  3881. )
  3882. except Exception:
  3883. pass
  3884. async def _compute_ams_mapping_for_printer(
  3885. self,
  3886. db: AsyncSession,
  3887. printer_id: int,
  3888. item: PrintQueueItem,
  3889. *,
  3890. only_slots: set[int] | None = None,
  3891. reserved_trays: set[int] | None = None,
  3892. ) -> list[int] | None:
  3893. """Compute AMS mapping for a printer based on filament requirements.
  3894. Called when a queue item has no ams_mapping set — either for model-based
  3895. items after printer assignment, or printer-specific items (e.g. from VP).
  3896. Args:
  3897. db: Database session
  3898. printer_id: The assigned printer ID
  3899. item: The queue item (contains archive_id or library_file_id)
  3900. only_slots: Match only these filament slots; every other slot comes
  3901. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3902. reserved_trays: Global tray IDs to leave out of the match, because
  3903. the stored mapping already gives them to another slot.
  3904. Returns:
  3905. AMS mapping array or None if no mapping needed/possible
  3906. """
  3907. # Get printer status
  3908. status = printer_manager.get_status(printer_id)
  3909. if not status:
  3910. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3911. return None
  3912. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3913. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3914. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3915. # an AMS on the *other* nozzle, and the matcher falls through to a
  3916. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3917. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3918. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3919. # Get filament requirements from source file
  3920. filament_reqs = await self._get_filament_requirements(db, item)
  3921. if not filament_reqs:
  3922. # When the 3MF can't be read but force-color overrides are present, build a
  3923. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3924. if item.filament_overrides:
  3925. try:
  3926. overrides = json.loads(item.filament_overrides)
  3927. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3928. if force_overrides:
  3929. logger.info(
  3930. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3931. "force-color override(s)",
  3932. item.id,
  3933. len(force_overrides),
  3934. )
  3935. return self._build_override_direct_mapping(force_overrides, status)
  3936. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3937. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3938. logger.debug("No filament requirements found for queue item %s", item.id)
  3939. return None
  3940. self._apply_filament_overrides(item, filament_reqs)
  3941. if only_slots is not None:
  3942. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3943. if not filament_reqs:
  3944. return None
  3945. # Build loaded filaments from printer status
  3946. loaded_filaments = self._build_loaded_filaments(status)
  3947. if reserved_trays:
  3948. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3949. if not loaded_filaments:
  3950. logger.debug("No filaments loaded on printer %s", printer_id)
  3951. return None
  3952. # Check if user prefers lowest remaining filament when multiple spools match
  3953. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3954. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3955. # Without backup, the printer will not switch to a second spool when the
  3956. # picked one runs out — so sorting toward the lowest leaves the print
  3957. # at risk of running dry mid-job. None (unknown: no status report with
  3958. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3959. if prefer_lowest and status.ams_filament_backup is False:
  3960. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3961. prefer_lowest = False
  3962. # When the preference is on, surface Bambuddy's inventory-side
  3963. # remaining for each slot that's bound to a tracked spool, so the
  3964. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3965. # entirely when the preference is off — no behaviour change for
  3966. # users who haven't opted in.
  3967. inventory_remain_overrides: dict[int, float] | None = None
  3968. if prefer_lowest:
  3969. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3970. # Compute mapping: match required filaments to available slots
  3971. return self._match_filaments_to_slots(
  3972. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3973. )
  3974. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3975. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3976. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3977. diagnosis (#2771) describes the filament the matcher actually looked
  3978. for, not the one the 3MF was sliced with — naming the pre-override
  3979. filament in a user-facing error would send the user to load the wrong
  3980. spool.
  3981. """
  3982. if not item.filament_overrides:
  3983. return
  3984. try:
  3985. overrides = json.loads(item.filament_overrides)
  3986. override_map = {o["slot_id"]: o for o in overrides}
  3987. for req in filament_reqs:
  3988. if req["slot_id"] in override_map:
  3989. override = override_map[req["slot_id"]]
  3990. req["type"] = override["type"]
  3991. req["color"] = override["color"]
  3992. # A manual/preference override SWAPS the slot's filament, so the
  3993. # 3MF's original tray_info_idx now points at the old spool and must
  3994. # be cleared — matching then falls back to type+colour. A
  3995. # force_color_match override is not a swap: it carries the 3MF's
  3996. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3997. # it here too, letting the matcher pin the correct variant slot on a
  3998. # printer holding two same-colour spools of different variants (#2650).
  3999. # A spool that names no variant still counts; one naming another
  4000. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4001. req["tray_info_idx"] = (
  4002. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4003. )
  4004. # The matcher satisfies a forced slot only the way
  4005. # `_get_missing_force_color_slots` does, never by a similar
  4006. # colour or the type alone (#3280).
  4007. req["force_color_match"] = bool(override.get("force_color_match"))
  4008. logger.debug(
  4009. "Queue item %s: Override slot %d -> %s %s",
  4010. item.id,
  4011. req["slot_id"],
  4012. override["type"],
  4013. override["color"],
  4014. )
  4015. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4016. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4017. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4018. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4019. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4020. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4021. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4022. treated as the filament requirement for that slot and matched against the
  4023. current AMS state of the printer.
  4024. Returns the same format as ``_match_filaments_to_slots``, or None when
  4025. the AMS has no loaded filaments.
  4026. """
  4027. loaded = self._build_loaded_filaments(status)
  4028. if not loaded:
  4029. return None
  4030. reqs = [
  4031. {
  4032. "slot_id": o["slot_id"],
  4033. "type": o.get("type", ""),
  4034. "color": o.get("color", ""),
  4035. # These are all force_color_match overrides, so the idx (when the
  4036. # 3MF carried one) is the intended variant, not a stale swap —
  4037. # keep it so the matcher pins the right variant slot (#2650); a
  4038. # spool naming another variant does not satisfy it (#3280).
  4039. "tray_info_idx": o.get("tray_info_idx", ""),
  4040. "force_color_match": True,
  4041. }
  4042. for o in force_overrides
  4043. ]
  4044. return self._match_filaments_to_slots(reqs, loaded)
  4045. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4046. """Resolve the queue item's source 3MF and parse the per-slot
  4047. filament requirements out of it. Thin DB-resolver wrapper around
  4048. ``filament_requirements.extract_filament_requirements`` so the VP
  4049. queue-mode write path (#1188) can reuse the same parser at upload
  4050. time.
  4051. """
  4052. from backend.app.services.filament_requirements import extract_filament_requirements
  4053. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4054. # so every caller gets its own copy — a shared list would leak one
  4055. # item's overrides into the next item that happens to print the same
  4056. # plate.
  4057. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4058. if memo_key in self._filament_req_memo:
  4059. cached = self._filament_req_memo[memo_key]
  4060. return [dict(r) for r in cached] if cached else None
  4061. file_path: Path | None = None
  4062. if item.archive_id:
  4063. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4064. archive = result.scalar_one_or_none()
  4065. if archive:
  4066. file_path = settings.base_dir / archive.file_path
  4067. elif item.library_file_id:
  4068. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4069. library_file = result.scalar_one_or_none()
  4070. if library_file:
  4071. lib_path = Path(library_file.file_path)
  4072. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4073. if not file_path or not file_path.exists():
  4074. self._filament_req_memo[memo_key] = None
  4075. return None
  4076. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4077. self._filament_req_memo[memo_key] = filaments or None
  4078. return [dict(r) for r in filaments] if filaments else None
  4079. def _build_loaded_filaments(self, status) -> list[dict]:
  4080. """Build list of loaded filaments from printer status.
  4081. Args:
  4082. status: PrinterState from printer_manager
  4083. Returns:
  4084. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4085. """
  4086. filaments = []
  4087. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4088. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4089. # Routes external spools to an extruder (#2771). Mirrors
  4090. # `buildLoadedFilaments` in the frontend.
  4091. vt_trays = status.raw_data.get("vt_tray") or []
  4092. is_dual_nozzle = reports_two_nozzles(status)
  4093. # Parse AMS units from raw_data
  4094. ams_data = status.raw_data.get("ams", [])
  4095. for ams_unit in ams_data:
  4096. ams_id = int(ams_unit.get("id", 0))
  4097. trays = ams_unit.get("tray", [])
  4098. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4099. for tray in trays:
  4100. tray_type = tray.get("tray_type")
  4101. if tray_type:
  4102. tray_id = int(tray.get("id", 0))
  4103. tray_color = tray.get("tray_color", "")
  4104. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4105. tray_info_idx = tray.get("tray_info_idx", "")
  4106. # Normalize color: remove alpha, add hash
  4107. color = self._normalize_color(tray_color)
  4108. # Calculate global tray ID
  4109. # AMS-HT units have IDs starting at 128 with a single tray
  4110. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4111. filaments.append(
  4112. {
  4113. "type": tray_type,
  4114. "color": color,
  4115. # `color` reads a missing colour as #808080; this
  4116. # says whether the printer reported one at all.
  4117. "color_known": bool(tray_color),
  4118. "tray_info_idx": tray_info_idx,
  4119. "ams_id": ams_id,
  4120. "tray_id": tray_id,
  4121. "is_ht": is_ht,
  4122. "is_external": False,
  4123. "global_tray_id": global_tray_id,
  4124. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4125. "remain": tray.get("remain", -1),
  4126. }
  4127. )
  4128. # Check external spool(s) (vt_tray is a list)
  4129. for idx, vt in enumerate(vt_trays):
  4130. if vt.get("tray_type"):
  4131. color = self._normalize_color(vt.get("tray_color", ""))
  4132. tray_id = int(vt.get("id", 254))
  4133. filaments.append(
  4134. {
  4135. "type": vt["tray_type"],
  4136. "color": color,
  4137. "color_known": bool(vt.get("tray_color")),
  4138. "tray_info_idx": vt.get("tray_info_idx", ""),
  4139. "ams_id": -1,
  4140. "tray_id": idx,
  4141. "is_ht": False,
  4142. "is_external": True,
  4143. "global_tray_id": tray_id,
  4144. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4145. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4146. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4147. "remain": vt.get("remain", -1),
  4148. }
  4149. )
  4150. return filaments
  4151. def _normalize_color(self, color: str | None) -> str:
  4152. """Normalize color to #RRGGBB format."""
  4153. if not color:
  4154. return "#808080"
  4155. hex_color = color.replace("#", "")[:6]
  4156. return f"#{hex_color}"
  4157. def _normalize_color_for_compare(self, color: str | None) -> str:
  4158. """Normalize color for comparison (lowercase, no hash)."""
  4159. if not color:
  4160. return ""
  4161. return color.replace("#", "").lower()[:6]
  4162. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4163. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4164. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4165. stays the per-channel box that shipped — this only decides which of
  4166. several eligible spools is closest, so nothing becomes usable or
  4167. unusable because of it.
  4168. It ranks by how far apart the colours *look*, not how far apart their
  4169. numbers are. RGB distance overweights blue badly enough to invert the
  4170. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4171. the nearer of two eligible spools by RGB and the further by a factor of
  4172. four once measured perceptually.
  4173. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4174. transparent filament is not a colour the user chose, and counting it
  4175. would stop a transparent filament matching itself.
  4176. """
  4177. return perceptual_color_distance(color1, color2)
  4178. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4179. """Check if two colors are visually similar within a threshold."""
  4180. hex1 = self._normalize_color_for_compare(color1)
  4181. hex2 = self._normalize_color_for_compare(color2)
  4182. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4183. return False
  4184. try:
  4185. r1 = int(hex1[0:2], 16)
  4186. g1 = int(hex1[2:4], 16)
  4187. b1 = int(hex1[4:6], 16)
  4188. r2 = int(hex2[0:2], 16)
  4189. g2 = int(hex2[2:4], 16)
  4190. b2 = int(hex2[4:6], 16)
  4191. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4192. except ValueError:
  4193. return False
  4194. async def _build_inventory_remain_overrides(
  4195. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4196. ) -> dict[int, float]:
  4197. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4198. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4199. The MQTT ``remain`` field on a tray is the printer firmware's
  4200. RFID-decremented value, which has two limitations the "Prefer Lowest
  4201. Remaining Filament" feature has been ignoring (#1508):
  4202. - it's only meaningful for Bambu RFID spools; everything else reports
  4203. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4204. compare equal and the sort collapses to AMS-slot order — the user
  4205. who's curating inventory weights gets the lower-slot pick instead
  4206. of the lower-remaining pick;
  4207. - even when set, it's the *printer's* counter, not Bambuddy's
  4208. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4209. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4210. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4211. When the user has bound a spool to a slot, their own inventory
  4212. tracking is authoritative; this helper surfaces that value so the
  4213. sort can prefer it. Slots without a binding are absent from the
  4214. returned map — the caller then falls back to MQTT ``remain`` for
  4215. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4216. Returns an empty map on any failure (no inventory bindings, DB
  4217. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4218. is a preference, not a guarantee.
  4219. """
  4220. if not loaded:
  4221. return {}
  4222. # External / virtual-tray slots are tracked separately from AMS — skip
  4223. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4224. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4225. # match is fiddly and out of scope for this fix).
  4226. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4227. if not tracked_slots:
  4228. return {}
  4229. is_spoolman = await self._is_spoolman_mode(db)
  4230. overrides: dict[int, float] = {}
  4231. if is_spoolman:
  4232. result = await db.execute(
  4233. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4234. )
  4235. assignments = list(result.scalars().all())
  4236. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4237. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4238. for ams_id, tray_id, gtid in tracked_slots:
  4239. spoolman_id = by_slot.get((ams_id, tray_id))
  4240. if spoolman_id is None:
  4241. continue
  4242. grams = await _spoolman_remaining_grams(spoolman_id)
  4243. if grams is not None:
  4244. overrides[gtid] = grams
  4245. return overrides
  4246. # Internal inventory mode (default). selectinload matches the pattern
  4247. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4248. # plus an eager-loaded relationship rather than an explicit join, so
  4249. # the row-attribute shape is exactly what those routes already rely on.
  4250. result = await db.execute(
  4251. select(SpoolAssignment)
  4252. .options(selectinload(SpoolAssignment.spool))
  4253. .where(SpoolAssignment.printer_id == printer_id)
  4254. )
  4255. assignments = list(result.scalars().all())
  4256. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4257. for ams_id, tray_id, gtid in tracked_slots:
  4258. spool = by_slot.get((ams_id, tray_id))
  4259. if spool is None:
  4260. continue
  4261. label = float(spool.label_weight or 0)
  4262. used = float(spool.weight_used or 0)
  4263. overrides[gtid] = max(0.0, label - used)
  4264. return overrides
  4265. @staticmethod
  4266. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4267. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4268. here to avoid making this module import-dependent on that private
  4269. helper's signature."""
  4270. try:
  4271. from backend.app.api.routes.settings import get_setting
  4272. v = await get_setting(db, "spoolman_enabled")
  4273. return bool(v) and v.lower() == "true"
  4274. except Exception:
  4275. return False
  4276. @staticmethod
  4277. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4278. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4279. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4280. so a tied sort produces the same physical-position order the pre-#1508
  4281. stable sort did (preserves the regression-free baseline):
  4282. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4283. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4284. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4285. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4286. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4287. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4288. """
  4289. if ams_id is None or ams_id < 0:
  4290. return 10_000
  4291. if ams_id >= 128:
  4292. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4293. return ams_id * 4 + (tray_id or 0)
  4294. @staticmethod
  4295. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4296. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4297. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4298. non-tracked spools (the user has told us they care about these
  4299. specifically), then ascending by remaining within each tier, then
  4300. ascending by AMS slot position as the deterministic tie-breaker.
  4301. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4302. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4303. because the tier flag dominates — which is what lets us mix grams
  4304. (inventory) and percent (MQTT) without a unit conversion.
  4305. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4306. spools the printer DOES know something about sort ahead of those
  4307. it knows nothing about — preserves pre-#1508 behaviour for the
  4308. no-inventory-binding case.
  4309. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4310. external on ties, matching the legacy emission-order stable sort.
  4311. """
  4312. gtid = f.get("global_tray_id")
  4313. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4314. if overrides and gtid in overrides:
  4315. return (0, overrides[gtid], slot_order)
  4316. remain = f.get("remain", -1)
  4317. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4318. def _match_filaments_to_slots(
  4319. self,
  4320. required: list[dict],
  4321. loaded: list[dict],
  4322. prefer_lowest: bool = False,
  4323. inventory_remain_overrides: dict[int, float] | None = None,
  4324. fts_installed: bool = False,
  4325. ) -> list[int] | None:
  4326. """Match required filaments to loaded filaments and build AMS mapping.
  4327. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4328. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4329. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4330. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4331. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4332. matching among those trays.
  4333. Args:
  4334. required: List of required filaments with slot_id, type, color, tray_info_idx
  4335. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4336. Returns:
  4337. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4338. """
  4339. if not required:
  4340. return None
  4341. # Track used trays to avoid duplicate assignment
  4342. used_tray_ids: set[int] = set()
  4343. comparisons = []
  4344. # Forced slots first: a slot that would take any tray of its type must
  4345. # not take the one tray a forced slot can use (#3280). The mapping is
  4346. # built by slot_id below, so the order only decides who goes first.
  4347. # Among forced slots, those naming a variant first, as
  4348. # `_get_missing_force_color_slots` counts them.
  4349. for req in sorted(
  4350. required,
  4351. key=lambda r: (
  4352. not r.get("force_color_match"),
  4353. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4354. ),
  4355. ):
  4356. req_type = (req.get("type") or "").upper()
  4357. req_color = req.get("color", "")
  4358. req_tray_info_idx = req.get("tray_info_idx", "")
  4359. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4360. idx_match = None
  4361. exact_match = None
  4362. similar_match = None
  4363. similar_distance = float("inf")
  4364. type_only_match = None
  4365. # Get available trays (not already used)
  4366. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4367. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4368. # Hard filter — cross-nozzle assignment causes print failures
  4369. # ("position of left hotend is abnormal"), so never fall back.
  4370. # Skipped when an FTS is installed: it routes any AMS slot to either
  4371. # extruder, so restricting to one nozzle would wrongly exclude the
  4372. # correct spool sitting in the other nozzle's AMS (#2186).
  4373. req_nozzle_id = req.get("nozzle_id")
  4374. if req_nozzle_id is not None and not fts_installed:
  4375. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4376. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4377. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4378. # _prefer_lowest_sort_key for the full rationale.
  4379. if prefer_lowest:
  4380. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4381. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4382. # One line per filament req so a bug report can be diagnosed
  4383. # without enabling debug logging: shows what the matcher saw
  4384. # (req shape + sorted candidate trays with their remain values
  4385. # and any inventory override that was applied). Mirrored by
  4386. # the picked-match log at the bottom of the loop.
  4387. logger.info(
  4388. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4389. req.get("slot_id"),
  4390. req_type,
  4391. req_color,
  4392. req_tray_info_idx,
  4393. req_nozzle_id,
  4394. [
  4395. {
  4396. "gtid": f.get("global_tray_id"),
  4397. "type": f.get("type"),
  4398. "color": f.get("color"),
  4399. "tii": f.get("tray_info_idx"),
  4400. "remain": f.get("remain"),
  4401. "inv_g": (
  4402. inventory_remain_overrides.get(f.get("global_tray_id"))
  4403. if inventory_remain_overrides
  4404. else None
  4405. ),
  4406. }
  4407. for f in available
  4408. ],
  4409. )
  4410. # A forced slot takes only what `_get_missing_force_color_slots`
  4411. # accepts: same type, exact colour, and the same variant when both
  4412. # sides name one -- preferring the tray that does. Nothing looser:
  4413. # the model-based path holds a job the printer cannot satisfy this
  4414. # way, and a printer-pinned job fell through to type_only and
  4415. # printed in whatever colour came first (#3280).
  4416. forced = bool(req.get("force_color_match"))
  4417. if forced:
  4418. want_type = canonical_filament_type(req_type)
  4419. want_color = self._normalize_color_for_compare(req_color)
  4420. candidates = [
  4421. f
  4422. for f in available
  4423. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4424. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4425. and (
  4426. not req_tray_info_idx
  4427. or not f.get("tray_info_idx")
  4428. or f.get("tray_info_idx") == req_tray_info_idx
  4429. )
  4430. ]
  4431. exact_match = next(
  4432. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4433. candidates[0] if candidates else None,
  4434. )
  4435. # Check if tray_info_idx is unique among available trays
  4436. if req_tray_info_idx and not forced:
  4437. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4438. if len(idx_matches) == 1:
  4439. # Unique tray_info_idx - use it as definitive match
  4440. idx_match = idx_matches[0]
  4441. logger.debug(
  4442. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4443. f"-> tray {idx_match['global_tray_id']}"
  4444. )
  4445. elif len(idx_matches) > 1:
  4446. # Multiple trays with same tray_info_idx - use color matching among them
  4447. logger.debug(
  4448. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4449. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4450. )
  4451. if prefer_lowest:
  4452. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4453. # Use color matching within this subset
  4454. for f in idx_matches:
  4455. f_color = f.get("color", "")
  4456. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4457. if not exact_match:
  4458. exact_match = f
  4459. elif self._colors_are_similar(f_color, req_color):
  4460. distance = self._color_distance(f_color, req_color)
  4461. if distance is not None and distance < similar_distance:
  4462. similar_match = f
  4463. similar_distance = distance
  4464. elif not type_only_match:
  4465. type_only_match = f
  4466. # If no idx_match yet, do standard type/color matching on all available trays
  4467. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4468. for f in available:
  4469. f_type = (f.get("type") or "").upper()
  4470. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4471. continue
  4472. # Type matches - check color
  4473. f_color = f.get("color", "")
  4474. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4475. if not exact_match:
  4476. exact_match = f
  4477. elif self._colors_are_similar(f_color, req_color):
  4478. # Nearest wins, not first-in-tray-order. `available` is
  4479. # already in the caller's order (slot order, or the
  4480. # prefer-lowest sort), and `<` keeps the earliest of
  4481. # equally close spools — so that order survives as the
  4482. # tie-break (#2804).
  4483. distance = self._color_distance(f_color, req_color)
  4484. if distance is not None and distance < similar_distance:
  4485. similar_match = f
  4486. similar_distance = distance
  4487. elif not type_only_match:
  4488. type_only_match = f
  4489. match = idx_match or exact_match or similar_match or type_only_match
  4490. if match:
  4491. used_tray_ids.add(match["global_tray_id"])
  4492. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4493. else:
  4494. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4495. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4496. # "Why did it pick that spool" is the question every wrong-filament
  4497. # report starts with, and a `similar_color` win is now a ranked
  4498. # choice among several eligible spools rather than whichever tray
  4499. # came first, so it is worth being able to see after the fact.
  4500. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4501. # is on (#1766).
  4502. if match:
  4503. bucket = (
  4504. "idx"
  4505. if idx_match is not None
  4506. else "exact_color"
  4507. if exact_match is not None
  4508. else "similar_color"
  4509. if similar_match is not None
  4510. else "type_only"
  4511. )
  4512. logger.info(
  4513. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4514. match["global_tray_id"],
  4515. bucket,
  4516. req.get("slot_id"),
  4517. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4518. )
  4519. else:
  4520. logger.info(
  4521. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4522. req.get("slot_id"),
  4523. req_type,
  4524. req_color,
  4525. req_tray_info_idx,
  4526. ", force color match" if forced else "",
  4527. )
  4528. # Build mapping array
  4529. if not comparisons:
  4530. return None
  4531. max_slot_id = max(c["slot_id"] for c in comparisons)
  4532. if max_slot_id <= 0:
  4533. return None
  4534. mapping = [-1] * max_slot_id
  4535. for c in comparisons:
  4536. slot_id = c["slot_id"]
  4537. if slot_id and slot_id > 0:
  4538. mapping[slot_id - 1] = c["global_tray_id"]
  4539. return mapping
  4540. def _mark_printer_dispatched(
  4541. self,
  4542. printer_id: int,
  4543. pre_state: str | None,
  4544. pre_subtask_id: str | None,
  4545. ) -> None:
  4546. """Record that a print command was just sent to ``printer_id``.
  4547. Held until either the watchdog observes a state/subtask transition
  4548. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4549. """
  4550. if not pre_state:
  4551. # No pre_state means we can't detect a transition — fall back to a
  4552. # pure time-based hold using empty string as a sentinel that won't
  4553. # match any real printer state.
  4554. pre_state = ""
  4555. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4556. def _release_dispatch_hold(self, printer_id: int) -> None:
  4557. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4558. self._dispatch_holds.pop(printer_id, None)
  4559. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4560. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4561. Returns False (and clears the hold) once any of these are true:
  4562. - hard timeout (``_dispatch_max_hold``) has elapsed
  4563. - the printer has transitioned out of pre_state and we're past the
  4564. minimum cooldown
  4565. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4566. past the minimum cooldown
  4567. Otherwise the printer is held — caller should treat it as busy.
  4568. """
  4569. entry = self._dispatch_holds.get(printer_id)
  4570. if not entry:
  4571. return False
  4572. started_at, pre_state, pre_subtask_id = entry
  4573. elapsed = time.monotonic() - started_at
  4574. if elapsed >= self._dispatch_max_hold:
  4575. self._dispatch_holds.pop(printer_id, None)
  4576. return False
  4577. # Without a pre_state we can't detect a transition — fall back to the
  4578. # min cooldown alone, then drop the hold.
  4579. if not pre_state:
  4580. if elapsed >= self._dispatch_min_cooldown:
  4581. self._dispatch_holds.pop(printer_id, None)
  4582. return False
  4583. return True
  4584. status = printer_manager.get_status(printer_id)
  4585. current_state = getattr(status, "state", None) if status else None
  4586. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4587. transitioned = (current_state is not None and current_state != pre_state) or (
  4588. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4589. )
  4590. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4591. self._dispatch_holds.pop(printer_id, None)
  4592. return False
  4593. return True
  4594. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4595. """Check if a printer is connected and idle."""
  4596. if not printer_manager.is_connected(printer_id):
  4597. logger.debug("Printer %d: not connected", printer_id)
  4598. return False
  4599. state = printer_manager.get_status(printer_id)
  4600. if not state:
  4601. logger.debug("Printer %d: no status available", printer_id)
  4602. return False
  4603. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4604. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4605. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4606. # printer, it boots back into IDLE with no memory of the previous finish; without
  4607. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4608. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4609. logger.debug(
  4610. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4611. printer_id,
  4612. state.state,
  4613. )
  4614. return False
  4615. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4616. if not idle:
  4617. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4618. return False
  4619. # A print would run from the SD card the firmware is being written to.
  4620. from backend.app.services.firmware_update import upload_in_progress
  4621. if upload_in_progress(printer_id):
  4622. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4623. return False
  4624. return True
  4625. @staticmethod
  4626. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4627. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4628. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4629. and that the fixed-printer branch has already found connected, so the two
  4630. offline cases answer at their own exits and never arrive here.
  4631. The default is the model-based branch's ``Busy:`` wording, which
  4632. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4633. the right answer for the connected-but-no-telemetry second or two after a
  4634. reconnect: the model-based branch has always reported it that way, and it
  4635. is not something to wake anybody up for.
  4636. A plate nobody has confirmed is the one case here that does not resolve
  4637. itself — somebody has to walk over to the printer — so it is worded as
  4638. itself and allowed to notify.
  4639. """
  4640. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4641. return f"Waiting for plate confirmation: {printer_name}"
  4642. return f"Busy: {printer_name}"
  4643. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4644. """Read a setting value from the database."""
  4645. result = await db.execute(select(Settings).where(Settings.key == key))
  4646. setting = result.scalar_one_or_none()
  4647. return setting.value if setting else None
  4648. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4649. """Read a boolean setting from the database."""
  4650. result = await db.execute(select(Settings).where(Settings.key == key))
  4651. setting = result.scalar_one_or_none()
  4652. if setting:
  4653. return setting.value.lower() == "true"
  4654. return default
  4655. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4656. """Read an int setting; falls back to default on missing/unparseable rows."""
  4657. result = await db.execute(select(Settings).where(Settings.key == key))
  4658. setting = result.scalar_one_or_none()
  4659. if setting and setting.value:
  4660. try:
  4661. return int(setting.value)
  4662. except ValueError:
  4663. pass
  4664. return default
  4665. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4666. """Get drying presets (user-configured or built-in defaults)."""
  4667. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4668. setting = result.scalar_one_or_none()
  4669. if setting and setting.value:
  4670. try:
  4671. presets = json.loads(setting.value)
  4672. if isinstance(presets, dict) and presets:
  4673. return presets
  4674. except json.JSONDecodeError:
  4675. pass
  4676. return self.DEFAULT_DRYING_PRESETS
  4677. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4678. """Per-filament humidity thresholds (#1605).
  4679. Returns the user-configured overrides map keyed by normalized filament
  4680. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4681. unknown / unmapped types. Empty / unset → empty dict, in which case
  4682. callers fall back to ``ams_humidity_fair``.
  4683. """
  4684. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4685. setting = result.scalar_one_or_none()
  4686. if not setting or not setting.value:
  4687. return {}
  4688. try:
  4689. data = json.loads(setting.value)
  4690. except json.JSONDecodeError:
  4691. return {}
  4692. if not isinstance(data, dict):
  4693. return {}
  4694. out: dict[str, int] = {}
  4695. for key, value in data.items():
  4696. try:
  4697. out[str(key).upper() if key != "default" else "default"] = int(value)
  4698. except (TypeError, ValueError):
  4699. continue
  4700. return out
  4701. # Materials whose AMS spelling differs from the key the tables above use.
  4702. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4703. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4704. # good PA row (#3067).
  4705. #
  4706. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4707. # The drying popover has resolved these correctly since #2774 and the
  4708. # scheduler never did, which is exactly why #3067's reporter could dry a
  4709. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4710. #
  4711. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4712. # of nylon, so it is the one entry that is a judgement rather than a
  4713. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4714. # way, and PA's row is the hottest the table has. Drying it there is closer
  4715. # to right than not drying it at all, which is what it got before.
  4716. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4717. "NYLON": "PA",
  4718. "PA6": "PA",
  4719. "PA11": "PA",
  4720. "PA12": "PA",
  4721. "PAHT": "PA",
  4722. "PPA": "PA",
  4723. }
  4724. @classmethod
  4725. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4726. """The key in *table* that answers for this tray's material, or None.
  4727. The printer reports the material in ``tray_type``, and it spells filled
  4728. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4729. tables here are keyed by base material, so matching the raw string alone
  4730. found a row for 8 of the 41 types a printer can report and skipped the
  4731. rest -- silently, because every caller reads "no row" as "nothing to do
  4732. for this tray". Auto-drying therefore ignored every composite spool on
  4733. the install (#3067).
  4734. Exact match first, so a table the user has extended with a row of its
  4735. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4736. base material's. Then the suffix is dropped, then the alias map above
  4737. answers for the polyamide spellings.
  4738. Returns None rather than a default: what to do with an unrecognised
  4739. material differs per caller, and only the caller knows whether "no row"
  4740. means skip the tray or fall back to a catch-all. Nothing here invents a
  4741. temperature for a material the table does not list.
  4742. """
  4743. raw = cls._normalize_filament_type(tray_type or "")
  4744. if not raw:
  4745. return None
  4746. for candidate in (raw, raw.split("-")[0]):
  4747. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4748. if key in table:
  4749. return key
  4750. return None
  4751. @staticmethod
  4752. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4753. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4754. For mixed filament types loaded into one AMS, returns the most
  4755. restrictive (lowest) threshold across all loaded tray types — matches
  4756. the conservative-params strategy already used for drying temp/hours.
  4757. Empty / unloaded trays contribute no constraint. Unknown types use the
  4758. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4759. when no per-type map is configured at all.
  4760. """
  4761. default = thresholds.get("default", fallback)
  4762. if not thresholds:
  4763. return fallback
  4764. candidates: list[int] = []
  4765. for tray in trays:
  4766. tray_type = str(tray.get("tray_type") or "").strip()
  4767. if not tray_type:
  4768. continue
  4769. # A composite carries its base material's threshold when it has no
  4770. # row of its own, the same way it takes its drying preset (#3067).
  4771. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4772. candidates.append(thresholds[key] if key is not None else default)
  4773. if not candidates:
  4774. return default
  4775. return min(candidates)
  4776. def _get_conservative_drying_params(
  4777. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4778. ) -> tuple[int, int, str] | None:
  4779. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4780. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4781. """
  4782. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4783. hours_key = f"{temp_key}_hours"
  4784. min_temp = None
  4785. max_hours = None
  4786. filament_type = ""
  4787. for tray in trays:
  4788. tray_type = tray.get("tray_type", "")
  4789. if not tray_type:
  4790. continue
  4791. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4792. # which is what stopped auto-drying on every composite spool (#3067).
  4793. base_type = self._resolve_filament_key(tray_type, presets)
  4794. if base_type is None:
  4795. continue
  4796. # The table is user-editable JSON with no per-row validation, so a
  4797. # row can be present and empty. That has always meant "skip this
  4798. # material", and it has to keep meaning it: the reads below fall
  4799. # back to 55C/12h per missing field, which is a temperature nobody
  4800. # chose and would deform a PLA spool.
  4801. preset = presets[base_type]
  4802. if not preset:
  4803. continue
  4804. temp = preset.get(temp_key, 55)
  4805. hours = preset.get(hours_key, 12)
  4806. # Conservative: lowest temp, longest duration
  4807. if min_temp is None or temp < min_temp:
  4808. min_temp = temp
  4809. if max_hours is None or hours > max_hours:
  4810. max_hours = hours
  4811. if not filament_type:
  4812. filament_type = base_type
  4813. if min_temp is None:
  4814. return None
  4815. return (min_temp, max_hours or 12, filament_type)
  4816. async def _check_filament_low(self, db: AsyncSession) -> None:
  4817. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4818. ``on_filament_low`` has had a column, a schema field, a route, a template
  4819. and a UI toggle since the notification system was built, and no caller --
  4820. so the toggle could be switched on and could never fire. This is the
  4821. producer.
  4822. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4823. ``low_stock_threshold_pct`` override is already exactly this decision:
  4824. already configurable, already surfaced, already driving the Inventory
  4825. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4826. consulted -- it has been measured up to 56 points out against a scale,
  4827. which is not a number to page someone on.
  4828. Only slots with an assigned spool produce an event. A slot Bambuddy
  4829. cannot resolve to a spool has no remaining weight it can stand behind,
  4830. and guessing one is how the remain percentage would have got in.
  4831. """
  4832. from backend.app.models.spool import Spool
  4833. # Time-gated rather than run on every pass. run() sleeps
  4834. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4835. # early-return path counts as productive while an upload is in flight
  4836. # (#2602), so an unthrottled check would re-read the whole spool
  4837. # collection every 3 seconds for the length of a batch drain. In
  4838. # Spoolman mode that is a request storm against a third-party service,
  4839. # which is the thing this producer's design note argues against; and
  4840. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4841. # check_queue holding the scheduler's session, so the outage would
  4842. # throttle the print queue itself. A low spool is not a 3-second
  4843. # concern -- the idle interval is the natural resolution.
  4844. now = time.monotonic()
  4845. if now < self._filament_low_next_check:
  4846. return
  4847. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4848. try:
  4849. # on_filament_low defaults to off on every provider, so on most
  4850. # installs nobody wants this alert. Without this the check would
  4851. # still read every assigned spool each interval -- the whole
  4852. # collection over HTTP in Spoolman mode -- for an event that is
  4853. # switched off. One query against the provider table settles it
  4854. # before any spool work, the same guard the bed-cooled waiter uses.
  4855. # No printer_id: this asks whether any provider wants the event at
  4856. # all; per-printer scoping is applied when the event is sent.
  4857. #
  4858. # While nobody wants it, no pass sees a slot go back above its
  4859. # threshold, so nothing can re-arm; a spool refilled under the same
  4860. # id in that time would stay silenced until a restart. Forgetting
  4861. # what was sent is right anyway: whoever switches the event back on
  4862. # is told about the spools that are low now.
  4863. #
  4864. # The MQTT relay publishes the same event, so a connected relay is
  4865. # reason enough to run the check. Its record is forgotten when the
  4866. # relay is switched off, not when the broker drops: a reconnect must
  4867. # not re-send every low slot.
  4868. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4869. relay = mqtt_relay.enabled and mqtt_relay.connected
  4870. if not notify:
  4871. self._notified_filament_low.clear()
  4872. if not mqtt_relay.enabled:
  4873. self._relayed_filament_low.clear()
  4874. if not notify and not relay:
  4875. return
  4876. global_threshold = await self._get_low_stock_threshold(db)
  4877. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4878. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4879. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4880. if spoolman_on:
  4881. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4882. else:
  4883. rows = (
  4884. await db.execute(
  4885. select(SpoolAssignment, Spool)
  4886. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4887. # An archived spool is not stock. The Inventory page's
  4888. # Low Stock count skips them (InventoryPage.tsx:1089)
  4889. # and get_all_spools without allow_archived already
  4890. # excludes them in Spoolman mode, so without this the
  4891. # internal path is the only one that alerts on them.
  4892. .where(Spool.archived_at.is_(None))
  4893. )
  4894. ).all()
  4895. for assignment, spool in rows:
  4896. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4897. if pct is None:
  4898. continue
  4899. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4900. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4901. pct,
  4902. threshold,
  4903. spool.color_name,
  4904. )
  4905. if not slots:
  4906. # Nothing resolvable this pass. Deliberately not clearing the
  4907. # notified set: a Spoolman that is briefly unreachable would
  4908. # otherwise re-alert on every spool as soon as it came back.
  4909. return
  4910. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4911. except Exception as e:
  4912. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4913. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4914. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4915. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4916. if raw is None or raw.value is None:
  4917. return 20.0
  4918. try:
  4919. value = float(raw.value)
  4920. except (TypeError, ValueError):
  4921. return 20.0
  4922. return value if 0 < value <= 100 else 20.0
  4923. async def _filament_low_slots_spoolman(
  4924. self, db: AsyncSession, global_threshold: float
  4925. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4926. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4927. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4928. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4929. so the global threshold is the only one that applies here. That matches
  4930. what the Inventory page already does in this mode.
  4931. One ``get_all_spools`` call covers every slot rather than a request per
  4932. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4933. without ``allow_archived`` -- which is the behaviour the internal path
  4934. has to ask for explicitly.
  4935. An unreachable Spoolman returns no slots rather than raising. It is an
  4936. ordinary state for a third-party service, not an error in this pass: the
  4937. caller's "nothing resolvable" branch already leaves the notified set
  4938. alone, which is exactly right here, whereas letting it reach the broad
  4939. ``except`` would write a full traceback every time the check runs.
  4940. """
  4941. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4942. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4943. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4944. if not assignments:
  4945. return {}
  4946. client = await get_spoolman_client()
  4947. if client is None:
  4948. return {}
  4949. try:
  4950. all_spools = await client.get_all_spools()
  4951. except SpoolmanUnavailableError as e:
  4952. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4953. return {}
  4954. by_id: dict[int, dict] = {}
  4955. for raw in all_spools:
  4956. raw_id = raw.get("id")
  4957. if isinstance(raw_id, int):
  4958. by_id[raw_id] = raw
  4959. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4960. for assignment in assignments:
  4961. raw = by_id.get(assignment.spoolman_spool_id)
  4962. if raw is None:
  4963. continue
  4964. try:
  4965. mapped = _map_spoolman_spool(raw)
  4966. except ValueError:
  4967. continue
  4968. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4969. if pct is None:
  4970. continue
  4971. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4972. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4973. return slots
  4974. async def _emit_filament_low(
  4975. self,
  4976. db: AsyncSession,
  4977. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4978. *,
  4979. notify: bool = True,
  4980. relay: bool = False,
  4981. ) -> None:
  4982. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4983. printers: dict[int, Printer] = {}
  4984. for key, (pct, threshold, color) in slots.items():
  4985. printer_id, ams_id, tray_id, spool_id = key
  4986. if pct >= threshold:
  4987. # Back above the line: re-arm rather than expire on a timer, so a
  4988. # refilled slot can alert again and a spool sitting just under the
  4989. # threshold stays quiet.
  4990. self._notified_filament_low.discard(key)
  4991. self._relayed_filament_low.discard(key)
  4992. continue
  4993. send_notification = notify and key not in self._notified_filament_low
  4994. # Only while connected, so a crossing the relay missed reaches it
  4995. # after the reconnect.
  4996. send_relay = relay and key not in self._relayed_filament_low
  4997. if not send_notification and not send_relay:
  4998. continue
  4999. # Marked before sending, which is a choice rather than the only
  5000. # option, and it is the opposite failure mode from the one the
  5001. # debounce argues against: one transient provider failure loses this
  5002. # alert until the spool goes back above the threshold and crosses it
  5003. # again. Marking after a successful send would trade that for
  5004. # re-alerting on every pass while a provider is down -- which is the
  5005. # repetition the whole debounce exists to prevent, and the louder of
  5006. # the two failures. A spool that is low stays low, so the next real
  5007. # signal is not far away; a provider stuck retrying is a signal that
  5008. # never stops.
  5009. if send_notification:
  5010. self._notified_filament_low.add(key)
  5011. if send_relay:
  5012. self._relayed_filament_low.add(key)
  5013. if printer_id not in printers:
  5014. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5015. if printer is None:
  5016. continue
  5017. printers[printer_id] = printer
  5018. printer = printers[printer_id]
  5019. slot = _ams_slot_label(ams_id, tray_id)
  5020. if send_notification:
  5021. try:
  5022. await notification_service.on_filament_low(
  5023. printer_id,
  5024. printer.name,
  5025. slot,
  5026. int(pct),
  5027. db,
  5028. color=color,
  5029. )
  5030. except Exception as e:
  5031. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5032. if send_relay:
  5033. try:
  5034. await mqtt_relay.on_filament_low(
  5035. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5036. )
  5037. except Exception as e:
  5038. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5039. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5040. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5041. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5042. a schema field, a template and a UI toggle, and nothing that computes the
  5043. condition -- the Forecast panel does it in the browser, so with no page
  5044. open nothing could ever alert. This runs the same arithmetic
  5045. (``stock_forecast``) from the scheduler loop.
  5046. An alert is sent when a SKU *moves into* a condition, once, and again
  5047. after the condition has cleared. A SKU that worsens from reorder to break
  5048. alerts again as a break, because the panel treats the two as exclusive; one
  5049. that eases from break back to reorder does not alert again.
  5050. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5051. while it is still low tells you.
  5052. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5053. loop runs every 3 s while an upload is in flight, and the whole spool
  5054. collection is read over HTTP in Spoolman mode. Both events default to off
  5055. on every provider, so nothing is read unless a provider wants one.
  5056. """
  5057. now = time.monotonic()
  5058. if now < self._stock_forecast_next_check:
  5059. return
  5060. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5061. try:
  5062. if self._stock_alerts_persisted is None:
  5063. await self._load_stock_alerts(db)
  5064. wanted = {
  5065. "reorder": bool(
  5066. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5067. ),
  5068. "break": bool(
  5069. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5070. ),
  5071. }
  5072. if not any(wanted.values()):
  5073. # Nobody wants either event. Forget what was sent, so whoever
  5074. # switches one on is told about the SKUs that are low now.
  5075. self._notified_stock_alerts.clear()
  5076. await self._save_stock_alerts(db)
  5077. return
  5078. forecasts = await self._stock_forecasts(db)
  5079. if forecasts is None:
  5080. # Spoolman unreachable. Deliberately not clearing the notified
  5081. # set: a brief outage would otherwise re-alert every SKU when it
  5082. # came back.
  5083. return
  5084. await self._emit_stock_alerts(db, forecasts, wanted)
  5085. await self._save_stock_alerts(db)
  5086. except Exception as e:
  5087. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5088. def _serialize_stock_alerts(self) -> str:
  5089. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5090. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5091. return json.dumps(rows)
  5092. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5093. """Read the notified set saved by the last run, once per process.
  5094. A missing or unreadable row is an empty set: the worst that does is one
  5095. repeat of what a restart used to cause every time.
  5096. """
  5097. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5098. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5099. if raw and raw.value:
  5100. try:
  5101. for key, kind, events in json.loads(raw.value):
  5102. if len(key) == 4 and kind in ("reorder", "break"):
  5103. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5104. except (ValueError, TypeError):
  5105. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5106. loaded = {}
  5107. self._notified_stock_alerts = loaded
  5108. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5109. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5110. """Write the notified set to its settings row if it changed since it was last read or written."""
  5111. serialized = self._serialize_stock_alerts()
  5112. if serialized == self._stock_alerts_persisted:
  5113. return
  5114. from backend.app.core.db_dialect import upsert_setting
  5115. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5116. await db.commit()
  5117. self._stock_alerts_persisted = serialized
  5118. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5119. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5120. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5121. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5122. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5123. sku_settings = {
  5124. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5125. lead_time_days=row.lead_time_days,
  5126. safety_margin_value=row.safety_margin_value,
  5127. safety_margin_unit=row.safety_margin_unit,
  5128. alerts_snoozed=bool(row.alerts_snoozed),
  5129. )
  5130. for row in sku_rows
  5131. }
  5132. if await self._get_bool_setting(db, "spoolman_enabled"):
  5133. spools = await self._stock_spools_spoolman()
  5134. if spools is None:
  5135. return None
  5136. # Spoolman owns the usage in this mode and Bambuddy's own history
  5137. # table holds nothing for those spools, so the rate is always the
  5138. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  5139. # are local spool ids, and a Spoolman id that happens to match one
  5140. # (left over from before Spoolman was switched on) would borrow an
  5141. # unrelated spool's history.
  5142. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5143. else:
  5144. spools = await self._stock_spools_internal(db)
  5145. history = await self._stock_usage_history(db)
  5146. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5147. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5148. from backend.app.models.spool import Spool
  5149. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  5150. return [
  5151. stock_forecast.StockSpool(
  5152. id=spool.id,
  5153. material=spool.material,
  5154. subtype=spool.subtype,
  5155. brand=spool.brand,
  5156. color_name=spool.color_name,
  5157. label_weight=float(spool.label_weight or 0),
  5158. weight_used=float(spool.weight_used or 0),
  5159. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5160. created_at=spool.created_at,
  5161. )
  5162. for spool in rows
  5163. ]
  5164. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  5165. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5166. rows = (
  5167. await db.execute(
  5168. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5169. .order_by(SpoolUsageHistory.created_at.desc())
  5170. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5171. )
  5172. ).all()
  5173. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5174. for spool_id, created_at, weight_used in rows:
  5175. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5176. # filtered before the limit, so the window matches the forecast panel's.
  5177. if created_at is None or spool_id is None:
  5178. continue
  5179. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5180. return history
  5181. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5182. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5183. ``get_all_spools`` leaves archived spools out unless asked, which is the
  5184. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  5185. is the same mapping the Inventory page (and so the panel) reads.
  5186. """
  5187. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5188. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5189. client = await get_spoolman_client()
  5190. if client is None:
  5191. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5192. return None
  5193. try:
  5194. raw_spools = await client.get_all_spools()
  5195. except SpoolmanUnavailableError as e:
  5196. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5197. return None
  5198. spools: list[stock_forecast.StockSpool] = []
  5199. for raw in raw_spools:
  5200. try:
  5201. mapped = _map_spoolman_spool(raw)
  5202. except ValueError:
  5203. continue
  5204. created_at = None
  5205. if mapped.get("created_at"):
  5206. try:
  5207. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  5208. except ValueError:
  5209. created_at = None
  5210. spools.append(
  5211. stock_forecast.StockSpool(
  5212. id=mapped["id"],
  5213. material=mapped["material"],
  5214. subtype=mapped.get("subtype"),
  5215. brand=mapped.get("brand"),
  5216. color_name=mapped.get("color_name"),
  5217. label_weight=float(mapped.get("label_weight") or 0),
  5218. weight_used=float(mapped.get("weight_used") or 0),
  5219. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5220. created_at=created_at,
  5221. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5222. )
  5223. )
  5224. return spools
  5225. async def _emit_stock_alerts(
  5226. self,
  5227. db: AsyncSession,
  5228. forecasts: stock_forecast.ForecastMap,
  5229. wanted: dict[str, bool],
  5230. ) -> None:
  5231. """Send the notifications for each SKU that has moved into a stock alert condition.
  5232. A SKU in break has also reached its reorder point, so both events apply to
  5233. it: the break event goes to providers that have it on, and the reorder event
  5234. to the providers that have only that one on. A provider with both on gets the
  5235. break and no second message.
  5236. What is remembered per SKU is the condition and which events had a
  5237. subscriber when it was sent. An event with no subscriber is forgotten, so
  5238. switching it on later reports the SKUs already in that condition.
  5239. """
  5240. active_events = {event for event, on in wanted.items() if on}
  5241. for key, (forecast, spool) in forecasts.items():
  5242. kind: str | None = None
  5243. if not forecast.snoozed:
  5244. if forecast.stock_break_alert:
  5245. kind = "break"
  5246. elif forecast.reorder_alert:
  5247. kind = "reorder"
  5248. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5249. events = applicable & active_events
  5250. if not events:
  5251. self._notified_stock_alerts.pop(key, None)
  5252. continue
  5253. previous = self._notified_stock_alerts.get(key)
  5254. told = (previous[1] & active_events) if previous else frozenset()
  5255. # Trimmed to the events this condition can send. That is what makes easing from
  5256. # break back to reorder silent (the reorder event was told with the break) and
  5257. # worsening again news again (the break event is no longer remembered).
  5258. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5259. # Recorded before sending, for the reason _emit_filament_low gives: a
  5260. # provider that is down should lose this alert, not repeat it every hour.
  5261. to_send = events - told
  5262. # Both flags imply a positive rate and so a day count.
  5263. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5264. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5265. color = None if spool.color_name_is_synthesized else spool.color_name
  5266. try:
  5267. if "break" in to_send:
  5268. await notification_service.on_stock_break_alert(
  5269. spool.material,
  5270. spool.brand,
  5271. forecast.remaining_g,
  5272. rate,
  5273. days_left,
  5274. forecast.effective_lead_time_days,
  5275. db,
  5276. subtype=spool.subtype,
  5277. color=color,
  5278. )
  5279. if "reorder" in to_send:
  5280. await notification_service.on_stock_reorder_alert(
  5281. spool.material,
  5282. spool.brand,
  5283. forecast.remaining_g,
  5284. rate,
  5285. days_left,
  5286. db,
  5287. subtype=spool.subtype,
  5288. color=color,
  5289. skip_break_subscribers=kind == "break",
  5290. )
  5291. except Exception as e:
  5292. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5293. # A SKU with no spools left is no longer alerting.
  5294. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5295. del self._notified_stock_alerts[key]
  5296. @staticmethod
  5297. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5298. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5299. from backend.app.core.auth import is_auth_enabled
  5300. if user_id is None or not await is_auth_enabled(db):
  5301. return ALL_PRINTERS
  5302. return await resolve_user_id_printer_scope(db, user_id)
  5303. async def _model_job_printer_ids(
  5304. self,
  5305. db: AsyncSession,
  5306. item: PrintQueueItem,
  5307. scope: PrinterScope,
  5308. cache: dict[tuple[str, str | None, int | None], set[int]],
  5309. ) -> set[int]:
  5310. """Every printer an "Any <model>" job could land on: the active printers
  5311. of each of its candidate models, in its location, that its creator may use.
  5312. ``cache`` holds one lookup per model, location and creator for the pass,
  5313. so a long queue of model jobs does not query once per job."""
  5314. printer_ids: set[int] = set()
  5315. for candidate in _candidates_for(item):
  5316. if not candidate.target_model:
  5317. continue
  5318. key = (candidate.target_model, item.target_location, item.created_by_id)
  5319. if key not in cache:
  5320. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5321. cache[key] = {printer.id for printer in printers}
  5322. printer_ids |= cache[key]
  5323. return printer_ids
  5324. async def _check_auto_drying(
  5325. self,
  5326. db: AsyncSession,
  5327. queue_items: list[PrintQueueItem],
  5328. dispatching_printers: set[int],
  5329. ):
  5330. """Start drying on idle printers based on humidity.
  5331. Three modes (can all be enabled independently):
  5332. - queue_drying_enabled: Dry between scheduled queue prints
  5333. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5334. - print_drying_enabled: Also evaluate printers that are currently printing,
  5335. when model+firmware supports "Print While Drying" (gated by
  5336. supports_drying_while_printing). Drying temperature is capped at
  5337. max(40, preset_temp - 5) to protect spools mid-print.
  5338. """
  5339. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5340. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5341. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5342. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5343. # The wait belongs to ambient drying: the settings UI only shows it while
  5344. # ambient drying is on, so a value left behind when ambient is turned off
  5345. # must not keep delaying the one path that still reaches the wait gate
  5346. # without it (a mid-print start under print_drying).
  5347. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5348. # Clear every streak as soon as the wait is inactive. An early return (or
  5349. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5350. # a quick toggle-on inherit an old streak.
  5351. if not sustained_wait_active:
  5352. self._auto_dry_above.clear()
  5353. if not queue_drying_enabled and not ambient_drying_enabled:
  5354. # Stop active drying on all printers if both features disabled
  5355. if self._drying_in_progress:
  5356. for pid in list(self._drying_in_progress):
  5357. if pid in self._scheduled_drying_printer_ids:
  5358. continue
  5359. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5360. await self._stop_drying(pid)
  5361. return
  5362. # Update drying state from printer status (handles backend restart)
  5363. self._sync_drying_state()
  5364. # Find printers with scheduled items (for queue drying mode)
  5365. # An "Any <model>" job counts for every printer it could land on.
  5366. printers_with_scheduled: set[int] = set()
  5367. # Printers with a job that could start now: the ones block mode keeps
  5368. # a new cycle off. A job waiting for its start time is what queue
  5369. # drying dries ahead of.
  5370. printers_with_ready_items: set[int] = set()
  5371. now_utc = datetime.now(timezone.utc)
  5372. creator_scopes: dict[int | None, PrinterScope] = {}
  5373. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5374. for item in queue_items:
  5375. if item.printer_id:
  5376. item_printers = {item.printer_id}
  5377. elif item.target_model or item.variants:
  5378. if item.created_by_id not in creator_scopes:
  5379. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5380. item_printers = await self._model_job_printer_ids(
  5381. db, item, creator_scopes[item.created_by_id], model_printers
  5382. )
  5383. else:
  5384. continue
  5385. if item.scheduled_time and not item.manual_start:
  5386. printers_with_scheduled |= item_printers
  5387. sched = item.scheduled_time
  5388. if sched is not None and sched.tzinfo is None:
  5389. sched = sched.replace(tzinfo=timezone.utc)
  5390. if sched is None or sched <= now_utc:
  5391. printers_with_ready_items |= item_printers
  5392. # If only queue mode is on and no printers have scheduled items, stop drying
  5393. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5394. # may still be eligible for mid-print drying regardless of queue state).
  5395. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5396. for pid in list(self._drying_in_progress):
  5397. if pid in self._scheduled_drying_printer_ids:
  5398. continue
  5399. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5400. await self._stop_drying(pid)
  5401. return
  5402. # Get humidity threshold (global fallback)
  5403. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5404. setting = result.scalar_one_or_none()
  5405. global_humidity_threshold = int(setting.value) if setting else 60
  5406. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5407. # to the global threshold for every AMS unit.
  5408. per_type_thresholds = await self._get_humidity_thresholds(db)
  5409. # Get drying presets
  5410. presets = await self._get_drying_presets(db)
  5411. # Determine if drying should be skipped for printers with pending items
  5412. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5413. # Get all active printers
  5414. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5415. for printer in all_printers.scalars():
  5416. pid = printer.id
  5417. # Resolve model+firmware up front — needed to decide whether this printer
  5418. # qualifies for mid-print drying (busy printer on capable hardware).
  5419. state = printer_manager.get_status(pid)
  5420. if not state:
  5421. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5422. continue
  5423. model = printer_manager.get_model(pid)
  5424. firmware = state.firmware_version
  5425. # "Mid-print" has to mean the printer is actually printing (#2801).
  5426. # It used to be inferred from the dispatch set, which also holds
  5427. # printers that merely could not be dispatched to -- so a printer
  5428. # sitting in FINISH behind an unacknowledged plate was treated as
  5429. # printing, had its drying temperature capped by the mid-print
  5430. # spool protection, and was logged as (mid-print) while idle.
  5431. is_printing = state.state in _ACTIVE_PRINT_STATES
  5432. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5433. # A printer whose print is running or imminent is left alone unless
  5434. # it can dry through it. `dispatching_printers` is deliberately the
  5435. # narrow set: running, held post-dispatch, or mid-upload.
  5436. if (is_printing or pid in dispatching_printers) and not mid_print:
  5437. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5438. continue
  5439. if not mid_print:
  5440. # In queue-only mode, only dry printers that have scheduled prints
  5441. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5442. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5443. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5444. await self._stop_drying(pid)
  5445. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5446. continue
  5447. # When block mode is on, don't START new drying on printers with
  5448. # a job that could start now: the cycle would hold it. One
  5449. # scheduled for later may pre-dry; if the cycle is still running
  5450. # at its time, the hold applies then. Already-drying printers go
  5451. # through so humidity auto-stop logic still runs.
  5452. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5453. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5454. continue
  5455. if not printer_manager.is_connected(pid):
  5456. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5457. continue
  5458. # Plate-clear is deliberately ignored here (#2801). It answers
  5459. # "is the bed ready for the next job", which says nothing about
  5460. # whether the AMS may heat -- and the gap between a finished print
  5461. # and the acknowledgment is exactly when drying is most useful,
  5462. # because the printer is free and nobody is waiting on it. Leaving
  5463. # the plate unacknowledged is also how people hold the queue by
  5464. # hand, and that hold should not cost them their drying.
  5465. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5466. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5467. continue
  5468. # Check drying capability. For mid-print path, supports_drying_while_printing
  5469. # was already verified when computing mid_print above.
  5470. if not mid_print and not supports_drying(model, firmware):
  5471. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5472. continue
  5473. # Check each AMS unit from raw_data
  5474. ams_list = state.raw_data.get("ams", [])
  5475. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5476. for ams_data in ams_list:
  5477. module_type = str(ams_data.get("module_type") or "")
  5478. ams_id = int(ams_data.get("id", 0))
  5479. # Only n3f/n3s support drying
  5480. if module_type not in ("n3f", "n3s"):
  5481. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5482. continue
  5483. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5484. # Most-restrictive of all loaded tray types; falls back to the
  5485. # global threshold when no overrides are configured.
  5486. trays = ams_data.get("tray", []) or []
  5487. humidity_threshold = self.resolve_humidity_threshold(
  5488. trays, per_type_thresholds, global_humidity_threshold
  5489. )
  5490. dry_time = int(ams_data.get("dry_time") or 0)
  5491. # Read humidity as a percentage. The 1-5 index is never
  5492. # substituted: it is inverted, and being unable to exceed any
  5493. # threshold it would read as "dry" forever (#3140). ``None``
  5494. # already means "skip this unit" everywhere below.
  5495. humidity_pct = ams_humidity_percent(ams_data)
  5496. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5497. unit_key = (pid, ams_id)
  5498. unit_state = self._auto_dry_units.get(unit_key)
  5499. # Already drying — let it run to its configured duration (#1892).
  5500. #
  5501. # We deliberately do NOT stop drying from a humidity re-check here.
  5502. # Relative humidity drops steeply in heated air, so the AMS sensor
  5503. # reads ~15-20% within minutes of the dryer starting even while the
  5504. # filament is still saturated. A humidity-based early-stop therefore
  5505. # always fires at the minimum-time floor, truncating both user-started
  5506. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5507. # The firmware stops when the configured duration elapses; scheduling
  5508. # stops (print takes priority, queue no longer needs drying) are
  5509. # handled separately via _stop_drying().
  5510. if dry_time > 0:
  5511. if pid not in self._drying_in_progress:
  5512. # Drying we didn't start (manual or from before restart) —
  5513. # track it so scheduling stops still apply; never auto-stop it.
  5514. self._drying_in_progress[pid] = time.monotonic()
  5515. if unit_state is not None:
  5516. unit_state["running"] = True
  5517. logger.debug(
  5518. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5519. pid,
  5520. ams_id,
  5521. dry_time,
  5522. humidity,
  5523. )
  5524. continue
  5525. # Nothing is drying. Close out a cycle we armed ourselves and
  5526. # judge whether it achieved anything (#2770).
  5527. #
  5528. # "Achieved anything" is measured against the LOWEST reading any
  5529. # cycle on this unit has ended at, not against the threshold and
  5530. # not against the previous cycle. A spool that is genuinely wet
  5531. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5532. # allowed to keep going for as long as it is still coming down,
  5533. # however far it still is from the threshold. What must not
  5534. # continue is a cycle that ends exactly where the last one did,
  5535. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5536. # Comparing against the running minimum rather than the previous
  5537. # end is what stops a sensor oscillating by one point between two
  5538. # values from reading as progress every other cycle.
  5539. if unit_state is not None and unit_state.pop("running", False):
  5540. unit_state["ended_at"] = time.monotonic()
  5541. # The streak that armed this cycle is spent; the next one
  5542. # starts fresh (and accumulates through the re-arm cooldown
  5543. # below, so the wait overlaps the cooldown, never stacks on
  5544. # top of it).
  5545. self._auto_dry_above.pop(unit_key, None)
  5546. if humidity is not None and humidity > humidity_threshold:
  5547. best = unit_state.get("best_end_humidity")
  5548. if isinstance(best, int) and humidity < best:
  5549. # Still coming down. Keep going, however far the
  5550. # threshold still is.
  5551. unproductive = 0
  5552. else:
  5553. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5554. if not isinstance(best, int) or humidity < best:
  5555. unit_state["best_end_humidity"] = humidity
  5556. unit_state["unproductive"] = unproductive
  5557. logger.info(
  5558. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5559. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5560. pid,
  5561. ams_id,
  5562. humidity,
  5563. humidity_threshold,
  5564. unit_state.get("best_end_humidity"),
  5565. unproductive,
  5566. )
  5567. # A cycle that ended at or below the threshold needs no
  5568. # counter reset here: the branch below drops the whole entry.
  5569. # Humidity below threshold — no need to start drying. This is
  5570. # also the only thing that lifts a suspension: the reading we
  5571. # gave up on has come down, so auto-drying works again and the
  5572. # unit goes back to having no history at all.
  5573. if humidity is None or humidity <= humidity_threshold:
  5574. if unit_state is not None and unit_state.get("suspended"):
  5575. logger.info(
  5576. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5577. "threshold, resuming automatic drying",
  5578. pid,
  5579. ams_id,
  5580. humidity,
  5581. humidity_threshold,
  5582. )
  5583. # Clear the judgement, keep the clock (#2801). Dropping the
  5584. # whole entry also dropped `ended_at`, and with it the
  5585. # 30-minute cooldown -- so a reading that dips to the
  5586. # threshold as the AMS cools and comes back above it once
  5587. # warm wiped its own history and re-armed immediately. That
  5588. # oscillation is the very thing #2770's cooldown exists to
  5589. # ride out, and it is worst at exactly the margin that makes
  5590. # a unit dry repeatedly: a point or two above the threshold.
  5591. if unit_state is not None:
  5592. unit_state.pop("suspended", None)
  5593. unit_state.pop("unproductive", None)
  5594. unit_state.pop("best_end_humidity", None)
  5595. # A real below-threshold reading ends any sustained-wait
  5596. # streak (#2518) -- "continuously above" means exactly that.
  5597. # An absent reading (humidity is None) is no-information and
  5598. # leaves the streak alone; the observation-gap guard handles
  5599. # a prolonged sensor silence.
  5600. if humidity is not None:
  5601. _above = self._auto_dry_above.pop(unit_key, None)
  5602. if _above is not None and sustained_wait_active:
  5603. logger.info(
  5604. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5605. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5606. pid,
  5607. ams_id,
  5608. humidity,
  5609. time.monotonic() - _above["since"],
  5610. sustained_minutes,
  5611. humidity_threshold,
  5612. )
  5613. logger.debug(
  5614. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5615. pid,
  5616. ams_id,
  5617. humidity,
  5618. humidity_threshold,
  5619. )
  5620. continue
  5621. # Sustained-humidity streak (#2518): updated on every pass that
  5622. # observes the reading above the threshold, BEFORE the
  5623. # suspension/cooldown gates below -- a suspended or cooling-down
  5624. # unit still accumulates streak time, so the wait overlaps those
  5625. # gates instead of stacking after them. Inert when the feature
  5626. # is off: no entries are written, and an entry left over from a
  5627. # toggle-off is dropped so it cannot seed a stale streak later.
  5628. if sustained_wait_active:
  5629. _now = time.monotonic()
  5630. # Four missed scheduler passes, floored: a single slow pass
  5631. # must not void a streak, but the ceiling has to scale with
  5632. # the cadence or a slow loop silently restarts every streak.
  5633. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5634. _above = self._auto_dry_above.get(unit_key)
  5635. if _above is None:
  5636. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5637. elif _now - _above["last"] > _gap_ceiling:
  5638. # Restart, and say so at the same level as the dip
  5639. # reset: a silent restart voids the streak invisibly,
  5640. # and a user who set a long wait and never gets a dry
  5641. # has no way to see why.
  5642. logger.info(
  5643. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5644. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5645. pid,
  5646. ams_id,
  5647. _now - _above["last"],
  5648. _gap_ceiling,
  5649. sustained_minutes,
  5650. )
  5651. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5652. else:
  5653. _above["last"] = _now
  5654. else:
  5655. self._auto_dry_above.pop(unit_key, None)
  5656. if unit_state is not None:
  5657. if unit_state.get("suspended"):
  5658. logger.debug(
  5659. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5660. "above the %d%% threshold",
  5661. pid,
  5662. ams_id,
  5663. int(unit_state.get("unproductive", 0)),
  5664. humidity_threshold,
  5665. )
  5666. continue
  5667. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5668. unit_state["suspended"] = True
  5669. logger.warning(
  5670. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5671. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5672. "higher while it is warm, so a threshold in that range can never be reached and "
  5673. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5674. pid,
  5675. ams_id,
  5676. int(unit_state.get("unproductive", 0)),
  5677. humidity,
  5678. humidity_threshold,
  5679. )
  5680. await self._notify_auto_drying_suspended(
  5681. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5682. )
  5683. continue
  5684. ended_at = unit_state.get("ended_at")
  5685. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5686. logger.debug(
  5687. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5688. "cycle before the humidity reading is worth acting on",
  5689. pid,
  5690. ams_id,
  5691. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5692. )
  5693. continue
  5694. # Check cannot-dry reasons (power constraints etc.). Sits
  5695. # ahead of the sustained wait so a unit the firmware refuses
  5696. # to dry never logs a wait it was never going to cash in.
  5697. sf_reasons = ams_data.get("dry_sf_reason", [])
  5698. if sf_reasons:
  5699. logger.debug(
  5700. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5701. pid,
  5702. ams_id,
  5703. sf_reasons,
  5704. )
  5705. continue
  5706. # Sustained-humidity wait (#2518): ambient-triggered starts
  5707. # wait; only a printer with a scheduled queue item pending
  5708. # keeps the instant behavior, because that drying has a real
  5709. # deadline. Mid-print is deliberately NOT exempt while ambient
  5710. # drying is on: a humidity start on a printer that happens to be
  5711. # printing is as vulnerable to a lid-open spike as one on an idle
  5712. # printer (proven live: a 2-point threshold crossing mid-print
  5713. # bought a parked 12h command). Inactive when ambient drying is
  5714. # off: print_drying then still starts mid-print cycles on its own
  5715. # (#1816, "regardless of queue state"), and those stay instant.
  5716. if sustained_wait_active and pid not in printers_with_scheduled:
  5717. _above = self._auto_dry_above.get(unit_key)
  5718. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5719. if _waited < sustained_minutes * 60:
  5720. logger.debug(
  5721. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5722. "threshold for %.0fs of the required %dm",
  5723. pid,
  5724. ams_id,
  5725. humidity,
  5726. humidity_threshold,
  5727. _waited,
  5728. sustained_minutes,
  5729. )
  5730. continue
  5731. # Get conservative drying params for mixed filaments
  5732. params = self._get_conservative_drying_params(trays, module_type, presets)
  5733. if not params:
  5734. logger.debug(
  5735. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5736. )
  5737. continue
  5738. temp, duration_hours, filament_type = params
  5739. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5740. # "drying temperature must not exceed the filament's softening temperature"
  5741. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5742. # ineffective and firmware will reject anyway.
  5743. if mid_print:
  5744. temp = max(40, temp - 5)
  5745. # Start drying
  5746. logger.info(
  5747. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5748. "starting %s drying at %d°C for %dh%s",
  5749. pid,
  5750. ams_id,
  5751. humidity,
  5752. humidity_threshold,
  5753. filament_type,
  5754. temp,
  5755. duration_hours,
  5756. " (mid-print)" if mid_print else "",
  5757. )
  5758. success = printer_manager.send_drying_command(
  5759. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5760. )
  5761. if success:
  5762. self._drying_in_progress[pid] = time.monotonic()
  5763. armed = self._auto_dry_units.setdefault(
  5764. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5765. )
  5766. armed["running"] = True
  5767. async def _notify_auto_drying_suspended(
  5768. self,
  5769. db: AsyncSession,
  5770. printer: Printer,
  5771. ams_id: int,
  5772. humidity: int,
  5773. threshold: int,
  5774. cycles: int,
  5775. ) -> None:
  5776. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5777. Fires once per suspension — the caller sets ``suspended`` before calling
  5778. and every later pass short-circuits on it — because the whole point is
  5779. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5780. building needs that to reach them, and the hourly humidity alarm they
  5781. are already getting says the opposite of what happened here.
  5782. Never raises: a notification provider being down must not stop the
  5783. suspension itself from taking effect.
  5784. """
  5785. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5786. try:
  5787. await notification_service.on_ams_drying_suspended(
  5788. printer.id,
  5789. printer.name,
  5790. ams_label,
  5791. float(humidity),
  5792. float(threshold),
  5793. cycles,
  5794. db,
  5795. )
  5796. except Exception as e:
  5797. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5798. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5799. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5800. The unproductive-cycle counter exists to notice that *drying* is not
  5801. moving the humidity reading. A cycle that ended because somebody sent a
  5802. stop says nothing about that — it was cut short before it had a chance —
  5803. so counting it would suspend auto-drying for a reason that has nothing to
  5804. do with the loop the counter is there to break.
  5805. Two callers, both of them a stop Bambuddy is responsible for: the
  5806. print-takes-priority stop below, and the manual Stop button. Left
  5807. uncalled, an install that dries between queue jobs would suspend its own
  5808. auto-drying after two prints interrupted a dry — exactly the install
  5809. queue-drying exists for.
  5810. The rest of the unit's history is kept: the cooldown before re-arming
  5811. still applies, and an earlier count still stands.
  5812. """
  5813. state = self._auto_dry_units.get((printer_id, ams_id))
  5814. if state is not None:
  5815. state.pop("running", None)
  5816. state["ended_at"] = time.monotonic()
  5817. # A stopped cycle spends the streak that armed it, same as a completed
  5818. # one (#2518).
  5819. self._auto_dry_above.pop((printer_id, ams_id), None)
  5820. def _sync_drying_state(self):
  5821. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5822. One direction only: it prunes, it never adds. A printer drying without an
  5823. entry here — because the user started the cycle from Studio, the printer's
  5824. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5825. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5826. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5827. That is deliberate for now rather than an oversight: populating this from
  5828. telemetry would hand the scheduler authority to stop drying a user started
  5829. by hand. It also means the backend-restart case this used to claim to
  5830. handle is not handled.
  5831. """
  5832. to_remove = []
  5833. for pid in self._drying_in_progress:
  5834. state = printer_manager.get_status(pid)
  5835. if not state:
  5836. to_remove.append(pid)
  5837. continue
  5838. # Check if any AMS unit is still drying
  5839. ams_list = state.raw_data.get("ams", [])
  5840. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5841. if not any_drying:
  5842. to_remove.append(pid)
  5843. for pid in to_remove:
  5844. self._drying_in_progress.pop(pid, None)
  5845. # A printer that has gone away entirely takes its per-AMS auto-drying
  5846. # history with it (#2770), so a printer deleted and re-added does not
  5847. # inherit a suspension it never earned.
  5848. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5849. self._auto_dry_units.pop(key, None)
  5850. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5851. # printer starts a fresh wait, and vanished printers do not leak
  5852. # entries.
  5853. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5854. self._auto_dry_above.pop(key, None)
  5855. @staticmethod
  5856. def _drying_is_only_parked(printer_id: int) -> bool:
  5857. """True when every AMS unit with a drying timer on this printer is parked.
  5858. A parked timer (#2896: the command was taken but the countdown never
  5859. runs) does not end on its own, so nothing may wait on it. False when no
  5860. unit reports a timer yet -- a command just sent that the firmware has not
  5861. reported back is real drying about to begin.
  5862. """
  5863. state = printer_manager.get_status(printer_id)
  5864. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5865. timed = []
  5866. for unit in units:
  5867. try:
  5868. if int(unit.get("dry_time") or 0) > 0:
  5869. timed.append(unit)
  5870. except (TypeError, ValueError):
  5871. continue
  5872. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5873. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5874. """True when a running cycle can be left alone while the next print runs.
  5875. Some hardware dries happily through a print and #2758 settled that we
  5876. should not tear those cycles down: the X2D there was refusing to
  5877. *start* a job, which is a different problem, and stopping drying before
  5878. every dispatch would throw away cycles the printer was content to run.
  5879. Where the model cannot do it, or the user has not enabled it, the print
  5880. takes priority and the cycle stops -- which is what the queue_drying_block
  5881. setting has always promised in its off position.
  5882. """
  5883. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5884. return False
  5885. status = printer_manager.get_status(printer_id)
  5886. return supports_drying_while_printing(
  5887. printer_manager.get_model(printer_id),
  5888. status.firmware_version if status else None,
  5889. )
  5890. async def _stop_drying(self, printer_id: int):
  5891. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5892. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5893. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5894. enough to kill a cycle the user had started by hand on a *different*
  5895. unit of the same printer (#2801). That contradicted the contract
  5896. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5897. only knows about cycles Bambuddy began, so the action must not reach
  5898. past them either.
  5899. """
  5900. state = printer_manager.get_status(printer_id)
  5901. if not state:
  5902. self._drying_in_progress.pop(printer_id, None)
  5903. return
  5904. ams_list = state.raw_data.get("ams", [])
  5905. for ams_data in ams_list:
  5906. dry_time = int(ams_data.get("dry_time") or 0)
  5907. if dry_time > 0:
  5908. ams_id = int(ams_data.get("id", 0))
  5909. if (printer_id, ams_id) not in self._auto_dry_units:
  5910. logger.debug(
  5911. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5912. printer_id,
  5913. ams_id,
  5914. )
  5915. continue
  5916. logger.info(
  5917. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5918. printer_id,
  5919. ams_id,
  5920. )
  5921. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5922. self.forget_auto_dry_cycle(printer_id, ams_id)
  5923. self._drying_in_progress.pop(printer_id, None)
  5924. # Scheduled manual drying (#2638) -----------------------------------
  5925. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5926. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5927. async def _check_scheduled_dryings(self, db: AsyncSession):
  5928. """Dispatch due scheduled drying runs and track running ones."""
  5929. now = utcnow_naive()
  5930. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5931. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5932. since_prune = time.monotonic()
  5933. if (
  5934. self._last_scheduled_drying_prune is None
  5935. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5936. ):
  5937. self._last_scheduled_drying_prune = since_prune
  5938. await db.execute(
  5939. delete(ScheduledDrying).where(
  5940. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5941. ScheduledDrying.completed_at.is_not(None),
  5942. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5943. )
  5944. )
  5945. # Same order as the list route: with two rows due on one printer the
  5946. # earliest scheduled wins rather than whatever the DB hands back first.
  5947. result = await db.execute(
  5948. select(ScheduledDrying)
  5949. .where(ScheduledDrying.status.in_(("pending", "running")))
  5950. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5951. )
  5952. rows = list(result.scalars().all())
  5953. # Rebuild from the DB every tick so route-side cancels and completions
  5954. # show up. Auto-drying's stop-all branches check this set before
  5955. # stopping anything (#2638).
  5956. # Kept from the previous pass so a run that ended between passes — a
  5957. # cancel through the route, say — can still be released below.
  5958. previously_running = self._scheduled_drying_printer_ids
  5959. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5960. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5961. # Model and firmware come from the printer row, not the live state.
  5962. printer_ids = {row.printer_id for row in rows}
  5963. printers_by_id: dict[int, Printer] = {}
  5964. if printer_ids:
  5965. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5966. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5967. for row in rows:
  5968. if row.status == "running":
  5969. self._update_running_scheduled_drying(row, now)
  5970. continue
  5971. if row.start_after is not None and row.start_after > now:
  5972. continue
  5973. state = printer_manager.get_status(row.printer_id)
  5974. if not state:
  5975. row.waiting_reason = "printer_offline"
  5976. continue
  5977. # Same preflight the immediate endpoint runs. Without it the publish
  5978. # succeeds, the row goes to running, the printer ignores the command
  5979. # and the run silently cancels itself after the grace window.
  5980. printer = printers_by_id.get(row.printer_id)
  5981. unsupported = drying_preflight.check_drying_supported(
  5982. printer.model if printer else None, state.firmware_version
  5983. )
  5984. if unsupported:
  5985. row.status = "failed"
  5986. row.error_message = unsupported
  5987. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5988. row.completed_at = now
  5989. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5990. continue
  5991. if (
  5992. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5993. ) or row.printer_id in running_printer_ids:
  5994. row.waiting_reason = "already_drying"
  5995. continue
  5996. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5997. row.waiting_reason = "printer_busy"
  5998. continue
  5999. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6000. if target is None:
  6001. row.waiting_reason = "ams_not_found"
  6002. continue
  6003. blocking = drying_preflight.blocking_reason_codes(target)
  6004. if blocking:
  6005. # Keep the power case distinct; it needs the user to act, so the
  6006. # card can say so instead of waiting silently.
  6007. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6008. continue
  6009. filament = drying_preflight.resolve_filament(target, row.filament)
  6010. logger.info(
  6011. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6012. row.id,
  6013. row.printer_id,
  6014. row.ams_id,
  6015. row.temp,
  6016. row.duration_hours,
  6017. )
  6018. success = printer_manager.send_drying_command(
  6019. row.printer_id,
  6020. row.ams_id,
  6021. row.temp,
  6022. row.duration_hours,
  6023. mode=1,
  6024. filament=filament,
  6025. rotate_tray=row.rotate_tray,
  6026. )
  6027. if success:
  6028. row.status = "running"
  6029. row.started_at = now
  6030. row.waiting_reason = None
  6031. row.filament = filament
  6032. self._drying_in_progress[row.printer_id] = time.monotonic()
  6033. self._scheduled_drying_printer_ids.add(row.printer_id)
  6034. running_printer_ids.add(row.printer_id)
  6035. else:
  6036. row.waiting_reason = "printer_offline"
  6037. # Release the printers whose run has ended. `_drying_in_progress` is
  6038. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6039. # but that call sits behind the auto-drying enabled check, and this
  6040. # method is the one writer that runs whether auto-drying is on or not.
  6041. # With it off, nothing would ever drop the entry short of a print being
  6042. # dispatched to the same printer, so the next scheduled run would wait
  6043. # on "already_drying" forever and `queue_drying_block` would hold the
  6044. # printer's prints too. Covers a run that ended during this pass and one
  6045. # cancelled through the route between passes.
  6046. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6047. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6048. self._drying_in_progress.pop(printer_id, None)
  6049. await db.commit()
  6050. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6051. """Detect completion or interruption of a running scheduled drying.
  6052. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6053. drying. Within the grace window after start we ignore dry_time==0
  6054. (the status lags the command). After that, dry_time==0 near the end
  6055. of the configured duration means completed. Much earlier means the
  6056. run was stopped: re-queue it if a print preempted the dryer, but a
  6057. stop while the printer is idle was deliberate, so cancel the row
  6058. rather than restart drying the user just stopped.
  6059. """
  6060. if row.started_at is None:
  6061. row.started_at = now
  6062. return
  6063. elapsed = (now - row.started_at).total_seconds()
  6064. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6065. return
  6066. state = printer_manager.get_status(row.printer_id)
  6067. if not state:
  6068. return # offline mid-dry; resolve when it reconnects
  6069. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6070. # throw on a malformed id would cost the whole pass including print
  6071. # dispatch, every tick.
  6072. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6073. try:
  6074. dry_time = int(target.get("dry_time") or 0) if target else 0
  6075. except (TypeError, ValueError):
  6076. dry_time = 0
  6077. if dry_time > 0 and is_countdown_parked(target):
  6078. # The printer took the command but the countdown is not running
  6079. # (#2896) and will never reach 0, so the run would stay "running"
  6080. # forever. A print in progress is the likely cause (the power budget
  6081. # is spent), so re-queue it like any interruption; the next start
  6082. # waits for the printer to be idle. Parked on an idle printer is a
  6083. # refusal, not something a retry fixes. The timer itself is left on
  6084. # the printer: it may yet start once power frees up.
  6085. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6086. logger.info(
  6087. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6088. row.id,
  6089. row.ams_id,
  6090. )
  6091. row.status = "pending"
  6092. row.started_at = None
  6093. row.waiting_reason = "interrupted"
  6094. else:
  6095. logger.warning(
  6096. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6097. row.id,
  6098. row.ams_id,
  6099. )
  6100. row.status = "failed"
  6101. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6102. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6103. row.completed_at = now
  6104. return
  6105. if dry_time > 0:
  6106. return
  6107. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6108. row.status = "completed"
  6109. row.completed_at = now
  6110. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6111. row.status = "pending"
  6112. row.started_at = None
  6113. row.waiting_reason = "interrupted"
  6114. else:
  6115. row.status = "cancelled"
  6116. row.completed_at = now
  6117. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6118. """Get all smart plugs associated with a printer."""
  6119. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6120. return list(result.scalars().all())
  6121. @staticmethod
  6122. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6123. """Pick the plug to power-cycle a printer back online with (#2629).
  6124. Only a plug flagged ``controls_printer_power`` can actually bring the
  6125. printer back; waiting for a boot on an accessory (filter fan, lights)
  6126. just burns the power-on timeout and fails the dispatch. Falls back to
  6127. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6128. Callers must pass a non-empty list.
  6129. """
  6130. for plug in auto_on_plugs:
  6131. if plug.controls_printer_power:
  6132. return plug
  6133. return auto_on_plugs[0]
  6134. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6135. # chamber-temperature recommendations BambuStudio ships for the matching
  6136. # filament profile; users can override via Settings → Workflow → Preheat
  6137. # card. "default" applies when a loaded tray's normalised type isn't in
  6138. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6139. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6140. "PLA": 0,
  6141. "PETG": 0,
  6142. "PETG-CF": 40,
  6143. "ABS": 45,
  6144. "ASA": 45,
  6145. "PA": 50,
  6146. "PA-CF": 55,
  6147. "PC": 50,
  6148. "PC-FR": 50,
  6149. "TPU": 0,
  6150. "PVA": 0,
  6151. "default": 0,
  6152. }
  6153. @classmethod
  6154. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6155. """The bundled map under the same key casing a parsed one gets.
  6156. The constant is declared with a lowercase ``default`` because that is
  6157. the key the Settings editor writes and displays. Every read of the map
  6158. happens after ``str(key).upper()``, so handing the constant back as
  6159. declared broke the contract the parser documents: an install that had
  6160. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6161. and the resolution loop's fallback silently found nothing. It read the
  6162. right number only because the bundled default happens to be 0 -- change
  6163. that constant and every unconfigured install would keep preheating to
  6164. zero with no way to tell why.
  6165. """
  6166. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6167. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6168. """Parse the user-configured filament→chamber-target map, falling back
  6169. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6170. are uppercased and the 'default' fallback is always present in the
  6171. returned dict so the resolution loop can index it unconditionally."""
  6172. raw = await self._get_setting(db, "preheat_filament_targets")
  6173. if not raw:
  6174. return self._bundled_preheat_targets()
  6175. try:
  6176. parsed = json.loads(raw)
  6177. if not isinstance(parsed, dict):
  6178. raise ValueError("not an object")
  6179. except (json.JSONDecodeError, ValueError) as exc:
  6180. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6181. return self._bundled_preheat_targets()
  6182. # Coerce values to int; drop unparseable rows so a stray string
  6183. # doesn't crash the loop.
  6184. out: dict[str, int] = {}
  6185. for key, value in parsed.items():
  6186. try:
  6187. out[str(key).upper()] = int(value)
  6188. except (TypeError, ValueError):
  6189. continue
  6190. if "DEFAULT" not in out:
  6191. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6192. return out
  6193. @staticmethod
  6194. def _normalize_filament_type(tray_type: str) -> str:
  6195. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6196. existing drying-preset normalisation (split-at-space, upper-case) so
  6197. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6198. "PA-CF" (no space to split on).
  6199. This is the first stage of ``_resolve_filament_key``, which goes on to
  6200. drop the suffix and consult the alias map; on its own it only decides
  6201. what the tray is called, not which row answers for it.
  6202. Indexing the split rather than testing the input: a tray_type of spaces
  6203. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6204. it through to an IndexError.
  6205. """
  6206. words = (tray_type or "").split()
  6207. return words[0].upper() if words else ""
  6208. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6209. """Per-filament chamber target for one tray's reported type, or 0 when
  6210. the tray is empty / RFID-less and reports no type at all.
  6211. A filled or foamed variant wants its base material's chamber when the
  6212. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6213. not the 0 an unknown type falls to. The specific type is still tried
  6214. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6215. (#2902).
  6216. That lookup is now the shared one, which adds the polyamide aliases on
  6217. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6218. too, rather than the catch-all it was landing on (#3067).
  6219. """
  6220. if not self._normalize_filament_type(tray_type or ""):
  6221. return 0
  6222. key = self._resolve_filament_key(tray_type, targets)
  6223. if key is not None:
  6224. return targets[key]
  6225. # A type the map does not list at all, which is not the same as a tray
  6226. # with nothing in it -- that already returned 0 above.
  6227. return targets.get("DEFAULT", 0)
  6228. def _derive_chamber_target(
  6229. self,
  6230. printer: Printer,
  6231. targets: dict[str, int],
  6232. item: PrintQueueItem | None = None,
  6233. ) -> int:
  6234. """Chamber target for the trays this print actually loads: the max of
  6235. their per-filament targets. Returns 0 when there is nothing to read (no
  6236. status, no AMS telemetry — e.g. external-spool prints) or when every
  6237. tray considered maps to 0, and the chamber phase then short-circuits in
  6238. the main loop.
  6239. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6240. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6241. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6242. plus soak burned ahead of each upload, on a printer whose chamber never
  6243. reaches the target anyway (#2886). An item with no usable mapping falls
  6244. back to scanning every loaded tray: that is the only signal left, and
  6245. narrowing to nothing would skip preheat on prints that genuinely need
  6246. it.
  6247. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6248. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6249. less slots have empty `tray_type` and contribute nothing. The external
  6250. spool is consulted only when the mapping names it (>= 254); it stays
  6251. out of the unnarrowed scan, so an item without a mapping derives from
  6252. the AMS alone exactly as before.
  6253. """
  6254. state = printer_manager.get_status(printer.id)
  6255. if state is None:
  6256. return 0
  6257. raw_data = state.raw_data or {}
  6258. used = _used_global_tray_ids(item)
  6259. ams_list = raw_data.get("ams")
  6260. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6261. if isinstance(ams_list, dict):
  6262. ams_list = ams_list.get("ams") or []
  6263. if not isinstance(ams_list, list):
  6264. ams_list = []
  6265. best = 0
  6266. for ams in ams_list:
  6267. if not isinstance(ams, dict):
  6268. continue
  6269. ams_id = _int_or(ams.get("id"), 0)
  6270. for tray in ams.get("tray") or []:
  6271. # A non-dict entry has never been seen from real firmware, but
  6272. # `.get` on one raises, and nothing between here and
  6273. # `_dispatch_one`'s try/finally catches it — the item would be
  6274. # left holding its dispatch claim. Preheat is best-effort by
  6275. # contract, so step over it instead.
  6276. if not isinstance(tray, dict):
  6277. continue
  6278. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6279. continue
  6280. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6281. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6282. for vt in raw_data.get("vt_tray") or []:
  6283. if not isinstance(vt, dict):
  6284. continue
  6285. # `_build_loaded_filaments` addresses external feeds by the id
  6286. # the firmware reports — 255 main, 254 deputy — defaulting to
  6287. # 254 when the field is absent. Same expression here so the two
  6288. # agree on which entry a mapping's 254/255 refers to.
  6289. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6290. continue
  6291. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6292. return best
  6293. def _release_keep_warm(self, pid: int) -> None:
  6294. """Release keep-warm on a printer that left the candidate set.
  6295. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6296. reports the target we set (``entry.held_target``), so a user or
  6297. subsequent print that changed the bed target since is not clobbered.
  6298. Best-effort, never raises.
  6299. The entry is kept, not dropped, when the printer cannot be reached
  6300. right now: a printer that is briefly offline still has a hot bed, and
  6301. holding the entry is what keeps the max-duration timeout applying and
  6302. lets a later tick retry the release. Only a printer that has left the
  6303. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6304. """
  6305. entry = self._keep_warm.get(pid)
  6306. if entry is None:
  6307. return
  6308. state = printer_manager.get_status(pid)
  6309. client = printer_manager.get_client(pid)
  6310. if state is None or client is None:
  6311. logger.debug(
  6312. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6313. pid,
  6314. )
  6315. return
  6316. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6317. if int(cur_bed_target) != entry.held_target:
  6318. # Someone else owns the bed now, so there is nothing of ours to
  6319. # undo and nothing left to track.
  6320. logger.info(
  6321. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6322. pid,
  6323. int(cur_bed_target),
  6324. entry.held_target,
  6325. )
  6326. self._keep_warm.pop(pid, None)
  6327. return
  6328. try:
  6329. client.set_bed_temperature(0)
  6330. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6331. self._keep_warm.pop(pid, None)
  6332. except Exception as exc:
  6333. # Keep the entry so the next tick tries again rather than leaving
  6334. # the bed hot with nothing tracking it.
  6335. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6336. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6337. """Release printers that dropped out of the keep-warm candidate set.
  6338. Called from ``_apply_keep_warm`` on every tick (with the current
  6339. candidate set), and from ``check_queue``'s no-pending-items early
  6340. return (with an empty candidate set) so orphaned holds still get
  6341. released when the queue empties. Also called with an empty candidate
  6342. set when any of the three gate settings toggles off, so a printer
  6343. whose feature was disabled mid-hold gets its bed released.
  6344. Printers being dispatched this tick are excluded from the bed-off
  6345. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6346. transient 0 in between would just churn against preheat. Ownership of
  6347. the hot bed transfers to the preheat rollback pin instead — if the
  6348. dispatch aborts before the print starts (failed upload, cancelled
  6349. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6350. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6351. is the ONLY thing standing between an aborted dispatch and a bed
  6352. left hot with no owner. A successful print start clears the pin and
  6353. the print's own gcode takes over, as usual.
  6354. """
  6355. for _pid in list(self._keep_warm):
  6356. if _pid in active_candidates:
  6357. continue
  6358. if _pid in dispatched:
  6359. handed_over = self._keep_warm.pop(_pid, None)
  6360. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6361. if handed_over is not None:
  6362. self._preheat_pin_bed[_pid] = handed_over.held_target
  6363. continue
  6364. self._release_keep_warm(_pid)
  6365. async def _apply_keep_warm(
  6366. self,
  6367. db: AsyncSession,
  6368. items: list[PrintQueueItem],
  6369. dispatch_ids: list[int] | set[int],
  6370. busy_printers: set[int],
  6371. require_plate_clear: bool,
  6372. ) -> None:
  6373. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6374. When a printer just finished a job (FINISH state) and the next queued
  6375. item needs chamber heating, hold the bed hot so the chamber stays warm
  6376. during the bed-clearing window. The bed is the chamber's heating
  6377. element here, not a print surface — nothing is printing during the
  6378. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6379. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6380. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6381. aftermarket chamber heaters), raised to the item's own parsed
  6382. bed_temperature when that is higher. Items whose archive metadata has
  6383. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6384. get a hold — chamber need is what gates the feature, not metadata.
  6385. Skips entirely for filaments that map to a 0°C chamber target
  6386. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6387. names, so a hot-chamber spool it never touches does not hold the bed of
  6388. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6389. whole unit, as every item was before. Printers being dispatched this
  6390. cycle are excluded:
  6391. ``_preheat_and_soak`` already handles their bed temperature.
  6392. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6393. released to 0 and the entry is latched ``expired=True`` so
  6394. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6395. MQTT: publish is skipped when firmware already has the target.
  6396. The release sweep runs BEFORE the engagement gate so a printer that
  6397. was owned by keep-warm still gets its bed released when any of the
  6398. three gate settings is toggled off mid-hold. The
  6399. ``check_queue`` early-return-when-no-items path also calls
  6400. ``_sweep_keep_warm`` directly to release orphaned holds.
  6401. """
  6402. dispatch_set = set(dispatch_ids)
  6403. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6404. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6405. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6406. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6407. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6408. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6409. # Release sweep first — must run even when gate_open is False so a
  6410. # printer owned by keep-warm when a gate toggles off gets released.
  6411. self._sweep_keep_warm(
  6412. active_candidates=warm_candidates if gate_open else set(),
  6413. dispatched=dispatched_printers,
  6414. )
  6415. if not gate_open:
  6416. return
  6417. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6418. max_hold_seconds = (
  6419. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6420. )
  6421. now_mono = time.monotonic()
  6422. filament_targets: dict[str, int] | None = None
  6423. for pid in warm_candidates:
  6424. entry = self._keep_warm.get(pid)
  6425. # Latched-expired: max-duration timeout already fired for this
  6426. # printer. Skip until the release sweep drops the entry (i.e.
  6427. # until the printer leaves the candidate set).
  6428. if entry is not None and entry.expired:
  6429. continue
  6430. # These two guards sit ahead of the max-duration check below, so an
  6431. # engaged hold only ages out while its printer is still reachable
  6432. # and still in FINISH. That is deliberate rather than a hole: with
  6433. # no status or no client there is no M140 to send anyway, and the
  6434. # elapsed check runs off `entry.started` so it fires on the first
  6435. # tick after the printer comes back. Leaving FINISH means the plate
  6436. # was cleared, which drops the printer out of `warm_candidates` and
  6437. # hands it to `_release_keep_warm` instead. The invariant worth
  6438. # preserving if this is ever reordered: every path out of an
  6439. # engaged hold ends in a bed-off, whether by timeout or release.
  6440. state = printer_manager.get_status(pid)
  6441. if state is None or state.state != "FINISH":
  6442. continue
  6443. client = printer_manager.get_client(pid)
  6444. if client is None:
  6445. continue
  6446. next_item = next((it for it in items if it.printer_id == pid), None)
  6447. if next_item is None:
  6448. continue
  6449. # Hold temperature: the configured keep-warm temp, raised to the
  6450. # item's own bed temp when the metadata reports a higher one. A
  6451. # missing bed_temperature (Orca gcode.3mf exports parse without
  6452. # one) does NOT skip the hold — chamber need gates the feature.
  6453. archive = next_item.archive
  6454. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6455. bed_target = max(item_bed, hold_temp)
  6456. if bed_target <= 0:
  6457. continue
  6458. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6459. if explicit is not None:
  6460. chamber_needed = int(explicit) > 0
  6461. else:
  6462. if filament_targets is None:
  6463. filament_targets = await self._get_preheat_filament_targets(db)
  6464. printer_obj = await self._get_printer(db, pid)
  6465. chamber_needed = (
  6466. printer_obj is not None
  6467. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6468. )
  6469. if not chamber_needed:
  6470. continue
  6471. # Seed the timer on first engagement; keep it on subsequent ticks
  6472. # (never re-seed — that would defeat the max-duration cap).
  6473. if entry is None:
  6474. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6475. self._keep_warm[pid] = entry
  6476. elapsed = now_mono - entry.started
  6477. if elapsed > max_hold_seconds:
  6478. # Timeout: publish bed → 0 once (if firmware still holds our
  6479. # target) and latch expired. The entry stays until the release
  6480. # sweep drops it, preventing the next tick from re-seeding.
  6481. logger.warning(
  6482. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6483. pid,
  6484. elapsed,
  6485. )
  6486. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6487. if int(cur_bed_target) == entry.held_target:
  6488. try:
  6489. client.set_bed_temperature(0)
  6490. except Exception as exc:
  6491. logger.warning(
  6492. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6493. pid,
  6494. exc,
  6495. )
  6496. else:
  6497. logger.info(
  6498. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6499. pid,
  6500. int(cur_bed_target),
  6501. entry.held_target,
  6502. )
  6503. entry.expired = True
  6504. continue
  6505. # Idempotence: skip publish when firmware already has our target.
  6506. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6507. if int(cur_bed_target) == bed_target:
  6508. entry.held_target = bed_target
  6509. continue
  6510. try:
  6511. client.set_bed_temperature(bed_target)
  6512. entry.held_target = bed_target
  6513. logger.info(
  6514. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6515. bed_target,
  6516. pid,
  6517. )
  6518. except Exception as exc:
  6519. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6520. def _sample_chamber_temps(self) -> None:
  6521. """Record a chamber temperature sample for every connected printer.
  6522. Called once per scheduler tick (every 3–30 s). Entries older than
  6523. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6524. Also evicts per-printer state whose printer_id is no longer registered
  6525. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6526. """
  6527. now = time.monotonic()
  6528. cutoff = now - self._chamber_history_ttl
  6529. statuses = printer_manager.get_all_statuses()
  6530. known_pids = set(statuses.keys())
  6531. for pid, status in statuses.items():
  6532. if status is None or not status.connected:
  6533. continue
  6534. temps = status.temperatures or {}
  6535. chamber = temps.get("chamber")
  6536. if chamber is None:
  6537. continue
  6538. hist = self._chamber_history.setdefault(pid, deque())
  6539. hist.append((now, float(chamber)))
  6540. while hist and hist[0][0] < cutoff:
  6541. hist.popleft()
  6542. # Evict state for printers that are no longer registered with the manager.
  6543. # This is the one place a keep-warm entry is dropped without releasing
  6544. # the bed: the printer is gone from the manager, so there is no client
  6545. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6546. # for printers that are merely unreachable, which is what makes this
  6547. # the terminal case rather than a silent leak.
  6548. for pid in list(self._chamber_history):
  6549. if pid not in known_pids:
  6550. self._chamber_history.pop(pid, None)
  6551. for pid in list(self._keep_warm):
  6552. if pid not in known_pids:
  6553. logger.info(
  6554. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6555. pid,
  6556. )
  6557. self._keep_warm.pop(pid, None)
  6558. for pid in list(self._preheat_pin):
  6559. if pid not in known_pids:
  6560. self._preheat_pin.pop(pid, None)
  6561. self._preheat_pin_bed.pop(pid, None)
  6562. def _chamber_soak_remaining(
  6563. self,
  6564. printer_id: int,
  6565. chamber_target: float,
  6566. soak_seconds: int,
  6567. tolerance: float = 2.0,
  6568. ) -> int:
  6569. """Return how many seconds of soak time are still needed.
  6570. Credits the time the chamber has already spent at temperature against
  6571. the configured soak. The credit may not start earlier than any of:
  6572. * **The newest sample.** Nothing recent means the printer stopped
  6573. reporting mid-observation and the chamber may have cooled unseen, so
  6574. the full soak is required. (A 2 h history whose last reading is half
  6575. an hour old is not evidence of anything — the measured cooling rate
  6576. is fast enough to cross the threshold in that time.)
  6577. * **The most recent contiguous run of samples.** A gap wider than
  6578. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6579. far side is not evidence of temperature.
  6580. * **The end of the most recent real dip below the threshold.**
  6581. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6582. — see that constant for the thermal reasoning. A stray low reading is
  6583. an artifact, and treating it as cooling would discard a soak that
  6584. actually happened.
  6585. Returns ``soak_seconds`` when nothing can be credited (no history,
  6586. stale history, or the chamber is below the threshold right now) and 0
  6587. once the credited time covers the whole soak.
  6588. """
  6589. hist = self._chamber_history.get(printer_id)
  6590. if not hist:
  6591. return soak_seconds
  6592. now = time.monotonic()
  6593. newest_ts, newest_temp = hist[-1]
  6594. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6595. return soak_seconds # stale — no fresh evidence to credit
  6596. threshold = chamber_target - tolerance
  6597. if newest_temp < threshold:
  6598. return soak_seconds # below target right now; nothing is soaked
  6599. samples = list(hist)
  6600. # Earliest point we have unbroken observations for.
  6601. credit_from = samples[-1][0]
  6602. for i in range(len(samples) - 1, 0, -1):
  6603. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6604. break
  6605. credit_from = samples[i - 1][0]
  6606. # Pull the credit forward to the end of the last significant dip. Each
  6607. # excursion is measured between the in-range readings that bracket it,
  6608. # so a lone stray sample is charged one sampling interval rather than
  6609. # zero, and the comparison errs towards calling a dip real.
  6610. i = 0
  6611. while i < len(samples):
  6612. if samples[i][1] >= threshold:
  6613. i += 1
  6614. continue
  6615. j = i
  6616. while j < len(samples) and samples[j][1] < threshold:
  6617. j += 1
  6618. # `newest_temp >= threshold` was checked above, so j is in range.
  6619. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6620. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6621. # Credit resumes at the last below-threshold sample rather than
  6622. # the first good one after it, so a recovered dip over-credits
  6623. # by up to one sampling interval — the opposite lean to the
  6624. # bracketing above. Both are bounded by the sample cadence and
  6625. # dwarfed by the grace period, so neither is worth the extra
  6626. # arithmetic to remove.
  6627. credit_from = max(credit_from, samples[j - 1][0])
  6628. i = j
  6629. return max(0, soak_seconds - int(now - credit_from))
  6630. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6631. """Tell an in-flight dispatch that its item no longer wants to print.
  6632. Called by the queue's cancel and delete routes. Those only write to the
  6633. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6634. observe — so preheat would keep heating for the rest of max_wait + soak
  6635. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6636. blocking every other queued item behind a print that is not happening.
  6637. Signalling in memory rather than re-reading the row keeps this off the
  6638. database entirely: no second session, no transaction held across a long
  6639. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6640. Bambuddy serves from a single uvicorn process with one scheduler task,
  6641. so the route and the dispatch always share this object. The flag is
  6642. advisory — dropping it (e.g. after a restart) only costs a wasted
  6643. preheat, never a wrongly-abandoned print.
  6644. Only ids with a dispatch actually in flight are recorded, so the set
  6645. stays bounded by the upload pool rather than growing once per cancelled
  6646. item for the life of the process. Skipping the rest loses nothing: an
  6647. item that is not in flight cannot start heating later either, because
  6648. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6649. the caller has already committed a terminal status (or deleted the row)
  6650. before calling this.
  6651. """
  6652. if item_id in self._inflight:
  6653. self._cancelled_dispatches.add(item_id)
  6654. # A print sent for it earlier that never started is not one any more.
  6655. self._forget_unstarted_print(item_id, unless_printing=False)
  6656. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6657. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6658. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6659. while it is parked, so the wait is chopped into
  6660. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6661. """
  6662. remaining = float(seconds)
  6663. while remaining > 0:
  6664. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6665. await asyncio.sleep(slice_secs)
  6666. remaining -= slice_secs
  6667. if item_id in self._cancelled_dispatches:
  6668. return False
  6669. return True
  6670. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6671. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6672. The full preheat stage does this as part of its own dispatch: an H2D
  6673. left in heating mode by the ABS job before it would otherwise cook the
  6674. PLA that follows. The skip path never reaches that code, so it calls
  6675. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6676. add to the rollback pin, because a flap set to cooling for a print that
  6677. needs no heat is where it should have been either way.
  6678. Best-effort like everything else in the stage: a refused command logs
  6679. and the dispatch carries on.
  6680. """
  6681. model = printer.model or ""
  6682. if not supports_airduct(model):
  6683. return
  6684. state = printer_manager.get_status(printer.id)
  6685. current = getattr(state, "airduct_mode", None) if state else None
  6686. if current == _AIRDUCT_MODE_COOLING:
  6687. return
  6688. client = printer_manager.get_client(printer.id)
  6689. if client is None:
  6690. return
  6691. try:
  6692. client.set_airduct_mode("cooling")
  6693. except Exception as exc:
  6694. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6695. async def _preheat_and_soak(
  6696. self,
  6697. db: AsyncSession,
  6698. item: PrintQueueItem,
  6699. printer: Printer,
  6700. archive: PrintArchive | None,
  6701. ) -> bool:
  6702. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6703. Returns True when the dispatch should carry on to the upload — including
  6704. every case where preheat is skipped, since a skipped preheat is not a
  6705. reason to abandon the print. Returns False only when the item stopped
  6706. wanting to be printed while the stage was waiting (cancelled or
  6707. deleted); the caller must then abandon the dispatch, and
  6708. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6709. Resolution order:
  6710. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6711. to the global `preheat_enabled` setting; 'on' forces the stage on
  6712. even if the global is off.
  6713. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6714. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6715. across the trays `item.ams_mapping` names (every loaded slot when
  6716. it names none).
  6717. 3. A target of 0 off the filament map skips the whole stage: the
  6718. materials this print loads want no chamber, so there is nothing to
  6719. soak for and the bed phase would only delay the upload (#3041).
  6720. An explicit 0 typed into the per-item override, or a per-item
  6721. 'on', still runs the bed phase and the soak — both are the user
  6722. asking for a warm bed in so many words.
  6723. 4. Three hardware tiers branch the wait loop:
  6724. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6725. send M141 to the resolved target, then wait for the chamber sensor
  6726. to reach it (or the max-wait timeout to elapse).
  6727. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6728. no M141; the bed is the only heat source, so we wait for the chamber
  6729. sensor to rise via bed radiation OR fall through on timeout.
  6730. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6731. temperature; the function just heats the bed and holds for the
  6732. configured soak duration.
  6733. The bed target comes from the archive's parsed metadata
  6734. (`bed_temperature`); if missing the preheat stage logs and returns
  6735. without dispatching anything, rather than guessing at a default that
  6736. might wreck filament setup.
  6737. Failures are logged but never re-raised — preheat is best-effort. A
  6738. printer that goes offline mid-soak, a refused gcode command, or a
  6739. missing temperature reading must not turn into a failed queue item; the
  6740. normal upload + start path runs immediately after this method returns.
  6741. """
  6742. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6743. if override == "off":
  6744. return True
  6745. if override == "inherit":
  6746. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6747. if not enabled:
  6748. return True
  6749. # override == "on" forces the stage on regardless of the global setting.
  6750. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6751. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6752. # Chamber target resolution:
  6753. # 1. Explicit per-item override beats everything (user knows best).
  6754. # 2. Otherwise derive from the filament types this print loads, via
  6755. # the per-filament target map. A PLA-only print derives 0 and the
  6756. # block below skips the stage without the user touching anything,
  6757. # even when an ASA spool is sitting in another slot of the same
  6758. # AMS (#2886).
  6759. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6760. if explicit_target is not None and explicit_target > 0:
  6761. chamber_target = int(explicit_target)
  6762. chamber_source = "item-override"
  6763. elif explicit_target == 0:
  6764. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6765. chamber_source = "item-override-zero"
  6766. else:
  6767. targets = await self._get_preheat_filament_targets(db)
  6768. chamber_target = self._derive_chamber_target(printer, targets, item)
  6769. chamber_source = "filament-map"
  6770. # Nothing to preheat *for*. A zero that came out of the filament map is
  6771. # the map saying this print's materials want no chamber conditioning --
  6772. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6773. # anyway heated the bed and then held it for the full soak, which
  6774. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6775. # own G-code sets the bed the moment it starts, so preheating it here
  6776. # only moves that heating ahead of the upload instead of overlapping
  6777. # with it, and the soak has no chamber to condition (#3041).
  6778. #
  6779. # An explicit statement from the user still runs the stage. Forcing the
  6780. # per-item override to 'on', or typing a chamber target of exactly 0,
  6781. # both mean "preheat the bed for this print" -- the second is
  6782. # documented as doing precisely that. Only the automatic path, the
  6783. # global toggle plus the filament map, short-circuits here.
  6784. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6785. logger.info(
  6786. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6787. "target, so there is nothing to soak for (override=%s model=%s)",
  6788. item.id,
  6789. override,
  6790. printer.model or "",
  6791. )
  6792. self._preheat_flap_to_cooling(item.id, printer)
  6793. return True
  6794. bed_target = await _queued_plate_bed_temperature(item, archive)
  6795. if bed_target <= 0:
  6796. # No bed temperature in the slicer metadata. When the print needs a
  6797. # hot chamber the bed is simply how we heat it, so fall back to the
  6798. # configured chamber-heating bed temperature rather than skipping
  6799. # the whole stage — otherwise the print starts with a cold chamber,
  6800. # which is exactly what preheat exists to prevent. Without a chamber
  6801. # requirement there is nothing to preheat *for*, so skip as before
  6802. # rather than guess a bed temperature for the print itself.
  6803. if chamber_target <= 0:
  6804. logger.info(
  6805. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6806. item.id,
  6807. )
  6808. return True
  6809. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6810. logger.info(
  6811. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6812. "%d°C to drive the chamber to %d°C",
  6813. item.id,
  6814. bed_target,
  6815. chamber_target,
  6816. )
  6817. client = printer_manager.get_client(printer.id)
  6818. if client is None:
  6819. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6820. return True
  6821. model = printer.model or ""
  6822. has_heater = supports_chamber_heater(model)
  6823. has_sensor = supports_chamber_temp(model)
  6824. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6825. # Fast path: if the chamber has been continuously above target for at
  6826. # least soak_seconds and the bed is already at temperature, skip the
  6827. # entire preheat stage. Typical case: keep-warm held the bed between
  6828. # consecutive same-material prints and the chamber never dropped.
  6829. if do_chamber and has_sensor and soak_seconds > 0:
  6830. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6831. if remaining == 0:
  6832. cur = printer_manager.get_status(printer.id)
  6833. if cur:
  6834. cur_temps = cur.temperatures or {}
  6835. if (
  6836. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6837. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6838. ):
  6839. logger.info(
  6840. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6841. "and bed is already at temperature (chamber history fast-path)",
  6842. item.id,
  6843. chamber_target,
  6844. soak_seconds,
  6845. )
  6846. # Still set targets to prevent cooling during the 3MF upload window.
  6847. # Register each successful set in the preheat pin so `_dispatch_one`
  6848. # unwinds them on any non-success exit.
  6849. pin = self._preheat_pin.setdefault(printer.id, set())
  6850. try:
  6851. client.set_bed_temperature(bed_target)
  6852. pin.add("bed")
  6853. self._preheat_pin_bed[printer.id] = bed_target
  6854. except Exception as exc:
  6855. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6856. if supports_airduct(model):
  6857. cur_airduct = getattr(cur, "airduct_mode", None)
  6858. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6859. try:
  6860. client.set_airduct_mode("heating")
  6861. # Only undo what we can see we replaced. `None`
  6862. # means no mode has been observed yet, and
  6863. # rolling that back to cooling would assert a
  6864. # state the printer never reported.
  6865. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6866. pin.add("airduct")
  6867. except Exception as exc:
  6868. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6869. if has_heater:
  6870. try:
  6871. client.set_chamber_temperature(chamber_target)
  6872. pin.add("chamber")
  6873. except Exception as exc:
  6874. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6875. return True
  6876. logger.info(
  6877. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6878. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6879. item.id,
  6880. bed_target,
  6881. chamber_target if do_chamber else 0,
  6882. chamber_source,
  6883. override,
  6884. model,
  6885. has_heater,
  6886. has_sensor,
  6887. max_wait,
  6888. soak_seconds,
  6889. )
  6890. # Preheat rollback registry: everything we set below is recorded here so
  6891. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6892. # (bed off, chamber off, airduct back to cooling) on any non-success
  6893. # exit. Populated as each command succeeds; consumed and cleared by
  6894. # `_dispatch_one`.
  6895. pin = self._preheat_pin.setdefault(printer.id, set())
  6896. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6897. # cache the target locally so the polling reads below see consistent
  6898. # state (firmware MQTT echoes lag by ~1s).
  6899. try:
  6900. client.set_bed_temperature(bed_target)
  6901. pin.add("bed")
  6902. self._preheat_pin_bed[printer.id] = bed_target
  6903. except Exception as exc:
  6904. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6905. return True
  6906. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6907. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6908. # left it on, regardless of M141. Default cooling actively vents the
  6909. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6910. # cooling never converges — the heater fights the open exhaust. We
  6911. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6912. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6913. # on an H2D that was previously running ABS would otherwise stay in
  6914. # heating mode and overheat PLA). The current-state read keeps the
  6915. # command idempotent — no MQTT chatter when the flap is already where
  6916. # we want it.
  6917. if supports_airduct(model):
  6918. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6919. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6920. current_state = printer_manager.get_status(printer.id)
  6921. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6922. if current_airduct != desired_id:
  6923. try:
  6924. client.set_airduct_mode(desired_airduct)
  6925. # As in the fast path: only pin a rollback for a flap we
  6926. # saw in cooling. `current_airduct` of None means no mode
  6927. # has been observed, so there is nothing to restore to.
  6928. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6929. pin.add("airduct")
  6930. except Exception as exc:
  6931. logger.warning(
  6932. "Queue item %s: preheat airduct %s mode failed: %s",
  6933. item.id,
  6934. desired_airduct,
  6935. exc,
  6936. )
  6937. if do_chamber and has_heater:
  6938. try:
  6939. client.set_chamber_temperature(chamber_target)
  6940. pin.add("chamber")
  6941. except Exception as exc:
  6942. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6943. # Release the pooled DB connection before the (potentially many-minute)
  6944. # heat-soak wait below (#2572). Every setting this method needs is read
  6945. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6946. # it never touches the DB. Without this the caller's transaction sat
  6947. # "idle in transaction" for the whole soak, pinning one pooled connection
  6948. # per preheating printer. expire_on_commit=False keeps item/printer
  6949. # readable afterwards; there are no pending writes to lose here.
  6950. await db.commit()
  6951. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6952. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6953. # Poll every 3s — frequent enough for responsive logging without
  6954. # spamming the MQTT state stream. The "converged" predicate is:
  6955. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6956. # AND
  6957. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6958. BED_TOLERANCE = 2.0
  6959. CHAMBER_TOLERANCE = 2.0
  6960. POLL_INTERVAL = 3.0
  6961. deadline = asyncio.get_event_loop().time() + max_wait
  6962. while True:
  6963. state = printer_manager.get_status(printer.id)
  6964. if state is None:
  6965. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6966. break
  6967. temps = state.temperatures or {}
  6968. bed_now = float(temps.get("bed", 0) or 0)
  6969. chamber_now = float(temps.get("chamber", 0) or 0)
  6970. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6971. if not do_chamber:
  6972. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6973. elif not has_sensor:
  6974. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6975. else:
  6976. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6977. if bed_ok and chamber_ok:
  6978. logger.info(
  6979. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6980. item.id,
  6981. bed_now,
  6982. chamber_now,
  6983. )
  6984. break
  6985. if asyncio.get_event_loop().time() >= deadline:
  6986. logger.info(
  6987. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6988. item.id,
  6989. bed_now,
  6990. bed_target,
  6991. chamber_now,
  6992. chamber_target if do_chamber else 0,
  6993. )
  6994. break
  6995. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6996. logger.info(
  6997. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6998. item.id,
  6999. )
  7000. return False
  7001. if soak_seconds > 0:
  7002. if do_chamber and has_sensor:
  7003. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7004. else:
  7005. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7006. if remaining > 0:
  7007. logger.info(
  7008. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7009. "has been above target for ~%ds already)",
  7010. item.id,
  7011. remaining,
  7012. soak_seconds,
  7013. soak_seconds - remaining,
  7014. )
  7015. if not await self._preheat_sleep(item.id, remaining):
  7016. logger.info(
  7017. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7018. item.id,
  7019. )
  7020. return False
  7021. else:
  7022. logger.info(
  7023. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7024. item.id,
  7025. chamber_target,
  7026. soak_seconds,
  7027. )
  7028. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7029. return True
  7030. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7031. """Turn on smart plug and wait for printer to connect.
  7032. Returns True if printer connected successfully within timeout.
  7033. """
  7034. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7035. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7036. # Check current plug state
  7037. status = await service.get_status(plug)
  7038. if not status.get("reachable"):
  7039. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7040. return False
  7041. # Turn on if not already on
  7042. if status.get("state") != "ON":
  7043. success = await service.turn_on(plug)
  7044. if not success:
  7045. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7046. return False
  7047. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7048. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7049. # Get printer from database for connection
  7050. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7051. printer = result.scalar_one_or_none()
  7052. if not printer:
  7053. logger.error("Printer %s not found in database", printer_id)
  7054. return False
  7055. # End the pass's transaction before waiting up to minutes for the boot:
  7056. # held open, it pins a pooled connection idle in transaction
  7057. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7058. # through it.
  7059. await db.commit()
  7060. # Wait for printer to boot (give it some time before trying to connect)
  7061. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7062. await asyncio.sleep(30)
  7063. # Try to connect to the printer periodically
  7064. elapsed = 30 # Already waited 30s
  7065. while elapsed < self._power_on_wait_time:
  7066. # Try to connect
  7067. logger.info("Attempting to connect to printer %s...", printer_id)
  7068. try:
  7069. connected = await printer_manager.connect_printer(printer)
  7070. if connected:
  7071. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7072. # Give it a moment to stabilize and get status
  7073. await asyncio.sleep(5)
  7074. return True
  7075. except Exception as e:
  7076. logger.debug("Connection attempt failed: %s", e)
  7077. await asyncio.sleep(self._power_on_check_interval)
  7078. elapsed += self._power_on_check_interval
  7079. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7080. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7081. return False
  7082. async def _check_previous_success(
  7083. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7084. ) -> bool:
  7085. """Check if the previous print on this printer succeeded.
  7086. ``printer_id`` names the printer to look at when the item has none yet
  7087. (a job for any printer of a model, checked against the one offered).
  7088. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7089. deliberate action, not a failure, so subsequent items should still
  7090. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7091. a skip isn't an actual print attempt, so it must not gate downstream
  7092. items — counting it as a failed predecessor was the cascade bug that
  7093. let a single cancellation block 18 items over 3 days for the reporter.
  7094. Only `failed` and `aborted` — real print-attempt failures — block.
  7095. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7096. action — #1818) are also excluded from the lookback so the user can
  7097. clear the gate after fixing the physical issue without having to
  7098. re-queue every downstream job.
  7099. """
  7100. result = await db.execute(
  7101. select(PrintQueueItem)
  7102. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7103. .where(PrintQueueItem.id != item.id)
  7104. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7105. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7106. # A row ended without a completion time must not count as the
  7107. # latest: PostgreSQL sorts NULL first in a descending order.
  7108. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7109. .limit(1)
  7110. )
  7111. prev_item = result.scalar_one_or_none()
  7112. # If no previous item, assume success (first in queue)
  7113. if not prev_item:
  7114. return True
  7115. return prev_item.status in ("completed", "cancelled")
  7116. async def _repoint_siblings_at_archive(
  7117. self,
  7118. db: AsyncSession,
  7119. *,
  7120. consumed_library_file_id: int,
  7121. archive_id: int,
  7122. dispatched_item_id: int,
  7123. ) -> int:
  7124. """Move the other queue items off a library row that is about to be deleted (#2819).
  7125. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7126. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7127. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7128. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7129. clones, so the first dispatch could pull the file out from under rows that
  7130. had not run yet. What those rows did next depended on the database, and
  7131. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7132. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7133. they were left pointing at a row that no longer existed, failing with
  7134. "Library file not found" whenever someone started them -- or sitting
  7135. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7136. constraint, so there the rows were deleted outright and the queued copies
  7137. simply vanished, with no error and no history.
  7138. The archive holds its own copy of the 3MF, so the remaining copies can print
  7139. from it instead. Two things happen here, and both must happen *before* the
  7140. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7141. * every row still naming the file has ``library_file_id`` cleared, which is
  7142. what takes it out of the cascade's reach. That covers rows this cannot
  7143. re-point as well -- a copy already printing from its own archive, and the
  7144. finished ones, which are not spare parts but the record a batch order
  7145. counts its progress from.
  7146. * the rows that still need something to print are pointed at the archive.
  7147. Returns how many items were re-pointed.
  7148. """
  7149. variant_item_ids = (
  7150. (
  7151. await db.execute(
  7152. select(PrintQueueVariant.queue_item_id).where(
  7153. PrintQueueVariant.library_file_id == consumed_library_file_id
  7154. )
  7155. )
  7156. )
  7157. .scalars()
  7158. .all()
  7159. )
  7160. # Candidate rows naming the consumed file have to go rather than be
  7161. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7162. # one out of the cascade. This is what PostgreSQL already does, and
  7163. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7164. # outcome changes -- the two backends simply stop disagreeing about
  7165. # whether the row is still there.
  7166. #
  7167. # It also has to happen before the re-point below: a cross-model item
  7168. # (#671) picks a variant every pass and folds it onto the row, and
  7169. # _resolve_variant clears archive_id as it does so, which would undo the
  7170. # re-point on the very next lap.
  7171. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7172. # An item left with other candidates still has somewhere to go, and those
  7173. # carry their own target model -- pointing it at this archive would print a
  7174. # file the matcher never chose. It is excluded from the re-point and simply
  7175. # re-resolves against what is left.
  7176. surviving_variant_item_ids = set(
  7177. (
  7178. await db.execute(
  7179. select(PrintQueueVariant.queue_item_id).where(
  7180. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7181. )
  7182. )
  7183. )
  7184. .scalars()
  7185. .all()
  7186. )
  7187. repoint_ids = set(
  7188. (
  7189. await db.execute(
  7190. select(PrintQueueItem.id)
  7191. .where(PrintQueueItem.id != dispatched_item_id)
  7192. .where(PrintQueueItem.archive_id.is_(None))
  7193. # "skipped" belongs here with the two live states: it is not
  7194. # terminal. Clearing a printer's previous-success gate puts
  7195. # every item skipped by it back to "pending"
  7196. # (resume_after_failure), and one restored onto a deleted
  7197. # file is the same orphan by a slower route. "failed",
  7198. # "cancelled", "aborted" and "completed" never return.
  7199. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7200. .where(
  7201. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7202. )
  7203. .where(
  7204. or_(
  7205. PrintQueueItem.library_file_id == consumed_library_file_id,
  7206. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7207. )
  7208. )
  7209. )
  7210. )
  7211. .scalars()
  7212. .all()
  7213. )
  7214. if repoint_ids:
  7215. await db.execute(
  7216. update(PrintQueueItem)
  7217. .where(PrintQueueItem.id.in_(repoint_ids))
  7218. .values(
  7219. archive_id=archive_id,
  7220. library_file_id=None,
  7221. # The file this flag named is already consumed. Leaving it set
  7222. # would arm every re-pointed copy to delete whatever library
  7223. # row it is next given.
  7224. cleanup_library_after_dispatch=False,
  7225. )
  7226. )
  7227. logger.info(
  7228. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7229. sorted(repoint_ids),
  7230. archive_id,
  7231. consumed_library_file_id,
  7232. dispatched_item_id,
  7233. )
  7234. # Everything else that still names the file: taken out of the cascade's
  7235. # reach without touching what it prints. The file is gone either way; what
  7236. # this preserves is the row.
  7237. await db.execute(
  7238. update(PrintQueueItem)
  7239. .where(PrintQueueItem.id != dispatched_item_id)
  7240. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7241. .values(library_file_id=None)
  7242. )
  7243. return len(repoint_ids)
  7244. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7245. """Schedule power-off if the queue item enabled auto_off_after.
  7246. Delegates to the smart-plug manager so the off honours each plug's
  7247. configured strategy (time delay or temperature threshold), is cancelled
  7248. if the printer starts printing again, and never cuts power on a loaded
  7249. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7250. powered off on the timeout regardless of print state.
  7251. """
  7252. if not item.auto_off_after:
  7253. return
  7254. try:
  7255. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7256. except Exception as e:
  7257. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7258. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7259. """Get a human-readable name for a queue item."""
  7260. if item.archive_id:
  7261. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7262. archive = result.scalar_one_or_none()
  7263. if archive:
  7264. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7265. if item.library_file_id:
  7266. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7267. library_file = result.scalar_one_or_none()
  7268. if library_file:
  7269. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7270. # A cross-model item (#671) holds no file of its own until a printer is
  7271. # picked, so name it after its first candidate — otherwise every waiting
  7272. # notification for one reads "Job #12". Queried rather than read off
  7273. # item.variants because callers outside the selection loop have not
  7274. # eager-loaded them, and a lazy load raises in async.
  7275. first_variant_name = (
  7276. await db.execute(
  7277. select(LibraryFile.filename)
  7278. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7279. .where(PrintQueueVariant.queue_item_id == item.id)
  7280. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7281. .limit(1)
  7282. )
  7283. ).scalar_one_or_none()
  7284. if first_variant_name:
  7285. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7286. return f"Job #{item.id}"
  7287. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7288. """Get printer by ID."""
  7289. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7290. return result.scalar_one_or_none()
  7291. async def _notify_dispatch_gave_up(
  7292. self,
  7293. queue_item_id: int,
  7294. printer_id: int,
  7295. created_by_id: int | None,
  7296. reason: str = "Printer accepted the file but never started printing",
  7297. ) -> None:
  7298. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7299. Called from the watchdog, which is a background task with no session of
  7300. its own — hence the fresh one here. Best-effort throughout: the row is
  7301. already marked failed and that is the load-bearing part; a notification
  7302. provider being down must not resurrect the retry loop we just stopped.
  7303. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7304. path passes its own, because "accepted the file but never started" is the
  7305. opposite of what happened there — the printer refused it outright (#2732).
  7306. """
  7307. try:
  7308. async with async_session() as db:
  7309. item = await db.get(PrintQueueItem, queue_item_id)
  7310. if not item:
  7311. return
  7312. job_name = await self._get_job_name(db, item)
  7313. printer = await self._get_printer(db, printer_id)
  7314. await notification_service.on_queue_job_failed(
  7315. job_name=job_name,
  7316. printer_id=printer_id,
  7317. printer_name=printer.name if printer else "Unknown",
  7318. reason=reason,
  7319. db=db,
  7320. )
  7321. except Exception as e:
  7322. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7323. try:
  7324. await ws_manager.send_queue_item_failed(
  7325. user_id=created_by_id,
  7326. queue_item_id=queue_item_id,
  7327. printer_id=printer_id,
  7328. reason="never_started",
  7329. )
  7330. except Exception:
  7331. pass # toast is best-effort
  7332. async def _filament_short_on(
  7333. self,
  7334. db: AsyncSession,
  7335. item: PrintQueueItem,
  7336. printer_id: int,
  7337. *,
  7338. require_known: bool = False,
  7339. ) -> bool:
  7340. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7341. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7342. assigned there, with the mapping the item would get there, but changes
  7343. nothing. The model-based matcher uses it to prefer a printer whose
  7344. spools can finish the job.
  7345. False whenever the gate would let the item through: "Print Anyway",
  7346. no mapping, or a check that fails. With ``require_known`` all three of
  7347. those, and any printed slot whose remaining amount is unknown, count
  7348. as short instead: releasing a held job starts it with nobody asked, so
  7349. it needs the amount on record, not merely nothing against it.
  7350. """
  7351. if item.skip_filament_check:
  7352. return False
  7353. try:
  7354. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7355. if not mapping:
  7356. return require_known
  7357. deficit = await compute_deficit_for_queue_item(
  7358. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7359. )
  7360. except Exception as e:
  7361. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7362. return require_known
  7363. return bool(deficit)
  7364. async def _release_short_model_hold(
  7365. self,
  7366. db: AsyncSession,
  7367. item: PrintQueueItem,
  7368. unavailable: set[int],
  7369. require_plate_clear: bool,
  7370. printer_scope: PrinterScope,
  7371. ) -> bool:
  7372. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7373. The deficit gate holds a model-based job on the printer the matcher
  7374. gave it, because "Print Anyway" needs a printer to print on. When
  7375. another idle printer of the job's model has the filament, the job is
  7376. moved to that printer and its hold lifted, and the fixed-printer
  7377. branch dispatches it in this same pass, through the same checks a
  7378. held job meets when the user presses Start. It is moved rather than
  7379. put back in the pool because the model-based branch would pick again
  7380. without requiring the amounts on record (below), and could pick a
  7381. different printer. Only the deficit gate sets ``filament_short``, so a
  7382. job held for any other reason stays held.
  7383. The printer it is held on is left out: a spool loaded there is started
  7384. with Start, as before, rather than while someone may still be loading
  7385. the next one. Each job is checked at most every
  7386. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7387. on each idle printer again.
  7388. Cross-model jobs (#671) stay held: checking a variant writes its file
  7389. onto the item, which would leave a job that is not moved holding
  7390. another variant's file for the printer it waits on.
  7391. A printer qualifies only on a positive finding: every slot the plate
  7392. prints mapped to a spool whose remaining amount is on record and
  7393. enough. A printer whose spools Bambuddy does not track is not one.
  7394. Returns True when the job was moved. A check that fails keeps the hold
  7395. rather than stopping the queue pass.
  7396. """
  7397. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7398. return False
  7399. if not item.target_model or item.variants:
  7400. return False
  7401. now = time.monotonic()
  7402. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7403. return False
  7404. self._short_hold_checked_at[item.id] = now
  7405. try:
  7406. candidates = _candidates_for(item)
  7407. if not candidates:
  7408. return False
  7409. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7410. async def is_short(pid: int) -> bool:
  7411. return await self._filament_short_on(db, item, pid, require_known=True)
  7412. async def unmatched_on(pid: int) -> list[str]:
  7413. return await self._unmatched_on(db, item, pid)
  7414. match_id, _ = await self._find_idle_printer_for_model(
  7415. db,
  7416. item.target_model,
  7417. unavailable | {item.printer_id},
  7418. effective_types,
  7419. item.target_location,
  7420. filament_overrides=filament_overrides,
  7421. require_plate_clear=require_plate_clear,
  7422. printer_scope=printer_scope,
  7423. is_short=is_short,
  7424. unmatched_on=unmatched_on,
  7425. )
  7426. # Every idle printer short comes back as the first of them.
  7427. if match_id is None or await is_short(match_id):
  7428. return False
  7429. except Exception as e:
  7430. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7431. return False
  7432. logger.info(
  7433. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7434. item.id,
  7435. match_id,
  7436. item.printer_id,
  7437. )
  7438. self._short_hold_checked_at.pop(item.id, None)
  7439. item.printer_id = match_id
  7440. # Resolved against the printer it leaves (#3239): the tray mapping and
  7441. # the nozzle positions.
  7442. drop_printer_resolved(item)
  7443. item.manual_start = False
  7444. item.filament_short = False
  7445. item.waiting_reason = None
  7446. await db.commit()
  7447. try:
  7448. printer = await self._get_printer(db, match_id)
  7449. await notification_service.on_queue_job_assigned(
  7450. job_name=await self._get_job_name(db, item),
  7451. printer_id=match_id,
  7452. printer_name=printer.name if printer else "Unknown",
  7453. target_model=item.target_model,
  7454. db=db,
  7455. )
  7456. except Exception as e:
  7457. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7458. return True
  7459. async def _block_on_filament_deficit(
  7460. self,
  7461. db: AsyncSession,
  7462. item: PrintQueueItem,
  7463. ) -> bool:
  7464. """Promote the item to manual_start when the assigned spool is short (#1496).
  7465. Returns True when this dispatch attempt was blocked, False when the
  7466. item is clear to start. A previously-flagged item whose spool has
  7467. since been swapped to one with enough material clears the flag here
  7468. so the next scheduler tick dispatches it.
  7469. """
  7470. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7471. # don't re-flag, don't even compute. Without this short-circuit the
  7472. # scheduler bounces between "user said anyway" (route clears
  7473. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7474. # on identical spool state) (#1698-followup).
  7475. if item.skip_filament_check:
  7476. # #1762 diagnostic: surface the short-circuit at INFO so a
  7477. # future "Print Anyway didn't work" report (e.g. issue #1762
  7478. # comment 3) has actionable evidence in the support bundle
  7479. # without needing DEBUG enabled.
  7480. logger.info(
  7481. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7482. item.id,
  7483. )
  7484. return False
  7485. try:
  7486. deficit = await compute_deficit_for_queue_item(db, item)
  7487. except Exception as e:
  7488. # Never let a flaky deficit check wedge the queue — log and let
  7489. # dispatch proceed. The PrintModal-side check still runs on the
  7490. # manual paths.
  7491. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7492. return False
  7493. if deficit:
  7494. item.filament_short = True
  7495. item.manual_start = True
  7496. await db.commit()
  7497. job_name = await self._get_job_name(db, item)
  7498. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7499. logger.info(
  7500. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7501. item.id,
  7502. len(deficit),
  7503. )
  7504. try:
  7505. await notification_service.on_queue_job_waiting(
  7506. job_name=job_name,
  7507. target_model=(printer.model if printer else "") or "",
  7508. waiting_reason="filament_short",
  7509. db=db,
  7510. printer_id=item.printer_id,
  7511. )
  7512. except Exception as e:
  7513. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7514. return True
  7515. # No deficit — clear any stale flag from a previous tick.
  7516. if item.filament_short:
  7517. item.filament_short = False
  7518. await db.commit()
  7519. return False
  7520. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7521. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7522. Compared the way the matcher compares, so the same hex or a similar one
  7523. is a match. Only slots the plate prints, mapped to a tray the printer
  7524. reports, with a colour on both sides: anything else is not a colour the
  7525. job printed in.
  7526. """
  7527. by_tray = {f["global_tray_id"]: f for f in loaded}
  7528. found = []
  7529. for req in required:
  7530. slot_id = req.get("slot_id") or 0
  7531. if slot_id <= 0 or slot_id > len(mapping):
  7532. continue
  7533. tray_id = mapping[slot_id - 1]
  7534. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7535. if tray is not None and tray.get("color_known") is False:
  7536. # A spool without a colour set is not a different colour.
  7537. continue
  7538. wanted = self._normalize_color_for_compare(req.get("color"))
  7539. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7540. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7541. continue
  7542. found.append(
  7543. {
  7544. "slot_id": slot_id,
  7545. "type": req.get("type") or "",
  7546. "wanted": f"#{wanted.upper()}",
  7547. "got": f"#{got.upper()}",
  7548. "tray": tray_id,
  7549. }
  7550. )
  7551. return found
  7552. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7553. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7554. Read from the mapping the job is about to be sent with, whoever made
  7555. it: the matcher's same-material fallback, a preset match in another
  7556. colour, or a slot picked by hand. The file's colour is the one after
  7557. overrides, so a colour swapped on purpose is not one. None whenever
  7558. there is nothing to compare, and on any failure: a missing note must
  7559. never stop a print.
  7560. """
  7561. try:
  7562. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7563. if not isinstance(mapping, list) or not item.printer_id:
  7564. return None
  7565. status = printer_manager.get_status(item.printer_id)
  7566. if status is None:
  7567. return None
  7568. required = await self._get_filament_requirements(db, item)
  7569. if not required:
  7570. return None
  7571. self._apply_filament_overrides(item, required)
  7572. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7573. except Exception as e:
  7574. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7575. return None
  7576. if found:
  7577. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7578. return json.dumps(found) if found else None
  7579. async def _unmatched_requirements(
  7580. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7581. ) -> list[dict]:
  7582. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7583. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7584. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7585. on why an empty list is not one.
  7586. """
  7587. if mapping is None:
  7588. status = printer_manager.get_status(printer_id)
  7589. if status is None or not self._build_loaded_filaments(status):
  7590. return []
  7591. # Every required slot reads unresolved against an empty mapping.
  7592. mapping = []
  7593. required = await self._get_filament_requirements(db, item)
  7594. if required:
  7595. self._apply_filament_overrides(item, required)
  7596. else:
  7597. # An unreadable 3MF still has its forced colours to go by: they are
  7598. # what the mapping was built from (#3280).
  7599. required = _forced_override_requirements(item)
  7600. return _unresolved_required(required, mapping) if required else []
  7601. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7602. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7603. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7604. Choosing a printer for an "any model" job only checked that each type
  7605. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7606. the spool on the other nozzle, or one spool asked for twice, passes. The
  7607. hold then gave the printer back, and the next pass chose it again.
  7608. Empty when the hold would let the item through, including "Print
  7609. Anyway" and a match that fails: the printer is then chosen as before.
  7610. """
  7611. if item.skip_filament_check:
  7612. return []
  7613. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7614. if key in self._unmatched_memo:
  7615. return list(self._unmatched_memo[key])
  7616. try:
  7617. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7618. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7619. except Exception as e:
  7620. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7621. return []
  7622. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7623. self._unmatched_memo[key] = described
  7624. return list(described)
  7625. async def _block_on_unmatched_filament(
  7626. self,
  7627. db: AsyncSession,
  7628. item: PrintQueueItem,
  7629. release_assignment: bool = False,
  7630. ) -> bool:
  7631. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7632. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7633. goes ahead, letting the printer choose — which is how a job prints in the
  7634. wrong material without anyone being asked. Holding is the same answer the
  7635. deficit gate already gives for "the spool is too light", so it reuses the
  7636. same promote-and-notify machinery.
  7637. Keyed off unresolved slots in the *computed* mapping intersected with the
  7638. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7639. read: on its own it also pads slots this plate does not print, so the
  7640. array alone would hold perfectly good jobs. Reading the mapping rather
  7641. than the printer's loaded filament types also inherits the matcher's
  7642. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7643. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7644. type-only scan would wave that through.
  7645. A mapping that resolved *nothing* is the same finding arriving as an
  7646. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7647. could not replace, and dispatch then goes out as ``use_ams`` with no
  7648. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7649. That is held too, but only once live status positively reports loaded
  7650. trays: #2589's mapping is bogus precisely because the AMS was not known
  7651. yet, and its empty loaded list is that ignorance rather than a miss.
  7652. ``release_assignment`` is for the model-based path, which commits its
  7653. printer choice before the gates run. Holding an "any P2S" job would
  7654. otherwise pin it to the one P2S that could not run it.
  7655. Returns True when this dispatch attempt was blocked.
  7656. """
  7657. if item.skip_filament_check or not item.printer_id:
  7658. return False
  7659. mapping: list | None = None
  7660. if item.ams_mapping:
  7661. try:
  7662. mapping = json.loads(item.ams_mapping)
  7663. except (json.JSONDecodeError, TypeError):
  7664. return False
  7665. if not isinstance(mapping, list):
  7666. return False
  7667. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7668. if not unmatched:
  7669. # No cleanup needed here: once start is pressed the item is no
  7670. # longer staged, and whichever exit runs next overwrites the reason
  7671. # (`hold_item` on the fixed-printer branch, the assignment on the
  7672. # model-based one), as does dispatch.
  7673. return False
  7674. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7675. held_by = item.printer_id
  7676. item.manual_start = True
  7677. # Human-readable: this renders on the queue row.
  7678. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7679. if release_assignment:
  7680. # "Any P2S" means any, so the job returns to the pool rather than
  7681. # waiting on the printer that could not take it. The mapping goes
  7682. # with the assignment: its tray IDs were resolved against the
  7683. # printer being released and mean nothing on the next one (#2799),
  7684. # and keeping them would hold the job again even on a printer that
  7685. # has the filament, since an unresolved slot is deliberately not a
  7686. # conflict worth recomputing over.
  7687. item.printer_id = None
  7688. drop_printer_resolved(item)
  7689. await db.commit()
  7690. job_name = await self._get_job_name(db, item)
  7691. printer = await self._get_printer(db, held_by)
  7692. logger.info(
  7693. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7694. item.id,
  7695. held_by,
  7696. wanted,
  7697. )
  7698. try:
  7699. await notification_service.on_queue_job_waiting(
  7700. job_name=job_name,
  7701. target_model=(printer.model if printer else "") or "",
  7702. waiting_reason=f"needs {wanted}",
  7703. db=db,
  7704. # Released to the pool: no printer holds it any more.
  7705. printer_id=None if release_assignment else held_by,
  7706. )
  7707. except Exception as e:
  7708. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7709. return True
  7710. @staticmethod
  7711. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7712. """The queue item's owner as the row has it now.
  7713. item.created_by_id was read before preheat and upload, which can take
  7714. minutes; deleting the user clears the row, not this session's copy.
  7715. """
  7716. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7717. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7718. """Hand the queue item's owner to printer_manager so the
  7719. print-complete callback can credit the user in PrintLogEntry (#1670).
  7720. No-ops when the item has no `created_by_id` or the referenced user
  7721. row is missing (e.g. user deleted between queue-add and dispatch —
  7722. in that case the print log row falls back to the existing un-credited
  7723. behaviour rather than crashing the dispatch).
  7724. """
  7725. from backend.app.models.user import User
  7726. # Read from the row, not item.created_by_id or db.get: both can still
  7727. # hold a user deleted during the upload, after delete_user forgot them
  7728. # (on SQLite the id may be someone new's by the time the print ends).
  7729. # Joined with the printer too: one deleted during the upload was
  7730. # forgotten as well, and this would write the owner back under its id.
  7731. owner = (
  7732. await db.execute(
  7733. select(User.id, User.username)
  7734. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7735. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7736. .where(PrintQueueItem.id == item.id)
  7737. )
  7738. ).first()
  7739. if owner:
  7740. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7741. if item.printer_id is not None:
  7742. self._unconfirmed_print_user[item.id] = item.printer_id
  7743. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7744. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7745. A cancel lands in another session while the upload runs (the edit route
  7746. even tells users to cancel a job that is being sent). An unconditional
  7747. write here would turn that cancellation into a failure, with a failure
  7748. notification, and block the next job that needs the previous print to
  7749. have succeeded. Returns whether the item was marked failed.
  7750. """
  7751. result = cast(
  7752. CursorResult,
  7753. await db.execute(
  7754. update(PrintQueueItem)
  7755. .where(PrintQueueItem.id == item.id)
  7756. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7757. # Failed before the print started: no slot printed in any colour (#3279).
  7758. .values(
  7759. status="failed",
  7760. error_message=message,
  7761. completed_at=datetime.now(timezone.utc),
  7762. color_substitutions=None,
  7763. )
  7764. .execution_options(synchronize_session=False)
  7765. ),
  7766. )
  7767. await db.commit()
  7768. if result.rowcount == 0:
  7769. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7770. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7771. return False
  7772. await db.refresh(item)
  7773. from backend.app.services.print_batch import refresh_batches_after
  7774. await refresh_batches_after([item.id])
  7775. return True
  7776. @staticmethod
  7777. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7778. """Put a job whose printer turned busy before the start back in the queue.
  7779. Only if it is still printing: a stop that landed meanwhile stands.
  7780. """
  7781. await db.execute(
  7782. update(PrintQueueItem)
  7783. .where(PrintQueueItem.id == item.id)
  7784. .where(PrintQueueItem.status == "printing")
  7785. .values(status="pending", started_at=None, color_substitutions=None)
  7786. .execution_options(synchronize_session=False)
  7787. )
  7788. await db.commit()
  7789. @staticmethod
  7790. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7791. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7792. try:
  7793. await ws_manager.send_queue_item_failed(
  7794. user_id=toast_uid,
  7795. queue_item_id=item.id,
  7796. printer_id=item.printer_id,
  7797. reason="cancelled_mid_dispatch",
  7798. )
  7799. except Exception:
  7800. pass # toast is best-effort
  7801. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7802. """Upload file and start print for a queue item.
  7803. Supports two sources:
  7804. - archive_id: Print from an existing archive
  7805. - library_file_id: Print from a library file (file manager)
  7806. """
  7807. logger.info("Starting queue item %s", item.id)
  7808. # Also covers a reservation left active by a process interruption
  7809. # during an earlier attempt. `_dispatch_one` releases this marker on
  7810. # every exit unless start_print() confirms that the command was sent.
  7811. self._unconfirmed_budget_reservations.add(item.id)
  7812. try:
  7813. from backend.app.models.user import User
  7814. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7815. # Recompute at the final authorization boundary as well as enqueue
  7816. # time. This covers rows created before the server-side estimate
  7817. # migration and prevents any alternate write path from weakening
  7818. # the budget reservation.
  7819. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7820. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7821. item.estimated_cost = await estimate_queue_source_cost(
  7822. db,
  7823. archive=archive,
  7824. library_file=library_file,
  7825. plate_id=item.plate_id,
  7826. ams_mapping=item.ams_mapping,
  7827. printer_id=item.printer_id,
  7828. )
  7829. await validate_print_budget(
  7830. db,
  7831. cost_center_id=item.cost_center_id,
  7832. estimated_cost=item.estimated_cost,
  7833. current_user=queue_user,
  7834. exclude_queue_item_id=item.id,
  7835. exclude_reservation_source_type="print_queue",
  7836. exclude_reservation_source_id=item.id,
  7837. )
  7838. budget_reservation = await create_budget_reservation(
  7839. db,
  7840. cost_center_id=item.cost_center_id,
  7841. estimated_cost=item.estimated_cost,
  7842. current_user=queue_user,
  7843. source_type="print_queue",
  7844. source_id=item.id,
  7845. print_archive_id=item.archive_id,
  7846. exclude_queue_item_id=item.id,
  7847. )
  7848. await db.commit()
  7849. except HTTPException as exc:
  7850. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7851. return
  7852. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7853. await self._power_off_if_needed(db, item)
  7854. return
  7855. # Get printer first (needed for both paths)
  7856. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7857. printer = result.scalar_one_or_none()
  7858. if not printer:
  7859. if not await self._fail_dispatch(db, item, "Printer not found"):
  7860. return
  7861. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7862. await self._power_off_if_needed(db, item)
  7863. return
  7864. # Check printer is connected
  7865. if not printer_manager.is_connected(item.printer_id):
  7866. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7867. return
  7868. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7869. await self._power_off_if_needed(db, item)
  7870. return
  7871. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7872. # `items` was taken at the top of check_queue, but the user can /cancel
  7873. # any pending row in the gap before we reach this point. Re-read the
  7874. # row and bail out cleanly instead of starting an FTP upload for a row
  7875. # that's already cancelled. The atomic CAS at the pending→printing
  7876. # transition (below, before start_print) is the load-bearing guard;
  7877. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7878. await db.refresh(item)
  7879. if item.status != "pending":
  7880. logger.info(
  7881. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7882. item.id,
  7883. item.status,
  7884. )
  7885. return
  7886. # Busy-printer guard (#2598). check_queue gates dispatch on
  7887. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7888. # keep reporting FINISH for tens of seconds *after* it accepted a
  7889. # project_file (see the watchdog's phase-B note). A watchdog revert
  7890. # (#2555) also releases the dispatch hold, so a re-selected item can
  7891. # reach here while its printer has actually started printing. Uploading
  7892. # and dispatching then collides with the live job — the firmware answers
  7893. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7894. # live state right before the expensive FTP upload: if the printer is
  7895. # busy, leave the item pending and let a later tick dispatch it once the
  7896. # printer is genuinely idle. No wasted upload, no collision.
  7897. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7898. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7899. logger.info(
  7900. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7901. "leaving item pending for a later tick (#2598)",
  7902. item.id,
  7903. item.printer_id,
  7904. pre_dispatch_state,
  7905. )
  7906. return
  7907. # Determine source: archive or library file
  7908. archive = None
  7909. library_file = None
  7910. file_path = None
  7911. filename = None
  7912. cleanup_disk_paths: list[Path] = []
  7913. # Set when a dispatch consumes its library file, so the photos can be
  7914. # carried over after the commit that removes the row (#3077).
  7915. consumed_library_file_id: int | None = None
  7916. consumed_photos: list[str] = []
  7917. if item.archive_id:
  7918. # Print from archive
  7919. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7920. archive = result.scalar_one_or_none()
  7921. if not archive:
  7922. if not await self._fail_dispatch(db, item, "Archive not found"):
  7923. return
  7924. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7925. await self._power_off_if_needed(db, item)
  7926. return
  7927. # Persist the queue item's selected plate onto the archive so Print
  7928. # History can show the actual plate after cancel/fail/complete (#2603).
  7929. # Only when the archive doesn't already carry one, so a reprint of a
  7930. # plate-specific archive isn't relabelled by a differently-plated
  7931. # queue row.
  7932. if archive.plate_id is None and item.plate_id is not None:
  7933. archive.plate_id = item.plate_id
  7934. # Ask-for-outcome opt-in rides from the queue item to the archive
  7935. # the same way (#1898); never cleared here so a reprint of an
  7936. # archive that already asked keeps asking.
  7937. if item.confirm_outcome:
  7938. archive.confirm_requested = True
  7939. file_path = settings.base_dir / archive.file_path
  7940. filename = archive.filename
  7941. elif item.library_file_id:
  7942. # Print from library file (file manager)
  7943. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7944. library_file = result.scalar_one_or_none()
  7945. if not library_file:
  7946. # "Not found" covers two different situations and only one of
  7947. # them is recoverable, so say which. A trashed file is still
  7948. # there and restoring it makes a re-queued job work; a file that
  7949. # is really gone needs a different one. Neither is knowable from
  7950. # the queue, which is the whole complaint about this message.
  7951. trashed = (
  7952. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7953. ).scalar_one_or_none()
  7954. if not await self._fail_dispatch(
  7955. db,
  7956. item,
  7957. (
  7958. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7959. if trashed
  7960. else "Library file not found — it was deleted after this job was queued"
  7961. ),
  7962. ):
  7963. return
  7964. logger.error(
  7965. "Queue item %s: library file %s is %s",
  7966. item.id,
  7967. item.library_file_id,
  7968. "in the trash" if trashed else "gone",
  7969. )
  7970. await self._power_off_if_needed(db, item)
  7971. return
  7972. # Library files store absolute paths
  7973. lib_path = Path(library_file.file_path)
  7974. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7975. filename = library_file.filename
  7976. # Create archive from library file so usage tracking has access to the 3MF
  7977. queue_item_id = item.id
  7978. # Held separately: a cleanup dispatch clears item.library_file_id
  7979. # below, and the log line at the end of this block reported that
  7980. # cleared field -- so every consumed print logged "from library
  7981. # file None", which is the one case worth being able to trace.
  7982. source_library_file_id = item.library_file_id
  7983. try:
  7984. from backend.app.services.archive import ArchiveService
  7985. archive_service = ArchiveService(db)
  7986. archive = await archive_service.archive_print(
  7987. printer_id=item.printer_id,
  7988. source_file=file_path,
  7989. original_filename=filename,
  7990. created_by_id=item.created_by_id,
  7991. project_id=item.project_id,
  7992. cost_center_id=item.cost_center_id,
  7993. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7994. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7995. )
  7996. if archive:
  7997. item.archive_id = archive.id
  7998. if item.confirm_outcome:
  7999. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8000. if budget_reservation is not None:
  8001. budget_reservation.print_archive_id = archive.id
  8002. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8003. consumed_library_file_id = library_file.id
  8004. item.library_file_id = None
  8005. cleanup_disk_paths.append(file_path)
  8006. if library_file.thumbnail_path:
  8007. thumb_path = Path(library_file.thumbnail_path)
  8008. if not thumb_path.is_absolute():
  8009. thumb_path = settings.base_dir / library_file.thumbnail_path
  8010. cleanup_disk_paths.append(thumb_path)
  8011. # Before the delete, not after: on PostgreSQL the FK
  8012. # cascade would already have taken these rows (#2819).
  8013. await self._repoint_siblings_at_archive(
  8014. db,
  8015. consumed_library_file_id=consumed_library_file_id,
  8016. archive_id=archive.id,
  8017. dispatched_item_id=item.id,
  8018. )
  8019. # Read while the row is still here; the photos move
  8020. # below, once the delete has actually committed.
  8021. consumed_photos = list(library_file.photos or [])
  8022. # The delete clears the link on the earlier archives of
  8023. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8024. # SQLite). This one is loaded, so set it here too, or it
  8025. # keeps the stale id in the session.
  8026. archive.library_file_id = None
  8027. await db.delete(library_file)
  8028. file_path = settings.base_dir / archive.file_path
  8029. filename = archive.filename
  8030. # Commit, not flush — flush opens the SQLite write
  8031. # transaction (item.archive_id update + library_file
  8032. # delete) and would hold the WAL writer lock through the
  8033. # FTP upload below, causing "database is locked" cascades
  8034. # for sensor history + concurrent cancels (#1853).
  8035. await db.commit()
  8036. logger.info(
  8037. "Queue item %s: Created archive %s from library file %s",
  8038. item.id,
  8039. archive.id,
  8040. source_library_file_id,
  8041. )
  8042. except Exception as e:
  8043. logger.warning(
  8044. "Queue item %s: Failed to create archive from library file: %s",
  8045. queue_item_id,
  8046. e,
  8047. exc_info=True,
  8048. )
  8049. await db.rollback()
  8050. item = await db.get(PrintQueueItem, queue_item_id)
  8051. if item:
  8052. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8053. return
  8054. await self._power_off_if_needed(db, item)
  8055. return
  8056. if not archive:
  8057. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8058. return
  8059. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8060. await self._power_off_if_needed(db, item)
  8061. return
  8062. # The photos follow the file into the archive that replaces it, for
  8063. # the same reason the siblings do (#3077). After the commit above,
  8064. # never before it: that commit can fail ("database is locked",
  8065. # #1853) and roll the library row back, and photos already moved
  8066. # would leave it naming a directory that no longer exists. The
  8067. # file and thumbnail unlinks are deferred for the same reason.
  8068. if consumed_library_file_id is not None and consumed_photos:
  8069. # Held as a plain int, read here while the session is still
  8070. # healthy, because the handler below may not touch an ORM
  8071. # instance at all. The commit it exists for fails inside the
  8072. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8073. # first DML statement, so a busy writer surfaces as "database
  8074. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8075. # internally through safe_reraise before re-raising, which
  8076. # expires every loaded instance and leaves the session in
  8077. # pending-rollback state -- so `archive.id` inside the except
  8078. # would itself raise PendingRollbackError and the rollback
  8079. # below would never be reached.
  8080. archive_id = archive.id
  8081. try:
  8082. carried_photos = move_library_photos(
  8083. consumed_library_file_id,
  8084. consumed_photos,
  8085. archive_photos_dir(archive),
  8086. )
  8087. if carried_photos:
  8088. archive.photos = list(archive.photos or []) + carried_photos
  8089. await db.commit()
  8090. except Exception as e:
  8091. # The archive and the delete are already committed; the
  8092. # print goes ahead either way. Worst case the pictures sit
  8093. # unnamed in the archive's own directory.
  8094. #
  8095. # Ints only until the rollback has run, per the note above,
  8096. # which is why this logs queue_item_id and not item.id --
  8097. # the sibling handler forty lines up does the same.
  8098. logger.warning(
  8099. "Queue item %s: failed to carry library photos into archive %s: %s",
  8100. queue_item_id,
  8101. archive_id,
  8102. e,
  8103. )
  8104. await db.rollback()
  8105. # rollback() expires every loaded instance, and in async
  8106. # SQLAlchemy the next plain attribute read is lazy IO
  8107. # outside the greenlet -- MissingGreenlet, which would turn
  8108. # this cosmetic failure into a dispatch crash in exactly the
  8109. # "database is locked" case the block exists for (#1853).
  8110. # The nozzle guard, the upload and the start all keep
  8111. # reading item, archive and printer, so all three go back
  8112. # into the session before falling through.
  8113. item = await db.get(PrintQueueItem, queue_item_id)
  8114. archive = await db.get(PrintArchive, archive_id)
  8115. printer = await db.get(Printer, item.printer_id) if item else None
  8116. if not item or not archive or not printer:
  8117. logger.error(
  8118. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8119. queue_item_id,
  8120. archive_id,
  8121. )
  8122. return
  8123. else:
  8124. # Neither archive nor library file specified
  8125. if not await self._fail_dispatch(db, item, "No source file specified"):
  8126. return
  8127. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8128. await self._power_off_if_needed(db, item)
  8129. return
  8130. # Check file exists on disk
  8131. if not file_path.exists():
  8132. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8133. return
  8134. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8135. await self._power_off_if_needed(db, item)
  8136. return
  8137. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8138. # size dispatched to a printer with a different nozzle installed is
  8139. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8140. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8141. # gives the user no idea what went wrong. Catch it here, before we spend
  8142. # time preheating and uploading, and fail with an actionable message.
  8143. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8144. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8145. # the printer hasn't reported its nozzles yet, we fall through and let the
  8146. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8147. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8148. # as one of the two hotends is a 0.6.
  8149. #
  8150. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8151. # (#2885): the printer fetches one as part of starting the print, so the
  8152. # set to test against is "reachable", not "currently mounted". This runs
  8153. # well before the rack picker at the bottom of this method, so without
  8154. # the rack in scope here that picker never got the chance to run.
  8155. sliced_nozzle = archive.nozzle_diameter if archive else None
  8156. if sliced_nozzle:
  8157. nozzle_status = printer_manager.get_status(item.printer_id)
  8158. installed = _installed_nozzle_diameters(nozzle_status)
  8159. rack = _rack_nozzle_diameters(nozzle_status)
  8160. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8161. if mismatch_msg:
  8162. if not await self._fail_dispatch(db, item, mismatch_msg):
  8163. return
  8164. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8165. await notification_service.on_queue_job_failed(
  8166. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8167. printer_id=printer.id,
  8168. printer_name=printer.name,
  8169. reason=mismatch_msg,
  8170. db=db,
  8171. )
  8172. try:
  8173. await ws_manager.send_queue_item_failed(
  8174. user_id=item.created_by_id,
  8175. queue_item_id=item.id,
  8176. printer_id=item.printer_id,
  8177. reason="nozzle_mismatch",
  8178. )
  8179. except Exception:
  8180. pass
  8181. await self._power_off_if_needed(db, item)
  8182. return
  8183. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8184. # bed (and chamber, if applicable) is at temperature when the firmware
  8185. # starts the actual print routine. Best-effort: any failure logs and
  8186. # falls through to the normal upload+start path rather than turning a
  8187. # configuration issue into a failed queue item.
  8188. # Returns False only when the item was cancelled or deleted while the
  8189. # stage was holding at temperature. Uploading and starting it anyway
  8190. # would print a job the user has already called off, so abandon the
  8191. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8192. if not await self._preheat_and_soak(db, item, printer, archive):
  8193. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8194. return
  8195. # See `_effective_plate_id` for why this is resolved once here rather
  8196. # than each site below repeating `item.plate_id or 1`.
  8197. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8198. # G-code injection for auto-print systems (#422)
  8199. injected_path = None
  8200. # #2547: tracked separately from `injected_path`, which is also set when
  8201. # only a START snippet was injected. Only an END snippet changes what the
  8202. # camera sees at print completion.
  8203. end_gcode_injected = False
  8204. if item.gcode_injection:
  8205. try:
  8206. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8207. if snippets_raw:
  8208. snippets = json.loads(snippets_raw)
  8209. model_snippets = snippets.get(printer.model, {})
  8210. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8211. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8212. if start_gc or end_gc:
  8213. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8214. injected_path = inject_gcode_into_3mf(
  8215. file_path, effective_plate_id, start_gc or None, end_gc or None
  8216. )
  8217. if injected_path:
  8218. file_path = injected_path
  8219. end_gcode_injected = bool(end_gc)
  8220. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8221. else:
  8222. logger.warning(
  8223. "Queue item %s: G-code injection returned no result, using original", item.id
  8224. )
  8225. except Exception as e:
  8226. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8227. # #2547: the finish-photo path can't learn from telemetry that this print
  8228. # ends with user End G-code — which means the plate may be gone by the
  8229. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8230. # the print once the printer confirms it running.
  8231. if end_gcode_injected:
  8232. print_dispatch_context.mark_pending(printer.id)
  8233. # Upload to root directory (not /cache/) - the start_print command references
  8234. # files by name only (ftp://{filename}), so they must be in the root
  8235. remote_filename = derive_remote_filename(filename)
  8236. remote_path = f"/{remote_filename}"
  8237. # Get FTP retry settings
  8238. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8239. logger.info(
  8240. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8241. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8242. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8243. )
  8244. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8245. # Every read this method needs (printer, archive/library, preheat) is
  8246. # done, and the library-file branch already committed its archive
  8247. # creation. Without this the transaction opened by the first SELECT above
  8248. # stays "idle in transaction" for the entire upload — multiple seconds
  8249. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8250. # a farm dispatching many jobs at once then exhausts the pool. This was
  8251. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8252. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8253. # readable; the status writes below (upload-failure path and the
  8254. # pending->printing CAS) transparently open a fresh transaction.
  8255. # The owner is read here, after preheat, so the commit releases this read too.
  8256. toast_uid = await self._queue_owner_id(db, item)
  8257. await db.commit()
  8258. # Delete existing file if present (avoids 553 error on overwrite)
  8259. try:
  8260. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8261. delete_result = await delete_file_async(
  8262. printer.ip_address,
  8263. printer.access_code,
  8264. remote_path,
  8265. socket_timeout=ftp_timeout,
  8266. printer_model=printer.model,
  8267. # This delete and the upload below are one bounded, user-initiated
  8268. # unit -- at most nine connections -- so neither skips on the
  8269. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8270. # trace this delete took the TLS failure and armed the cool-off,
  8271. # and the upload's four attempts were then spent against it
  8272. # without a socket being opened.
  8273. respect_handshake_cooloff=False,
  8274. )
  8275. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8276. except Exception as e:
  8277. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8278. # Dispatch toast — announce the upload start with the total byte
  8279. # count so the frontend can render an honest progress bar.
  8280. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8281. try:
  8282. total_bytes = file_path.stat().st_size
  8283. except OSError:
  8284. total_bytes = 0
  8285. try:
  8286. await ws_manager.send_queue_item_uploading(
  8287. user_id=toast_uid,
  8288. queue_item_id=item.id,
  8289. printer_id=item.printer_id,
  8290. printer_name=printer.name,
  8291. file_name=toast_file_name,
  8292. total_bytes=total_bytes,
  8293. )
  8294. except Exception:
  8295. pass # toast is best-effort
  8296. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8297. # A deadline expiry gets its own message: "check your SD card" is the
  8298. # wrong advice for a link that was simply too slow to finish (#2529).
  8299. upload_error: str | None = None
  8300. # Why the upload failed, straight from the client rather than inferred.
  8301. # Owned here, so a background fetch for another print cannot overwrite
  8302. # it between the failure and the sentence built from it (#2899).
  8303. upload_failure = FtpFailureReport()
  8304. try:
  8305. if ftp_retry_enabled:
  8306. uploaded = await with_ftp_retry(
  8307. upload_file_async,
  8308. printer.ip_address,
  8309. printer.access_code,
  8310. file_path,
  8311. remote_path,
  8312. socket_timeout=ftp_timeout,
  8313. printer_model=printer.model,
  8314. progress_callback=progress_bridge,
  8315. respect_handshake_cooloff=False,
  8316. failure=upload_failure,
  8317. max_retries=ftp_retry_count,
  8318. retry_delay=ftp_retry_delay,
  8319. operation_name=f"Upload print to {printer.name}",
  8320. )
  8321. else:
  8322. uploaded = await upload_file_async(
  8323. printer.ip_address,
  8324. printer.access_code,
  8325. file_path,
  8326. remote_path,
  8327. socket_timeout=ftp_timeout,
  8328. printer_model=printer.model,
  8329. progress_callback=progress_bridge,
  8330. respect_handshake_cooloff=False,
  8331. failure=upload_failure,
  8332. )
  8333. except UploadCancelled as e:
  8334. uploaded = False
  8335. upload_error = (
  8336. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8337. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8338. )
  8339. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8340. except Exception as e:
  8341. uploaded = False
  8342. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8343. # Clean up injected temp file after upload attempt
  8344. if injected_path and injected_path.exists():
  8345. injected_path.unlink(missing_ok=True)
  8346. # Again after the upload, which can take minutes: an owner deleted
  8347. # meanwhile gets no more toasts, and neither does whoever has their id.
  8348. toast_uid = await self._queue_owner_id(db, item)
  8349. # The printer's copy at this path was replaced (or deleted above): the
  8350. # file browser's previews must not show the old one.
  8351. from backend.app.services.printer_file_cache import printer_file_cache
  8352. printer_file_cache.forget(printer.id, remote_path)
  8353. if not uploaded:
  8354. # This used to be one string for every upload failure, telling
  8355. # everyone to check the SD card. The client knows which of seven
  8356. # things went wrong and logs each one differently; it just had no
  8357. # way to say so here, so the card got named even for a TLS
  8358. # handshake that never reached the printer's filesystem (#2899).
  8359. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8360. failure = upload_failure.failure
  8361. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8362. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  8363. return
  8364. if not await self._fail_dispatch(db, item, error_msg):
  8365. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8366. return
  8367. logger.error(
  8368. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8369. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8370. )
  8371. # Send failure notification
  8372. await notification_service.on_queue_job_failed(
  8373. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8374. printer_id=printer.id,
  8375. printer_name=printer.name,
  8376. # The same sentence the queue shows. A push notification saying
  8377. # something different from the UI is its own small bug (#2899).
  8378. reason=error_msg,
  8379. db=db,
  8380. )
  8381. try:
  8382. await ws_manager.send_queue_item_failed(
  8383. user_id=toast_uid,
  8384. queue_item_id=item.id,
  8385. printer_id=item.printer_id,
  8386. reason="upload_failed",
  8387. )
  8388. except Exception:
  8389. pass
  8390. await self._power_off_if_needed(db, item)
  8391. return
  8392. # The printer took a file, so any run of refused uploads is over: the
  8393. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8394. self._upload_refusals.pop(printer.id, None)
  8395. self._upload_refusal_notified.discard(printer.id)
  8396. # Parse AMS mapping if stored
  8397. ams_mapping = None
  8398. if item.ams_mapping:
  8399. try:
  8400. ams_mapping = json.loads(item.ams_mapping)
  8401. except json.JSONDecodeError:
  8402. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8403. # Register as expected print so we don't create a duplicate archive
  8404. # Only applicable for archive-based prints
  8405. if archive:
  8406. from backend.app.main import register_expected_print
  8407. register_expected_print(
  8408. item.printer_id,
  8409. remote_filename,
  8410. archive.id,
  8411. ams_mapping=ams_mapping,
  8412. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8413. # no print-start email, and neither does whoever has their id.
  8414. created_by_id=toast_uid,
  8415. cost_center_id=item.cost_center_id,
  8416. # The plate actually dispatched, not the queue item's raw
  8417. # column: on None, `register_expected_print` stores nothing,
  8418. # and `extract_filament_usage_from_3mf` then books every
  8419. # filament in the file rather than the one plate that printed.
  8420. plate_id=effective_plate_id,
  8421. )
  8422. # Registration happens before the print command by necessity (the
  8423. # printer can report the print before the send returns), so record
  8424. # what to undo if we never get as far as sending. `_dispatch_one`
  8425. # rolls back anything still pending here on every exit — exception,
  8426. # early return, or cancel winning the CAS below.
  8427. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8428. # Propagate the queue item's owner into printer_manager so the
  8429. # print-complete callback can credit the user in the PrintLogEntry
  8430. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8431. # items) or when the user clicks the manual-start button.
  8432. await self._propagate_owner_to_printer_manager(db, item)
  8433. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8434. # This prevents phantom reprints if the backend crashes/restarts after the
  8435. # print command is sent but before the status update is committed.
  8436. # If we crash after this commit but before start_print(), the item will be
  8437. # in "printing" status without actually printing - but that's safer than
  8438. # accidentally reprinting the same file hours later.
  8439. #
  8440. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8441. # initial pending read at the top of check_queue and this point) flips
  8442. # the row to "cancelled" in a separate session. Without the WHERE
  8443. # status='pending' clause, the unconditional update here would silently
  8444. # overwrite that cancellation and we'd ship the MQTT start_print below
  8445. # — printer obeys, user sees "I pressed cancel and the print started".
  8446. # rowcount==0 means the user won the race; bail out, best-effort delete
  8447. # the file we just uploaded, do NOT send start_print.
  8448. now_utc = datetime.now(timezone.utc)
  8449. billing_run_id = str(uuid.uuid4())
  8450. # Written with the move to printing, so a retried send replaces the
  8451. # last answer and a cancelled one leaves the row alone (#3279).
  8452. color_substitutions = await self._color_substitutions_for(db, item)
  8453. cas = await db.execute(
  8454. update(PrintQueueItem)
  8455. .where(PrintQueueItem.id == item.id)
  8456. .where(PrintQueueItem.status == "pending")
  8457. .values(
  8458. status="printing",
  8459. started_at=now_utc,
  8460. billing_run_id=billing_run_id,
  8461. color_substitutions=color_substitutions,
  8462. )
  8463. )
  8464. await db.commit()
  8465. if cas.rowcount == 0:
  8466. logger.info(
  8467. "Queue item %s no longer pending at print-command time "
  8468. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8469. item.id,
  8470. )
  8471. try:
  8472. await delete_file_async(
  8473. printer.ip_address,
  8474. printer.access_code,
  8475. remote_path,
  8476. socket_timeout=ftp_timeout,
  8477. printer_model=printer.model,
  8478. )
  8479. except Exception as cleanup_err:
  8480. logger.debug(
  8481. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8482. item.id,
  8483. cleanup_err,
  8484. )
  8485. try:
  8486. await ws_manager.send_queue_item_failed(
  8487. user_id=toast_uid,
  8488. queue_item_id=item.id,
  8489. printer_id=item.printer_id,
  8490. reason="cancelled_mid_dispatch",
  8491. )
  8492. except Exception:
  8493. pass
  8494. return
  8495. # Sync the in-memory item so subsequent code that reads item.status /
  8496. # item.started_at sees the values we just persisted.
  8497. item.status = "printing"
  8498. item.started_at = now_utc
  8499. item.billing_run_id = billing_run_id
  8500. if archive is not None:
  8501. archive.billing_run_id = billing_run_id
  8502. # Legacy transaction deletion used an archive-wide skip flag.
  8503. # A newly dispatched run has its own UUID/tombstone, so it must be
  8504. # billable independently of any older deleted run on this archive.
  8505. archive.wallet_charge_skipped = False
  8506. # Persist before MQTT send so completion and restart recovery can
  8507. # always recover the internal billing identity.
  8508. await db.commit()
  8509. for cleanup_path in cleanup_disk_paths:
  8510. try:
  8511. if cleanup_path.exists():
  8512. cleanup_path.unlink()
  8513. except OSError as cleanup_err:
  8514. logger.warning(
  8515. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8516. json.dumps(
  8517. {
  8518. "queue_item_id": item.id,
  8519. "path": str(cleanup_path),
  8520. "error": str(cleanup_err),
  8521. },
  8522. sort_keys=True,
  8523. ),
  8524. )
  8525. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8526. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8527. # #1898: with the opt-in default-good setting, moving on to the next
  8528. # print resolves the previous print's unanswered outcome prompt as
  8529. # "good" — this path also covers the camera-based plate detection,
  8530. # which releases the gate by allowing dispatch rather than by an
  8531. # explicit acknowledgment. Rides on the dispatch transaction.
  8532. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8533. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8534. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8535. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8536. # Capture state before dispatch so the watchdog can detect whether the
  8537. # printer actually transitioned (#967). Also capture subtask_id so the
  8538. # watchdog can recognise "command landed but state hasn't flipped yet"
  8539. # on slow H2D transitions (#1078).
  8540. pre_status = printer_manager.get_status(item.printer_id)
  8541. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8542. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8543. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8544. # #1721: respect the user's explicit timelapse choice. The #1397
  8545. # force-on at dispatch was removed because it caused per-layer nozzle
  8546. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8547. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8548. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8549. # FINISH-state fallback — no need to force a video.
  8550. effective_timelapse = bool(item.timelapse)
  8551. # Nozzle-rack fallback (#2800). A job that never passed through the
  8552. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8553. # dispatches with no nozzle field at all and chooses for itself — which
  8554. # is how a print levelled on one hotend and then printed on another,
  8555. # millimetres above the plate. Derive the per-slot extruder assignment
  8556. # from the file being dispatched.
  8557. #
  8558. # Done here rather than at queue time because this is the first point
  8559. # that knows both the actual printer and the actual file: an item can
  8560. # be created without a printer (model-based assignment), reassigned
  8561. # afterwards, or have its file swapped for a G-code-injected copy just
  8562. # above. Every queue-creation path — the print dialog, a bulk library
  8563. # add, the webhook, a pipeline run — is covered by the one call.
  8564. # Skipped when the item already carries a Bambu Studio capture: that
  8565. # one wins downstream anyway, so reading the 3MF again would be work
  8566. # thrown away on every dispatch.
  8567. # Rack position resolution (#1784), tried before the #2800 fallback
  8568. # below because it can express what that one cannot: a plate wanting a
  8569. # *different* hotend off the rack per filament group. The position per
  8570. # group is the operator's pick — the 3MF states it nowhere, proven by
  8571. # sending one plate twice with different picks and finding the two
  8572. # files identical bar float noise — so it is resolved here against the
  8573. # rack as it stands right now, after the upload, not at queue time.
  8574. resolved_nozzle_mapping = None
  8575. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8576. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8577. if rack_plan is not None:
  8578. try:
  8579. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8580. except (json.JSONDecodeError, TypeError):
  8581. stored_choice = {}
  8582. logger.warning(
  8583. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8584. item.id,
  8585. item.nozzle_rack_choice,
  8586. )
  8587. # JSON object keys are strings; the groups are ints.
  8588. choice: dict[int, int] = {}
  8589. for key, value in (stored_choice or {}).items():
  8590. try:
  8591. choice[int(key)] = int(value)
  8592. except (TypeError, ValueError):
  8593. continue
  8594. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8595. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8596. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8597. )
  8598. if resolved_nozzle_mapping is None and choice:
  8599. # An explicit pick that no longer holds stops the print. The
  8600. # operator named a hotend; printing from a different one is
  8601. # how a plate gets levelled on one nozzle and drawn with
  8602. # another, millimetres above the bed. Nothing has been sent
  8603. # to the printer yet, so failing here costs only the upload.
  8604. # The file is already on the SD card by this point, and a
  8605. # 3MF left there is a phantom print waiting to be started
  8606. # from the touchscreen. Same cleanup the start_print
  8607. # failure path below does, for the same reason.
  8608. try:
  8609. await delete_file_async(
  8610. printer.ip_address,
  8611. printer.access_code,
  8612. remote_path,
  8613. printer_model=printer.model,
  8614. )
  8615. except Exception:
  8616. pass # Best-effort — don't fail the error handler
  8617. if not await self._fail_dispatch(
  8618. db,
  8619. item,
  8620. (
  8621. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8622. "Edit the item to choose another position."
  8623. ),
  8624. ):
  8625. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8626. return
  8627. logger.warning(
  8628. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8629. item.id,
  8630. printer.name,
  8631. rack_error,
  8632. choice,
  8633. [slot.get("id") for slot in live_rack],
  8634. )
  8635. await notification_service.on_queue_job_failed(
  8636. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8637. printer_id=printer.id,
  8638. printer_name=printer.name,
  8639. reason=item.error_message,
  8640. db=db,
  8641. )
  8642. try:
  8643. await ws_manager.send_queue_item_failed(
  8644. user_id=toast_uid,
  8645. queue_item_id=item.id,
  8646. printer_id=item.printer_id,
  8647. reason="nozzle_rack_pick_stale",
  8648. )
  8649. except Exception:
  8650. pass # Best-effort — don't fail the error handler
  8651. return
  8652. if resolved_nozzle_mapping is None:
  8653. # Nothing was picked and nothing could be assigned. Falls
  8654. # through to the #2800 path, which is what ran before this
  8655. # existed — strictly not worse than today.
  8656. logger.info(
  8657. "Queue item %s: no rack positions assignable (%s); falling back",
  8658. item.id,
  8659. rack_error,
  8660. )
  8661. else:
  8662. logger.info(
  8663. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8664. item.id,
  8665. resolved_nozzle_mapping,
  8666. rack_plan.slot_groups,
  8667. choice or "auto",
  8668. )
  8669. nozzle_slot_extruders = None
  8670. if (
  8671. not item.nozzle_mapping
  8672. and resolved_nozzle_mapping is None
  8673. and file_path is not None
  8674. and is_nozzle_rack_model(printer.model)
  8675. ):
  8676. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8677. if slot_extruders:
  8678. nozzle_slot_extruders = json.dumps(slot_extruders)
  8679. # Every filament this plate prints is on the external spool -> the print
  8680. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8681. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8682. # table", which is what held the reporter's P1S at Heatbed preheating
  8683. # for ten minutes before it gave up (#3087). The MQTT command builder
  8684. # already downgrades a mapping that is *only* external ([254]), but a
  8685. # multi-filament project pads the slots this plate does not print with
  8686. # -1 — BambuStudio's own convention — and down there a -1 is
  8687. # indistinguishable from a slot that never resolved, which must never be
  8688. # sent to the spool holder (#2589). Here the plate's filament list says
  8689. # which is which, so the answer is exact rather than a guess.
  8690. #
  8691. # Deliberately narrow: this fires only when every consumed slot is an
  8692. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8693. # alone and the firmware still rejects the print, exactly as today. And
  8694. # only for single-nozzle printers, mirroring the builder's own reconcile
  8695. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8696. # whether to use the AMS, so it is not ours to rewrite.
  8697. effective_use_ams = item.use_ams
  8698. plate_uses_only_external = False
  8699. if (
  8700. ams_mapping
  8701. and file_path is not None
  8702. # Cheap gate before opening the file: with nothing on the spool
  8703. # holder anywhere in the mapping, no subset of it can be all
  8704. # external, so most dispatches never pay for the parse. The
  8705. # isinstance also keeps a malformed stored mapping (a bare number
  8706. # from a hand-edited row) failing where it always failed, in the
  8707. # command builder, rather than here.
  8708. and isinstance(ams_mapping, list)
  8709. and any(_is_external_tray(t) for t in ams_mapping)
  8710. and not _might_be_dual_nozzle(printer.model, pre_status)
  8711. ):
  8712. from backend.app.services.filament_requirements import extract_filament_requirements
  8713. consumed = _consumed_mapping_entries(
  8714. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8715. )
  8716. if consumed and all(_is_external_tray(t) for t in consumed):
  8717. # Exact for this plate: the command builder must not turn the
  8718. # AMS back on for a real tray another plate of the file uses,
  8719. # whether the job asked for the AMS or already had it off.
  8720. plate_uses_only_external = True
  8721. if plate_uses_only_external and effective_use_ams:
  8722. effective_use_ams = False
  8723. logger.info(
  8724. "Queue item %s: every filament plate %s prints is on the external spool "
  8725. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8726. item.id,
  8727. effective_plate_id,
  8728. ams_mapping,
  8729. )
  8730. # A slot that lost its K-profile selection (a power cycle resets every
  8731. # slot to the default K) would print on the default. The idle check in
  8732. # the status handler normally restores it first, but nothing guarantees
  8733. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8734. # Never allowed to stop the print it is protecting.
  8735. try:
  8736. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8737. except Exception:
  8738. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8739. # Start the print with AMS mapping, plate_id and print options.
  8740. # nozzle_mapping rides through verbatim — JSON string captured from
  8741. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8742. # parses + injects it only for dual-nozzle models so a null on every
  8743. # other model is a transparent pass-through. The rack fallback is
  8744. # resolved down there too, where the live rack position is known.
  8745. started = printer_manager.start_print(
  8746. item.printer_id,
  8747. remote_filename,
  8748. plate_id=effective_plate_id,
  8749. ams_mapping=ams_mapping,
  8750. bed_levelling=item.bed_levelling,
  8751. flow_cali=item.flow_cali,
  8752. vibration_cali=item.vibration_cali,
  8753. layer_inspect=item.layer_inspect,
  8754. timelapse=effective_timelapse,
  8755. use_ams=effective_use_ams,
  8756. plate_uses_only_external=plate_uses_only_external,
  8757. nozzle_offset_cali=item.nozzle_offset_cali,
  8758. nozzle_mapping=item.nozzle_mapping
  8759. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8760. nozzle_slot_extruders=nozzle_slot_extruders,
  8761. )
  8762. if started:
  8763. # The command is away, so the expectation is now legitimate and must
  8764. # survive. Anything still in this dict when _dispatch_one exits gets
  8765. # rolled back.
  8766. self._unconfirmed_expected_print.pop(item.id, None)
  8767. self._unconfirmed_budget_reservations.discard(item.id)
  8768. self._unconfirmed_print_user.pop(item.id, None)
  8769. if item.printer_id is not None:
  8770. self._sent_unstarted_print[item.id] = (
  8771. item.printer_id,
  8772. remote_filename if archive else None,
  8773. archive.id if archive else None,
  8774. )
  8775. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8776. # target, chamber target, airduct heating) — the gcode owns
  8777. # heater/flap control from here. Clearing the pin prevents
  8778. # `_dispatch_one`'s finally from unwinding a live print.
  8779. self._preheat_pin.pop(item.printer_id, None)
  8780. self._preheat_pin_bed.pop(item.printer_id, None)
  8781. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8782. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8783. # status='processing' from upload start until the printer acked
  8784. # (or timed out). The frontend derives "Awaiting printer…" purely
  8785. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8786. # event would push the status chip out of 'PROCESSING' prematurely
  8787. # — which is exactly what the screenshot at #1625-followup
  8788. # complained about.
  8789. # Register the local 3MF in the cover-cache so /cover skips FTP
  8790. # (#1166 follow-up). file_path was resolved earlier from either the
  8791. # archive or the library file row.
  8792. if file_path is not None:
  8793. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8794. # Hold the printer against further dispatches until the watchdog
  8795. # confirms the printer transitioned (or until the hard timeout).
  8796. # Prevents multi-plate batches from triple-dispatching onto the
  8797. # same H2D Pro while it digests the first project_file (#1157).
  8798. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8799. # Watchdog: if the printer never transitions out of pre_state AND
  8800. # never advances subtask_id, the MQTT publish was accepted locally but
  8801. # didn't reach the printer (half-broken session — same shape as
  8802. # #887/#936). Revert the queue item so the next dispatch can pick it
  8803. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8804. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8805. # that would otherwise cause the item to re-dispatch as a reprint
  8806. # of the just-finished job (#1078).
  8807. if pre_state:
  8808. spawn_background_task(
  8809. self._watchdog_print_start(
  8810. item.id,
  8811. item.printer_id,
  8812. pre_state,
  8813. pre_subtask_id,
  8814. pre_gcode_file,
  8815. created_by_id=toast_uid,
  8816. ),
  8817. name=f"watchdog-print-start-{item.id}",
  8818. )
  8819. # Get estimated time for notification.
  8820. #
  8821. # This used to fall back to `library_file.print_time_seconds`, a column
  8822. # LibraryFile does not have — the print time it knows about lives in
  8823. # `file_metadata`. So a library print whose archive carried no parseable
  8824. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8825. # AttributeError right here, *after* the printer had already been sent
  8826. # the job: the started-notification never fired, and the exception
  8827. # unwound the whole queue pass, so every other printer still waiting to
  8828. # be dispatched on that tick silently missed its turn.
  8829. #
  8830. # The queue item caches the print time at creation ("Cached from
  8831. # archive/library"), which is the value this was reaching for.
  8832. estimated_time = None
  8833. if archive and archive.print_time_seconds:
  8834. estimated_time = archive.print_time_seconds
  8835. elif item.print_time_seconds:
  8836. estimated_time = item.print_time_seconds
  8837. # Send job started notification
  8838. await notification_service.on_queue_job_started(
  8839. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8840. printer_id=printer.id,
  8841. printer_name=printer.name,
  8842. db=db,
  8843. estimated_time=estimated_time,
  8844. )
  8845. # MQTT relay - publish queue job started
  8846. try:
  8847. await mqtt_relay.on_queue_job_started(
  8848. job_id=item.id,
  8849. filename=filename,
  8850. printer_id=printer.id,
  8851. printer_name=printer.name,
  8852. printer_serial=printer.serial_number,
  8853. )
  8854. except Exception:
  8855. pass # Don't fail if MQTT fails
  8856. else:
  8857. # Clean up uploaded file from SD card to prevent phantom prints
  8858. try:
  8859. await delete_file_async(
  8860. printer.ip_address,
  8861. printer.access_code,
  8862. remote_path,
  8863. printer_model=printer.model,
  8864. )
  8865. except Exception:
  8866. pass # Best-effort — don't fail the error handler
  8867. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8868. # state can flip from idle to active in the window between the
  8869. # pre-dispatch check above and this publish (the FTP upload takes
  8870. # seconds); start_print() then refuses to send project_file to the
  8871. # now-busy printer and returns False. Failing the item here would be
  8872. # wrong — the printer is fine, it is simply busy — so revert to
  8873. # pending and let a later tick dispatch it once the printer is idle,
  8874. # exactly like the pre-dispatch guard. Only a start_print() False on
  8875. # an idle/unknown printer is a genuine command failure.
  8876. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8877. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8878. logger.info(
  8879. "Queue item %s: printer %s became busy (state=%s) before the start "
  8880. "command was sent — deferring, reverting item to pending (#2598)",
  8881. item.id,
  8882. item.printer_id,
  8883. post_dispatch_state,
  8884. )
  8885. await self._defer_until_printer_idle(db, item)
  8886. return
  8887. # Print command failed - revert status
  8888. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8889. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8890. return
  8891. logger.error(
  8892. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8893. f"printer_manager.start_print() returned False. "
  8894. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8895. f"Check printer status and backend logs for details."
  8896. )
  8897. # Send failure notification
  8898. await notification_service.on_queue_job_failed(
  8899. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8900. printer_id=printer.id,
  8901. printer_name=printer.name,
  8902. reason="Failed to send print command to printer - check printer connection and status",
  8903. db=db,
  8904. )
  8905. try:
  8906. await ws_manager.send_queue_item_failed(
  8907. user_id=toast_uid,
  8908. queue_item_id=item.id,
  8909. printer_id=item.printer_id,
  8910. reason="start_command_failed",
  8911. )
  8912. except Exception:
  8913. pass
  8914. await self._power_off_if_needed(db, item)
  8915. @staticmethod
  8916. async def _watchdog_print_start(
  8917. queue_item_id: int,
  8918. printer_id: int,
  8919. pre_state: str,
  8920. pre_subtask_id: str | None = None,
  8921. pre_gcode_file: str | None = None,
  8922. timeout: float = 90.0,
  8923. phase_b_timeout: float = 180.0,
  8924. poll_interval: float = 3.0,
  8925. created_by_id: int | None = None,
  8926. ) -> None:
  8927. """Revert a queue item if the printer never acknowledges the start command.
  8928. Bambuddy optimistically marks the queue item as "printing" right after the
  8929. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8930. Phase A (up to ``timeout``): wait for either an active-state transition
  8931. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8932. primary signal; subtask_id advance handles the H2D case where state can
  8933. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8934. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8935. was lost on a half-broken session (#887/#936) — revert and force
  8936. reconnect (the #967 recovery path).
  8937. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8938. alone): keep watching for the active-state transition. subtask_id alone
  8939. proves the file landed but not that the printer started — and a printer
  8940. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8941. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8942. used to leave the queue item stuck in 'printing' forever because the
  8943. old watchdog returned success as soon as subtask_id advanced. If Phase
  8944. B times out, revert the queue item so the user can retry without
  8945. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8946. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8947. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8948. transitions that also don't emit an early subtask_id tick.
  8949. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8950. refuses to verify our commands will never start this job or any other,
  8951. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8952. burns an upload slot the rest of the farm is queued behind — that path
  8953. is for a printer that might still come good, which this one cannot
  8954. (#2732). It fails the item on the spot with the actual reason instead.
  8955. """
  8956. last_status = None
  8957. landed_on_subtask = False
  8958. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8959. # every push carrying an `hms` key, so the fault can come and go between
  8960. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8961. command_rejected = False
  8962. # Latched for the same reason as command_rejected: drying can finish, or
  8963. # be stopped by the user, part-way through the dispatch window. Seeing it
  8964. # once is what matters — it is the state the printer was in when it
  8965. # declined to start (#2758).
  8966. drying_ams_ids: list[int] = []
  8967. # The printer answered the start with a refusal: nothing will start,
  8968. # and the command was not lost, so no reconnect either.
  8969. start_refusal: tuple[str, str | None] | None = None
  8970. deadline = time.monotonic() + timeout
  8971. while time.monotonic() < deadline:
  8972. await asyncio.sleep(poll_interval)
  8973. status = printer_manager.get_status(printer_id)
  8974. if not status:
  8975. # Printer disconnected — don't mess with the DB. Drop the
  8976. # in-memory dispatch hold too so a fresh dispatch can retry
  8977. # once the printer comes back; the hard timeout would
  8978. # otherwise hold the printer unnecessarily.
  8979. scheduler._release_dispatch_hold(printer_id)
  8980. return
  8981. last_status = status
  8982. if status.state in _ACTIVE_PRINT_STATES:
  8983. # Printer is actively processing the job — release the
  8984. # post-dispatch hold so the next pending item for this printer
  8985. # can be evaluated normally. We do NOT accept arbitrary state
  8986. # transitions: a printer going FINISH -> IDLE (user dismissed
  8987. # the post-print prompt without accepting our project_file)
  8988. # would otherwise look like "command landed" and leave the
  8989. # queue item stuck in 'printing' forever (#1370).
  8990. scheduler._release_dispatch_hold(printer_id)
  8991. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8992. try:
  8993. await ws_manager.send_queue_item_acked(
  8994. user_id=created_by_id,
  8995. queue_item_id=queue_item_id,
  8996. printer_id=printer_id,
  8997. )
  8998. except Exception:
  8999. pass
  9000. return
  9001. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9002. # Checked only after the active-state exit above: a stale HMS left
  9003. # over from an earlier job must never abort a print that is visibly
  9004. # running. An actually-refused command leaves the printer idle, so
  9005. # this ordering costs the detection nothing.
  9006. if _mqtt_commands_rejected(status):
  9007. command_rejected = True
  9008. break
  9009. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9010. if isinstance(refusal, tuple):
  9011. start_refusal = refusal
  9012. break
  9013. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9014. # Phase A exit — printer accepted the file (subtask_id flipped
  9015. # to our submission id). Don't return yet: the printer may
  9016. # have accepted the command but never actually start (e.g.
  9017. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9018. # B watches for the active-state transition.
  9019. landed_on_subtask = True
  9020. break
  9021. if landed_on_subtask and not command_rejected:
  9022. phase_b_deadline = time.monotonic() + phase_b_timeout
  9023. while time.monotonic() < phase_b_deadline:
  9024. await asyncio.sleep(poll_interval)
  9025. status = printer_manager.get_status(printer_id)
  9026. if not status:
  9027. scheduler._release_dispatch_hold(printer_id)
  9028. return
  9029. last_status = status
  9030. if status.state in _ACTIVE_PRINT_STATES:
  9031. scheduler._release_dispatch_hold(printer_id)
  9032. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9033. try:
  9034. await ws_manager.send_queue_item_acked(
  9035. user_id=created_by_id,
  9036. queue_item_id=queue_item_id,
  9037. printer_id=printer_id,
  9038. )
  9039. except Exception:
  9040. pass
  9041. return
  9042. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9043. # Same ordering rule as Phase A: a running print wins over a
  9044. # lingering HMS.
  9045. if _mqtt_commands_rejected(status):
  9046. command_rejected = True
  9047. break
  9048. # No active-state transition. Revert the item so the scheduler can retry.
  9049. # Drop the in-memory hold so the retry isn't blocked by it.
  9050. scheduler._release_dispatch_hold(printer_id)
  9051. # Logged on every failed dispatch window, not just the last one, so a
  9052. # support bundle shows the correlation from the first attempt rather than
  9053. # only after the retry budget is spent (#2758).
  9054. if drying_ams_ids:
  9055. logger.info(
  9056. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9057. queue_item_id,
  9058. printer_id,
  9059. ", ".join(str(i) for i in drying_ams_ids),
  9060. )
  9061. # Four outcomes from the revert attempt, each routed differently:
  9062. # "reverted": row flipped from printing -> pending, run recovery
  9063. # "gave_up": same, but the retry budget is spent — row failed
  9064. # rather than pending, so it stops going round again
  9065. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9066. # on_print_complete or user). Skip recovery entirely
  9067. # — the print clearly landed somewhere even if the
  9068. # watchdog didn't see the active-state transition.
  9069. # "revert_failed": SQLite contention exhausted retries. Still run
  9070. # recovery so the MQTT session gets a fresh client_id
  9071. # on the half-broken-session path.
  9072. #
  9073. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9074. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9075. # the watchdog again. For a printer that is genuinely wedged that loop never
  9076. # ends — the reporter had one printer "since this morning still not launch"
  9077. # — and each lap also consumes an upload slot that the other printers in the
  9078. # farm are waiting on. Retrying is right; retrying forever is not.
  9079. async def _do_revert(db):
  9080. item = await db.get(PrintQueueItem, queue_item_id)
  9081. if not item or item.status != "printing":
  9082. return "already_moved_on"
  9083. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9084. item.started_at = None
  9085. # The print never started: no slot printed in any colour (#3279).
  9086. item.color_substitutions = None
  9087. # Charge the attempt to the candidate that was actually dispatched, so
  9088. # a cross-model item (#671) reaches for its other file next lap instead
  9089. # of retrying the printer that just failed to start. Matched by file
  9090. # because that is what the resolver copied onto the row.
  9091. if item.library_file_id is not None:
  9092. await db.execute(
  9093. update(PrintQueueVariant)
  9094. .where(PrintQueueVariant.queue_item_id == item.id)
  9095. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9096. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9097. )
  9098. if command_rejected:
  9099. # No retry budget for this one: the printer refused to verify the
  9100. # command, and re-uploading the same 3MF to the same printer will
  9101. # be refused the same way. Fail now with the fix rather than after
  9102. # three laps of a message about SD cards (#2732).
  9103. item.status = "failed"
  9104. item.error_message = (
  9105. "The printer rejected the print command: MQTT command verification failed "
  9106. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9107. "then start the job again."
  9108. )
  9109. item.completed_at = datetime.now(timezone.utc)
  9110. await db.commit()
  9111. return "command_rejected"
  9112. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9113. item.status = "failed"
  9114. if drying_ams_ids:
  9115. # #2758: the generic message below sent the reporter looking
  9116. # at the SD card while the actual obstacle — AMS units in a
  9117. # drying cycle — was on screen the whole time. Name what we
  9118. # observed and let the user judge it; Bambuddy does not stop
  9119. # the cycle itself, because on this hardware drying can run
  9120. # alongside a print and stopping it may not be the fix.
  9121. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9122. item.error_message = (
  9123. f"The printer accepted the file but never started printing, after "
  9124. f"{item.dispatch_attempts} attempts. {units} "
  9125. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9126. f"some printers refuse to begin a print while an AMS is in a drying "
  9127. f"cycle, and an AMS drying without its external power supply can also "
  9128. f"leave too little power for the start-of-print calibration. Stop the "
  9129. f"drying, or connect the AMS power supply, and start the job again."
  9130. )
  9131. else:
  9132. item.error_message = (
  9133. f"The printer accepted the file but never started printing, after "
  9134. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9135. f"prompt or error, confirm its SD card is readable, and start the job again."
  9136. )
  9137. item.completed_at = datetime.now(timezone.utc)
  9138. await release_budget_reservation(
  9139. db,
  9140. source_type="print_queue",
  9141. source_id=item.id,
  9142. status="released",
  9143. )
  9144. await db.commit()
  9145. return "gave_up"
  9146. item.status = "pending"
  9147. await db.commit()
  9148. return "reverted"
  9149. try:
  9150. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9151. except Exception as e:
  9152. logger.warning(
  9153. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9154. "scheduler may keep treating this item as in-flight",
  9155. queue_item_id,
  9156. printer_id,
  9157. e,
  9158. )
  9159. revert_outcome = "revert_failed"
  9160. if revert_outcome in ("command_rejected", "gave_up"):
  9161. # The item is failed: its print user and expected print must not
  9162. # pass the printer's next print off as Bambuddy's.
  9163. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9164. from backend.app.services.print_batch import refresh_batches_after
  9165. await refresh_batches_after([queue_item_id])
  9166. elif revert_outcome == "reverted":
  9167. # Another try claims the printer again. Until then no print on it
  9168. # is vouched for as this item's, except a late start of its file.
  9169. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9170. elif revert_outcome == "already_moved_on":
  9171. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9172. if revert_outcome == "already_moved_on":
  9173. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9174. # other path) already moved the item past 'printing', don't run the
  9175. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9176. # session breaks ongoing prints on the same printer.
  9177. return
  9178. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9179. if revert_outcome == "command_rejected":
  9180. logger.error(
  9181. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9182. "failed) — the print command was rejected, not lost. Failing the item "
  9183. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9184. queue_item_id,
  9185. printer_id,
  9186. HMS_MQTT_VERIFY_FAILED,
  9187. )
  9188. await scheduler._notify_dispatch_gave_up(
  9189. queue_item_id,
  9190. printer_id,
  9191. created_by_id,
  9192. reason="Printer rejected the print command (MQTT command verification failed)",
  9193. )
  9194. # Same reasoning as the landed_on_subtask path below: the file is on
  9195. # the printer and a forced reconnect would only add 0500_4003 to a
  9196. # problem that has nothing to do with the MQTT session (#1150).
  9197. return
  9198. if revert_outcome == "gave_up":
  9199. logger.error(
  9200. "Queue item %s: printer %d never started the print after %d dispatch "
  9201. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9202. "re-uploading it again (#2555)",
  9203. queue_item_id,
  9204. printer_id,
  9205. DISPATCH_MAX_ATTEMPTS,
  9206. total_timeout,
  9207. )
  9208. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9209. elif revert_outcome == "reverted":
  9210. if start_refusal is not None:
  9211. logger.warning(
  9212. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9213. "reverted to 'pending' for retry",
  9214. queue_item_id,
  9215. printer_id,
  9216. start_refusal[0],
  9217. start_refusal[1],
  9218. )
  9219. elif landed_on_subtask:
  9220. logger.warning(
  9221. "Queue item %s: printer %d accepted project_file (subtask_id "
  9222. "advanced) but never transitioned to an active state within "
  9223. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9224. "for retry (#1678)",
  9225. queue_item_id,
  9226. printer_id,
  9227. total_timeout,
  9228. )
  9229. else:
  9230. logger.warning(
  9231. "Queue item %s: printer %d did not respond to print command within "
  9232. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9233. "for retry (#967)",
  9234. queue_item_id,
  9235. printer_id,
  9236. timeout,
  9237. pre_state,
  9238. pre_subtask_id,
  9239. )
  9240. # Phase B was entered iff subtask_id advanced, which means the
  9241. # project_file landed on the printer. A forced reconnect at this point
  9242. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9243. # skip the recovery entirely.
  9244. if landed_on_subtask or start_refusal is not None:
  9245. return
  9246. # Phase A timeout path: if the printer's gcode_file changed since
  9247. # pre-dispatch, the project_file command landed and the printer is
  9248. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9249. # If gcode_file is unchanged, the publish was silently swallowed
  9250. # (#887/#936) and force_reconnect recovery is what we want.
  9251. client = printer_manager.get_client(printer_id)
  9252. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9253. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9254. if publish_landed:
  9255. logger.warning(
  9256. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9257. "received the command and is parsing slowly. Skipping forced "
  9258. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9259. queue_item_id,
  9260. current_gcode_file,
  9261. pre_gcode_file,
  9262. )
  9263. elif client and hasattr(client, "force_reconnect_stale_session"):
  9264. client.force_reconnect_stale_session(
  9265. f"queue print command unacknowledged after {timeout:.0f}s "
  9266. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9267. )
  9268. # Global scheduler instance
  9269. scheduler = PrintScheduler()