print_scheduler.py 538 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635
  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 (
  34. drying_preflight,
  35. kprofile_drift,
  36. print_dispatch_context,
  37. slicer_ams_pick,
  38. stock_forecast,
  39. )
  40. from backend.app.services.bambu_ftp import (
  41. FtpFailureKind,
  42. FtpFailureReport,
  43. UploadCancelled,
  44. cache_3mf_download,
  45. delete_file_async,
  46. describe_upload_failure,
  47. get_ftp_retry_settings,
  48. upload_file_async,
  49. with_ftp_retry,
  50. )
  51. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  52. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  53. from backend.app.services.finance_budget import (
  54. create_budget_reservation,
  55. release_budget_reservation,
  56. validate_print_budget,
  57. )
  58. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  59. from backend.app.services.mqtt_relay import mqtt_relay
  60. from backend.app.services.notification_service import notification_service
  61. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  62. from backend.app.services.printer_manager import (
  63. printer_manager,
  64. printer_tray_layout,
  65. supports_airduct,
  66. supports_chamber_heater,
  67. supports_chamber_temp,
  68. supports_drying,
  69. supports_drying_while_printing,
  70. )
  71. from backend.app.services.queue_item_printer import drop_printer_resolved
  72. from backend.app.services.slot_nozzle import reports_two_nozzles
  73. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  74. from backend.app.services.spool_assignment_notifications import (
  75. _global_tray_from_assignment,
  76. _slot_label_from_global_tray,
  77. )
  78. from backend.app.utils.ams_drying import is_countdown_parked
  79. from backend.app.utils.ams_humidity import ams_humidity_percent
  80. from backend.app.utils.archive_paths import archive_photos_dir
  81. from backend.app.utils.color_utils import perceptual_color_distance
  82. from backend.app.utils.filament_types import canonical_filament_type
  83. from backend.app.utils.filename import InvalidFilenameError, derive_remote_filename, validate_print_filename
  84. from backend.app.utils.library_paths import move_library_photos
  85. from backend.app.utils.local_time import utcnow_naive
  86. from backend.app.utils.printer_models import (
  87. is_dual_nozzle_model,
  88. is_gcode_compatible,
  89. is_nozzle_rack_model,
  90. normalize_printer_model,
  91. )
  92. from backend.app.utils.threemf_tools import (
  93. default_plate_number,
  94. extract_rack_plan_from_3mf,
  95. extract_slot_extruders_from_3mf,
  96. plate_bed_temperature,
  97. select_plate_gcode_name,
  98. )
  99. from backend.app.utils.tray_ids import (
  100. TrayLayout,
  101. is_ams_ht_id,
  102. is_external_tray,
  103. unit_label,
  104. )
  105. logger = logging.getLogger(__name__)
  106. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  107. """Human slot name for an assignment tuple, in the spelling already in use.
  108. Composed from the notification side's own pair rather than spelled out again
  109. here. The hand-rolled version this replaces got three real slot kinds wrong:
  110. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  111. ``chr(191)``; both externals collapsed to one label, because an external
  112. assignment stores ams_id 255 with tray_id picking left or right
  113. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  114. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  115. Naming the same slot two ways is its own defect once an alert and the
  116. Inventory page are meant to be talking about the same tray, so this defers
  117. rather than adding a fifth spelling.
  118. """
  119. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  120. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  121. # interval: the fast path runs every 3 s while an upload is in flight, and a
  122. # low spool does not need answering at that resolution (#2913).
  123. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  124. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  125. # days, so a finer check would only repeat the same answer.
  126. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  127. # The settings row that holds which stock alerts have already been sent (#2955).
  128. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  129. # The Inventory page asks for this many usage records and the forecast panel
  130. # builds its rates from them; the alert reads the same window so the two agree.
  131. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  132. def _spoolman_time(value: object) -> datetime | None:
  133. """A Spoolman ISO timestamp, or None when missing or unreadable."""
  134. if not value:
  135. return None
  136. try:
  137. return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
  138. except ValueError:
  139. return None
  140. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  141. """Remaining filament as a percentage of the label weight.
  142. The same arithmetic the Inventory page's Low Stock count uses, and it works
  143. unchanged in both inventory modes: internal spools store ``weight_used``
  144. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  145. ``remaining_weight`` so the shape matches. Returns None when there is no
  146. label weight to be a percentage of -- a spool that cannot say how full it
  147. started cannot say how empty it is.
  148. """
  149. if not label_weight or label_weight <= 0:
  150. return None
  151. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  152. return remaining / float(label_weight) * 100.0
  153. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  154. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  155. # byte gate) from before the scheduler unification. Time gate keeps small
  156. # files from going silent (a single 8 KB chunk fires once and that's it);
  157. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  158. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  159. # sub-200 ms files.
  160. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  161. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  162. # How far back chamber temperature samples are retained. 2h comfortably spans
  163. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  164. # before the next print.
  165. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  166. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  167. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  168. # who clear plates promptly will want far less than this; it is deliberately
  169. # the cautious end, since the cost of it being too short is only a re-soak.
  170. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  171. # Max acceptable gap between two consecutive chamber samples before we treat
  172. # the older one as belonging to a separate observation run (printer went
  173. # offline and came back). Above ~30s cadence with a safety margin.
  174. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  175. # How long the chamber must read below target before we accept that it really
  176. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  177. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  178. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  179. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  180. # sub-target readings are therefore a door opening or noise, not lost soak,
  181. # and a plate swap (exactly when keep-warm is running) produces one. Six
  182. # minutes clears the longest such artifact observed (~5 min once bracketed by
  183. # its neighbouring samples) and still sits far below the 23-minute floor for
  184. # real cooling.
  185. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  186. # How often the preheat stage re-checks that the item it is heating for still
  187. # wants to be printed. Cancelling only writes `status` to the database — it
  188. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  189. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  190. # and the printer stays in `busy_printers`, blocking every other queued item
  191. # behind a print that is not happening.
  192. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  193. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  194. _AIRDUCT_MODE_COOLING = 0
  195. _AIRDUCT_MODE_HEATING = 1
  196. # How long a queue row may stay 'printing' while its printer sits in a terminal
  197. # state before the scheduler closes it itself (#2829).
  198. #
  199. # A real completion arrives within seconds of the printer going terminal, so
  200. # five minutes is far outside the normal path — this only ever sees a row whose
  201. # completion was refused or never delivered. It is the whole cost of the
  202. # failure to the user, though: a stranded row blocks every later job for that
  203. # printer, so it should not be raised without reason.
  204. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  205. # gcode_state values that mean the print is over, mapped to the queue status
  206. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  207. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  208. # which the queue calls cancelled) so a recovered row cannot disagree with one
  209. # closed by the normal path.
  210. _TERMINAL_STATE_QUEUE_STATUS = {
  211. "FINISH": "completed",
  212. "FAILED": "failed",
  213. "IDLE": "cancelled",
  214. }
  215. def _terminal_queue_status(state) -> str | None:
  216. """Queue status implied by *state*, or None if the print is not over.
  217. None for a disconnected printer as well as a busy one: a printer we are not
  218. talking to has a stale ``state`` field that proves nothing about what it is
  219. doing now.
  220. """
  221. if state is None or not getattr(state, "connected", False):
  222. return None
  223. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  224. @dataclass
  225. class _KeepWarmEntry:
  226. """Per-printer keep-warm state.
  227. - ``started``: monotonic time when keep-warm first fired for this printer.
  228. Used by the max-duration timeout.
  229. - ``held_target``: last bed target we successfully published. On release
  230. we only send bed-off when firmware still reports this value, so a user
  231. or subsequent print that changed the target isn't clobbered.
  232. - ``expired``: latched True when the max-duration timeout fires. Prevents
  233. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  234. release sweep drops the entry entirely once the printer leaves the
  235. candidate set.
  236. """
  237. started: float
  238. held_target: int
  239. expired: bool = False
  240. # Auto-drying re-arm guards (#2770).
  241. #
  242. # An AMS reports HIGHER relative humidity while it is warm than once it has
  243. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  244. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  245. # threshold set inside that band therefore cannot be satisfied while the box is
  246. # hot, and the firmware is free to end a cycle whenever it decides the filament
  247. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  248. # the threshold and arms another cycle. The reporter's log has five 12-hour
  249. # cycles armed inside four hours, one of them six seconds after the previous
  250. # ended.
  251. #
  252. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  253. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  254. # manual or firmware-run dry is untouched.
  255. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  256. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  257. # A cycle whose timer stood still (#3478): the firmware took the command and
  258. # left the heater off, so dry_time stays put with dry_status Off. It tells
  259. # nothing about humidity, so it has its own counter; this many in a row
  260. # suspends the unit with a message that says the unit did not heat, not that
  261. # the threshold is too low.
  262. AUTO_DRY_MAX_NEVER_HEATED_CYCLES = 2
  263. def _never_heated(unit_state: dict[str, object]) -> int:
  264. """Cycles in a row whose timer stood still on this unit (#3478)."""
  265. count = unit_state.get("never_heated")
  266. return count if isinstance(count, int) else 0
  267. # Sustained-humidity wait (#2518): an above-threshold streak is only
  268. # "continuous" if some pass observed it within the gap ceiling. A unit that
  269. # goes unobserved longer (print running, printer disconnected, sensor silent)
  270. # restarts its streak rather than inheriting a stale one. The ceiling is
  271. # derived from the scheduler cadence — four missed passes — with this floor so
  272. # a fast-polling configuration does not void streaks on a single hiccup.
  273. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  274. # How long a finished scheduled drying row is kept before it is pruned.
  275. SCHEDULED_DRYING_RETENTION_DAYS = 7
  276. # How often that prune actually runs. The check itself is called on every queue
  277. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  278. # write transaction, which SQLite serialises against every other writer. Rows
  279. # only become prunable a week after they finish, so anything short of hourly is
  280. # paying that cost for nothing.
  281. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  282. class _UploadProgressBridge:
  283. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  284. ``upload_file_async`` runs the FTP transfer in an executor thread and
  285. invokes its ``progress_callback`` from that thread, so the callback
  286. body cannot ``await`` directly. This bridge captures the asyncio loop
  287. at construction (on the scheduler thread) and uses
  288. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  289. matches the legacy background_dispatch.py path 1:1 so the toast feels
  290. identical to the pre-#1625 experience.
  291. Failures inside the emit are swallowed — progress is a UX nicety, the
  292. upload itself must not fail because of a WS hiccup.
  293. """
  294. def __init__(self, user_id: int | None, queue_item_id: int):
  295. self._user_id = user_id
  296. self._queue_item_id = queue_item_id
  297. try:
  298. self._loop = asyncio.get_running_loop()
  299. except RuntimeError:
  300. self._loop = None
  301. self._last_emit_bytes = 0
  302. self._last_emit_monotonic = 0.0
  303. self._has_emitted = False
  304. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  305. if self._loop is None or total_bytes <= 0:
  306. return
  307. now = time.monotonic()
  308. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  309. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  310. # the four matter most: first-call so the user sees something even
  311. # for sub-chunk-size files; uploaded >= total so the bar locks at
  312. # 100% even when the throttle would otherwise eat it.
  313. should_emit = (
  314. not self._has_emitted
  315. or bytes_transferred >= total_bytes
  316. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  317. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  318. )
  319. if not should_emit:
  320. return
  321. self._has_emitted = True
  322. self._last_emit_bytes = bytes_transferred
  323. self._last_emit_monotonic = now
  324. try:
  325. asyncio.run_coroutine_threadsafe(
  326. ws_manager.send_queue_item_upload_progress(
  327. user_id=self._user_id,
  328. queue_item_id=self._queue_item_id,
  329. bytes_transferred=bytes_transferred,
  330. total_bytes=total_bytes,
  331. ),
  332. self._loop,
  333. )
  334. except Exception:
  335. pass # progress is best-effort, never block the upload
  336. # Bambu firmware states that mean the project_file has actually been accepted
  337. # and the printer is now processing / running / paused mid-print. Used by the
  338. # dispatch watchdog (#1370): a transition into one of these states means the
  339. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  340. # a post-print prompt) is NOT a valid "command landed" signal even though the
  341. # state value did change. SLICING is included because some firmwares park
  342. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  343. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  344. # How many times the start-watchdog may revert an item to 'pending' before it
  345. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  346. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  347. # both never recovers and starves the other printers of dispatch slots. Three
  348. # is chosen to clear the transient causes the watchdog already recovers from —
  349. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  350. # force-reconnect on the very next attempt — while still bounding the loop.
  351. DISPATCH_MAX_ATTEMPTS = 3
  352. # Upload failures that mean the file never reached the printer's storage: the
  353. # file service refused or never answered (#3210). These put the item back in
  354. # the queue instead of failing it, because nothing about the job is wrong --
  355. # and failing it left the printer idle, so the next pass handed it the next
  356. # item, which failed the same way. One P2S whose file service was out of
  357. # connection slots ate 43 queued jobs in ten minutes that way.
  358. #
  359. # STORAGE (a missing, full or unusable card or USB drive) and AUTH (a rejected
  360. # access code) were left out at first, because they need the user. But
  361. # failing the item leaves the printer just as idle, and #3409's H2D with an
  362. # unusable USB stick ate seven jobs within an hour. Every job sent to that
  363. # printer fails the same way, so they wait too; the retry finds the fix once
  364. # the user has made it.
  365. #
  366. # A 553 can also be this one file: a name the card's filesystem cannot hold.
  367. # That one fails the item, see `_start_print`.
  368. #
  369. # Not here: NOT_FOUND (a path problem, which can be this one file), UNKNOWN,
  370. # and an upload that overran its deadline -- each retry of that costs a whole
  371. # upload that would be just as slow.
  372. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  373. {
  374. FtpFailureKind.HANDSHAKE,
  375. FtpFailureKind.SESSIONS,
  376. FtpFailureKind.COOLOFF,
  377. FtpFailureKind.TIMEOUT,
  378. FtpFailureKind.NETWORK,
  379. FtpFailureKind.STORAGE,
  380. FtpFailureKind.AUTH,
  381. }
  382. )
  383. def _refused_upload_hold_reason(printer_label: str, kind: FtpFailureKind | None) -> str:
  384. """What a job waiting on a printer that refused its last upload shows.
  385. Storage and the access code need the user to do something, so they say
  386. what, and so does a printer out of FTP sessions: those have been seen to
  387. stay until the printer restarts (#3474). The rest clear on their own.
  388. """
  389. if kind is FtpFailureKind.STORAGE:
  390. return f"{printer_label} refused to store the file — check its SD card or USB drive. {_REFUSED_UPLOAD_TAIL}"
  391. if kind is FtpFailureKind.AUTH:
  392. return (
  393. f"{printer_label} refused the file transfer — check its access code on the Printers page. "
  394. f"{_REFUSED_UPLOAD_TAIL}"
  395. )
  396. if kind is FtpFailureKind.SESSIONS:
  397. return (
  398. f"{printer_label} has no file-transfer sessions left (421 too many connections) — "
  399. f"if this does not clear within a few minutes, restart the printer. {_REFUSED_UPLOAD_TAIL}"
  400. )
  401. return f"{printer_label} is not accepting files — {_REFUSED_UPLOAD_TAIL}"
  402. _REFUSED_UPLOAD_TAIL = "Bambuddy will retry automatically"
  403. def _asks_nothing_new(waiting_reason: str) -> bool:
  404. """A model job's reason made only of busy printers and printers that refused an upload.
  405. The refusal sent its own notification (`_requeue_after_upload_refused`),
  406. so this one has nothing to add.
  407. """
  408. parts = [p.strip() for p in waiting_reason.split(" | ")]
  409. return all(p.startswith("Busy:") or p.endswith(_REFUSED_UPLOAD_TAIL) for p in parts)
  410. # How long a printer whose upload was put back stays out of dispatch (#3210).
  411. # The first window matches the FTP client's own handshake cool-off, so the
  412. # retry lands after the client would talk to the printer again anyway. Each
  413. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  414. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  415. # five connection attempts and a page of log. A successful upload resets it.
  416. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  417. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  418. def _upload_backoff_seconds(refusals: int) -> int:
  419. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  420. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  421. @dataclass(slots=True)
  422. class _ModelCandidate:
  423. """One (file, printer model) pair the model-based matcher may try.
  424. Model-based assignment used to have exactly one of these per item, held
  425. directly in the item's own columns. Cross-model queue items (#671) have
  426. several, held in ``print_queue_variants``. Both shapes are normalised into
  427. this so the matching, the cross-model gate and the waiting-reason handling
  428. are written once and an item without variants provably takes the same path
  429. it took before variants existed.
  430. ``variant`` is None for the item's own columns and set for a real variant
  431. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  432. item once that candidate wins.
  433. """
  434. target_model: str | None
  435. sliced_for: str | None
  436. required_filament_types: str | None
  437. filament_overrides: str | None
  438. variant: "PrintQueueVariant | None" = None
  439. def _sliced_for_model(archive, library_file) -> str | None:
  440. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  441. if archive is not None:
  442. return archive.sliced_for_model
  443. if library_file is not None and library_file.file_metadata:
  444. return library_file.file_metadata.get("sliced_for_model")
  445. return None
  446. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  447. """The filament a candidate needs, as ``(types, overrides)``.
  448. Both columns are JSON text written by the slicer step. Malformed content is
  449. treated as no constraint rather than as an error: a job whose overrides
  450. cannot be parsed still prints, it just gets no filament-based narrowing.
  451. Overrides carry their own types, so the returned type list is the union of
  452. the two — an override on one slot must not drop the requirements of the
  453. slots it says nothing about.
  454. Shared by the matcher and by the smart-plug wake step so both ask a printer
  455. for the same filament (#2876). Waking a printer the matcher would then
  456. reject on colour is the bug this exists to prevent.
  457. """
  458. required_types = None
  459. if candidate.required_filament_types:
  460. try:
  461. required_types = json.loads(candidate.required_filament_types)
  462. except json.JSONDecodeError:
  463. pass
  464. filament_overrides = None
  465. if candidate.filament_overrides:
  466. try:
  467. filament_overrides = json.loads(candidate.filament_overrides)
  468. except json.JSONDecodeError:
  469. pass
  470. effective_types = required_types
  471. if filament_overrides:
  472. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  473. if override_types:
  474. effective_types = sorted(set(required_types or []) | set(override_types))
  475. return effective_types, filament_overrides
  476. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  477. """Whether ``item`` was competing for the printer another item just took.
  478. The SJF starvation guard marks a job as jumped when a shorter one lower in
  479. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  480. compete for the same printer, so the guard has to look across both lanes
  481. (#3200); looking only inside the dispatched item's own lane let a stream of
  482. short model-based jobs hold a longer pinned job back indefinitely.
  483. Location filters are not checked: over-marking only lifts an item that was
  484. going to wait anyway, while under-marking is the starvation this prevents.
  485. """
  486. if item.printer_id is not None:
  487. return item.printer_id == printer_id
  488. if not printer_model:
  489. return False
  490. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  491. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  492. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  493. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  494. """Candidate files for ``item``, best first.
  495. An item with no variant rows yields exactly one candidate built from its own
  496. columns — the pre-#671 behaviour, unchanged.
  497. Variants come back least-attempted first, ties broken by the user's
  498. ``position``. On the first pass every count is zero, so this is purely the
  499. user's priority order. After a start-watchdog bounce the printer that failed
  500. drops behind, so the next lap tries the other machine rather than spending the
  501. item's whole retry budget on the one that is wedged. Once every candidate has
  502. been tried equally often they cycle again, which keeps the item-level
  503. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  504. still gives up, it just does not give up without trying them.
  505. """
  506. if not item.variants:
  507. if not item.archive_id and not item.library_file_id:
  508. # Nothing to print at all. Dispatching would fail deep in the upload
  509. # on "No archive_id or library_file_id"; the caller holds the item
  510. # with an explanation instead.
  511. return []
  512. return [
  513. _ModelCandidate(
  514. target_model=item.target_model,
  515. sliced_for=_sliced_for_model(item.archive, item.library_file),
  516. required_filament_types=item.required_filament_types,
  517. filament_overrides=item.filament_overrides,
  518. )
  519. ]
  520. # Drop candidates whose file is gone or in the trash. Both are reachable and
  521. # neither is covered by the schema: library deletes are soft (the row lives
  522. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  523. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  524. # fires there and a hard delete leaves the variant row pointing at nothing.
  525. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  526. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  527. return [
  528. _ModelCandidate(
  529. target_model=v.target_model,
  530. sliced_for=_sliced_for_model(None, v.library_file),
  531. required_filament_types=v.required_filament_types,
  532. filament_overrides=v.filament_overrides,
  533. variant=v,
  534. )
  535. for v in ordered
  536. ]
  537. # Why a job for any printer of a model waits when every free one's last print
  538. # failed. The queue page matches it to offer Resume for the model.
  539. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  540. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  541. """Fold one waiting reason per candidate into a single line for the item.
  542. A cross-model item produces a reason per candidate, and pasting them
  543. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  544. — on which machine?). Each reason is prefixed with its model, except in the
  545. single-candidate case where the item already displays its target model and
  546. the prefix would be noise.
  547. Identical reasons collapse rather than repeat, so three idle-less models
  548. read as one clause.
  549. When *every* candidate is merely busy the parts are joined with the ``" | "``
  550. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  551. unprefixed. That case must keep testing busy-only: a fleet that is simply
  552. printing needs no user action, and labelling the clauses would turn each pass
  553. over a two-model item into a "job waiting" notification.
  554. """
  555. reasons = [(model, reason) for model, reason in per_model if reason]
  556. if not reasons:
  557. return None
  558. if len(reasons) == 1:
  559. return reasons[0][1]
  560. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  561. if len(distinct) == 1:
  562. return distinct[0]
  563. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  564. return " | ".join(distinct)
  565. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  566. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  567. """Human label for the models an item is waiting on ("H2S or H2C").
  568. Notifications take a single target model. For a cross-model item the item's
  569. own ``target_model`` is whichever variant happens to be first, which reads as
  570. a lie once it is the H2C that actually runs — so name all of them.
  571. """
  572. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  573. if not models:
  574. return None
  575. return " or ".join(models)
  576. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  577. """True if ``mapping`` is a non-empty list whose every entry is the
  578. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  579. Such a mapping is a bug artifact: a frontend status-load race can serialize
  580. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  581. recomputed from live status at dispatch rather than trusted, otherwise it
  582. reaches the print command and is silently downgraded to external-spool mode.
  583. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  584. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  585. explicit external selection (``>= 254``) is NOT unresolved either — those
  586. keep their meaning.
  587. """
  588. if not isinstance(mapping, list) or not mapping:
  589. return False
  590. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  591. def _is_tray_id(value: object) -> bool:
  592. """True when ``value`` can be read as a global tray ID.
  593. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  594. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  595. against whatever happens to be loaded there.
  596. """
  597. return isinstance(value, int) and not isinstance(value, bool)
  598. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  599. # stages an item (#2799). The manual_start branch clears every other reason on
  600. # a staged item (#3074); this one is the reason it was staged, so it stays.
  601. _UNMATCHED_HOLD_PREFIX = "Needs "
  602. # How often an "any model" job held for low filament looks for another printer
  603. # of its model that has enough (#3137). Each look matches its filament on every
  604. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  605. _SHORT_HOLD_RECHECK_SECONDS = 120
  606. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  607. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  608. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  609. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  610. """The item's force_color_match overrides as filament requirements (#3280).
  611. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  612. read, so the checks after it judge the same list.
  613. """
  614. try:
  615. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  616. except (json.JSONDecodeError, TypeError):
  617. return []
  618. if not isinstance(overrides, list):
  619. return []
  620. return [
  621. {
  622. "slot_id": o.get("slot_id"),
  623. "type": o.get("type", ""),
  624. "color": o.get("color", ""),
  625. "tray_info_idx": o.get("tray_info_idx", ""),
  626. "force_color_match": True,
  627. }
  628. for o in overrides
  629. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  630. ]
  631. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  632. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  633. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  634. for a filament this plate does not use. A slot past the end of the mapping
  635. is unresolved too.
  636. """
  637. unresolved = []
  638. for req in required:
  639. slot_id = req.get("slot_id") or 0
  640. if slot_id <= 0:
  641. continue
  642. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  643. if not _is_tray_id(tray) or tray < 0:
  644. unresolved.append(req)
  645. return unresolved
  646. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  647. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  648. # on `_mapping_is_all_unresolved`.
  649. _EXTERNAL_TRAY_ID_MIN = 254
  650. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  651. """The ``mapping`` entries for the slots this plate actually prints.
  652. ``required`` comes from ``extract_filament_requirements``, which drops any
  653. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  654. consumes, and one absent from it is padding. That distinction is why this
  655. decision lives here and not in the MQTT command builder: a ``-1`` in the
  656. mapping means either "this plate does not print filament N" or "we never
  657. worked out which tray", and only the plate's own filament list separates
  658. them. The builder sees both as the same byte, which is how a plate whose one
  659. printed filament sat on the external spool went out as `use_ams=true` with a
  660. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  661. with 07FF_8012 (#3087).
  662. Returns None whenever the two cannot be lined up — no mapping, no parsed
  663. requirements, or a requirement the mapping is too short to cover — so every
  664. caller falls back to existing behaviour rather than acting on a guess.
  665. """
  666. if not isinstance(mapping, list) or not mapping or not required:
  667. return None
  668. entries = []
  669. for filament in required:
  670. slot_id = filament.get("slot_id")
  671. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  672. # The mapping and the requirements disagree about how many filaments
  673. # the file has. They came from different reads, so judge nothing.
  674. return None
  675. entries.append(mapping[slot_id - 1])
  676. return entries or None
  677. def _is_external_tray(tray_id, rack: bool = False) -> bool:
  678. """True for an explicit external-spool selection (254/255, and 247-253 on a
  679. ``rack`` printer), not for an unresolved slot and not for an AMS tray."""
  680. if tray_id is None:
  681. return False
  682. try:
  683. value = int(tray_id)
  684. except (TypeError, ValueError):
  685. return False
  686. return value >= _EXTERNAL_TRAY_ID_MIN or is_external_tray(value, rack)
  687. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  688. """Whether this printer could have two extruders, judged generously.
  689. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  690. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  691. why the MQTT command builder skips its own use_ams reconcile there. Anything
  692. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  693. with, external spools or not.
  694. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  695. behaviour it has always had, while a wrong "no" would rewrite a field that
  696. steers which nozzle prints. The model name is the first answer (it is what
  697. the command builder falls back to as well), then the same live evidence the
  698. dispatcher's extruder annotation uses — a second nozzle reporting a
  699. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  700. since a single-nozzle printer has exactly one.
  701. """
  702. if is_dual_nozzle_model(printer_model):
  703. return True
  704. nozzles = getattr(status, "nozzles", None) or []
  705. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  706. return True
  707. raw = getattr(status, "raw_data", None) or {}
  708. if raw.get("ams_extruder_map"):
  709. return True
  710. vt_trays = raw.get("vt_tray") or []
  711. # Not a nozzle-rack printer's one external input per hotend (H3C, 247-255).
  712. return isinstance(vt_trays, list) and len(vt_trays) > 1 and not TrayLayout.from_units(None, vt_trays).rack
  713. def _int_or(value, default: int) -> int:
  714. """``int(value)``, or ``default`` when the field is missing or junk.
  715. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  716. the next — and a tray id that fails to parse must not take the whole
  717. derivation down with it.
  718. """
  719. try:
  720. return int(value)
  721. except (TypeError, ValueError):
  722. return default
  723. # What a queue job's dispatch is worked out from, and an edit can change.
  724. _DISPATCH_INPUTS = (
  725. "printer_id",
  726. "status",
  727. "ams_mapping",
  728. "plate_id",
  729. "filament_overrides",
  730. "skip_filament_check",
  731. "target_model",
  732. "target_location",
  733. )
  734. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  735. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  736. The pass works on the jobs as loaded at its start, and it may have waited
  737. since: a plug powering a printer on takes minutes. A job edited meanwhile
  738. (moved to another printer, given a mapping or another plate, cancelled)
  739. is left to the next pass, which reads it fresh: deciding from the stale
  740. copy would overwrite the edit, or send the job where it no longer goes.
  741. The query flushes the pass's own pending changes first, so those don't
  742. count as edits.
  743. """
  744. row = (
  745. await db.execute(
  746. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  747. )
  748. ).one_or_none()
  749. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  750. return False
  751. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  752. return True
  753. def _global_tray_id(ams_id: int, tray_id: int, layout: TrayLayout | None = None) -> int:
  754. """Bambu Studio's global tray id (``utils.tray_ids``) of a slot on the printer ``layout`` describes.
  755. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  756. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  757. agree or a mapping cannot be read back against live tray telemetry.
  758. """
  759. return (layout or TrayLayout()).global_tray_id(ams_id, tray_id)
  760. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  761. """The global tray ids ``item`` actually prints from, or None if unknown.
  762. ``ams_mapping`` is the array the print command carries: position = filament
  763. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  764. not use. None means "no usable statement" — no mapping, unparseable JSON,
  765. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  766. documents), or one that resolves to no tray at all. Callers must treat None
  767. as "consider every loaded tray" rather than "consider none": narrowing on
  768. an absent mapping would silently drop requirements the print really has.
  769. """
  770. raw = getattr(item, "ams_mapping", None)
  771. if not raw:
  772. return None
  773. if isinstance(raw, str):
  774. try:
  775. mapping = json.loads(raw)
  776. except (json.JSONDecodeError, TypeError):
  777. return None
  778. else:
  779. mapping = raw
  780. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  781. return None
  782. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  783. return used or None
  784. def _mqtt_commands_rejected(status) -> bool:
  785. """True when the printer is currently reporting that it refused a command.
  786. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  787. a control command it could not verify. Queries still answer, so the printer
  788. looks connected and idle while project_file, gcode_line and
  789. ams_change_filament are all dropped — no amount of waiting or re-uploading
  790. changes that (#2732).
  791. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  792. ``print_error`` path builds HMSError differently), so this is safe to call on
  793. every watchdog poll.
  794. """
  795. for err in getattr(status, "hms_errors", None) or []:
  796. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  797. return True
  798. return False
  799. def _drying_ams_ids(status) -> list[int]:
  800. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  801. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  802. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  803. started (#2758) — it is a diagnostic, not a gate.
  804. Deliberately not used to block or stop drying before dispatch. This printer
  805. class supports drying concurrently with an active print
  806. (``supports_drying_while_printing``), so drying is not incompatible with
  807. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  808. while two AMS units were drying, one of them without its external PSU. Until
  809. it is known whether the blocker is drying itself or the power budget
  810. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  811. hardware is perfectly happy to continue.
  812. """
  813. ids: list[int] = []
  814. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  815. if not isinstance(unit, dict):
  816. continue
  817. try:
  818. if int(unit.get("dry_time") or 0) > 0:
  819. ids.append(int(unit.get("id", 0)))
  820. except (TypeError, ValueError):
  821. continue
  822. return ids
  823. def _parse_diameter(raw) -> float | None:
  824. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  825. try:
  826. value = float(raw)
  827. except (TypeError, ValueError):
  828. return None
  829. return value if value > 0 else None
  830. def _nozzle_info_by_id(status) -> dict[int, dict]:
  831. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  832. The field name is historical: on the H2 series ``nozzle_info`` carries an
  833. entry for *every* nozzle the printer knows about — the L/R hotends under
  834. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  835. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  836. :func:`_installed_nozzle_diameters` each take the half they need.
  837. """
  838. by_id: dict[int, dict] = {}
  839. for entry in getattr(status, "nozzle_rack", None) or []:
  840. if not isinstance(entry, dict):
  841. continue
  842. try:
  843. by_id[int(entry.get("id"))] = entry
  844. except (TypeError, ValueError):
  845. continue
  846. return by_id
  847. # What the firmware puts in a nozzle's serial number when the carriage or dock
  848. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  849. # its nozzle back in the rack (#2885).
  850. _EMPTY_NOZZLE_SERIAL = "N/A"
  851. def _nozzle_is_mounted(entry: dict | None) -> bool:
  852. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  853. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  854. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  855. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  856. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  857. the dock. So the diameter is not a presence signal (#2885).
  858. Emptiness has to be stated, not merely unstated. The serial must be the
  859. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  860. absent — an empty serial only means the printer didn't say, and a firmware
  861. that reports neither field normalises to exactly that. Treating "didn't
  862. say" as "empty" would silently switch the #1899 guard off on any such
  863. machine, so everything we cannot positively call empty counts as mounted.
  864. """
  865. if entry is None:
  866. return True
  867. serial = str(entry.get("serial_number") or "").strip().upper()
  868. if serial != _EMPTY_NOZZLE_SERIAL:
  869. return True
  870. try:
  871. max_temp = float(entry.get("max_temp") or 0)
  872. except (TypeError, ValueError):
  873. return True
  874. return max_temp > 0
  875. def _installed_nozzle_diameters(status) -> list[float]:
  876. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  877. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  878. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  879. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  880. told us its nozzle hardware" — callers must treat that as unknown, not as a
  881. mismatch, so we never block a print on missing data.
  882. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  883. though ``nozzles`` still carries a diameter for it: that value is stale, and
  884. counting it would let a slice match a nozzle the machine does not have
  885. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  886. """
  887. info = _nozzle_info_by_id(status)
  888. diameters: list[float] = []
  889. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  890. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  891. try:
  892. value = float(raw)
  893. except (TypeError, ValueError):
  894. continue
  895. if value > 0 and _nozzle_is_mounted(info.get(index)):
  896. diameters.append(value)
  897. return diameters
  898. def _rack_nozzle_diameters(status) -> list[float]:
  899. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  900. Keyed off the nozzle ids themselves rather than the printer model: only a
  901. rack machine ever reports ids 16-21, so there is no model registry to keep
  902. in sync. An empty dock is simply absent from the payload — measured on an
  903. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  904. present — so appearing here already means "a nozzle is in that dock".
  905. ``stat`` is deliberately not interpreted: its values aren't known, and
  906. reading it wrongly could hide a nozzle the printer would happily fetch.
  907. """
  908. diameters: list[float] = []
  909. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  910. if nozzle_id not in _RACK_NOZZLE_IDS:
  911. continue
  912. # PrinterState spells it "diameter"; the REST schema renames it to
  913. # "nozzle_diameter". Accept either so a caller holding the serialised
  914. # shape gets the same answer.
  915. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  916. if value is not None:
  917. diameters.append(value)
  918. return diameters
  919. def _format_diameters(diameters: list[float]) -> str:
  920. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  921. Deduplicated because a loaded rack holds several nozzles of the same size,
  922. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  923. short form doesn't. Matching still runs over the full list.
  924. """
  925. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  926. def _nozzle_mismatch_message(
  927. sliced_nozzle: float | None,
  928. installed: list[float],
  929. rack: list[float] | None = None,
  930. ) -> str | None:
  931. """Return an actionable error message when the sliced nozzle can't be
  932. printed on any nozzle the machine can reach, else None (#1899).
  933. Fail-safe: returns None whenever we lack the data to judge — no sliced
  934. diameter, or the printer reported no nozzles — so a print is only ever
  935. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  936. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  937. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  938. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  939. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  940. as reachable: the printer fetches one as part of starting the print, so a
  941. slice that matches a docked nozzle is not a mismatch. Without this the
  942. guard blocked every job whose nozzle happened not to be on a hotend at
  943. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  944. diameter already mounted could ever print, and the user had to fetch the
  945. nozzle by hand on the printer's own UI first (#2885).
  946. """
  947. reachable = [*installed, *(rack or [])]
  948. if not sliced_nozzle or not reachable:
  949. return None
  950. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  951. return None
  952. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  953. if rack:
  954. where += f" and {_format_diameters(rack)} in the nozzle rack"
  955. return (
  956. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  957. f"{where}. Re-slice for an available nozzle, or fit the matching "
  958. f"nozzle before printing."
  959. )
  960. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  961. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  962. Shared by the required and loaded sides, which name their extruder
  963. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  964. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  965. 1 the left/deputy — and both are absent on single-nozzle printers, where
  966. naming a nozzle would be noise.
  967. """
  968. parts = [(entry.get("type") or "filament").upper()]
  969. if entry.get("color"):
  970. parts.append(str(entry["color"]))
  971. nozzle = entry.get(nozzle_key)
  972. if nozzle == 0:
  973. parts.append("(right nozzle)")
  974. elif nozzle == 1:
  975. parts.append("(left nozzle)")
  976. return " ".join(parts)
  977. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  978. """Explain that nothing loaded matches what the file needs (#2771).
  979. Only ever built for a printer with no AMS, where the loaded list is short
  980. enough to quote in full and there is no "load another spool and hit Resume"
  981. recovery — the external spool holder is all there is, so the user needs to
  982. be told which filament to put on it.
  983. """
  984. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  985. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  986. return (
  987. f"No filament loaded on this printer matches the file. It needs {want}; "
  988. f"the printer has {have} and no AMS. Load the required filament on the "
  989. f"external spool holder, or send this job to a printer that has it."
  990. )
  991. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  992. """Bed temperature for the plate a queued job prints, 0 when unknown.
  993. The archive stores the highest bed temperature of any filament in the
  994. project, while the job may print another plate than the one archived: a
  995. PLA plate of a project that also holds PETG is heated for PLA. Read from
  996. the archive's file for the job's own plate, falling back to the stored
  997. value when the file can't be read.
  998. """
  999. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  1000. if archive is None or not archive.file_path:
  1001. return stored
  1002. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  1003. return temperature or stored
  1004. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  1005. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  1006. every call site below it: G-code injection, usage registration, rack-plan
  1007. lookup, slot-extruder lookup, the external-spool check, and the actual
  1008. print command.
  1009. A positive explicit ``plate_id`` on the queue item always wins. A
  1010. non-positive one is treated as "not set" and resolved from the archive,
  1011. the way the rest of the queue code already reads it (``if item.plate_id:``
  1012. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  1013. field, and passing a 0 straight through would build a print command for
  1014. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  1015. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  1016. Falling back to a bare ``1`` instead of reading the archive assumes a
  1017. single-plate file's one G-code is numbered 1, which only holds for a
  1018. plate exported on its own: one cut out of a larger project keeps its
  1019. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  1020. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  1021. the file, throws an HMS error, and sits wedged in IDLE until
  1022. power-cycled (#2947).
  1023. The call sites agreed on a fallback only by accident before this:
  1024. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  1025. the archive's own default plate internally whenever the plate id it's
  1026. handed isn't in the file, so it could silently inject into a different
  1027. plate than the one the print command itself asked for.
  1028. Falls back to 1 when the archive can't be read, holds no G-code member at
  1029. all, or its default member doesn't follow the ``plate_N`` naming
  1030. convention (a slicer that doesn't use it has no number to dispatch).
  1031. An explicit plate the archive doesn't hold is logged and then sent
  1032. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  1033. to a plate that is in the file would print a model nobody asked for,
  1034. which is the worse of the two.
  1035. """
  1036. try:
  1037. with zipfile.ZipFile(file_path, "r") as zf:
  1038. names = zf.namelist()
  1039. except (OSError, zipfile.BadZipFile) as exc:
  1040. logger.warning(
  1041. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  1042. "is unavailable; dispatching plate %s",
  1043. file_path,
  1044. exc,
  1045. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  1046. )
  1047. names = None
  1048. if explicit_plate_id is not None and explicit_plate_id > 0:
  1049. if (
  1050. names is not None
  1051. and default_plate_number(names) is not None
  1052. and select_plate_gcode_name(names, explicit_plate_id) is None
  1053. ):
  1054. logger.warning(
  1055. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  1056. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  1057. "file, since printing a different plate would print the wrong model (#2947)",
  1058. file_path,
  1059. explicit_plate_id,
  1060. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  1061. explicit_plate_id,
  1062. )
  1063. return explicit_plate_id
  1064. resolved = default_plate_number(names) if names is not None else None
  1065. return resolved if resolved is not None else 1
  1066. def _wear_order(printer: Printer) -> tuple[float, int]:
  1067. """Sort key for printers a model job could run on: fewest print hours, then id (#3480).
  1068. The same hours as maintenance's ``get_printer_total_hours``: the runtime
  1069. counter plus the baseline offset a user set for a second-hand or reset
  1070. machine.
  1071. """
  1072. hours = (printer.runtime_seconds or 0) / 3600.0 + (printer.print_hours_offset or 0.0)
  1073. return hours, printer.id
  1074. class PrintScheduler:
  1075. """Background scheduler that processes the print queue."""
  1076. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  1077. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  1078. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  1079. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  1080. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  1081. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  1082. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1083. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1084. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1085. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1086. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1087. }
  1088. def __init__(self):
  1089. self._running = False
  1090. self._check_interval = 30 # seconds
  1091. # After a pass that actually dispatched something, loop again almost
  1092. # immediately instead of sleeping the full interval (#2555). A dispatch
  1093. # changes printer state — a batch launch fans out over several passes as
  1094. # printers free up, a wedged head-of-line job reverts to pending, an
  1095. # upload slot opens — and the next batch of ready work should not have to
  1096. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1097. # pending items are behind printers that are genuinely busy printing),
  1098. # there is nothing to react to, so we fall back to the normal interval;
  1099. # that also means this can never tight-loop, since fast ticks only
  1100. # continue while dispatches keep happening and the queue is draining.
  1101. self._fast_check_interval = 3 # seconds
  1102. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1103. self._power_on_check_interval = 10 # seconds between connection checks
  1104. # Printers whose class-target power-on failed, mapped to the monotonic
  1105. # time their cool-off expires (#2786).
  1106. #
  1107. # Without this, one printer with an unreachable plug starves every
  1108. # sibling of its model forever: the wake step walks candidates in id
  1109. # order, spends the pass's single attempt on the same broken printer
  1110. # every time, and the healthy one two slots down is never reached. It
  1111. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1112. # which delays the whole queue, not just this job.
  1113. #
  1114. # Entries expire on read rather than being cleared on success: a printer
  1115. # inside its cool-off is skipped before the power-on is reached, so a
  1116. # live entry can never be overwritten by a success anyway. A printer
  1117. # that comes back by any other route stops being a wake candidate the
  1118. # moment it connects.
  1119. self._wake_failures: dict[int, float] = {}
  1120. self._wake_failure_cooloff = 600 # seconds
  1121. # Printers whose last upload never reached them, mapped to the monotonic
  1122. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1123. # as `_wake_failures`. Without it, a printer that cannot take files is
  1124. # idle on every pass, so it is picked on every pass.
  1125. self._upload_backoff: dict[int, float] = {}
  1126. # Refused uploads in a row per printer, which sets the next backoff
  1127. # window. Cleared by a successful upload to that printer.
  1128. self._upload_refusals: dict[int, int] = {}
  1129. # Why each printer in `_upload_backoff` refused its last upload, for
  1130. # the reason its jobs show. Cleared with `_upload_refusals`.
  1131. self._upload_refusal_kind: dict[int, FtpFailureKind] = {}
  1132. # The "job waiting" text last sent for each printer's current run of
  1133. # refusals. A refusal notifies only when its text differs, so a run
  1134. # notifies once, and again only if it turns into something the user
  1135. # has to fix. Cleared with `_upload_refusals`.
  1136. self._upload_refusal_notified: dict[int, str] = {}
  1137. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1138. self._drying_in_progress: dict[int, float] = {}
  1139. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1140. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1141. # cycle and the humidity finally coming down, so the normal steady
  1142. # state is an empty dict. Fields:
  1143. # running — a cycle we armed is (or should be) on the firmware
  1144. # ended_at — monotonic when we observed that cycle end
  1145. # unproductive — consecutive armed cycles that ended with the reading
  1146. # still above the threshold
  1147. # suspended — we have stopped arming this unit and said so
  1148. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1149. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1150. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1151. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1152. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1153. # arming setdefault all act on that meaning -- a unit that is merely
  1154. # waiting out its streak must not become stoppable or judgeable.
  1155. # since -- monotonic stamp when the current continuous above-threshold
  1156. # streak began
  1157. # last -- monotonic stamp of the last pass that observed the streak
  1158. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1159. # Slots already notified as low on filament:
  1160. # {(printer_id, ams_id, tray_id, spool_id)}.
  1161. # Cleared when the slot goes back above its threshold rather than on a
  1162. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1163. # boundary must not produce an alert on every pass, and a slot that has
  1164. # been refilled has to be able to alert again. See #2913.
  1165. #
  1166. # The spool id is part of the key because the slot alone cannot clear
  1167. # itself. Pull a low spool and put a different part-used one in the same
  1168. # slot: the key survives the pass where the slot resolves to nothing --
  1169. # deliberately, so a brief Spoolman outage does not re-alert everything
  1170. # when it returns -- and the replacement never goes above the threshold,
  1171. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1172. # different key and the stale one is inert.
  1173. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1174. # The same, for the MQTT relay's filament/low event: its own record, so
  1175. # one channel having been told never silences the other.
  1176. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1177. # Earliest monotonic time the next low-filament check may run (#2913).
  1178. self._filament_low_next_check: float = 0.0
  1179. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1180. # condition is "reorder" or "break", the events are those that had a
  1181. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1182. # condition clears, so it can alert again, and when nobody wants either
  1183. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1184. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1185. # re-send one message per SKU that is still low.
  1186. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1187. # The JSON last read from or written to that row; None until it has been read.
  1188. self._stock_alerts_persisted: str | None = None
  1189. # Earliest monotonic time the next stock forecast check may run (#2955).
  1190. self._stock_forecast_next_check: float = 0.0
  1191. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1192. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1193. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1194. # both features share _drying_in_progress.
  1195. self._scheduled_drying_printer_ids: set[int] = set()
  1196. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1197. # the first pass after a restart reaps anything left behind.
  1198. self._last_scheduled_drying_prune: float | None = None
  1199. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1200. # a project_file command must not get a second dispatch until either it
  1201. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1202. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1203. # during that window the DB busy_printers seed is empirically unreliable
  1204. # (multi-plate batches double-/triple-dispatched onto the same printer
  1205. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1206. # or revert.
  1207. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1208. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1209. # Minimum cooldown between dispatches to the same printer (covers the
  1210. # H2D's project_file digestion window).
  1211. self._dispatch_min_cooldown = 60.0
  1212. # Hard timeout — drop the hold even if we never observed a transition,
  1213. # so a lost MQTT session can't lock a printer out of the queue forever.
  1214. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1215. # watchdog runs first on the unhappy path.
  1216. self._dispatch_max_hold = 180.0
  1217. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1218. # an earlier pass and is still running. `_start_print` flips the row
  1219. # pending -> printing only *after* the upload completes, so until then
  1220. # the row stays `pending`: each tick, check_queue excludes these
  1221. # item_ids from re-selection and their printers from new dispatch /
  1222. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1223. # freed slots refill on the next fast tick. check_queue is the sole,
  1224. # sequential caller and the prune done-callbacks run in the same
  1225. # event-loop thread, so this dict needs no lock.
  1226. # item_id -> (task, printer_id)
  1227. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1228. # The archive each dispatch in flight prints into, held in
  1229. # services/archive_work so a merge leaves it alone until the dispatch
  1230. # ends: item_id -> archive_id. Same threading as above.
  1231. self._held_archives: dict[int, int] = {}
  1232. # Expected prints registered by `_start_print` that have not yet had a
  1233. # print command sent. Populated at registration, dropped once
  1234. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1235. # other exit. Same threading argument as `_inflight` above: one
  1236. # sequential caller, callbacks on the same loop, so no lock.
  1237. # item_id -> (printer_id, remote_filename, archive_id)
  1238. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1239. # Budget reservations created for a dispatch whose print command has
  1240. # not been confirmed yet. `_dispatch_one` releases these on every
  1241. # unsuccessful exit; a successful start removes the item id and leaves
  1242. # the reservation for finance_billing to consume with the archive.
  1243. self._unconfirmed_budget_reservations: set[int] = set()
  1244. # The print user `_start_print` handed to printer_manager for an item
  1245. # whose print command has not been sent yet (item_id -> printer_id).
  1246. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1247. # expected print above: it marks the printer's next print as Bambuddy's.
  1248. self._unconfirmed_print_user: dict[int, int] = {}
  1249. # Prints whose command went out but which the printer has not been
  1250. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1251. # the file and archive None for a library print. The watchdog drops the
  1252. # entry once the print runs, and withdraws what it stands for when the
  1253. # print never starts (see `_forget_unstarted_print`).
  1254. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1255. # Chamber temperature history for smart soak-time reduction.
  1256. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1257. # Entries older than _chamber_history_ttl are pruned on write.
  1258. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1259. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1260. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1261. # Populated on engagement in `_apply_keep_warm`, cleared by
  1262. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1263. # when a gate setting toggles off mid-hold — the release publishes
  1264. # bed → 0 first).
  1265. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1266. # Preheat rollback registry: printer_id -> subset of
  1267. # {"bed", "chamber", "airduct"} listing which preheat commands
  1268. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1269. # every entry still present at exit unless the print successfully
  1270. # started, so a failed upload / cancel / exception never leaves the
  1271. # printer heating for a job that isn't happening.
  1272. self._preheat_pin: dict[int, set[str]] = {}
  1273. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1274. # rollback can tell its own target from one someone else has since
  1275. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1276. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1277. self._preheat_pin_bed: dict[int, int] = {}
  1278. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1279. # its preheat was still holding at temperature. Set by
  1280. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1281. # `_preheat_sleep`, and cleared when the dispatch exits.
  1282. self._cancelled_dispatches: set[int] = set()
  1283. # printer_id -> monotonic time it was first seen terminal while one of
  1284. # its queue rows was still 'printing'. Reset by any non-terminal
  1285. # observation, so it measures an unbroken run rather than a total.
  1286. # In-memory on purpose: a restart re-arms the grace period, which only
  1287. # delays a recovery that is already the exceptional path (#2829).
  1288. self._terminal_since: dict[int, float] = {}
  1289. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1290. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1291. # across idle printers repeats that for every one of them in a single
  1292. # pass. Cleared at the top of each pass so a re-sliced file is never
  1293. # served from a previous tick.
  1294. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1295. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1296. # matcher about every idle candidate, and a pass can ask again for the
  1297. # same job and printer (another variant, a previous-print retry, the
  1298. # low-filament move). Cleared with the requirement memo.
  1299. self._unmatched_memo: dict[tuple, list[str]] = {}
  1300. # When each "any model" job held for low filament last looked for
  1301. # another printer (#3137), by queue item id.
  1302. self._short_hold_checked_at: dict[int, float] = {}
  1303. async def run(self):
  1304. """Main loop - check queue every interval."""
  1305. self._running = True
  1306. logger.info("Print scheduler started")
  1307. await self._clear_stale_dispatch_claims(at_startup=True)
  1308. while self._running:
  1309. dispatched = False
  1310. try:
  1311. self._sample_chamber_temps()
  1312. # No-op while any upload is in flight; on a quiet tick it releases
  1313. # a claim whose best-effort clear failed (e.g. the database was
  1314. # briefly unreachable), instead of leaving the row wedged until
  1315. # the next restart.
  1316. await self._clear_stale_dispatch_claims()
  1317. await self._close_stranded_printing_items()
  1318. dispatched = await self.check_queue()
  1319. except Exception as e:
  1320. logger.error("Scheduler error: %s", e)
  1321. # Re-check quickly after a productive pass so a draining batch does
  1322. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1323. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1324. async def _close_stranded_printing_items(self) -> None:
  1325. """Close a ``printing`` row the completion event never closed (#2829).
  1326. ``on_print_complete`` refuses to close a row when the completion's
  1327. subtask name disagrees with the file the row was dispatched with, so a
  1328. completion meant for something else (the printer's own
  1329. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1330. The refusal has no way back, though: nothing else ever closes the row,
  1331. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1332. one bad comparison wedges that printer's queue until a human presses
  1333. cancel. That is what #2829's reporters hit, and the guard's own
  1334. docstring already called stranding the worse of the two failures.
  1335. This is the way back. When a row has been ``printing`` while its
  1336. printer sat in a terminal state for the whole grace period, the print
  1337. is over however the event was read, and the row is closed with the
  1338. status the printer's own state implies.
  1339. Deliberately conservative:
  1340. * Only a connected printer counts. A disconnected one has a stale
  1341. ``state`` and proves nothing.
  1342. * The clock is reset by any non-terminal observation, so this cannot
  1343. fire on a printer that is merely between stages.
  1344. * The grace period is far longer than the gap between a printer
  1345. finishing and its completion arriving, so the normal path always
  1346. wins the race and this only ever sees genuine strandings.
  1347. What it does *not* do is replay the completion's side effects --
  1348. notifications, billing, auto-off. It restores the queue, which is the
  1349. harm being undone; the archive was updated by the normal path
  1350. regardless, since only the queue block refuses. A recovery that
  1351. silently re-fired notifications minutes late would be its own bug.
  1352. """
  1353. try:
  1354. async with async_session() as db:
  1355. result = await db.execute(
  1356. select(PrintQueueItem)
  1357. .where(PrintQueueItem.status == "printing")
  1358. .where(PrintQueueItem.printer_id.is_not(None))
  1359. )
  1360. items = list(result.scalars().all())
  1361. if not items:
  1362. self._terminal_since.clear()
  1363. return
  1364. now = time.monotonic()
  1365. seen_printers: set[int] = set()
  1366. closed = False
  1367. for item in items:
  1368. printer_id = item.printer_id
  1369. seen_printers.add(printer_id)
  1370. state = printer_manager.get_status(printer_id)
  1371. status = _terminal_queue_status(state)
  1372. if status is None:
  1373. self._terminal_since.pop(printer_id, None)
  1374. continue
  1375. since = self._terminal_since.setdefault(printer_id, now)
  1376. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1377. continue
  1378. item.status = status
  1379. item.completed_at = datetime.now(timezone.utc)
  1380. closed = True
  1381. # The printer is idle: nothing it prints next is this item's.
  1382. self._forget_unstarted_print(item.id, unless_printing=True)
  1383. logger.warning(
  1384. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1385. "closing it as %s. Its completion event was never matched to it, which blocks "
  1386. "every later job for this printer (#2829).",
  1387. item.id,
  1388. printer_id,
  1389. getattr(state, "state", None),
  1390. now - since,
  1391. status,
  1392. )
  1393. if closed:
  1394. await db.commit()
  1395. from backend.app.services.print_batch import refresh_batches_after
  1396. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1397. for printer_id in list(self._terminal_since):
  1398. if printer_id not in seen_printers:
  1399. del self._terminal_since[printer_id]
  1400. except Exception as e:
  1401. # Best-effort, same as the claim sweep beside it: a recovery path
  1402. # that can itself break the scheduler loop is worse than the strand.
  1403. logger.error("Stranded-item sweep failed: %s", e)
  1404. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1405. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1406. A claim is only ever held by a live dispatch coroutine, so when this
  1407. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1408. is stale. At startup that is trivially true — no coroutine survives a
  1409. restart. It is equally true on any later tick where no upload is running,
  1410. which is what makes this safe to repeat rather than only run once.
  1411. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1412. the database is briefly unreachable at exactly the moment dispatch ends,
  1413. the claim survives and the row is wedged out of the selection query. That
  1414. used to last until the next restart (#2702 follow-up, seen when
  1415. PostgreSQL refused a connection mid-dispatch).
  1416. ``_inflight`` is populated when the task is spawned, before the coroutine
  1417. claims its row, and pruned by a done-callback that cannot run before the
  1418. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1419. race window and needs no age threshold. A size-derived upload deadline
  1420. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1421. """
  1422. if self._inflight:
  1423. return
  1424. try:
  1425. async with async_session() as db:
  1426. res = await db.execute(
  1427. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1428. )
  1429. await db.commit()
  1430. if res.rowcount:
  1431. logger.info(
  1432. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1433. res.rowcount,
  1434. " at startup" if at_startup else "",
  1435. )
  1436. except Exception as exc:
  1437. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1438. def stop(self):
  1439. """Stop the scheduler."""
  1440. self._running = False
  1441. logger.info("Print scheduler stopped")
  1442. def forget_printer(self, printer_id: int) -> None:
  1443. """Drop what is kept for a deleted printer, so the next printer given its
  1444. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1445. would keep it out of dispatch for up to an hour.
  1446. A dispatch already in flight keeps its own state (_inflight, the preheat
  1447. pins, unconfirmed prints): it unwinds that when it ends.
  1448. """
  1449. for keyed in (
  1450. self._upload_backoff,
  1451. self._upload_refusals,
  1452. self._upload_refusal_kind,
  1453. self._upload_refusal_notified,
  1454. self._wake_failures,
  1455. self._drying_in_progress,
  1456. self._dispatch_holds,
  1457. self._chamber_history,
  1458. self._keep_warm,
  1459. self._terminal_since,
  1460. ):
  1461. keyed.pop(printer_id, None)
  1462. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1463. for key in [key for key in keyed if key[0] == printer_id]:
  1464. del keyed[key]
  1465. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1466. del self._sent_unstarted_print[item_id]
  1467. async def check_queue(self) -> bool:
  1468. """Check for prints ready to start.
  1469. Returns True if this pass dispatched at least one item, so the caller
  1470. can loop again quickly instead of sleeping the full interval (#2555).
  1471. """
  1472. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1473. self._filament_req_memo.clear()
  1474. self._unmatched_memo.clear()
  1475. async with async_session() as db:
  1476. # Check if shortest-job-first scheduling is enabled
  1477. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1478. # Get all pending items in the one order the queue page shows them
  1479. # in (#3200). The first eligible item takes a printer, so this order
  1480. # decides who wins a printer that a pinned job and an "Any <model>"
  1481. # job both want. It used to start with ``printer_id``, which made the
  1482. # lane outrank the position: SQLite sorts NULL first, so model-based
  1483. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1484. # Neither is what the user dragged into place.
  1485. if sjf_enabled:
  1486. # SJF: items already jumped get top priority (starvation guard),
  1487. # then sort by print_time ascending. Items with no print time go
  1488. # last, and position breaks ties.
  1489. result = await db.execute(
  1490. select(PrintQueueItem)
  1491. .where(PrintQueueItem.status == "pending")
  1492. # Never re-select a row a dispatch worker has already claimed
  1493. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1494. # below, and the guard that lets an orphaned claim be ignored
  1495. # until startup reconciliation clears it.
  1496. .where(PrintQueueItem.dispatching_at.is_(None))
  1497. # archive/library_file are read by the cross-model gate
  1498. # (#2578); eager-load once per pass instead of a lazy-load
  1499. # (which would raise in async) per item.
  1500. .options(
  1501. selectinload(PrintQueueItem.archive),
  1502. selectinload(PrintQueueItem.library_file),
  1503. # Cross-model candidates (#671), plus each candidate's file
  1504. # for the same cross-model gate. Lazy-loading either would
  1505. # raise in async.
  1506. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1507. )
  1508. .order_by(
  1509. PrintQueueItem.been_jumped.desc(),
  1510. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1511. PrintQueueItem.position,
  1512. PrintQueueItem.id,
  1513. )
  1514. )
  1515. else:
  1516. result = await db.execute(
  1517. select(PrintQueueItem)
  1518. .where(PrintQueueItem.status == "pending")
  1519. # Skip rows already claimed by a dispatch worker (#2615).
  1520. .where(PrintQueueItem.dispatching_at.is_(None))
  1521. .options(
  1522. selectinload(PrintQueueItem.archive),
  1523. selectinload(PrintQueueItem.library_file),
  1524. # Cross-model candidates (#671), plus each candidate's file
  1525. # for the same cross-model gate. Lazy-loading either would
  1526. # raise in async.
  1527. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1528. )
  1529. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1530. )
  1531. items = list(result.scalars().all())
  1532. # Drop rows whose upload is still in flight from an earlier pass
  1533. # (#2602). They stay `pending` until the upload finishes, so without
  1534. # this a fast tick would re-select and re-dispatch the same row.
  1535. # Belt-and-suspenders with the printer exclusion below.
  1536. if self._inflight:
  1537. inflight_ids = set(self._inflight)
  1538. items = [it for it in items if it.id not in inflight_ids]
  1539. # Read plate-clear setting once per queue check. Default MUST be
  1540. # False to match the schema (SettingsSchema.require_plate_clear
  1541. # defaults False) and the frontend (toggle + card badge both treat a
  1542. # missing value as off). When no settings row exists, a True default
  1543. # here re-enabled the plate-clear gate the UI showed as disabled,
  1544. # blocking dispatch to FINISH-state printers forever with no UI path
  1545. # to clear it (#1865).
  1546. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1547. # Dispatch and track scheduled drying runs (#2638)
  1548. await self._check_scheduled_dryings(db)
  1549. if not items:
  1550. # No dispatchable pending items — still check auto-drying on idle
  1551. # printers, but keep any printer with an upload still in flight
  1552. # from an earlier pass out of it (#2602): its print is imminent,
  1553. # so it must not be auto-dried in the gap before the row flips to
  1554. # printing. Report the pass as productive while uploads run so the
  1555. # loop stays on the fast interval.
  1556. #
  1557. # Also release any keep-warm holds that got orphaned by the queue
  1558. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1559. # this early return, so call it directly with an empty candidate
  1560. # set. Without this, a printer whose queued item was cancelled or
  1561. # deleted would keep its bed at target until the max-duration
  1562. # timeout expired.
  1563. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1564. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1565. await self._check_auto_drying(db, [], inflight_printers)
  1566. await self._check_filament_low(db)
  1567. await self._check_stock_forecast(db)
  1568. return bool(self._inflight)
  1569. logger.info(
  1570. "Queue check: found %d pending items: %s",
  1571. len(items),
  1572. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1573. )
  1574. # Forget jobs that left the queue since they were last checked.
  1575. pending_ids = {i.id for i in items}
  1576. self._short_hold_checked_at = {
  1577. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1578. }
  1579. # Seed busy_printers with printers that already have an item in 'printing'
  1580. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1581. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1582. # lag several seconds behind the print command, so the next check_queue
  1583. # tick still sees IDLE and would double-dispatch onto the same printer.
  1584. # Without this guard, two pending items targeting the same printer
  1585. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1586. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1587. busy_result = await db.execute(
  1588. select(PrintQueueItem.printer_id)
  1589. .where(PrintQueueItem.status == "printing")
  1590. .where(PrintQueueItem.printer_id.is_not(None))
  1591. )
  1592. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1593. # Why each printer left this pass, recorded where the decision is
  1594. # made rather than re-derived when the summary is logged. #3018's
  1595. # bundle shows what the old summary produced: "printer 1 not
  1596. # available -- connected=True, state=IDLE" immediately followed by a
  1597. # dispatch to printer 1. Two things went wrong at once. The line read
  1598. # live state at log time, which by then no longer matched the state
  1599. # the decision was made on; and `busy_printers` holds both printers
  1600. # that cannot take work and printers this pass has claimed for it,
  1601. # which are opposite facts. It is the first line anyone greps for
  1602. # "why did my item not go out", so it has to say which.
  1603. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1604. # Printers this pass is dispatching to. They are in busy_printers so
  1605. # nothing else in the pass targets them -- that is a reservation, not
  1606. # an obstruction, and the summary says so.
  1607. claimed_printers: set[int] = set()
  1608. def mark_busy(printer_id: int, reason: str) -> None:
  1609. """Take ``printer_id`` out of this pass, recording why.
  1610. First reason wins: a printer already excluded by a stronger fact
  1611. -- a print running on it -- must not be relabelled by a weaker
  1612. check that ran later and would have excluded it anyway.
  1613. """
  1614. busy_printers.add(printer_id)
  1615. busy_reasons.setdefault(printer_id, reason)
  1616. def claim_printer(printer_id: int) -> None:
  1617. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1618. claimed_printers.add(printer_id)
  1619. mark_busy(printer_id, "selected for dispatch in this pass")
  1620. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1621. # worded for a different audience: the log wants "still inside its
  1622. # post-dispatch hold window", the queue row wants to know the printer
  1623. # is taken and nothing is broken. Only the cases that would read wrong
  1624. # as a plain "Busy" are recorded here; the rest fall back to it.
  1625. item_hold_reasons: dict[int, str] = {}
  1626. # Names and models for the printers this pass may have to write a
  1627. # waiting reason about, read once rather than per skip per tick. The
  1628. # model-based branch already has its names from `_printers_for_model`.
  1629. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1630. pinned_printers: dict[int, tuple[str, str]] = {}
  1631. if pinned_printer_ids:
  1632. pinned_rows = await db.execute(
  1633. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1634. )
  1635. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1636. def printer_label(printer_id: int) -> str:
  1637. """What to call this printer in a queue row."""
  1638. entry = pinned_printers.get(printer_id)
  1639. return (entry[0] if entry else "") or f"printer {printer_id}"
  1640. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1641. """Record why *item* is not going out, in the words the queue row shows.
  1642. The fixed-printer branch's single writer for ``waiting_reason``
  1643. (#3074). Before this, the sensor interlock was the only thing that
  1644. wrote the field there, so an item pinned to a printer that was
  1645. merely printing sat at `pending` with nothing to show for it —
  1646. indistinguishable from a queue that had stopped working — while
  1647. the same job queued as "Any <model>" explained itself.
  1648. Every exit from that branch now calls this, which is also what
  1649. replaced the interlock's old habit of clearing the field up front:
  1650. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1651. because whichever exit runs next overwrites it and the dispatch
  1652. path clears it.
  1653. A notification goes out when this item starts asking for
  1654. something, and only then: the new reason needs the user, and what
  1655. it replaced did not. "What it replaced did not" has to include a
  1656. busy-only reason, not just an empty one. The sequence this branch
  1657. actually produces is a print running (``Busy: X1C-01``) and then
  1658. the plate it left behind (``Waiting for plate confirmation``), and
  1659. testing "was the field empty" would call that no transition at all
  1660. and stay quiet through the one case worth saying out loud.
  1661. The cost is that a printer dropping offline, coming back busy and
  1662. dropping again asks twice rather than once. That is the honest
  1663. reading — it went wrong twice — and the alternative was a rule
  1664. that never fired for the case this was built for.
  1665. *notify* is how a caller opts out. The sensor interlock does: it
  1666. has never sent this notification, and a change about what the
  1667. queue *displays* is not the place to start (#1148).
  1668. """
  1669. if item.waiting_reason == reason:
  1670. return
  1671. # Busy-only and empty are the same thing here: neither is the
  1672. # queue asking the user for anything.
  1673. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1674. item.waiting_reason = reason
  1675. await db.commit()
  1676. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1677. return
  1678. try:
  1679. job_name = await self._get_job_name(db, item)
  1680. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1681. await notification_service.on_queue_job_waiting(
  1682. job_name=job_name,
  1683. target_model=(entry[1] if entry else "") or "",
  1684. waiting_reason=reason,
  1685. db=db,
  1686. printer_id=item.printer_id,
  1687. )
  1688. except Exception as e:
  1689. # A queue that cannot say why it is waiting is the bug being
  1690. # fixed here; a queue that stops dispatching because a
  1691. # notification provider is down would be a worse one.
  1692. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1693. async def hold_for_printer(
  1694. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1695. ) -> None:
  1696. """Take *printer_id* out of this pass and tell the item's owner why."""
  1697. mark_busy(printer_id, log_reason)
  1698. item_hold_reasons.setdefault(printer_id, item_reason)
  1699. await hold_item(item, item_reason)
  1700. # Defense-in-depth (#1157): augment busy_printers with any printer
  1701. # still in its post-dispatch hold window. Empirically, the DB seed
  1702. # above can miss in-flight items in a multi-plate batch — same-file
  1703. # plates were being dispatched 30 s apart while the H2D was still
  1704. # digesting the first project_file. The hold is keyed in-memory and
  1705. # released by the watchdog on the success path, so it adds a layer
  1706. # that doesn't depend on DB row visibility or completion-callback
  1707. # timing.
  1708. for held_printer_id in list(self._dispatch_holds.keys()):
  1709. if self._printer_in_dispatch_hold(held_printer_id):
  1710. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1711. # Exclude printers whose upload is still in flight from an earlier
  1712. # pass (#2602). The row is `pending` until the upload finishes and
  1713. # the printing-state seed / dispatch hold above only arm once the
  1714. # upload completes, so this is what holds the printer (and, via
  1715. # busy_printers, its auto-drying) out of the pass during the upload.
  1716. for _task, inflight_pid in self._inflight.values():
  1717. if inflight_pid is not None:
  1718. mark_busy(inflight_pid, "an upload to it is still in flight")
  1719. # Snapshot taken here, before the item loop adds anything (#2801).
  1720. #
  1721. # The three sources above all mean the same thing: a print on this
  1722. # printer is running or imminent. Everything the loop adds below
  1723. # means only "the queue could not dispatch to it this pass", which
  1724. # is a different statement -- a printer waiting on a plate-clear
  1725. # acknowledgment, an offline printer, one with no matching file.
  1726. #
  1727. # Auto-drying must only see the first kind. Reading the whole set
  1728. # as "is currently printing" is what put a plate-held printer down
  1729. # the mid-print path: it capped the drying temperature, logged the
  1730. # cycle as (mid-print), and skipped the very gate that was supposed
  1731. # to hold it. The interlock block below already documents the same
  1732. # hazard and works around it by staying out of busy_printers; this
  1733. # generalises that workaround instead of repeating it per case.
  1734. dispatching_printers: set[int] = set(busy_printers)
  1735. # Printers whose last upload never reached them (#3210). After the
  1736. # snapshot above on purpose: such a printer is idle, not about to
  1737. # print, and auto-drying must keep treating it as idle.
  1738. now_mono = time.monotonic()
  1739. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1740. # can leave them out: there is no print to keep a bed warm for.
  1741. # Their holds are written silently: the refusal that put a printer
  1742. # here sent the "job waiting" notification for its run (#3409).
  1743. backoff_printers: set[int] = set()
  1744. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1745. if now_mono >= retry_at:
  1746. del self._upload_backoff[backoff_pid]
  1747. continue
  1748. backoff_printers.add(backoff_pid)
  1749. mark_busy(
  1750. backoff_pid,
  1751. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1752. )
  1753. item_hold_reasons.setdefault(
  1754. backoff_pid,
  1755. _refused_upload_hold_reason(printer_label(backoff_pid), self._upload_refusal_kind.get(backoff_pid)),
  1756. )
  1757. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1758. # enclosure door left open, say. The fixed-printer branch turns
  1759. # this into a waiting_reason the user can act on; the model-based
  1760. # branch hides these printers from the matcher so an "Any <model>"
  1761. # job runs on a sibling instead of queueing behind the held one.
  1762. #
  1763. # Deliberately NOT merged into busy_printers, even though that set
  1764. # already means "unavailable this pass". _check_auto_drying reads
  1765. # it as "is currently printing" and would put an idle-but-held
  1766. # printer down the mid-print drying path, which caps the drying
  1767. # temperature and skips the queue-only gating. A held printer is
  1768. # idle; it should dry exactly as it did before.
  1769. #
  1770. # Only sensors we actually read and found alerting appear here; see
  1771. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1772. # holds nothing.
  1773. interlocked: dict[int, str] = {}
  1774. try:
  1775. interlocked = await ha_sensor_manager.blocked_printers(db)
  1776. except Exception as e:
  1777. # Never let the interlock stop the queue running. A broken
  1778. # lookup means no holds, not no dispatches.
  1779. logger.warning("Home Assistant interlock check failed: %s", e)
  1780. interlocked = {}
  1781. # Printers a smart plug can bring back, read once for the whole pass
  1782. # (#2786). Used by the model-based branch both to word "Offline" in
  1783. # the waiting reason and to decide what the wake step may switch on.
  1784. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1785. # At most one power-on per queue check. Each one blocks this loop
  1786. # for the boot wait, so a queue of ten class-targeted jobs must not
  1787. # switch on ten printers inside a single pass — the next pass wakes
  1788. # the next one (#2786).
  1789. power_on_attempted = False
  1790. # Log skip reasons once per queue check (not per item)
  1791. skip_reasons: dict[str, int] = {}
  1792. # Items selected for dispatch in this pass, one per printer. The
  1793. # loop below only *decides* — the uploads happen afterwards, in
  1794. # parallel (#2555). See _dispatch_selected().
  1795. dispatch_ids: list[int] = []
  1796. # Library rows queued with `cleanup_library_after_dispatch` (the
  1797. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1798. # that prints them: the row is deleted and the 3MF is unlinked from
  1799. # disk. That was safe only because dispatch was serial. Run two of
  1800. # them against the same row at once and the second DELETE matches no
  1801. # row (StaleDataError), and the winner's unlink can pull the file out
  1802. # from under the loser's in-flight upload.
  1803. #
  1804. # Only the cleanup flag mutates the row. An ordinary library print
  1805. # just reads it, so the common fan-out — one file, many printers,
  1806. # which is exactly the reporter's workload — still goes out fully in
  1807. # parallel. Narrow the guard to the mutating case; do not serialise
  1808. # the case the whole fix exists for.
  1809. dispatch_libs: set[int] = set()
  1810. consumed_libs: set[int] = set()
  1811. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1812. """True if dispatching `candidate` now would race another item's cleanup."""
  1813. lib_id = candidate.library_file_id
  1814. if lib_id is None:
  1815. return False
  1816. if candidate.cleanup_library_after_dispatch:
  1817. # We would delete a row someone else in this pass is reading.
  1818. return lib_id in dispatch_libs
  1819. # Someone else in this pass will delete the row out from under us.
  1820. return lib_id in consumed_libs
  1821. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1822. lib_id = candidate.library_file_id
  1823. if lib_id is None:
  1824. return
  1825. dispatch_libs.add(lib_id)
  1826. if candidate.cleanup_library_after_dispatch:
  1827. consumed_libs.add(lib_id)
  1828. # Printer scope of each job's creator (#1727), so an "any <model>"
  1829. # job only lands on a printer its creator may use. Loaded lazily,
  1830. # once per creator per pass.
  1831. from backend.app.core.auth import is_auth_enabled
  1832. scope_auth_enabled = await is_auth_enabled(db)
  1833. creator_scopes: dict[int, PrinterScope] = {}
  1834. # Printers a model job passes over while drying blocks the queue,
  1835. # as a pinned job waits for its own. A parked timer never ends,
  1836. # so it does not hold (#2896).
  1837. drying_held: set[int] = (
  1838. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1839. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1840. else set()
  1841. )
  1842. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1843. if not scope_auth_enabled or user_id is None:
  1844. return ALL_PRINTERS
  1845. if user_id not in creator_scopes:
  1846. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1847. return creator_scopes[user_id]
  1848. for item in items:
  1849. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1850. if item.scheduled_time:
  1851. sched = item.scheduled_time
  1852. if sched.tzinfo is None:
  1853. sched = sched.replace(tzinfo=timezone.utc)
  1854. if sched > datetime.now(timezone.utc):
  1855. # Waiting on the clock, not on a printer.
  1856. await hold_item(item, None)
  1857. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1858. continue
  1859. # Skip items that require manual start, except an "any model"
  1860. # job held for low filament that another idle printer can now
  1861. # run: that one is moved there and carries on below (#3137).
  1862. if item.manual_start and not (
  1863. item.filament_short
  1864. and await self._release_short_model_hold(
  1865. db,
  1866. item,
  1867. busy_printers | interlocked.keys() | drying_held,
  1868. require_plate_clear,
  1869. await _creator_scope(item.created_by_id),
  1870. )
  1871. ):
  1872. # Waiting on the user, not on a printer. Cleared here because
  1873. # this is the last pass that will look at the row: a staged
  1874. # item never reaches the branches below again, so a reason
  1875. # left from before it was staged would stand forever (#3074).
  1876. # The one exception is the unmatched-filament hold, whose
  1877. # reason was written at staging and is why the item waits:
  1878. # it names the filament to load (#2799). Pressing start
  1879. # clears manual_start, and the branches below overwrite it.
  1880. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1881. await hold_item(item, keep)
  1882. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1883. continue
  1884. if item.printer_id and item.printer_id not in pinned_printers:
  1885. # Moved by the release above to a printer no row named when
  1886. # the labels were read.
  1887. moved_to = await self._get_printer(db, item.printer_id)
  1888. if moved_to is not None:
  1889. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1890. if item.printer_id:
  1891. # Its creator may no longer use this printer (#1727): an
  1892. # admin took it away from their group after the job was
  1893. # queued, say to keep it free for a training session. Held,
  1894. # not failed, so it starts if access comes back or the user
  1895. # moves it to a printer they still have.
  1896. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1897. await hold_item(
  1898. item,
  1899. "Its owner no longer has access to this printer — move it to another printer",
  1900. notify=False,
  1901. )
  1902. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1903. continue
  1904. # Held by a sensor interlock (#1148). Checked before the
  1905. # busy_printers test that would otherwise swallow it
  1906. # silently — "waiting for a printer" and "waiting for you
  1907. # to shut the enclosure" need to read differently, and only
  1908. # one of them is something the user can fix.
  1909. #
  1910. # It used to be the only thing that wrote a waiting_reason on
  1911. # this branch, and it cleared the field up front so a lifted
  1912. # hold could not leave a shut door reading "Waiting on
  1913. # Enclosure Door". `hold_item` carries that guarantee now —
  1914. # every exit below writes — so the clear is gone and the
  1915. # interlock is an ordinary hold like the rest (#3074).
  1916. interlock_reason = interlocked.get(item.printer_id)
  1917. if interlock_reason:
  1918. # Silent, exactly as it has always been. #1148 built this
  1919. # as a hold that shows on the row, never as an alert, and
  1920. # routing it through the shared writer must not quietly
  1921. # turn every open door into a notification.
  1922. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1923. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1924. continue
  1925. # Specific printer assignment (existing behavior)
  1926. if item.printer_id in busy_printers:
  1927. # Whatever took the printer out of this pass — a print
  1928. # already running on it, a post-dispatch hold, an upload
  1929. # still in flight, an item ahead of this one in the same
  1930. # pass — reads the same way from the queue: the printer is
  1931. # taken and this item is in line for it. The exceptions
  1932. # that do not (an offline printer, say) recorded their own
  1933. # wording in `item_hold_reasons` when they held it.
  1934. await hold_item(
  1935. item,
  1936. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1937. notify=item.printer_id not in backoff_printers,
  1938. )
  1939. continue
  1940. # Check if printer is idle
  1941. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1942. printer_connected = printer_manager.is_connected(item.printer_id)
  1943. # If printer not connected, try to power on via smart plug
  1944. if not printer_connected:
  1945. plugs = await self._get_smart_plugs(db, item.printer_id)
  1946. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1947. if auto_on_plugs:
  1948. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1949. # Power on using the plug that actually feeds the printer, and
  1950. # wait for it to boot on that one only (#2629).
  1951. primary_plug = self._pick_power_plug(auto_on_plugs)
  1952. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1953. if powered_on:
  1954. # Also turn on any remaining auto_on plugs (e.g., filter)
  1955. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1956. try:
  1957. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1958. if await service.turn_on(extra_plug):
  1959. await publish_plug_state(
  1960. extra_plug.id,
  1961. extra_plug.name,
  1962. extra_plug.printer_id,
  1963. on=True,
  1964. ha_entity_id=extra_plug.ha_entity_id,
  1965. )
  1966. logger.info(
  1967. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1968. )
  1969. except Exception as e:
  1970. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1971. printer_connected = True
  1972. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1973. else:
  1974. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1975. await hold_for_printer(
  1976. item,
  1977. item.printer_id,
  1978. "smart-plug power-on failed",
  1979. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1980. )
  1981. continue
  1982. else:
  1983. # No plug or auto_on disabled. Worded exactly as the
  1984. # model-based branch words it (#2786): this is the one
  1985. # entry on that list the user has to act on, because
  1986. # Bambuddy will never switch this printer on itself.
  1987. await hold_for_printer(
  1988. item,
  1989. item.printer_id,
  1990. "offline, with no smart plug to power it on",
  1991. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1992. )
  1993. continue
  1994. # Check if printer is idle (busy with another print)
  1995. if not printer_idle:
  1996. await hold_for_printer(
  1997. item,
  1998. item.printer_id,
  1999. "not idle",
  2000. self._pinned_hold_reason(
  2001. item.printer_id, printer_label(item.printer_id), require_plate_clear
  2002. ),
  2003. )
  2004. continue
  2005. # Drying blocks the queue, if the user asked it to. A hold
  2006. # is a skip like any other, so it belongs here with the
  2007. # rest of the availability checks.
  2008. # A parked timer (#2896) never ends, so it must not hold the
  2009. # queue; it stays tracked so the stop paths still reach it.
  2010. if (
  2011. self._drying_in_progress.get(item.printer_id)
  2012. and not self._drying_is_only_parked(item.printer_id)
  2013. and await self._get_bool_setting(db, "queue_drying_block")
  2014. ):
  2015. # Busy-shaped on purpose: the cycle ends on its own and
  2016. # the job goes out, so there is nothing to alert about.
  2017. await hold_for_printer(
  2018. item,
  2019. item.printer_id,
  2020. "drying, and drying is set to block the queue",
  2021. f"Busy: {printer_label(item.printer_id)} (drying)",
  2022. )
  2023. continue
  2024. # Check condition (previous print success)
  2025. if item.require_previous_success:
  2026. if not await self._check_previous_success(db, item):
  2027. item.status = "skipped"
  2028. item.error_message = "Previous print failed or was aborted"
  2029. item.completed_at = datetime.now(timezone.utc)
  2030. # Not pending any more, so not waiting for anything.
  2031. item.waiting_reason = None
  2032. await db.commit()
  2033. logger.info("Skipped queue item %s - previous print failed", item.id)
  2034. # Send notification
  2035. job_name = await self._get_job_name(db, item)
  2036. printer = await self._get_printer(db, item.printer_id)
  2037. await notification_service.on_queue_job_skipped(
  2038. job_name=job_name,
  2039. printer_id=item.printer_id,
  2040. printer_name=printer.name if printer else "Unknown",
  2041. reason="Previous print failed or was aborted",
  2042. db=db,
  2043. )
  2044. continue
  2045. # Resolve the AMS mapping when it's missing OR unresolved
  2046. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  2047. # frontend status-load race can persist [-1] (#2589) — and
  2048. # must be recomputed from live trays rather than trusted.
  2049. if await _edited_since_loaded(db, item):
  2050. continue
  2051. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  2052. if unmappable:
  2053. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  2054. continue
  2055. # Filament-deficit pre-dispatch check (#1496). If the
  2056. # assigned spool can't satisfy any required slot grams,
  2057. # promote the item to manual_start so the user must
  2058. # acknowledge via the ▶ button (which re-checks live).
  2059. if await self._block_on_filament_deficit(db, item):
  2060. # Now staged for the user to start by hand, and the row
  2061. # shows the filament-short badge instead. Cleared because
  2062. # a staged item never reaches this branch again.
  2063. await hold_item(item, None)
  2064. continue
  2065. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  2066. # than let the printer pick a substitute for a slot the
  2067. # matcher could not resolve on this printer.
  2068. if await self._block_on_unmatched_filament(db, item):
  2069. continue
  2070. # Hold this item back for the next pass rather than racing
  2071. # another dispatch over the same transient library row. The
  2072. # printer is still marked busy so a later item does not jump
  2073. # its place in this printer's queue.
  2074. if _library_row_conflict(item):
  2075. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2076. await hold_for_printer(
  2077. item,
  2078. item.printer_id,
  2079. "holding its place while another item releases a library row",
  2080. f"Busy: {printer_label(item.printer_id)}",
  2081. )
  2082. continue
  2083. # Print takes priority: stop a cycle Bambuddy armed, now
  2084. # that this item is definitely going out.
  2085. #
  2086. # Placement is the whole point (#2801). This used to sit up
  2087. # with the availability checks, inside the not-idle branch
  2088. # -- so it fired only on the passes where the print was NOT
  2089. # going to start, and never on the ones where it was.
  2090. # Drying is not one of the things `_is_printer_idle` looks
  2091. # at, so a stop could never have unblocked that printer
  2092. # anyway; the cycle was spent for nothing, auto-drying
  2093. # re-armed on the next tick, and a plate left
  2094. # unacknowledged turned that into a loop on the scheduler
  2095. # interval. Every skip between there and here -- a failed
  2096. # previous print, an unmappable item, a filament deficit, a
  2097. # contested library row -- is another way to lose a cycle
  2098. # for a print that never happens, which is why this waits
  2099. # until the decision is actually made.
  2100. if self._drying_in_progress.get(
  2101. item.printer_id
  2102. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2103. await self._stop_drying(item.printer_id)
  2104. # Queue the dispatch instead of running it here — see
  2105. # _dispatch_selected(). busy_printers still gets the printer
  2106. # immediately, so nothing else in this pass can target it.
  2107. #
  2108. # The reason goes first: this item is not waiting for anything
  2109. # any more, and the model-based branch clears its own at the
  2110. # equivalent moment (#3074).
  2111. await hold_item(item, None)
  2112. _claim_library_row(item)
  2113. dispatch_ids.append(item.id)
  2114. claim_printer(item.printer_id)
  2115. # SJF starvation guard: mark items that were jumped
  2116. if sjf_enabled and item.print_time_seconds is not None:
  2117. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2118. for other in items:
  2119. if (
  2120. other.id != item.id
  2121. and other.id not in dispatch_ids
  2122. and other.status == "pending"
  2123. and _could_take_printer(other, item.printer_id, pinned_model)
  2124. and not other.been_jumped
  2125. and other.position < item.position
  2126. and (
  2127. other.print_time_seconds is None
  2128. or other.print_time_seconds > item.print_time_seconds
  2129. )
  2130. ):
  2131. other.been_jumped = True
  2132. await db.commit()
  2133. elif item.target_model or item.variants:
  2134. # Model-based assignment - find any idle printer of matching model.
  2135. # A plain model-based item has exactly one candidate, built from
  2136. # its own columns. A cross-model item (#671) has one per sliced
  2137. # variant and takes the first that matches, walking them in the
  2138. # user's priority order so the pick is reproducible when more
  2139. # than one printer is free in the same pass.
  2140. candidates = _candidates_for(item)
  2141. item_scope = await _creator_scope(item.created_by_id)
  2142. printer_id = None
  2143. chosen: _ModelCandidate | None = None
  2144. per_model_reasons: list[tuple[str | None, str]] = []
  2145. # Candidates that cleared the cross-model gate below. The
  2146. # smart-plug wake step may only consider these — waking a
  2147. # printer for a file that can never legally run on it is
  2148. # worse than not waking at all (#2786).
  2149. wakeable_candidates: list[_ModelCandidate] = []
  2150. # Printers passed over because their last print failed.
  2151. gate_blocked: set[int] = set()
  2152. if not candidates:
  2153. # Every candidate file has been deleted or trashed out from
  2154. # under this item. Hold it with something the user can act
  2155. # on rather than letting it look dispatchable forever.
  2156. per_model_reasons.append(
  2157. (
  2158. item.target_model,
  2159. "Every file for this job has been deleted — add a file back or remove the item",
  2160. )
  2161. )
  2162. for candidate in candidates:
  2163. effective_types, filament_overrides = _filament_constraints(candidate)
  2164. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2165. # for an incompatible model to a printer, no matter how the
  2166. # row got into the DB (old rows, direct API writes). Held
  2167. # as pending with an actionable waiting_reason — the user
  2168. # fixes it by editing the item's target model.
  2169. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2170. per_model_reasons.append(
  2171. (
  2172. candidate.target_model,
  2173. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2174. f"{candidate.target_model} — edit the item and fix its target model",
  2175. )
  2176. )
  2177. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2178. continue
  2179. wakeable_candidates.append(candidate)
  2180. async def is_short(
  2181. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2182. ) -> bool:
  2183. # The check reads the file and plate off the item,
  2184. # so it must hold this candidate's. Resolving is
  2185. # safe to repeat, and the winner is resolved again
  2186. # below.
  2187. self._resolve_variant(item, candidate)
  2188. return await self._filament_short_on(db, item, pid)
  2189. async def unmatched_on(
  2190. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2191. ) -> list[str]:
  2192. self._resolve_variant(item, candidate)
  2193. return await self._unmatched_on(db, item, pid)
  2194. while True:
  2195. match_id, match_reason = await self._find_idle_printer_for_model(
  2196. db,
  2197. candidate.target_model,
  2198. # Sensor-held printers are unavailable to the
  2199. # matcher but stay out of busy_printers itself
  2200. # (#1148) — see where `interlocked` is built.
  2201. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2202. effective_types,
  2203. item.target_location,
  2204. filament_overrides=filament_overrides,
  2205. require_plate_clear=require_plate_clear,
  2206. wakeable_ids=wakeable_printer_ids,
  2207. printer_scope=item_scope,
  2208. is_short=is_short,
  2209. drying_ids=drying_held,
  2210. unmatched_on=unmatched_on,
  2211. refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
  2212. )
  2213. # "Only if the previous print succeeded" is about the
  2214. # printer the job lands on: one whose last print failed
  2215. # is passed over for another of the model.
  2216. if (
  2217. match_id
  2218. and item.require_previous_success
  2219. and not await self._check_previous_success(db, item, printer_id=match_id)
  2220. ):
  2221. gate_blocked.add(match_id)
  2222. continue
  2223. break
  2224. if match_id:
  2225. printer_id = match_id
  2226. chosen = candidate
  2227. break
  2228. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2229. # Nothing is available and nothing has been woken this pass:
  2230. # switch one matching printer on. Assignment is left to the
  2231. # next pass, which sees the booted printer's live state
  2232. # instead of guessing at it seconds after connect (#2786).
  2233. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2234. woken_id, attempted_id = await self._wake_printer_for_model(
  2235. db,
  2236. wakeable_candidates,
  2237. item.target_location,
  2238. busy_printers | interlocked.keys(),
  2239. wakeable_printer_ids,
  2240. require_plate_clear,
  2241. printer_scope=item_scope,
  2242. )
  2243. # An attempt spends the pass's one wake whether or not
  2244. # it worked: it has already blocked the queue loop for
  2245. # the boot wait. A failed printer is held out of later
  2246. # passes by its own cool-off, deliberately NOT by
  2247. # busy_printers — it is off, not busy, and labelling it
  2248. # busy would both misdescribe it in every later item's
  2249. # waiting reason and suppress the notification, since
  2250. # an all-busy reason is treated as needing no action.
  2251. power_on_attempted = attempted_id is not None
  2252. if woken_id is not None:
  2253. # Hold this item back rather than dispatching onto a
  2254. # printer whose AMS has not reported yet.
  2255. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2256. continue
  2257. if printer_id is None and gate_blocked:
  2258. # The matcher reports the printers passed over as busy;
  2259. # what holds the job is their failed last print.
  2260. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2261. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2262. # Fold the winning variant's file and settings onto the item
  2263. # before anything else looks at them — the guards below and
  2264. # every step of the dispatch read the item's own columns.
  2265. if chosen is not None:
  2266. self._resolve_variant(item, chosen)
  2267. # Update waiting_reason if changed and send notification when first waiting
  2268. if item.waiting_reason != waiting_reason:
  2269. was_waiting = item.waiting_reason is not None
  2270. previous_reason = item.waiting_reason
  2271. item.waiting_reason = waiting_reason
  2272. await db.commit()
  2273. # Send waiting notification only when transitioning to waiting state
  2274. # and the reason requires user action (not just "all printers busy")
  2275. # Also when a job that only waited for a busy printer
  2276. # now waits on something the user has to do.
  2277. if (
  2278. waiting_reason
  2279. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2280. and not _asks_nothing_new(waiting_reason)
  2281. ):
  2282. job_name = await self._get_job_name(db, item)
  2283. await notification_service.on_queue_job_waiting(
  2284. job_name=job_name,
  2285. target_model=_candidate_model_label(candidates) or item.target_model,
  2286. waiting_reason=waiting_reason,
  2287. db=db,
  2288. )
  2289. if printer_id:
  2290. # Before claiming the printer: hold back rather than race
  2291. # another dispatch over the same transient library row.
  2292. # Checked here so a held item does not get a printer
  2293. # assigned and then sit on it. See _library_row_conflict().
  2294. #
  2295. # No busy_printers.add() here, unlike the fixed-printer
  2296. # branch above: that one protects its printer's own queue
  2297. # ordering, but this item was never assigned to `printer_id`
  2298. # — the matcher merely offered it. Marking it busy would
  2299. # strand an idle printer for the rest of the pass.
  2300. if _library_row_conflict(item):
  2301. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2302. continue
  2303. if await _edited_since_loaded(db, item):
  2304. continue
  2305. # Assign printer and start - clear waiting reason
  2306. item.printer_id = printer_id
  2307. item.waiting_reason = None
  2308. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2309. # Send assignment notification
  2310. job_name = await self._get_job_name(db, item)
  2311. printer = await self._get_printer(db, printer_id)
  2312. await notification_service.on_queue_job_assigned(
  2313. job_name=job_name,
  2314. printer_id=printer_id,
  2315. printer_name=printer.name if printer else "Unknown",
  2316. target_model=item.target_model,
  2317. db=db,
  2318. )
  2319. # A mapping on this item was not made for the printer just
  2320. # picked: it came with a job moved here from a fixed
  2321. # printer, or from a variant. Its tray IDs can name a
  2322. # tray of the right type in another colour here, which
  2323. # the fit check lets through (#3239). Match afresh, by
  2324. # type and colour.
  2325. if item.ams_mapping:
  2326. logger.info(
  2327. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2328. item.id,
  2329. item.ams_mapping,
  2330. printer_id,
  2331. )
  2332. item.ams_mapping = None
  2333. # On a nozzle-rack printer its own nozzle mapping likewise
  2334. # (set through the API or an order's plate spec): it names
  2335. # rack positions, and the dispatch sends a stored one as-is
  2336. # instead of resolving this printer's rack. Elsewhere it
  2337. # holds extruder indices, the same on every printer of the
  2338. # model (an H2D VP keeps the slicer's for that reason), and
  2339. # one that came with the chosen variant belongs to that
  2340. # variant's file: both stay.
  2341. if (
  2342. (chosen is None or chosen.variant is None)
  2343. and printer is not None
  2344. and is_nozzle_rack_model(printer.model)
  2345. ):
  2346. item.nozzle_mapping = None
  2347. # Resolve the AMS mapping for the assigned printer. It is
  2348. # always missing here, so this computes it, and it also
  2349. # self-heals a bogus stored [-1] (#2589).
  2350. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2351. if unmappable:
  2352. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2353. continue
  2354. # Filament-deficit pre-dispatch check (#1496).
  2355. if await self._block_on_filament_deficit(db, item):
  2356. continue
  2357. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2358. # selection already filters on filament type, so this is a
  2359. # backstop for an AMS that changed between assignment and
  2360. # dispatch, and for a type loaded on the wrong nozzle.
  2361. # The assignment made above is released with the hold —
  2362. # this item asked for a model, not this printer.
  2363. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2364. continue
  2365. # As for a pinned job: drying stops once the print is
  2366. # decided, unless it may run through it.
  2367. if self._drying_in_progress.get(
  2368. printer_id
  2369. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2370. await self._stop_drying(printer_id)
  2371. _claim_library_row(item)
  2372. dispatch_ids.append(item.id)
  2373. claim_printer(printer_id)
  2374. # SJF starvation guard: mark items that were jumped
  2375. if sjf_enabled and item.print_time_seconds is not None:
  2376. for other in items:
  2377. if (
  2378. other.id != item.id
  2379. and other.id not in dispatch_ids
  2380. and other.status == "pending"
  2381. and _could_take_printer(other, printer_id, item.target_model)
  2382. and not other.been_jumped
  2383. and other.position < item.position
  2384. and (
  2385. other.print_time_seconds is None
  2386. or other.print_time_seconds > item.print_time_seconds
  2387. )
  2388. ):
  2389. other.been_jumped = True
  2390. await db.commit()
  2391. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2392. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2393. # skip summary that only lands after the transfers have finished is
  2394. # useless for working out why an item did not go out.
  2395. if skip_reasons:
  2396. logger.info("Queue skip summary: %s", skip_reasons)
  2397. for pid in sorted(busy_printers):
  2398. reason = busy_reasons.get(pid, "no reason recorded")
  2399. if pid in claimed_printers:
  2400. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2401. continue
  2402. # The three live fields stay, because they are what someone
  2403. # reading a bundle wants next -- but they are labelled as read
  2404. # now, not as the state the decision was made on, which is what
  2405. # made the old line contradict itself.
  2406. state = printer_manager.get_status(pid)
  2407. logger.info(
  2408. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2409. pid,
  2410. reason,
  2411. printer_manager.is_connected(pid),
  2412. state.state if state else "NO_STATUS",
  2413. printer_manager.is_awaiting_plate_clear(pid),
  2414. )
  2415. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2416. # selection and `_launch_uploads`, so anything raising here would
  2417. # discard this tick's selections — computed AMS mappings and all —
  2418. # and, on a persistent fault, stop the queue dispatching entirely.
  2419. # Same reasoning as the deficit check's guard below: never let an
  2420. # auxiliary check wedge the queue. The bed simply stays wherever it
  2421. # was, and the next tick tries again.
  2422. try:
  2423. await self._apply_keep_warm(
  2424. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2425. )
  2426. except Exception as e:
  2427. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2428. # Read the concurrency limit BEFORE the commit below, not inside
  2429. # _dispatch_selected(). A SELECT on this session after the commit
  2430. # implicitly opens a fresh transaction that nothing then closes, and
  2431. # it would stay open for the whole dispatch — minutes of "idle in
  2432. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2433. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2434. # checkpointed while every dispatch is writing to it.
  2435. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2436. # Selection is done; every decision above is recorded on `db`
  2437. # (model-based printer assignment, computed ams_mapping). Flush it
  2438. # before the dispatch tasks open their own sessions, or they will
  2439. # read a row that still says printer_id=None. This also releases the
  2440. # connection back to the pool for the duration of the dispatch.
  2441. await db.commit()
  2442. if dispatch_ids:
  2443. item_printers = {it.id: it.printer_id for it in items}
  2444. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2445. # Auto-drying: start drying on idle printers that have no pending queue items
  2446. await self._check_auto_drying(db, items, dispatching_printers)
  2447. # Low filament: alert on assigned spools that have crossed their
  2448. # low-stock threshold (#2913). Runs on both paths out of this method
  2449. # for the same reason auto-drying does — an empty queue does not mean
  2450. # the spools in the printers stopped mattering.
  2451. await self._check_filament_low(db)
  2452. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2453. # is about to run out before a replenishment could arrive (#2955).
  2454. await self._check_stock_forecast(db)
  2455. # Keep the loop on the fast interval while any upload is in flight so
  2456. # a slot freed mid-tick refills within seconds rather than after the
  2457. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2458. # deferred because the pool was full) also counts as productive.
  2459. return bool(dispatch_ids) or bool(self._inflight)
  2460. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2461. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2462. Dispatch used to happen inline in the selection loop: ``await
  2463. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2464. performs the FTP upload, that serialized every printer behind every
  2465. other printer's transfer even though the printers are independent
  2466. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2467. gather was awaited before ``check_queue`` returned, so the run loop
  2468. stayed blocked until the *slowest* upload in the batch finished — a
  2469. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2470. 93-printer farm even as other printers came free (#2602).
  2471. Each upload now runs as an independent background task tracked in
  2472. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2473. `pending` until their upload completes) and their printers from the
  2474. next pass's selection, and this method launches at most
  2475. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2476. the next fast tick instead of waiting out the whole batch. The bound
  2477. exists because the printers are independent but the host is not: each
  2478. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2479. file handle.
  2480. The no-overlapping-dispatch invariant the batch-await used to provide
  2481. is now carried by the in-flight exclusion in check_queue. Everything
  2482. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2483. per-printer hold, and each item's independent failure handling — still
  2484. lives in ``_start_print`` and runs per task exactly as before.
  2485. Synchronous on purpose: it registers every launched task into
  2486. ``self._inflight`` before returning, so the next (sequential) tick sees
  2487. an accurate in-flight count with no interleaving await.
  2488. """
  2489. free = limit - len(self._inflight)
  2490. if free <= 0:
  2491. logger.info(
  2492. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2493. len(self._inflight),
  2494. limit,
  2495. len(item_ids),
  2496. item_ids,
  2497. )
  2498. return
  2499. to_launch = item_ids[:free]
  2500. deferred = item_ids[free:]
  2501. logger.info(
  2502. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2503. len(to_launch),
  2504. len(self._inflight),
  2505. limit,
  2506. f" — deferring {deferred} to a later tick" if deferred else "",
  2507. )
  2508. for item_id in to_launch:
  2509. task = spawn_background_task(
  2510. self._dispatch_one(item_id, item_printers.get(item_id)),
  2511. name=f"queue-upload-{item_id}",
  2512. )
  2513. self._inflight[item_id] = (task, item_printers.get(item_id))
  2514. # Prune on completion so the freed slot is refillable next tick.
  2515. # spawn_background_task already logs any uncaught exception; this
  2516. # only reclaims the pool slot (fires on success, failure, or cancel).
  2517. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2518. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2519. """Upload + start one queue item in its own session (pool worker, #2602).
  2520. Its own session: pool workers run concurrently and an AsyncSession is
  2521. not safe to share across tasks; it also keeps a slow upload from pinning
  2522. the scheduler's session (and, on SQLite, its transaction) open for the
  2523. transfer's duration.
  2524. ``selected_printer_id`` is the printer this item was selected for, taken
  2525. from the same snapshot the caller used. It exists so the preheat pin can
  2526. be unwound on the paths that never reach the ``finally`` below — see the
  2527. claim failure a few lines down. Optional so the direct-call tests keep
  2528. working; when it is absent those paths simply behave as they did before.
  2529. """
  2530. async with async_session() as item_db:
  2531. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2532. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2533. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2534. # routes reject reassignment (409), so printer_id can't change out from
  2535. # under the in-flight upload and split the queue row from the
  2536. # archive/expected-print/physical command.
  2537. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2538. logger.info(
  2539. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2540. item_id,
  2541. )
  2542. # This return is outside the try/finally below, so the rollback
  2543. # has to happen here. Selecting this item already handed any
  2544. # keep-warm hold on its printer over to the preheat pin
  2545. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2546. # unwind it. Bailing without doing so leaves the bed hot with
  2547. # nothing tracking it: the keep-warm entry is gone, so the
  2548. # max-duration cap no longer applies, and if this was the
  2549. # printer's last pending item nothing else will ever turn it
  2550. # off. Reachable whenever a cancel or delete lands between
  2551. # selection and the claim.
  2552. if selected_printer_id is not None:
  2553. self._rollback_preheat_pin(item_id, selected_printer_id)
  2554. return
  2555. # Seeded from the caller's snapshot so the `item vanished` return
  2556. # below still unwinds the pin; overwritten with the row's own
  2557. # printer_id as soon as we have it.
  2558. item_printer_id: int | None = selected_printer_id
  2559. try:
  2560. item = await item_db.get(PrintQueueItem, item_id)
  2561. if not item:
  2562. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2563. return
  2564. item_printer_id = item.printer_id
  2565. await self._start_print(item_db, item)
  2566. finally:
  2567. # Undo an expected-print registration whose print command never
  2568. # went out. One choke point covers every way `_start_print` can
  2569. # end without sending: a raised exception (a DB failure mid-
  2570. # dispatch is the reported case), an early return, a cancel
  2571. # winning the #1853 CAS, or `start_print()` returning False.
  2572. # A confirmed send removes the entry itself, so this is a no-op
  2573. # on the happy path.
  2574. self._rollback_unconfirmed_expected_print(item_id)
  2575. # Likewise the print user it set: the printer's next print is
  2576. # not this item's.
  2577. self._rollback_unconfirmed_print_user(item_id)
  2578. # Its archive is no longer held for it (archive_work).
  2579. self._release_held_archive(item_id)
  2580. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2581. # reservation survives only after start_print() accepted the
  2582. # command. Failure, cancellation, deferral, and exceptions all
  2583. # release it here.
  2584. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2585. # Unwind preheat state (bed/chamber/airduct) if the
  2586. # dispatch aborted before the print's own gcode took over.
  2587. # `_start_print` clears the pin on successful `start_print()`;
  2588. # anything still present here is by definition an aborted
  2589. # dispatch and gets rolled back so the printer isn't left
  2590. # heating for a job that isn't happening.
  2591. if item_printer_id is not None:
  2592. self._rollback_preheat_pin(item_id, item_printer_id)
  2593. # The cancellation flag only has meaning while this dispatch is
  2594. # running; drop it so the set cannot grow without bound and a
  2595. # re-queued item never inherits a stale cancellation.
  2596. self._cancelled_dispatches.discard(item_id)
  2597. # Release the claim on every exit. Once dispatch has finished the
  2598. # row's status carries the lock (printing/failed/cancelled are all
  2599. # != pending), so the token is only needed for the duration of the
  2600. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2601. # dispatchable again on the next tick.
  2602. await self._clear_dispatch_claim(item_db, item_id)
  2603. async def _requeue_after_upload_refused(
  2604. self,
  2605. db: AsyncSession,
  2606. item: PrintQueueItem,
  2607. printer: Printer,
  2608. error_msg: str,
  2609. toast_uid: int | None,
  2610. kind: FtpFailureKind,
  2611. ) -> None:
  2612. """Put an item back in the queue after its file never reached the printer (#3210).
  2613. The printer goes into `_upload_backoff`, which keeps every item away
  2614. from it until the window ends. The window grows with each refusal in a
  2615. row; see ``_upload_backoff_seconds``.
  2616. An item pinned to this printer keeps it, waits there, and is the one
  2617. that knocks again. An item for "Any <model>" goes back to the pool
  2618. instead, so another printer of the model can take it (#3409). Only the
  2619. assignment goes: the next model assignment drops whatever on the row
  2620. was worked out for one printer, as it does for every model job.
  2621. The first refusal in a run sends the one "Job waiting" notification,
  2622. and a later one only if it asks for something else (a card after a
  2623. dropped connection). It cannot wait for the hold the way it used to: a
  2624. released item is not held on this printer, so nothing would say why
  2625. it stopped. A job cancelled or moved during the upload sends none.
  2626. `dispatch_attempts` is not charged: that budget bounds a printer that
  2627. takes the file and then never starts, which this is not.
  2628. """
  2629. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2630. self._upload_refusals[printer.id] = refusals
  2631. self._upload_refusal_kind[printer.id] = kind
  2632. backoff = _upload_backoff_seconds(refusals)
  2633. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2634. released = False
  2635. if item.target_model:
  2636. # Only while it is still pending on this printer: a cancel, or a
  2637. # move the user made during the upload, stands.
  2638. result = cast(
  2639. CursorResult,
  2640. await db.execute(
  2641. update(PrintQueueItem)
  2642. .where(PrintQueueItem.id == item.id)
  2643. .where(PrintQueueItem.status == "pending")
  2644. .where(PrintQueueItem.printer_id == printer.id)
  2645. .values(printer_id=None, error_message=None)
  2646. .execution_options(synchronize_session=False)
  2647. ),
  2648. )
  2649. await db.commit()
  2650. released = result.rowcount > 0
  2651. elif item.error_message:
  2652. # The row is still `pending` -- it only moves to `printing` after a
  2653. # successful upload -- so there is no status to write back. Writing
  2654. # one anyway would undo a cancel that landed during the upload.
  2655. item.error_message = None
  2656. await db.commit()
  2657. logger.warning(
  2658. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue%s; "
  2659. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2660. item.id,
  2661. printer.id,
  2662. printer.name,
  2663. error_msg,
  2664. " and returned to the pool" if released else "",
  2665. refusals,
  2666. backoff,
  2667. )
  2668. reason = _refused_upload_hold_reason(printer.name or f"printer {printer.id}", kind)
  2669. if self._upload_refusal_notified.get(printer.id) != reason and await self._still_waiting_on(
  2670. db, item.id, None if released else printer.id
  2671. ):
  2672. self._upload_refusal_notified[printer.id] = reason
  2673. try:
  2674. await notification_service.on_queue_job_waiting(
  2675. job_name=await self._get_job_name(db, item),
  2676. target_model=item.target_model or printer.model or "",
  2677. waiting_reason=reason,
  2678. db=db,
  2679. printer_id=printer.id,
  2680. )
  2681. except Exception as e:
  2682. # The job is safe in the queue either way.
  2683. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  2684. try:
  2685. # Closes the dispatch toast for this attempt. Without it the toast
  2686. # keeps spinning on an upload that has ended.
  2687. await ws_manager.send_queue_item_failed(
  2688. user_id=toast_uid,
  2689. queue_item_id=item.id,
  2690. printer_id=printer.id,
  2691. reason="upload_failed",
  2692. )
  2693. except Exception:
  2694. pass # toast is best-effort
  2695. @staticmethod
  2696. async def _still_waiting_on(db: AsyncSession, item_id: int, printer_id: int | None) -> bool:
  2697. """Whether the item is still pending, on *printer_id* (None: unassigned)."""
  2698. row = (
  2699. await db.execute(
  2700. select(PrintQueueItem.status, PrintQueueItem.printer_id).where(PrintQueueItem.id == item_id)
  2701. )
  2702. ).one_or_none()
  2703. return row is not None and row.status == "pending" and row.printer_id == printer_id
  2704. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2705. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2706. if printer_id is not None:
  2707. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2708. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2709. """Withdraw the expected print and print user of a sent print that never started.
  2710. Both tell the rest of Bambuddy that the printer's next print is this
  2711. item's: left behind, a print started by hand later is taken for it.
  2712. With ``unless_printing``, a printer that is printing after all keeps
  2713. them, as that print is most likely this one starting late.
  2714. ``keep_expected`` withdraws only the print user, which vouches for any
  2715. print on the printer. The expected print names this item's file, so a
  2716. late start of it is still matched to its archive.
  2717. """
  2718. sent = self._sent_unstarted_print.get(item_id)
  2719. if sent is None:
  2720. return
  2721. printer_id, remote_filename, archive_id = sent
  2722. if unless_printing:
  2723. status = printer_manager.get_status(printer_id)
  2724. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2725. return
  2726. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2727. if keep_expected:
  2728. return
  2729. del self._sent_unstarted_print[item_id]
  2730. if remote_filename is not None and archive_id is not None:
  2731. try:
  2732. from backend.app.main import unregister_expected_print
  2733. unregister_expected_print(printer_id, remote_filename, archive_id)
  2734. except Exception:
  2735. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2736. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2737. """Drop an expectation for a print command that was never sent.
  2738. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2739. where the interesting exception is usually the one already propagating.
  2740. """
  2741. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2742. if pending is None:
  2743. return
  2744. printer_id, remote_filename, archive_id = pending
  2745. try:
  2746. from backend.app.main import unregister_expected_print
  2747. unregister_expected_print(printer_id, remote_filename, archive_id)
  2748. except Exception:
  2749. logger.warning(
  2750. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2751. item_id,
  2752. printer_id,
  2753. remote_filename,
  2754. archive_id,
  2755. exc_info=True,
  2756. )
  2757. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2758. """Release a queue reservation without touching the dispatch session."""
  2759. if item_id not in self._unconfirmed_budget_reservations:
  2760. return
  2761. for attempt in range(1, 4):
  2762. async with async_session() as cleanup_db:
  2763. try:
  2764. await release_budget_reservation(
  2765. cleanup_db,
  2766. source_type="print_queue",
  2767. source_id=item_id,
  2768. status="released",
  2769. )
  2770. await cleanup_db.commit()
  2771. self._unconfirmed_budget_reservations.discard(item_id)
  2772. return
  2773. except Exception as exc:
  2774. try:
  2775. await cleanup_db.rollback()
  2776. except Exception:
  2777. pass
  2778. if attempt == 3:
  2779. logger.error(
  2780. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2781. item_id,
  2782. attempt,
  2783. exc,
  2784. )
  2785. return
  2786. await asyncio.sleep(0.5 * attempt)
  2787. @staticmethod
  2788. def _reported_bed_target(printer_id: int) -> int | None:
  2789. """The bed target firmware currently reports, or None if it can't be read.
  2790. None means "no evidence", not "zero" — callers must not treat it as a
  2791. temperature. Deliberately total: this feeds cleanup paths that run in a
  2792. ``finally``, where a malformed status must not become the exception the
  2793. caller sees.
  2794. """
  2795. try:
  2796. state = printer_manager.get_status(printer_id)
  2797. if state is None:
  2798. return None
  2799. temps = state.temperatures
  2800. if not isinstance(temps, dict):
  2801. return None
  2802. return int(float(temps.get("bed_target", 0) or 0))
  2803. except (TypeError, ValueError, AttributeError):
  2804. return None
  2805. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2806. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2807. Turns the bed heater off, the chamber heater off, and opens the
  2808. airduct flap back to cooling — for whichever of those preheat
  2809. actually applied. `_start_print` clears the pin on successful
  2810. `start_print()`; anything still present when `_dispatch_one` exits
  2811. is by definition an aborted dispatch and gets rolled back here.
  2812. The bed is the one action that can be declined: if firmware has since
  2813. been given a target other than the one we pinned, it belongs to someone
  2814. else and is left alone. See the comment at that branch.
  2815. Also called directly from `_dispatch_one`'s claim-failure return, which
  2816. never reaches the ``finally``.
  2817. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2818. """
  2819. pin = self._preheat_pin.pop(printer_id, set())
  2820. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2821. if not pin:
  2822. return
  2823. client = printer_manager.get_client(printer_id)
  2824. if client is None:
  2825. logger.info(
  2826. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2827. item_id,
  2828. printer_id,
  2829. )
  2830. return
  2831. if "bed" in pin:
  2832. # Only undo our own target. If firmware reports something else, the
  2833. # user or another writer owns the bed now and zeroing it would
  2834. # clobber their choice -- the same guard `_release_keep_warm`
  2835. # applies to a keep-warm hold.
  2836. #
  2837. # Every uncertain case switches the bed off rather than leaving it:
  2838. # no recorded target (a pin written before this bookkeeping, or a
  2839. # setter that raised after pinning) and an unreadable status both
  2840. # fall through. A bed left hot with no owner is the worse failure,
  2841. # and this runs in a `finally` where raising would mask the real
  2842. # exception.
  2843. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2844. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2845. logger.info(
  2846. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2847. item_id,
  2848. printer_id,
  2849. cur_bed_target,
  2850. pinned_bed,
  2851. )
  2852. else:
  2853. try:
  2854. client.set_bed_temperature(0)
  2855. except Exception as exc:
  2856. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2857. if "chamber" in pin:
  2858. try:
  2859. client.set_chamber_temperature(0)
  2860. except Exception as exc:
  2861. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2862. if "airduct" in pin:
  2863. try:
  2864. client.set_airduct_mode("cooling")
  2865. except Exception as exc:
  2866. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2867. logger.info(
  2868. "Dispatch item %s (printer %d): preheat rollback → %s",
  2869. item_id,
  2870. printer_id,
  2871. sorted(pin),
  2872. )
  2873. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2874. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2875. Returns True if this call won the claim, False if the row was already
  2876. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2877. the load-bearing guard against reassign-during-dispatch (#2615).
  2878. ``printer_id`` is the printer the item was selected for: a row moved to
  2879. another printer since is not claimed, and the next pass selects it for
  2880. that one."""
  2881. query = (
  2882. update(PrintQueueItem)
  2883. .where(PrintQueueItem.id == item_id)
  2884. .where(PrintQueueItem.status == "pending")
  2885. .where(PrintQueueItem.dispatching_at.is_(None))
  2886. )
  2887. if printer_id is not None:
  2888. query = query.where(PrintQueueItem.printer_id == printer_id)
  2889. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2890. await db.commit()
  2891. return res.rowcount > 0
  2892. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2893. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2894. mask the dispatch outcome.
  2895. Retried, because the failure mode in practice is transient and narrow: a
  2896. database that is momentarily unreachable — PostgreSQL out of connection
  2897. slots is the observed case — refuses this write for a second or two while
  2898. the dispatch that just ended is still holding the row out of the selection
  2899. query. One attempt was enough to wedge the item; a couple of spaced
  2900. attempts clear it. Each attempt rolls back first, since a failed write
  2901. leaves the session needing it before it can be reused.
  2902. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2903. on the next quiet tick.
  2904. """
  2905. for attempt in range(1, 4):
  2906. try:
  2907. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2908. await db.commit()
  2909. return
  2910. except Exception as exc:
  2911. try:
  2912. await db.rollback()
  2913. except Exception:
  2914. pass
  2915. if attempt == 3:
  2916. logger.warning(
  2917. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2918. "— a later quiet tick will release it",
  2919. item_id,
  2920. attempt,
  2921. exc,
  2922. )
  2923. return
  2924. await asyncio.sleep(0.5 * attempt)
  2925. async def _printers_for_model(
  2926. self,
  2927. db: AsyncSession,
  2928. model: str,
  2929. target_location: str | None = None,
  2930. printer_scope: PrinterScope = ALL_PRINTERS,
  2931. ) -> list[Printer]:
  2932. """Active printers of *model*, optionally narrowed to one location.
  2933. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2934. answer "which printers can this job run on" from one query — a job can
  2935. only be woken onto a printer the matcher would also have considered.
  2936. ``printer_scope`` is the job creator's (#1727).
  2937. Fewest print hours first (#3480): both take the first printer that
  2938. fits, so an "Any" job goes to the least worn machine and a farm's jobs
  2939. spread by wear instead of all landing on the lowest id. The hours are
  2940. the maintenance counter's (runtime plus the baseline offset), which
  2941. counts every print, wherever it was started. Ties (printers still at
  2942. zero) go by id, so the order is stable.
  2943. """
  2944. normalized_model = normalize_printer_model(model) or model
  2945. query = (
  2946. select(Printer)
  2947. .where(func.lower(Printer.model) == normalized_model.lower())
  2948. .where(Printer.is_active == True) # noqa: E712
  2949. )
  2950. if target_location:
  2951. query = query.where(Printer.location == target_location)
  2952. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2953. query = query.where(clause)
  2954. result = await db.execute(query)
  2955. return sorted(result.scalars().all(), key=_wear_order)
  2956. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2957. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2958. Read once per queue check rather than per printer: it decides both
  2959. whether the wake step has anything to do and how an offline printer is
  2960. worded in the waiting reason — "Offline" and "offline with no Auto On
  2961. plug" are different problems, and the second is the one the user has to
  2962. fix themselves (#2786).
  2963. """
  2964. result = await db.execute(
  2965. select(SmartPlug.printer_id)
  2966. .where(SmartPlug.printer_id.is_not(None))
  2967. .where(SmartPlug.enabled == True) # noqa: E712
  2968. .where(SmartPlug.auto_on == True) # noqa: E712
  2969. )
  2970. return {pid for (pid,) in result.all() if pid is not None}
  2971. def _wake_recently_failed(self, printer_id: int) -> bool:
  2972. """True while this printer's failed power-on is still cooling off (#2786)."""
  2973. deadline = self._wake_failures.get(printer_id)
  2974. if deadline is None:
  2975. return False
  2976. if time.monotonic() >= deadline:
  2977. del self._wake_failures[printer_id]
  2978. return False
  2979. return True
  2980. async def _wake_printer_for_model(
  2981. self,
  2982. db: AsyncSession,
  2983. candidates: list[_ModelCandidate],
  2984. target_location: str | None,
  2985. exclude_ids: set[int],
  2986. wakeable_ids: set[int],
  2987. require_plate_clear: bool,
  2988. printer_scope: PrinterScope = ALL_PRINTERS,
  2989. ) -> tuple[int | None, int | None]:
  2990. """Power on one offline printer a model-based item could run on (#2786).
  2991. The fixed-printer branch has powered a printer on since smart plugs
  2992. existed. The model-based branch never could: its matcher drops an
  2993. offline printer into the "Offline:" waiting reason and nothing looks at
  2994. its plugs, so a class-targeted job with every matching printer switched
  2995. off sat pending forever. The reporter's log is the controlled
  2996. experiment — the same item, same plug, same Auto On setting, dispatched
  2997. the moment they edited it onto a specific printer.
  2998. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2999. power-on was actually tried, so the caller can tell "nothing here was
  3000. wakeable" (both None — cheap, other items may still find something)
  3001. from "we tried and it did not come up" (only ``attempted_id`` — the
  3002. boot timeout has already been spent).
  3003. A printer whose last known trays cannot satisfy the job is passed over
  3004. rather than woken (#2876): the colours are readable while it is off, so
  3005. switching a farm on one machine at a time to discover them wakes
  3006. printers that could never have taken the job.
  3007. Deliberately does NOT go on to match the job once a printer is up: AMS
  3008. trays arrive with the first status push after connect, so a filament
  3009. check against a printer that booted seconds ago can reject the printer
  3010. we just woke. The next queue pass matches it with live state.
  3011. At most one printer per pass. Each wake blocks the queue loop for the
  3012. boot wait, and a queue of ten class-targeted jobs must not switch on
  3013. ten printers inside one check.
  3014. """
  3015. for candidate in candidates:
  3016. if not candidate.target_model:
  3017. continue
  3018. required_types, filament_overrides = _filament_constraints(candidate)
  3019. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  3020. # Fewest print hours first, as the matcher picks (#3480).
  3021. for printer in printers:
  3022. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  3023. continue
  3024. if printer_manager.is_connected(printer.id):
  3025. continue
  3026. if self._wake_recently_failed(printer.id):
  3027. # Its plug did not bring it back a moment ago. Move on to a
  3028. # sibling instead of spending this pass — and every pass —
  3029. # on the same printer.
  3030. continue
  3031. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  3032. # Waking this one buys nothing: it would boot into IDLE and
  3033. # then be held by the plate-clear gate, which is exactly
  3034. # what the reporter's log shows happening for 80 minutes
  3035. # after a fixed-printer wake. The flag is Bambuddy-side and
  3036. # persisted, so it is readable while the printer is off.
  3037. logger.info(
  3038. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  3039. printer.id,
  3040. candidate.target_model,
  3041. )
  3042. continue
  3043. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  3044. if shortfall:
  3045. logger.info(
  3046. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  3047. printer.id,
  3048. candidate.target_model,
  3049. ", ".join(shortfall),
  3050. )
  3051. continue
  3052. plugs = await self._get_smart_plugs(db, printer.id)
  3053. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  3054. if not auto_on_plugs:
  3055. # wakeable_ids said otherwise — the plug changed under us
  3056. # mid-pass. Nothing to do but move on.
  3057. continue
  3058. logger.info(
  3059. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  3060. candidate.target_model,
  3061. printer.id,
  3062. )
  3063. primary_plug = self._pick_power_plug(auto_on_plugs)
  3064. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  3065. logger.warning(
  3066. "Could not power on printer %s via smart plug; not trying it again for %ss",
  3067. printer.id,
  3068. self._wake_failure_cooloff,
  3069. )
  3070. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  3071. return None, printer.id
  3072. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  3073. try:
  3074. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  3075. if await service.turn_on(extra_plug):
  3076. await publish_plug_state(
  3077. extra_plug.id,
  3078. extra_plug.name,
  3079. extra_plug.printer_id,
  3080. on=True,
  3081. ha_entity_id=extra_plug.ha_entity_id,
  3082. )
  3083. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  3084. except Exception as e:
  3085. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  3086. return printer.id, printer.id
  3087. return None, None
  3088. async def _find_idle_printer_for_model(
  3089. self,
  3090. db: AsyncSession,
  3091. model: str,
  3092. exclude_ids: set[int],
  3093. required_filament_types: list[str] | None = None,
  3094. target_location: str | None = None,
  3095. filament_overrides: list[dict] | None = None,
  3096. require_plate_clear: bool = True,
  3097. wakeable_ids: set[int] | None = None,
  3098. printer_scope: PrinterScope = ALL_PRINTERS,
  3099. is_short: Callable[[int], Awaitable[bool]] | None = None,
  3100. drying_ids: set[int] | None = None,
  3101. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  3102. refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
  3103. ) -> tuple[int | None, str | None]:
  3104. """Find an idle, connected printer matching the model with compatible filaments.
  3105. Args:
  3106. db: Database session
  3107. model: Printer model to match (e.g., "X1C", "P1S")
  3108. exclude_ids: Printer IDs to exclude (already busy)
  3109. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  3110. If provided, only printers with all required types loaded will match.
  3111. target_location: Optional location filter. If provided, only printers in this location are considered.
  3112. filament_overrides: Optional list of override dicts. Each entry may include
  3113. ``force_color_match: true`` to require an exact type+color match
  3114. on the printer for that slot. Without the flag the existing
  3115. colour-preference logic applies.
  3116. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  3117. offline printer is worded: one Bambuddy will switch on reads
  3118. differently from one the user has to go and switch on themselves.
  3119. is_short: Says whether a printer's spools are too light for the job (#3137).
  3120. A printer it flags is passed over while another eligible one
  3121. is not. When every eligible printer is short, the first is
  3122. returned all the same, so the deficit gate holds the job there
  3123. and "Print Anyway" still has a printer to print on.
  3124. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  3125. in the reason, as a pinned job's wait is.
  3126. unmatched_on: Names the filaments the slot matcher would leave without a
  3127. tray on a printer (#3280). A printer it names any for is
  3128. passed over like one missing a filament type: the checks
  3129. above only ask whether each type and forced colour is
  3130. loaded somewhere, not on the right nozzle or once per slot.
  3131. refused_uploads: Excluded printers out of dispatch after a refused upload,
  3132. with why (#3409). Each is named with the reason its own
  3133. queue rows show, not as "Busy".
  3134. Returns:
  3135. Tuple of (printer_id, waiting_reason):
  3136. - (printer_id, None) if a matching printer was found
  3137. - (None, reason) if no printer is available, with explanation
  3138. """
  3139. normalized_model = normalize_printer_model(model) or model
  3140. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  3141. location_suffix = f" in {target_location}" if target_location else ""
  3142. if not printers:
  3143. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3144. # Separate force-matched overrides from preference-only overrides
  3145. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3146. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3147. # Track reasons for skipping printers
  3148. printers_busy = []
  3149. # Printers out of dispatch after a refused upload, worded as the
  3150. # printer's own queue rows word it: "Busy" would read as printing (#3409).
  3151. printers_refused: list[str] = []
  3152. printers_offline = []
  3153. printers_offline_no_plug = []
  3154. printers_missing_filament: list[tuple[str, list[str]]] = []
  3155. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3156. # The first eligible printer that is short on filament, kept in case
  3157. # every eligible printer is (#3137).
  3158. short_fallback: int | None = None
  3159. for printer in printers:
  3160. if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
  3161. printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
  3162. continue
  3163. if printer.id in exclude_ids:
  3164. # Printer is already claimed by another job in this scheduling run.
  3165. # For force-color jobs, still check if the color would match — if not,
  3166. # report it as a color mismatch rather than plain "Busy" so the user
  3167. # knows the job needs a filament change, not just to wait for availability.
  3168. if force_overrides and not pref_overrides:
  3169. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3170. if missing_colors:
  3171. printers_missing_filament.append((printer.name, missing_colors))
  3172. continue
  3173. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3174. continue
  3175. is_connected = printer_manager.is_connected(printer.id)
  3176. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3177. if not is_connected:
  3178. # An offline printer whose last known filament cannot run this
  3179. # job is reported as needing filament rather than as offline
  3180. # (#2876). It is also the printer the smart-plug step will now
  3181. # decline to switch on, and "Offline:" on its own would leave
  3182. # that decision looking like nothing happening at all.
  3183. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3184. if shortfall:
  3185. printers_missing_filament.append((printer.name, shortfall))
  3186. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3187. printers_offline_no_plug.append(printer.name)
  3188. else:
  3189. printers_offline.append(printer.name)
  3190. continue
  3191. if not is_idle:
  3192. # Printer is currently printing. For force-color jobs, check whether the
  3193. # loaded color would satisfy the requirement — if not, surface it as a
  3194. # color-mismatch reason rather than plain "Busy" so the user understands
  3195. # that the job is waiting for a filament change, not just printer availability.
  3196. if force_overrides and not pref_overrides:
  3197. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3198. if missing_colors:
  3199. printers_missing_filament.append((printer.name, missing_colors))
  3200. logger.debug(
  3201. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3202. printer.id,
  3203. printer.name,
  3204. missing_colors,
  3205. )
  3206. continue
  3207. printers_busy.append(printer.name)
  3208. continue
  3209. # Validate filament compatibility if required types are specified
  3210. if required_filament_types:
  3211. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3212. if missing:
  3213. # When force_overrides are present, enrich missing entries with color info
  3214. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3215. if force_overrides:
  3216. force_color_map = {
  3217. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3218. for o in force_overrides
  3219. }
  3220. missing_enriched = [
  3221. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3222. for t in missing
  3223. ]
  3224. printers_missing_filament.append((printer.name, missing_enriched))
  3225. else:
  3226. printers_missing_filament.append((printer.name, missing))
  3227. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3228. continue
  3229. # Force color match: ALL flagged slots must have an exact type+color match
  3230. if force_overrides:
  3231. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3232. if missing_colors:
  3233. printers_missing_filament.append((printer.name, missing_colors))
  3234. logger.debug(
  3235. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3236. printer.id,
  3237. printer.name,
  3238. missing_colors,
  3239. )
  3240. continue
  3241. # The matcher has the last word: a printer it cannot map would be
  3242. # held and given back, then chosen again on the next pass (#3280).
  3243. if unmatched_on is not None:
  3244. unmatched = await unmatched_on(printer.id)
  3245. if unmatched:
  3246. printers_missing_filament.append((printer.name, unmatched))
  3247. logger.debug(
  3248. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3249. printer.id,
  3250. printer.name,
  3251. unmatched,
  3252. )
  3253. continue
  3254. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3255. if pref_overrides:
  3256. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3257. if color_matches > 0:
  3258. candidates.append((printer.id, color_matches))
  3259. else:
  3260. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3261. printers_missing_filament.append((printer.name, override_colors))
  3262. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3263. continue
  3264. else:
  3265. # The first eligible printer wins, which is the one with the
  3266. # fewest print hours (#3480, see _printers_for_model), unless
  3267. # its spools are too light for the job (#3137).
  3268. if is_short is not None and await is_short(printer.id):
  3269. if short_fallback is None:
  3270. short_fallback = printer.id
  3271. logger.info(
  3272. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3273. printer.id,
  3274. printer.name,
  3275. )
  3276. continue
  3277. return printer.id, None
  3278. # If we have candidates from preference override matching, pick the one with most color matches.
  3279. # The sort is stable: among equal matches the fewest print hours still go first (#3480).
  3280. if candidates:
  3281. candidates.sort(key=lambda c: c[1], reverse=True)
  3282. if is_short is not None:
  3283. for candidate_id, _ in candidates:
  3284. if not await is_short(candidate_id):
  3285. return candidate_id, None
  3286. logger.info(
  3287. "Model-based assignment: passing over printer %s, not enough filament",
  3288. candidate_id,
  3289. )
  3290. return candidates[0][0], None
  3291. if short_fallback is not None:
  3292. return short_fallback, None
  3293. # Build waiting reason from what we found
  3294. reasons = []
  3295. if printers_missing_filament:
  3296. # Filament/color mismatch is most actionable - show first
  3297. if force_overrides and not pref_overrides:
  3298. # All mismatches are force-color failures — use descriptive message only;
  3299. # but only if there are no busy printers that DO have the matching color.
  3300. # If a printer has the right color but is busy, surface "Busy" instead so
  3301. # the user knows the job will start automatically once that printer is free.
  3302. # Same for a printer that is merely offline: Bambuddy switches that one on
  3303. # by itself, so the job is not actually waiting on anybody to change a
  3304. # spool (#2876 — offline printers reach this list now that a switched-off
  3305. # printer's own filament is read).
  3306. if not printers_busy and not printers_offline and not printers_refused:
  3307. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3308. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3309. # else: fall through — the self-resolving entries are appended below
  3310. else:
  3311. names_and_missing = [
  3312. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3313. ]
  3314. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3315. reasons.extend(printers_refused)
  3316. if printers_busy:
  3317. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3318. if printers_offline:
  3319. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3320. if printers_offline_no_plug:
  3321. # Named separately because it is the one entry on this list the
  3322. # user has to act on: no enabled Auto On plug means Bambuddy will
  3323. # never power this printer on for the queue (#2786).
  3324. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3325. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3326. @staticmethod
  3327. def _is_busy_only(waiting_reason: str) -> bool:
  3328. """Check if the waiting reason only contains 'Busy' entries.
  3329. When all matching printers are simply busy printing, the queued job
  3330. will start automatically once a printer finishes — no user action
  3331. is required, so we skip the notification.
  3332. """
  3333. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3334. return all(p.startswith("Busy:") for p in parts)
  3335. def _get_missing_force_color_slots(
  3336. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3337. ) -> list[str]:
  3338. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3339. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3340. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3341. with an exact type+color match.
  3342. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3343. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3344. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3345. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3346. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3347. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3348. setups are unaffected.
  3349. Returns:
  3350. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3351. """
  3352. if raw_data is None:
  3353. status = printer_manager.get_status(printer_id)
  3354. if not status:
  3355. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3356. raw_data = status.raw_data
  3357. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3358. loaded: list[tuple[str, str, str]] = []
  3359. for ams_unit in raw_data.get("ams", []):
  3360. for tray in ams_unit.get("tray", []):
  3361. tray_type = tray.get("tray_type")
  3362. if tray_type:
  3363. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3364. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3365. for vt in raw_data.get("vt_tray") or []:
  3366. vt_type = vt.get("tray_type")
  3367. if vt_type:
  3368. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3369. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3370. # One spool per slot, the way the matcher assigns them: two slots asking
  3371. # for the same filament need two spools of it (#3280). Slots naming a
  3372. # variant go first and take that variant before a spool naming none, so
  3373. # a slot open to any variant cannot use up the one a later slot needs.
  3374. missing = []
  3375. taken: set[int] = set()
  3376. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3377. o_type = canonical_filament_type(o.get("type") or "")
  3378. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3379. o_idx = o.get("tray_info_idx") or ""
  3380. fits = [
  3381. i
  3382. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3383. if i not in taken
  3384. and t_type == o_type
  3385. and t_color == o_color
  3386. and (not o_idx or not t_idx or o_idx == t_idx)
  3387. ]
  3388. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3389. if pick is not None:
  3390. taken.add(pick)
  3391. else:
  3392. color_label = o.get("color_name") or o.get("color", "?")
  3393. missing.append(f"{o_type} ({color_label})")
  3394. return missing
  3395. def _get_missing_filament_types(
  3396. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3397. ) -> list[str]:
  3398. """Get the list of required filament types that are not loaded on the printer.
  3399. Args:
  3400. printer_id: The printer ID
  3401. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3402. Returns:
  3403. List of missing filament types (empty if all are loaded)
  3404. """
  3405. if raw_data is None:
  3406. status = printer_manager.get_status(printer_id)
  3407. if not status:
  3408. return required_types # Can't determine, assume all missing
  3409. raw_data = status.raw_data
  3410. # Collect all filament types loaded on this printer (AMS units + external spool)
  3411. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3412. loaded_types: set[str] = set()
  3413. # Check AMS units (stored in raw_data["ams"])
  3414. ams_data = raw_data.get("ams", [])
  3415. if ams_data:
  3416. for ams_unit in ams_data:
  3417. for tray in ams_unit.get("tray", []):
  3418. tray_type = tray.get("tray_type")
  3419. if tray_type:
  3420. loaded_types.add(canonical_filament_type(tray_type))
  3421. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3422. for vt in raw_data.get("vt_tray") or []:
  3423. vt_type = vt.get("tray_type")
  3424. if vt_type:
  3425. loaded_types.add(canonical_filament_type(vt_type))
  3426. # Find which required types are missing (using canonical type for equivalence)
  3427. missing = []
  3428. for req_type in required_types:
  3429. if canonical_filament_type(req_type) not in loaded_types:
  3430. missing.append(req_type)
  3431. return missing
  3432. def _count_override_color_matches(
  3433. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3434. ) -> int:
  3435. """Count how many filament overrides have an exact color match on the printer.
  3436. Used to prefer printers that already have the desired override colors loaded.
  3437. """
  3438. if raw_data is None:
  3439. status = printer_manager.get_status(printer_id)
  3440. if not status:
  3441. return 0
  3442. raw_data = status.raw_data
  3443. # Collect loaded filaments' type+color pairs
  3444. loaded: set[tuple[str, str]] = set()
  3445. for ams_unit in raw_data.get("ams", []):
  3446. for tray in ams_unit.get("tray", []):
  3447. tray_type = tray.get("tray_type")
  3448. # `or ""`, not a dict default: a slot can carry the key with a
  3449. # null value, and this now runs against switched-off printers
  3450. # too, where nobody is watching for the AttributeError.
  3451. tray_color = tray.get("tray_color") or ""
  3452. if tray_type:
  3453. color_norm = tray_color.replace("#", "").lower()[:6]
  3454. loaded.add((canonical_filament_type(tray_type), color_norm))
  3455. for vt in raw_data.get("vt_tray") or []:
  3456. vt_type = vt.get("tray_type")
  3457. if vt_type:
  3458. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3459. loaded.add((canonical_filament_type(vt_type), color_norm))
  3460. # Types compared as the type check compares them: a PA12-CF override
  3461. # is met by PA-CF in its colour.
  3462. matches = 0
  3463. for o in overrides:
  3464. o_type = canonical_filament_type(o.get("type") or "")
  3465. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3466. if (o_type, o_color) in loaded:
  3467. matches += 1
  3468. return matches
  3469. @staticmethod
  3470. def _tray_reading(printer_id: int) -> dict:
  3471. """The best tray reading available for a printer that is not printing.
  3472. Live status first: a printer keeps its last status after the power
  3473. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3474. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3475. for when the client itself has been dropped and taken its status with
  3476. it — which is what every power-on attempt does.
  3477. An empty result means "we have never heard", not "nothing is loaded":
  3478. the two are indistinguishable from here, and only the second would be
  3479. safe to act on.
  3480. """
  3481. status = printer_manager.get_status(printer_id)
  3482. raw = (status.raw_data if status else None) or {}
  3483. for ams_unit in raw.get("ams") or []:
  3484. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3485. return raw
  3486. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3487. return raw
  3488. return printer_manager.last_known_trays(printer_id)
  3489. def _cached_filament_shortfall(
  3490. self,
  3491. printer_id: int,
  3492. required_types: list[str] | None,
  3493. filament_overrides: list[dict] | None,
  3494. ) -> list[str]:
  3495. """What a switched-off printer's last known filament cannot provide (#2876).
  3496. The smart-plug wake step used to consider only the model, so a job for a
  3497. colour loaded on the last printer in ID order switched on every earlier
  3498. one in turn, evaluated it, rejected it on colour and left it running.
  3499. Bambuddy knew those colours the whole time. This asks the same three
  3500. questions the matcher asks a live printer — required types, forced
  3501. colours, preferred colours — of the trays it last reported, and returns
  3502. the answers in the same shape the "Waiting for filament" reason uses.
  3503. Empty means the printer may still be able to take the job.
  3504. Fails open, and deliberately: with no tray reading (never connected
  3505. since Bambuddy started, or the cache dropped by a reconnect) this
  3506. returns nothing to report and the printer is treated as it was before.
  3507. A farm restarted while its printers were off must not conclude that
  3508. none of them can print.
  3509. """
  3510. if not required_types and not filament_overrides:
  3511. return []
  3512. raw_data = self._tray_reading(printer_id)
  3513. if not raw_data:
  3514. return []
  3515. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3516. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3517. if required_types:
  3518. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3519. if missing:
  3520. # Same enrichment the live path applies: a bare "PLA" is not
  3521. # much help when what is missing is a particular PLA.
  3522. force_color_map = {
  3523. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3524. }
  3525. return [
  3526. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3527. for t in missing
  3528. ]
  3529. if force_overrides:
  3530. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3531. if missing_colors:
  3532. return missing_colors
  3533. # Preference overrides read as a preference but the matcher treats zero
  3534. # matches as a skip, so a printer with none of the wanted colours is
  3535. # rejected there too. Waking it would only produce that same rejection.
  3536. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3537. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3538. return []
  3539. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3540. """Fold the winning candidate's file and settings onto the queue row (#671).
  3541. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3542. never escapes the selection loop. By the time the pass commits, the row
  3543. looks exactly like an ordinary single-file model-based item, so the upload,
  3544. archive creation, expected-print registration, print history and reprint
  3545. paths need no knowledge that variants exist.
  3546. No-ops for a non-variant candidate, which is already the item's own columns.
  3547. Safe to run and re-run: the item's file columns are only ever *read* when it
  3548. has no variants, so an item that gets resolved and then skipped (library-row
  3549. conflict, previous-print gate) is simply resolved again on the next pass.
  3550. """
  3551. variant = candidate.variant
  3552. if variant is None:
  3553. return
  3554. item.library_file_id = variant.library_file_id
  3555. item.library_file = variant.library_file
  3556. # The dispatcher checks archive_id first and would print that instead of
  3557. # the file we just picked. Creation refuses to combine the two, so this
  3558. # only ever fires on a hand-written row — clear it rather than silently
  3559. # dispatch something the matcher never considered.
  3560. item.archive_id = None
  3561. item.archive = None
  3562. item.target_model = variant.target_model
  3563. item.plate_id = variant.plate_id
  3564. item.ams_mapping = variant.ams_mapping
  3565. item.nozzle_mapping = variant.nozzle_mapping
  3566. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3567. item.filament_overrides = variant.filament_overrides
  3568. item.required_filament_types = variant.required_filament_types
  3569. if variant.print_time_seconds is not None:
  3570. # The row carried the shortest candidate's estimate so SJF could order
  3571. # it before a printer was known; now that one is chosen, record what is
  3572. # actually going to run so history and the ETA agree with reality.
  3573. item.print_time_seconds = variant.print_time_seconds
  3574. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3575. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3576. Recomputes from live printer status when the stored mapping is missing OR
  3577. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3578. frontend status-load race can serialize [-1] before the printer's AMS
  3579. trays are known (#2589) — and must not be trusted: downstream it would be
  3580. silently downgraded to external-spool mode and print against an empty
  3581. feed. A resolved mapping is re-checked against the target printer's
  3582. live trays before it is trusted (#2799) and recomputed when it does not
  3583. fit. When it does fit, its resolved slots are kept as they are and only
  3584. the slots the plate prints that are still unresolved are matched again;
  3585. all of it is left alone when the user has acknowledged it with "Print
  3586. Anyway".
  3587. When recompute cannot resolve it either (no compatible tray loaded), the
  3588. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3589. external selection. On a printer that reported loaded trays,
  3590. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3591. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3592. and the firmware surfaces a clear AMS-mapping error instead of silently
  3593. printing to the empty external feed.
  3594. Returns an actionable message when that firmware error is the only
  3595. possible outcome — the matcher ran, matched nothing, and the printer has
  3596. no AMS to load a different spool into (#2771). The caller fails the item
  3597. on it instead of spending an upload on a print that cannot start.
  3598. Returns None everywhere else, including every case where we simply lack
  3599. the data to judge, so dispatch is only ever blocked on a positive
  3600. finding.
  3601. """
  3602. stored_mapping: list | None = None
  3603. if item.ams_mapping:
  3604. try:
  3605. stored_mapping = json.loads(item.ams_mapping)
  3606. except (json.JSONDecodeError, TypeError):
  3607. stored_mapping = None
  3608. # Present and resolved. Global tray IDs only mean something relative to
  3609. # the printer they were resolved against, so "resolved" is not the same
  3610. # as "resolved *here*" — check the mapping still fits the printer that
  3611. # is about to run this item before trusting it (#2799). "Print anyway"
  3612. # is the user overriding exactly this judgement, so it short-circuits.
  3613. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3614. if item.skip_filament_check:
  3615. return None
  3616. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3617. if conflict is None:
  3618. # It fits, but a slot the plate prints may still be empty: the
  3619. # spool was missing when it was mapped, and has perhaps been
  3620. # loaded since. Nothing else would ever look at that slot again,
  3621. # so a job held for it would be held again on every Start.
  3622. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3623. if filled is not None:
  3624. item.ams_mapping = json.dumps(filled)
  3625. logger.info(
  3626. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3627. item.id,
  3628. stored_mapping,
  3629. printer_id,
  3630. filled,
  3631. )
  3632. await db.commit()
  3633. return None
  3634. logger.warning(
  3635. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3636. item.id,
  3637. stored_mapping,
  3638. printer_id,
  3639. conflict,
  3640. )
  3641. # Drop it before recomputing so a failed recompute cannot fall back
  3642. # to the mapping we just rejected.
  3643. item.ams_mapping = None
  3644. stored_mapping = None
  3645. await db.commit()
  3646. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3647. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3648. item.ams_mapping = json.dumps(computed_mapping)
  3649. logger.info(
  3650. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3651. item.id,
  3652. printer_id,
  3653. computed_mapping,
  3654. )
  3655. await db.commit()
  3656. return None
  3657. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3658. if external_only is not None:
  3659. item.ams_mapping = json.dumps(external_only)
  3660. logger.info(
  3661. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3662. "mapping every filament to it: %s",
  3663. item.id,
  3664. printer_id,
  3665. external_only,
  3666. )
  3667. await db.commit()
  3668. return None
  3669. if _mapping_is_all_unresolved(stored_mapping):
  3670. logger.warning(
  3671. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3672. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3673. item.id,
  3674. stored_mapping,
  3675. printer_id,
  3676. )
  3677. item.ams_mapping = None
  3678. await db.commit()
  3679. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3680. async def _external_spool_only_mapping(
  3681. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3682. ) -> list[int] | None:
  3683. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3684. A printer without an AMS prints from its external spool, and an external
  3685. spool whose filament was never set reports no type, so the matcher has
  3686. nothing to match. Sent without a mapping, the print goes out with the AMS
  3687. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3688. to carry such a job through; a job placed by model or location no longer
  3689. keeps one, and one queued that way never had one.
  3690. Only on a positive report: the printer has said it has no AMS, it has a
  3691. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3692. is not ours to pick), and no feed has a filament set — with one set, the
  3693. matcher has already given its answer. Not for a job that asked for its
  3694. colours to be matched strictly: a spool without a filament set has no
  3695. colour to check. Returns None otherwise.
  3696. """
  3697. if item.filament_overrides:
  3698. try:
  3699. overrides = json.loads(item.filament_overrides)
  3700. except (json.JSONDecodeError, TypeError):
  3701. return None
  3702. if not isinstance(overrides, list) or any(
  3703. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3704. ):
  3705. return None
  3706. status = printer_manager.get_status(printer_id)
  3707. if status is None or not isinstance(status.raw_data, dict):
  3708. return None
  3709. ams_units = status.raw_data.get("ams")
  3710. if not isinstance(ams_units, list) or ams_units:
  3711. return None
  3712. vt_trays = status.raw_data.get("vt_tray")
  3713. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3714. return None
  3715. if self._build_loaded_filaments(status):
  3716. return None
  3717. printer = await self._get_printer(db, printer_id)
  3718. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3719. return None
  3720. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3721. if external < _EXTERNAL_TRAY_ID_MIN:
  3722. return None
  3723. required = await self._get_filament_requirements(db, item)
  3724. slot_ids = [r.get("slot_id") for r in required or []]
  3725. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3726. if not slot_ids:
  3727. return None
  3728. mapping = [-1] * max(slot_ids)
  3729. for slot_id in slot_ids:
  3730. mapping[slot_id - 1] = external
  3731. return mapping
  3732. async def _fill_unresolved_slots(
  3733. self,
  3734. db: AsyncSession,
  3735. printer_id: int,
  3736. item: PrintQueueItem,
  3737. stored_mapping: list | None,
  3738. ) -> list | None:
  3739. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3740. Every resolved entry is kept, so a tray the user picked by hand stays
  3741. picked. Only the plate's unresolved slots are matched, and only against
  3742. trays the mapping does not already use: the matcher never gives two
  3743. slots one tray, and filling a gap with a tray the user assigned to
  3744. another slot would print that slot's filament twice.
  3745. Returns None when there is nothing to fill or nothing could be filled.
  3746. """
  3747. if not isinstance(stored_mapping, list) or not stored_mapping:
  3748. return None
  3749. required = await self._get_filament_requirements(db, item)
  3750. if not required:
  3751. return None
  3752. self._apply_filament_overrides(item, required)
  3753. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3754. if not gaps:
  3755. return None
  3756. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3757. computed = await self._compute_ams_mapping_for_printer(
  3758. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3759. )
  3760. if not computed:
  3761. return None
  3762. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3763. filled = False
  3764. for slot_id in gaps:
  3765. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3766. if _is_tray_id(tray) and tray >= 0:
  3767. merged[slot_id - 1] = tray
  3768. filled = True
  3769. return merged if filled else None
  3770. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3771. """What a staged item would be held for if it were started now (#2799).
  3772. The Start button asks this before releasing an item, so that a job whose
  3773. filament is still not loaded offers "Print Anyway" instead of being
  3774. released, held again by the scheduler and leaving no way past the hold.
  3775. It reaches the same answer the dispatch path would: a stored mapping
  3776. that fits is kept and only its gaps are matched again, and one that
  3777. does not fit (or is missing) is replaced by a fresh match.
  3778. Returns the missing filaments, described the way the queue row
  3779. describes them, or None when nothing is missing or there is not enough
  3780. evidence to say: no printer yet (a model-based item picks one at
  3781. dispatch), no status, no trays reported, or no readable 3MF.
  3782. """
  3783. if item.skip_filament_check or not item.printer_id:
  3784. return None
  3785. status = printer_manager.get_status(item.printer_id)
  3786. if status is None or not self._build_loaded_filaments(status):
  3787. return None
  3788. # Called from a request, not from a pass: drop whatever the last pass
  3789. # memoised so this reads the file as it is now. A pass running at the
  3790. # same time only loses its cache.
  3791. self._filament_req_memo.clear()
  3792. mapping: list | None = None
  3793. if item.ams_mapping:
  3794. try:
  3795. mapping = json.loads(item.ams_mapping)
  3796. except (json.JSONDecodeError, TypeError):
  3797. mapping = None
  3798. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3799. mapping = None
  3800. if mapping is not None:
  3801. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3802. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3803. else:
  3804. mapping = None
  3805. if mapping is None:
  3806. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3807. required = await self._get_filament_requirements(db, item)
  3808. if required:
  3809. self._apply_filament_overrides(item, required)
  3810. else:
  3811. # The same fallback the hold uses, or Start would release a job the
  3812. # next pass holds again (#3280).
  3813. required = _forced_override_requirements(item)
  3814. if not required:
  3815. return None
  3816. missing = _unresolved_required(required, mapping)
  3817. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3818. async def _stored_mapping_conflict(
  3819. self,
  3820. db: AsyncSession,
  3821. printer_id: int,
  3822. item: PrintQueueItem,
  3823. stored_mapping: list | None,
  3824. ) -> str | None:
  3825. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3826. A mapping is a list of global tray IDs, and those are only meaningful
  3827. relative to the printer they were resolved against — the same rule
  3828. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3829. arrives at a printer it was not resolved for:
  3830. * the print dialog stamps one mapping onto every selected printer, so a
  3831. mapping computed against the first printer is dispatched verbatim to
  3832. the rest, whose AMS slot order differs;
  3833. * a spool is moved between queueing and dispatch.
  3834. Both end the same way: the slot index still resolves, so nothing looks
  3835. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3836. the firmware's own type check, so a PETG slot happily prints in ASA.
  3837. Returns a short reason when the mapping names a tray this printer does
  3838. not have loaded, points a slot at a tray holding a different filament
  3839. type, or points it at an external spool this printer reports empty while
  3840. its AMS holds that slot's filament (#3239). Returns None when the
  3841. mapping fits, and — deliberately — whenever we lack the evidence to
  3842. judge, so a recompute only ever follows a positive finding.
  3843. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3844. matcher had nothing, not that the mapping belongs to another printer,
  3845. and destroying a partially hand-resolved mapping over it would lose the
  3846. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3847. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3848. item when that finds nothing.
  3849. """
  3850. if not isinstance(stored_mapping, list) or not stored_mapping:
  3851. return None
  3852. status = printer_manager.get_status(printer_id)
  3853. if status is None:
  3854. return None
  3855. loaded = self._build_loaded_filaments(status)
  3856. if not loaded:
  3857. # Nothing reported yet (reconnect, first push pending). Saying
  3858. # "tray not loaded" here would recompute against an AMS we cannot
  3859. # see, which is how #2589 produced a bogus all-[-1] in the first
  3860. # place.
  3861. return None
  3862. by_tray = {f["global_tray_id"]: f for f in loaded}
  3863. layout = TrayLayout.from_state(status)
  3864. # Cheap pass first, on live status alone: every tray the mapping names
  3865. # has to exist here. This catches a foreign mapping without opening the
  3866. # 3MF, which is worth doing because the parse below is neither cached
  3867. # nor free.
  3868. for index, tray in enumerate(stored_mapping):
  3869. if not _is_tray_id(tray) or tray < 0:
  3870. continue
  3871. if tray in by_tray:
  3872. continue
  3873. if tray >= 254 or layout.is_external(tray):
  3874. # An external feed we have not heard about is absence of
  3875. # evidence about *that slot* — the rest of the mapping is still
  3876. # worth judging, so skip it rather than abandoning the pass.
  3877. continue
  3878. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3879. # Only now is the 3MF worth opening: the type check needs to know what
  3880. # each slot actually asked for. The external spool is checked the same
  3881. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3882. # two printers with different filament in the external feed is the same
  3883. # failure this method exists to catch.
  3884. required = await self._get_filament_requirements(db, item)
  3885. if not required:
  3886. return None
  3887. self._apply_filament_overrides(item, required)
  3888. # External feeds the printer reports and reports as empty. That is
  3889. # evidence, unlike an external feed it says nothing about (#3239).
  3890. empty_external: set[int] = set()
  3891. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3892. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3893. if isinstance(vt, dict) and not vt.get("tray_type"):
  3894. try:
  3895. empty_external.add(int(vt.get("id", 254)))
  3896. except (TypeError, ValueError):
  3897. continue
  3898. for req in required:
  3899. slot_id = req.get("slot_id") or 0
  3900. if slot_id <= 0:
  3901. continue
  3902. if slot_id > len(stored_mapping):
  3903. return f"slot {slot_id} is not covered by the mapping"
  3904. tray = stored_mapping[slot_id - 1]
  3905. if not _is_tray_id(tray) or tray < 0:
  3906. continue
  3907. loaded_tray = by_tray.get(tray)
  3908. if loaded_tray is None:
  3909. # A mapping made for a printer that feeds this slot from its
  3910. # external spool, sent to one whose external spool is empty and
  3911. # whose AMS holds the filament (#3239). Only then: an external
  3912. # spool can be loaded without its filament set, and on a printer
  3913. # with nothing else to offer that job printed before. The colour
  3914. # has to match too: with only another colour in the AMS, the
  3915. # printer asking for the spool beats printing in that colour.
  3916. want = canonical_filament_type(req.get("type"))
  3917. if (tray >= 254 or layout.is_external(tray)) and tray in empty_external and want:
  3918. ams_tray = next(
  3919. (
  3920. f
  3921. for f in loaded
  3922. if not f.get("is_external")
  3923. and canonical_filament_type(f.get("type")) == want
  3924. and self._colors_are_similar(f.get("color"), req.get("color"))
  3925. ),
  3926. None,
  3927. )
  3928. if ams_tray is not None:
  3929. return (
  3930. f"slot {slot_id} points at the external spool, which is empty, "
  3931. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3932. )
  3933. continue
  3934. want = canonical_filament_type(req.get("type"))
  3935. have = canonical_filament_type(loaded_tray.get("type"))
  3936. if want and have and want != have:
  3937. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3938. # A forced slot fits only a tray the matcher would give it (#3280).
  3939. if req.get("force_color_match"):
  3940. want_idx = req.get("tray_info_idx") or ""
  3941. have_idx = loaded_tray.get("tray_info_idx") or ""
  3942. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3943. loaded_tray.get("color")
  3944. ) or (want_idx and have_idx and want_idx != have_idx):
  3945. return (
  3946. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3947. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3948. )
  3949. return None
  3950. async def _unmappable_without_ams_message(
  3951. self,
  3952. db: AsyncSession,
  3953. printer_id: int,
  3954. item: PrintQueueItem,
  3955. computed_mapping: list[int] | None,
  3956. ) -> str | None:
  3957. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3958. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3959. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3960. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3961. uploaded several megabytes and burned its dispatch retries. This method
  3962. speaks only for the AMS-less case: there is nothing to resume into — the
  3963. external spool holder is the whole inventory — so the useful answer is to
  3964. say which filament is missing and stop. With an AMS attached it returns
  3965. None: where live status reported loaded trays,
  3966. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3967. reported none the print goes out and the firmware error is the answer —
  3968. the user can load the right spool and press Resume.
  3969. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3970. every branch that lacks the evidence to be sure returns None.
  3971. """
  3972. # None means the matcher never ran (no requirements parsed from the 3MF,
  3973. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3974. # dispatch as they always have.
  3975. if not _mapping_is_all_unresolved(computed_mapping):
  3976. return None
  3977. status = printer_manager.get_status(printer_id)
  3978. if status is None:
  3979. return None
  3980. # "No AMS" has to be a fact the printer stated, not the absence of a
  3981. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3982. # handled and is preserved across partial pushes thereafter, so a missing
  3983. # key means we have not heard yet — most likely a reconnect, where the
  3984. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3985. # empty list is the positive report of a printer with no AMS.
  3986. ams_units = status.raw_data.get("ams")
  3987. if not isinstance(ams_units, list) or ams_units:
  3988. return None
  3989. required = await self._get_filament_requirements(db, item)
  3990. loaded = self._build_loaded_filaments(status)
  3991. if not required or not loaded:
  3992. # Both were non-empty moments ago or the matcher could not have run.
  3993. # If the picture changed under us, say nothing rather than fail an
  3994. # item on stale evidence.
  3995. return None
  3996. self._apply_filament_overrides(item, required)
  3997. if any(r.get("force_color_match") for r in required):
  3998. # A forced colour is a spool the user can load on the external
  3999. # holder, so the unmatched hold stages the job instead (#3280).
  4000. return None
  4001. return _unmatched_filament_message(required, loaded)
  4002. async def _fail_unmappable_item(
  4003. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  4004. ) -> None:
  4005. """Fail a queue item whose filament mapping cannot resolve (#2771).
  4006. This replaces a failure, not a success: without it the item is uploaded,
  4007. rejected by the firmware with 0700_8012, retried twice more and failed
  4008. anyway with "never started the print after N dispatch attempts". So this
  4009. applies on the model-based path too. There it is rarely reached: choosing
  4010. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  4011. over one it cannot map, so an "Any <model>" job tries its siblings and
  4012. otherwise waits; this remains for a match that failed at selection time.
  4013. """
  4014. item.status = "failed"
  4015. item.error_message = message
  4016. item.completed_at = datetime.now(timezone.utc)
  4017. item.waiting_reason = None
  4018. await db.commit()
  4019. from backend.app.services.print_batch import refresh_batches_after
  4020. await refresh_batches_after([item.id])
  4021. logger.warning(
  4022. "Queue item %s: no usable AMS mapping on printer %s — %s",
  4023. item.id,
  4024. printer_id,
  4025. message,
  4026. )
  4027. job_name = await self._get_job_name(db, item)
  4028. printer = await self._get_printer(db, printer_id)
  4029. await notification_service.on_queue_job_failed(
  4030. job_name=job_name,
  4031. printer_id=printer_id,
  4032. printer_name=printer.name if printer else "Unknown",
  4033. reason=message,
  4034. db=db,
  4035. )
  4036. try:
  4037. await ws_manager.send_queue_item_failed(
  4038. user_id=item.created_by_id,
  4039. queue_item_id=item.id,
  4040. printer_id=printer_id,
  4041. reason="filament_unmappable",
  4042. )
  4043. except Exception:
  4044. pass
  4045. async def _compute_ams_mapping_for_printer(
  4046. self,
  4047. db: AsyncSession,
  4048. printer_id: int,
  4049. item: PrintQueueItem,
  4050. *,
  4051. only_slots: set[int] | None = None,
  4052. reserved_trays: set[int] | None = None,
  4053. ) -> list[int] | None:
  4054. """Compute AMS mapping for a printer based on filament requirements.
  4055. Called when a queue item has no ams_mapping set — either for model-based
  4056. items after printer assignment, or printer-specific items (e.g. from VP).
  4057. Args:
  4058. db: Database session
  4059. printer_id: The assigned printer ID
  4060. item: The queue item (contains archive_id or library_file_id)
  4061. only_slots: Match only these filament slots; every other slot comes
  4062. back unresolved (-1). Used to fill the gaps of a stored mapping.
  4063. reserved_trays: Global tray IDs to leave out of the match, because
  4064. the stored mapping already gives them to another slot.
  4065. Returns:
  4066. AMS mapping array or None if no mapping needed/possible
  4067. """
  4068. # Get printer status
  4069. status = printer_manager.get_status(printer_id)
  4070. if not status:
  4071. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  4072. return None
  4073. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  4074. # either extruder, so the per-nozzle hard filter below must NOT apply.
  4075. # Otherwise a print on one nozzle can't use a spool physically loaded in
  4076. # an AMS on the *other* nozzle, and the matcher falls through to a
  4077. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  4078. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  4079. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  4080. # Get filament requirements from source file
  4081. filament_reqs = await self._get_filament_requirements(db, item)
  4082. if not filament_reqs:
  4083. # When the 3MF can't be read but force-color overrides are present, build a
  4084. # direct mapping from the overrides so the printer uses the correct AMS slot.
  4085. if item.filament_overrides:
  4086. try:
  4087. overrides = json.loads(item.filament_overrides)
  4088. force_overrides = [o for o in overrides if o.get("force_color_match")]
  4089. if force_overrides:
  4090. logger.info(
  4091. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  4092. "force-color override(s)",
  4093. item.id,
  4094. len(force_overrides),
  4095. )
  4096. return self._build_override_direct_mapping(force_overrides, status)
  4097. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4098. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  4099. logger.debug("No filament requirements found for queue item %s", item.id)
  4100. return None
  4101. self._apply_filament_overrides(item, filament_reqs)
  4102. if only_slots is not None:
  4103. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  4104. if not filament_reqs:
  4105. return None
  4106. # Build loaded filaments from printer status
  4107. loaded_filaments = self._build_loaded_filaments(status)
  4108. if reserved_trays:
  4109. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  4110. if not loaded_filaments:
  4111. logger.debug("No filaments loaded on printer %s", printer_id)
  4112. return None
  4113. # Check if user prefers lowest remaining filament when multiple spools match
  4114. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  4115. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  4116. # Without backup, the printer will not switch to a second spool when the
  4117. # picked one runs out — so sorting toward the lowest leaves the print
  4118. # at risk of running dry mid-job. None (unknown: no status report with
  4119. # cfg or home_flag yet) preserves today's behaviour intentionally.
  4120. if prefer_lowest and status.ams_filament_backup is False:
  4121. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  4122. prefer_lowest = False
  4123. # When the preference is on, surface Bambuddy's inventory-side
  4124. # remaining for each slot that's bound to a tracked spool, so the
  4125. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  4126. # entirely when the preference is off — no behaviour change for
  4127. # users who haven't opted in.
  4128. inventory_remain_overrides: dict[int, float] | None = None
  4129. if prefer_lowest:
  4130. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  4131. # Compute mapping: match required filaments to available slots
  4132. return self._match_filaments_to_slots(
  4133. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  4134. )
  4135. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  4136. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  4137. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  4138. diagnosis (#2771) describes the filament the matcher actually looked
  4139. for, not the one the 3MF was sliced with — naming the pre-override
  4140. filament in a user-facing error would send the user to load the wrong
  4141. spool.
  4142. """
  4143. if not item.filament_overrides:
  4144. return
  4145. try:
  4146. overrides = json.loads(item.filament_overrides)
  4147. override_map = {o["slot_id"]: o for o in overrides}
  4148. for req in filament_reqs:
  4149. if req["slot_id"] in override_map:
  4150. override = override_map[req["slot_id"]]
  4151. req["type"] = override["type"]
  4152. req["color"] = override["color"]
  4153. # A manual/preference override SWAPS the slot's filament, so the
  4154. # 3MF's original tray_info_idx now points at the old spool and must
  4155. # be cleared — matching then falls back to type+colour. A
  4156. # force_color_match override is not a swap: it carries the 3MF's
  4157. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4158. # it here too, letting the matcher pin the correct variant slot on a
  4159. # printer holding two same-colour spools of different variants (#2650).
  4160. # A spool that names no variant still counts; one naming another
  4161. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4162. req["tray_info_idx"] = (
  4163. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4164. )
  4165. # The matcher satisfies a forced slot only the way
  4166. # `_get_missing_force_color_slots` does, never by a similar
  4167. # colour or the type alone (#3280).
  4168. req["force_color_match"] = bool(override.get("force_color_match"))
  4169. logger.debug(
  4170. "Queue item %s: Override slot %d -> %s %s",
  4171. item.id,
  4172. req["slot_id"],
  4173. override["type"],
  4174. override["color"],
  4175. )
  4176. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4177. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4178. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4179. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4180. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4181. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4182. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4183. treated as the filament requirement for that slot and matched against the
  4184. current AMS state of the printer.
  4185. Returns the same format as ``_match_filaments_to_slots``, or None when
  4186. the AMS has no loaded filaments.
  4187. """
  4188. loaded = self._build_loaded_filaments(status)
  4189. if not loaded:
  4190. return None
  4191. reqs = [
  4192. {
  4193. "slot_id": o["slot_id"],
  4194. "type": o.get("type", ""),
  4195. "color": o.get("color", ""),
  4196. # These are all force_color_match overrides, so the idx (when the
  4197. # 3MF carried one) is the intended variant, not a stale swap —
  4198. # keep it so the matcher pins the right variant slot (#2650); a
  4199. # spool naming another variant does not satisfy it (#3280).
  4200. "tray_info_idx": o.get("tray_info_idx", ""),
  4201. "force_color_match": True,
  4202. }
  4203. for o in force_overrides
  4204. ]
  4205. return self._match_filaments_to_slots(reqs, loaded)
  4206. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4207. """Resolve the queue item's source 3MF and parse the per-slot
  4208. filament requirements out of it. Thin DB-resolver wrapper around
  4209. ``filament_requirements.extract_filament_requirements`` so the VP
  4210. queue-mode write path (#1188) can reuse the same parser at upload
  4211. time.
  4212. """
  4213. from backend.app.services.filament_requirements import extract_filament_requirements
  4214. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4215. # so every caller gets its own copy — a shared list would leak one
  4216. # item's overrides into the next item that happens to print the same
  4217. # plate.
  4218. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4219. if memo_key in self._filament_req_memo:
  4220. cached = self._filament_req_memo[memo_key]
  4221. return [dict(r) for r in cached] if cached else None
  4222. file_path: Path | None = None
  4223. if item.archive_id:
  4224. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4225. archive = result.scalar_one_or_none()
  4226. if archive:
  4227. file_path = settings.base_dir / archive.file_path
  4228. elif item.library_file_id:
  4229. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4230. library_file = result.scalar_one_or_none()
  4231. if library_file:
  4232. lib_path = Path(library_file.file_path)
  4233. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4234. if not file_path or not file_path.exists():
  4235. self._filament_req_memo[memo_key] = None
  4236. return None
  4237. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4238. self._filament_req_memo[memo_key] = filaments or None
  4239. return [dict(r) for r in filaments] if filaments else None
  4240. def _build_loaded_filaments(self, status) -> list[dict]:
  4241. """Build list of loaded filaments from printer status.
  4242. Args:
  4243. status: PrinterState from printer_manager
  4244. Returns:
  4245. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4246. """
  4247. filaments = []
  4248. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4249. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4250. # Routes external spools to an extruder (#2771). Mirrors
  4251. # `buildLoadedFilaments` in the frontend.
  4252. vt_trays = status.raw_data.get("vt_tray") or []
  4253. is_dual_nozzle = reports_two_nozzles(status)
  4254. # Parse AMS units from raw_data
  4255. ams_data = status.raw_data.get("ams", [])
  4256. layout = TrayLayout.from_state(status)
  4257. for ams_unit in ams_data:
  4258. ams_id = int(ams_unit.get("id", 0))
  4259. trays = ams_unit.get("tray", [])
  4260. is_ht = is_ams_ht_id(ams_id) # AMS-HT unit ids; a regular AMS may list fewer trays
  4261. for tray in trays:
  4262. tray_type = tray.get("tray_type")
  4263. if tray_type:
  4264. tray_id = int(tray.get("id", 0))
  4265. tray_color = tray.get("tray_color", "")
  4266. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4267. tray_info_idx = tray.get("tray_info_idx", "")
  4268. # Normalize color: remove alpha, add hash
  4269. color = self._normalize_color(tray_color)
  4270. # Calculate global tray ID
  4271. # AMS-HT units have IDs starting at 128 with a single tray
  4272. global_tray_id = layout.global_tray_id(ams_id, tray_id)
  4273. filaments.append(
  4274. {
  4275. "type": tray_type,
  4276. "color": color,
  4277. # `color` reads a missing colour as #808080; this
  4278. # says whether the printer reported one at all.
  4279. "color_known": bool(tray_color),
  4280. "tray_info_idx": tray_info_idx,
  4281. "ams_id": ams_id,
  4282. "tray_id": tray_id,
  4283. "is_ht": is_ht,
  4284. "is_external": False,
  4285. "global_tray_id": global_tray_id,
  4286. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4287. "remain": tray.get("remain", -1),
  4288. }
  4289. )
  4290. # Check external spool(s) (vt_tray is a list)
  4291. for idx, vt in enumerate(vt_trays):
  4292. if vt.get("tray_type"):
  4293. color = self._normalize_color(vt.get("tray_color", ""))
  4294. tray_id = int(vt.get("id", 254))
  4295. filaments.append(
  4296. {
  4297. "type": vt["tray_type"],
  4298. "color": color,
  4299. "color_known": bool(vt.get("tray_color")),
  4300. "tray_info_idx": vt.get("tray_info_idx", ""),
  4301. "ams_id": -1,
  4302. "tray_id": idx,
  4303. "is_ht": False,
  4304. "is_external": True,
  4305. "global_tray_id": tray_id,
  4306. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4307. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4308. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4309. "remain": vt.get("remain", -1),
  4310. }
  4311. )
  4312. return filaments
  4313. def _normalize_color(self, color: str | None) -> str:
  4314. """Normalize color to #RRGGBB format."""
  4315. if not color:
  4316. return "#808080"
  4317. hex_color = color.replace("#", "")[:6]
  4318. return f"#{hex_color}"
  4319. def _normalize_color_for_compare(self, color: str | None) -> str:
  4320. """Normalize color for comparison (lowercase, no hash)."""
  4321. if not color:
  4322. return ""
  4323. return color.replace("#", "").lower()[:6]
  4324. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4325. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4326. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4327. stays the per-channel box that shipped — this only decides which of
  4328. several eligible spools is closest, so nothing becomes usable or
  4329. unusable because of it.
  4330. It ranks by how far apart the colours *look*, not how far apart their
  4331. numbers are. RGB distance overweights blue badly enough to invert the
  4332. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4333. the nearer of two eligible spools by RGB and the further by a factor of
  4334. four once measured perceptually.
  4335. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4336. transparent filament is not a colour the user chose, and counting it
  4337. would stop a transparent filament matching itself.
  4338. """
  4339. return perceptual_color_distance(color1, color2)
  4340. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4341. """Check if two colors are visually similar within a threshold."""
  4342. hex1 = self._normalize_color_for_compare(color1)
  4343. hex2 = self._normalize_color_for_compare(color2)
  4344. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4345. return False
  4346. try:
  4347. r1 = int(hex1[0:2], 16)
  4348. g1 = int(hex1[2:4], 16)
  4349. b1 = int(hex1[4:6], 16)
  4350. r2 = int(hex2[0:2], 16)
  4351. g2 = int(hex2[2:4], 16)
  4352. b2 = int(hex2[4:6], 16)
  4353. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4354. except ValueError:
  4355. return False
  4356. async def _build_inventory_remain_overrides(
  4357. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4358. ) -> dict[int, float]:
  4359. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4360. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4361. The MQTT ``remain`` field on a tray is the printer firmware's
  4362. RFID-decremented value, which has two limitations the "Prefer Lowest
  4363. Remaining Filament" feature has been ignoring (#1508):
  4364. - it's only meaningful for Bambu RFID spools; everything else reports
  4365. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4366. compare equal and the sort collapses to AMS-slot order — the user
  4367. who's curating inventory weights gets the lower-slot pick instead
  4368. of the lower-remaining pick;
  4369. - even when set, it's the *printer's* counter, not Bambuddy's
  4370. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4371. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4372. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4373. When the user has bound a spool to a slot, their own inventory
  4374. tracking is authoritative; this helper surfaces that value so the
  4375. sort can prefer it. Slots without a binding are absent from the
  4376. returned map — the caller then falls back to MQTT ``remain`` for
  4377. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4378. Returns an empty map on any failure (no inventory bindings, DB
  4379. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4380. is a preference, not a guarantee.
  4381. """
  4382. if not loaded:
  4383. return {}
  4384. # External / virtual-tray slots are tracked separately from AMS — skip
  4385. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4386. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4387. # match is fiddly and out of scope for this fix).
  4388. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4389. if not tracked_slots:
  4390. return {}
  4391. is_spoolman = await self._is_spoolman_mode(db)
  4392. overrides: dict[int, float] = {}
  4393. if is_spoolman:
  4394. result = await db.execute(
  4395. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4396. )
  4397. assignments = list(result.scalars().all())
  4398. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4399. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4400. for ams_id, tray_id, gtid in tracked_slots:
  4401. spoolman_id = by_slot.get((ams_id, tray_id))
  4402. if spoolman_id is None:
  4403. continue
  4404. grams = await _spoolman_remaining_grams(spoolman_id)
  4405. if grams is not None:
  4406. overrides[gtid] = grams
  4407. return overrides
  4408. # Internal inventory mode (default). selectinload matches the pattern
  4409. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4410. # plus an eager-loaded relationship rather than an explicit join, so
  4411. # the row-attribute shape is exactly what those routes already rely on.
  4412. result = await db.execute(
  4413. select(SpoolAssignment)
  4414. .options(selectinload(SpoolAssignment.spool))
  4415. .where(SpoolAssignment.printer_id == printer_id)
  4416. )
  4417. assignments = list(result.scalars().all())
  4418. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4419. for ams_id, tray_id, gtid in tracked_slots:
  4420. spool = by_slot.get((ams_id, tray_id))
  4421. if spool is None:
  4422. continue
  4423. label = float(spool.label_weight or 0)
  4424. used = float(spool.weight_used or 0)
  4425. overrides[gtid] = max(0.0, label - used)
  4426. return overrides
  4427. @staticmethod
  4428. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4429. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4430. here to avoid making this module import-dependent on that private
  4431. helper's signature."""
  4432. try:
  4433. from backend.app.api.routes.settings import get_setting
  4434. v = await get_setting(db, "spoolman_enabled")
  4435. return bool(v) and v.lower() == "true"
  4436. except Exception:
  4437. return False
  4438. @staticmethod
  4439. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4440. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4441. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4442. so a tied sort produces the same physical-position order the pre-#1508
  4443. stable sort did (preserves the regression-free baseline):
  4444. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4445. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4446. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4447. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4448. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4449. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4450. """
  4451. if ams_id is None or ams_id < 0:
  4452. return 10_000
  4453. if ams_id >= 128:
  4454. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4455. return ams_id * 4 + (tray_id or 0)
  4456. @staticmethod
  4457. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4458. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4459. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4460. non-tracked spools (the user has told us they care about these
  4461. specifically), then ascending by remaining within each tier, then
  4462. ascending by AMS slot position as the deterministic tie-breaker.
  4463. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4464. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4465. because the tier flag dominates — which is what lets us mix grams
  4466. (inventory) and percent (MQTT) without a unit conversion.
  4467. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4468. spools the printer DOES know something about sort ahead of those
  4469. it knows nothing about — preserves pre-#1508 behaviour for the
  4470. no-inventory-binding case.
  4471. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4472. external on ties, matching the legacy emission-order stable sort.
  4473. """
  4474. gtid = f.get("global_tray_id")
  4475. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4476. if overrides and gtid in overrides:
  4477. return (0, overrides[gtid], slot_order)
  4478. remain = f.get("remain", -1)
  4479. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4480. def _match_filaments_to_slots(
  4481. self,
  4482. required: list[dict],
  4483. loaded: list[dict],
  4484. prefer_lowest: bool = False,
  4485. inventory_remain_overrides: dict[int, float] | None = None,
  4486. fts_installed: bool = False,
  4487. ) -> list[int] | None:
  4488. """Match required filaments to loaded filaments and build AMS mapping.
  4489. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4490. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4491. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4492. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4493. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4494. matching among those trays.
  4495. Args:
  4496. required: List of required filaments with slot_id, type, color, tray_info_idx
  4497. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4498. Returns:
  4499. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4500. """
  4501. if not required:
  4502. return None
  4503. # Track used trays to avoid duplicate assignment
  4504. used_tray_ids: set[int] = set()
  4505. comparisons = []
  4506. # Forced slots first: a slot that would take any tray of its type must
  4507. # not take the one tray a forced slot can use (#3280). The mapping is
  4508. # built by slot_id below, so the order only decides who goes first.
  4509. # Among forced slots, those naming a variant first, as
  4510. # `_get_missing_force_color_slots` counts them.
  4511. for req in sorted(
  4512. required,
  4513. key=lambda r: (
  4514. not r.get("force_color_match"),
  4515. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4516. ),
  4517. ):
  4518. req_type = (req.get("type") or "").upper()
  4519. req_color = req.get("color", "")
  4520. req_tray_info_idx = req.get("tray_info_idx", "")
  4521. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4522. idx_match = None
  4523. exact_match = None
  4524. similar_match = None
  4525. similar_distance = float("inf")
  4526. type_only_match = None
  4527. # Get available trays (not already used)
  4528. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4529. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4530. # Hard filter — cross-nozzle assignment causes print failures
  4531. # ("position of left hotend is abnormal"), so never fall back.
  4532. # Skipped when an FTS is installed: it routes any AMS slot to either
  4533. # extruder, so restricting to one nozzle would wrongly exclude the
  4534. # correct spool sitting in the other nozzle's AMS (#2186).
  4535. req_nozzle_id = req.get("nozzle_id")
  4536. if req_nozzle_id is not None and not fts_installed:
  4537. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4538. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4539. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4540. # _prefer_lowest_sort_key for the full rationale.
  4541. if prefer_lowest:
  4542. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4543. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4544. # One line per filament req so a bug report can be diagnosed
  4545. # without enabling debug logging: shows what the matcher saw
  4546. # (req shape + sorted candidate trays with their remain values
  4547. # and any inventory override that was applied). Mirrored by
  4548. # the picked-match log at the bottom of the loop.
  4549. logger.info(
  4550. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4551. req.get("slot_id"),
  4552. req_type,
  4553. req_color,
  4554. req_tray_info_idx,
  4555. req_nozzle_id,
  4556. [
  4557. {
  4558. "gtid": f.get("global_tray_id"),
  4559. "type": f.get("type"),
  4560. "color": f.get("color"),
  4561. "tii": f.get("tray_info_idx"),
  4562. "remain": f.get("remain"),
  4563. "inv_g": (
  4564. inventory_remain_overrides.get(f.get("global_tray_id"))
  4565. if inventory_remain_overrides
  4566. else None
  4567. ),
  4568. }
  4569. for f in available
  4570. ],
  4571. )
  4572. # A forced slot takes only what `_get_missing_force_color_slots`
  4573. # accepts: same type, exact colour, and the same variant when both
  4574. # sides name one -- preferring the tray that does. Nothing looser:
  4575. # the model-based path holds a job the printer cannot satisfy this
  4576. # way, and a printer-pinned job fell through to type_only and
  4577. # printed in whatever colour came first (#3280).
  4578. forced = bool(req.get("force_color_match"))
  4579. if forced:
  4580. want_type = canonical_filament_type(req_type)
  4581. want_color = self._normalize_color_for_compare(req_color)
  4582. candidates = [
  4583. f
  4584. for f in available
  4585. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4586. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4587. and (
  4588. not req_tray_info_idx
  4589. or not f.get("tray_info_idx")
  4590. or f.get("tray_info_idx") == req_tray_info_idx
  4591. )
  4592. ]
  4593. exact_match = next(
  4594. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4595. candidates[0] if candidates else None,
  4596. )
  4597. # Check if tray_info_idx is unique among available trays
  4598. if req_tray_info_idx and not forced:
  4599. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4600. if len(idx_matches) == 1:
  4601. # Unique tray_info_idx - use it as definitive match
  4602. idx_match = idx_matches[0]
  4603. logger.debug(
  4604. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4605. f"-> tray {idx_match['global_tray_id']}"
  4606. )
  4607. elif len(idx_matches) > 1:
  4608. # Multiple trays with same tray_info_idx - use color matching among them
  4609. logger.debug(
  4610. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4611. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4612. )
  4613. if prefer_lowest:
  4614. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4615. # Use color matching within this subset
  4616. for f in idx_matches:
  4617. f_color = f.get("color", "")
  4618. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4619. if not exact_match:
  4620. exact_match = f
  4621. elif self._colors_are_similar(f_color, req_color):
  4622. distance = self._color_distance(f_color, req_color)
  4623. if distance is not None and distance < similar_distance:
  4624. similar_match = f
  4625. similar_distance = distance
  4626. elif not type_only_match:
  4627. type_only_match = f
  4628. # If no idx_match yet, do standard type/color matching on all available trays
  4629. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4630. for f in available:
  4631. f_type = (f.get("type") or "").upper()
  4632. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4633. continue
  4634. # Type matches - check color
  4635. f_color = f.get("color", "")
  4636. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4637. if not exact_match:
  4638. exact_match = f
  4639. elif self._colors_are_similar(f_color, req_color):
  4640. # Nearest wins, not first-in-tray-order. `available` is
  4641. # already in the caller's order (slot order, or the
  4642. # prefer-lowest sort), and `<` keeps the earliest of
  4643. # equally close spools — so that order survives as the
  4644. # tie-break (#2804).
  4645. distance = self._color_distance(f_color, req_color)
  4646. if distance is not None and distance < similar_distance:
  4647. similar_match = f
  4648. similar_distance = distance
  4649. elif not type_only_match:
  4650. type_only_match = f
  4651. match = idx_match or exact_match or similar_match or type_only_match
  4652. if match:
  4653. used_tray_ids.add(match["global_tray_id"])
  4654. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4655. else:
  4656. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4657. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4658. # "Why did it pick that spool" is the question every wrong-filament
  4659. # report starts with, and a `similar_color` win is now a ranked
  4660. # choice among several eligible spools rather than whichever tray
  4661. # came first, so it is worth being able to see after the fact.
  4662. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4663. # is on (#1766).
  4664. if match:
  4665. bucket = (
  4666. "idx"
  4667. if idx_match is not None
  4668. else "exact_color"
  4669. if exact_match is not None
  4670. else "similar_color"
  4671. if similar_match is not None
  4672. else "type_only"
  4673. )
  4674. logger.info(
  4675. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4676. match["global_tray_id"],
  4677. bucket,
  4678. req.get("slot_id"),
  4679. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4680. )
  4681. else:
  4682. logger.info(
  4683. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4684. req.get("slot_id"),
  4685. req_type,
  4686. req_color,
  4687. req_tray_info_idx,
  4688. ", force color match" if forced else "",
  4689. )
  4690. # Build mapping array
  4691. if not comparisons:
  4692. return None
  4693. max_slot_id = max(c["slot_id"] for c in comparisons)
  4694. if max_slot_id <= 0:
  4695. return None
  4696. mapping = [-1] * max_slot_id
  4697. for c in comparisons:
  4698. slot_id = c["slot_id"]
  4699. if slot_id and slot_id > 0:
  4700. mapping[slot_id - 1] = c["global_tray_id"]
  4701. return mapping
  4702. def _mark_printer_dispatched(
  4703. self,
  4704. printer_id: int,
  4705. pre_state: str | None,
  4706. pre_subtask_id: str | None,
  4707. ) -> None:
  4708. """Record that a print command was just sent to ``printer_id``.
  4709. Held until either the watchdog observes a state/subtask transition
  4710. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4711. """
  4712. if not pre_state:
  4713. # No pre_state means we can't detect a transition — fall back to a
  4714. # pure time-based hold using empty string as a sentinel that won't
  4715. # match any real printer state.
  4716. pre_state = ""
  4717. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4718. def _release_dispatch_hold(self, printer_id: int) -> None:
  4719. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4720. self._dispatch_holds.pop(printer_id, None)
  4721. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4722. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4723. Returns False (and clears the hold) once any of these are true:
  4724. - hard timeout (``_dispatch_max_hold``) has elapsed
  4725. - the printer has transitioned out of pre_state and we're past the
  4726. minimum cooldown
  4727. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4728. past the minimum cooldown
  4729. Otherwise the printer is held — caller should treat it as busy.
  4730. """
  4731. entry = self._dispatch_holds.get(printer_id)
  4732. if not entry:
  4733. return False
  4734. started_at, pre_state, pre_subtask_id = entry
  4735. elapsed = time.monotonic() - started_at
  4736. if elapsed >= self._dispatch_max_hold:
  4737. self._dispatch_holds.pop(printer_id, None)
  4738. return False
  4739. # Without a pre_state we can't detect a transition — fall back to the
  4740. # min cooldown alone, then drop the hold.
  4741. if not pre_state:
  4742. if elapsed >= self._dispatch_min_cooldown:
  4743. self._dispatch_holds.pop(printer_id, None)
  4744. return False
  4745. return True
  4746. status = printer_manager.get_status(printer_id)
  4747. current_state = getattr(status, "state", None) if status else None
  4748. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4749. transitioned = (current_state is not None and current_state != pre_state) or (
  4750. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4751. )
  4752. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4753. self._dispatch_holds.pop(printer_id, None)
  4754. return False
  4755. return True
  4756. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4757. """Check if a printer is connected and idle."""
  4758. if not printer_manager.is_connected(printer_id):
  4759. logger.debug("Printer %d: not connected", printer_id)
  4760. return False
  4761. state = printer_manager.get_status(printer_id)
  4762. if not state:
  4763. logger.debug("Printer %d: no status available", printer_id)
  4764. return False
  4765. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4766. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4767. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4768. # printer, it boots back into IDLE with no memory of the previous finish; without
  4769. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4770. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4771. logger.debug(
  4772. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4773. printer_id,
  4774. state.state,
  4775. )
  4776. return False
  4777. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4778. if not idle:
  4779. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4780. return False
  4781. # A print would run from the SD card the firmware is being written to.
  4782. from backend.app.services.firmware_update import upload_in_progress
  4783. if upload_in_progress(printer_id):
  4784. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4785. return False
  4786. return True
  4787. @staticmethod
  4788. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4789. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4790. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4791. and that the fixed-printer branch has already found connected, so the two
  4792. offline cases answer at their own exits and never arrive here.
  4793. The default is the model-based branch's ``Busy:`` wording, which
  4794. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4795. the right answer for the connected-but-no-telemetry second or two after a
  4796. reconnect: the model-based branch has always reported it that way, and it
  4797. is not something to wake anybody up for.
  4798. A plate nobody has confirmed is the one case here that does not resolve
  4799. itself — somebody has to walk over to the printer — so it is worded as
  4800. itself and allowed to notify.
  4801. """
  4802. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4803. return f"Waiting for plate confirmation: {printer_name}"
  4804. return f"Busy: {printer_name}"
  4805. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4806. """Read a setting value from the database."""
  4807. result = await db.execute(select(Settings).where(Settings.key == key))
  4808. setting = result.scalar_one_or_none()
  4809. return setting.value if setting else None
  4810. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4811. """Read a boolean setting from the database."""
  4812. result = await db.execute(select(Settings).where(Settings.key == key))
  4813. setting = result.scalar_one_or_none()
  4814. if setting:
  4815. return setting.value.lower() == "true"
  4816. return default
  4817. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4818. """Read an int setting; falls back to default on missing/unparseable rows."""
  4819. result = await db.execute(select(Settings).where(Settings.key == key))
  4820. setting = result.scalar_one_or_none()
  4821. if setting and setting.value:
  4822. try:
  4823. return int(setting.value)
  4824. except ValueError:
  4825. pass
  4826. return default
  4827. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4828. """Get drying presets (user-configured or built-in defaults)."""
  4829. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4830. setting = result.scalar_one_or_none()
  4831. if setting and setting.value:
  4832. try:
  4833. presets = json.loads(setting.value)
  4834. if isinstance(presets, dict) and presets:
  4835. return presets
  4836. except json.JSONDecodeError:
  4837. pass
  4838. return self.DEFAULT_DRYING_PRESETS
  4839. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4840. """Per-filament humidity thresholds (#1605).
  4841. Returns the user-configured overrides map keyed by normalized filament
  4842. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4843. unknown / unmapped types. Empty / unset → empty dict, in which case
  4844. callers fall back to ``ams_humidity_fair``.
  4845. """
  4846. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4847. setting = result.scalar_one_or_none()
  4848. if not setting or not setting.value:
  4849. return {}
  4850. try:
  4851. data = json.loads(setting.value)
  4852. except json.JSONDecodeError:
  4853. return {}
  4854. if not isinstance(data, dict):
  4855. return {}
  4856. out: dict[str, int] = {}
  4857. for key, value in data.items():
  4858. try:
  4859. out[str(key).upper() if key != "default" else "default"] = int(value)
  4860. except (TypeError, ValueError):
  4861. continue
  4862. return out
  4863. # Materials whose AMS spelling differs from the key the tables above use.
  4864. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4865. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4866. # good PA row (#3067).
  4867. #
  4868. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4869. # The drying popover has resolved these correctly since #2774 and the
  4870. # scheduler never did, which is exactly why #3067's reporter could dry a
  4871. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4872. #
  4873. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4874. # of nylon, so it is the one entry that is a judgement rather than a
  4875. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4876. # way, and PA's row is the hottest the table has. Drying it there is closer
  4877. # to right than not drying it at all, which is what it got before.
  4878. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4879. "NYLON": "PA",
  4880. "PA6": "PA",
  4881. "PA11": "PA",
  4882. "PA12": "PA",
  4883. "PAHT": "PA",
  4884. "PPA": "PA",
  4885. }
  4886. @classmethod
  4887. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4888. """The key in *table* that answers for this tray's material, or None.
  4889. The printer reports the material in ``tray_type``, and it spells filled
  4890. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4891. tables here are keyed by base material, so matching the raw string alone
  4892. found a row for 8 of the 41 types a printer can report and skipped the
  4893. rest -- silently, because every caller reads "no row" as "nothing to do
  4894. for this tray". Auto-drying therefore ignored every composite spool on
  4895. the install (#3067).
  4896. Exact match first, so a table the user has extended with a row of its
  4897. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4898. base material's. Then the suffix is dropped, then the alias map above
  4899. answers for the polyamide spellings.
  4900. Returns None rather than a default: what to do with an unrecognised
  4901. material differs per caller, and only the caller knows whether "no row"
  4902. means skip the tray or fall back to a catch-all. Nothing here invents a
  4903. temperature for a material the table does not list.
  4904. """
  4905. raw = cls._normalize_filament_type(tray_type or "")
  4906. if not raw:
  4907. return None
  4908. for candidate in (raw, raw.split("-")[0]):
  4909. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4910. if key in table:
  4911. return key
  4912. return None
  4913. @staticmethod
  4914. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4915. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4916. For mixed filament types loaded into one AMS, returns the most
  4917. restrictive (lowest) threshold across all loaded tray types — matches
  4918. the conservative-params strategy already used for drying temp/hours.
  4919. Empty / unloaded trays contribute no constraint. Unknown types use the
  4920. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4921. when no per-type map is configured at all.
  4922. """
  4923. default = thresholds.get("default", fallback)
  4924. if not thresholds:
  4925. return fallback
  4926. candidates: list[int] = []
  4927. for tray in trays:
  4928. tray_type = str(tray.get("tray_type") or "").strip()
  4929. if not tray_type:
  4930. continue
  4931. # A composite carries its base material's threshold when it has no
  4932. # row of its own, the same way it takes its drying preset (#3067).
  4933. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4934. candidates.append(thresholds[key] if key is not None else default)
  4935. if not candidates:
  4936. return default
  4937. return min(candidates)
  4938. def _get_conservative_drying_params(
  4939. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4940. ) -> tuple[int, int, str] | None:
  4941. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4942. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4943. """
  4944. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4945. hours_key = f"{temp_key}_hours"
  4946. min_temp = None
  4947. max_hours = None
  4948. filament_type = ""
  4949. for tray in trays:
  4950. tray_type = tray.get("tray_type", "")
  4951. if not tray_type:
  4952. continue
  4953. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4954. # which is what stopped auto-drying on every composite spool (#3067).
  4955. base_type = self._resolve_filament_key(tray_type, presets)
  4956. if base_type is None:
  4957. continue
  4958. # The table is user-editable JSON with no per-row validation, so a
  4959. # row can be present and empty. That has always meant "skip this
  4960. # material", and it has to keep meaning it: the reads below fall
  4961. # back to 55C/12h per missing field, which is a temperature nobody
  4962. # chose and would deform a PLA spool.
  4963. preset = presets[base_type]
  4964. if not preset:
  4965. continue
  4966. temp = preset.get(temp_key, 55)
  4967. hours = preset.get(hours_key, 12)
  4968. # Conservative: lowest temp, longest duration
  4969. if min_temp is None or temp < min_temp:
  4970. min_temp = temp
  4971. if max_hours is None or hours > max_hours:
  4972. max_hours = hours
  4973. if not filament_type:
  4974. filament_type = base_type
  4975. if min_temp is None:
  4976. return None
  4977. return (min_temp, max_hours or 12, filament_type)
  4978. async def _check_filament_low(self, db: AsyncSession) -> None:
  4979. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4980. ``on_filament_low`` has had a column, a schema field, a route, a template
  4981. and a UI toggle since the notification system was built, and no caller --
  4982. so the toggle could be switched on and could never fire. This is the
  4983. producer.
  4984. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4985. ``low_stock_threshold_pct`` override is already exactly this decision:
  4986. already configurable, already surfaced, already driving the Inventory
  4987. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4988. consulted -- it has been measured up to 56 points out against a scale,
  4989. which is not a number to page someone on.
  4990. Only slots with an assigned spool produce an event. A slot Bambuddy
  4991. cannot resolve to a spool has no remaining weight it can stand behind,
  4992. and guessing one is how the remain percentage would have got in.
  4993. """
  4994. from backend.app.models.spool import Spool
  4995. # Time-gated rather than run on every pass. run() sleeps
  4996. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4997. # early-return path counts as productive while an upload is in flight
  4998. # (#2602), so an unthrottled check would re-read the whole spool
  4999. # collection every 3 seconds for the length of a batch drain. In
  5000. # Spoolman mode that is a request storm against a third-party service,
  5001. # which is the thing this producer's design note argues against; and
  5002. # when Spoolman is down, _get_with_retry burns ~16 s inside
  5003. # check_queue holding the scheduler's session, so the outage would
  5004. # throttle the print queue itself. A low spool is not a 3-second
  5005. # concern -- the idle interval is the natural resolution.
  5006. now = time.monotonic()
  5007. if now < self._filament_low_next_check:
  5008. return
  5009. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  5010. try:
  5011. # on_filament_low defaults to off on every provider, so on most
  5012. # installs nobody wants this alert. Without this the check would
  5013. # still read every assigned spool each interval -- the whole
  5014. # collection over HTTP in Spoolman mode -- for an event that is
  5015. # switched off. One query against the provider table settles it
  5016. # before any spool work, the same guard the bed-cooled waiter uses.
  5017. # No printer_id: this asks whether any provider wants the event at
  5018. # all; per-printer scoping is applied when the event is sent.
  5019. #
  5020. # While nobody wants it, no pass sees a slot go back above its
  5021. # threshold, so nothing can re-arm; a spool refilled under the same
  5022. # id in that time would stay silenced until a restart. Forgetting
  5023. # what was sent is right anyway: whoever switches the event back on
  5024. # is told about the spools that are low now.
  5025. #
  5026. # The MQTT relay publishes the same event, so a connected relay is
  5027. # reason enough to run the check. Its record is forgotten when the
  5028. # relay is switched off, not when the broker drops: a reconnect must
  5029. # not re-send every low slot.
  5030. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  5031. relay = mqtt_relay.enabled and mqtt_relay.connected
  5032. if not notify:
  5033. self._notified_filament_low.clear()
  5034. if not mqtt_relay.enabled:
  5035. self._relayed_filament_low.clear()
  5036. if not notify and not relay:
  5037. return
  5038. global_threshold = await self._get_low_stock_threshold(db)
  5039. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  5040. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  5041. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5042. if spoolman_on:
  5043. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  5044. else:
  5045. rows = (
  5046. await db.execute(
  5047. select(SpoolAssignment, Spool)
  5048. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  5049. # An archived spool is not stock. The Inventory page's
  5050. # Low Stock count skips them (InventoryPage.tsx:1089)
  5051. # and get_all_spools without allow_archived already
  5052. # excludes them in Spoolman mode, so without this the
  5053. # internal path is the only one that alerts on them.
  5054. .where(Spool.archived_at.is_(None))
  5055. )
  5056. ).all()
  5057. for assignment, spool in rows:
  5058. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  5059. if pct is None:
  5060. continue
  5061. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  5062. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  5063. pct,
  5064. threshold,
  5065. spool.color_name,
  5066. )
  5067. if not slots:
  5068. # Nothing resolvable this pass. Deliberately not clearing the
  5069. # notified set: a Spoolman that is briefly unreachable would
  5070. # otherwise re-alert on every spool as soon as it came back.
  5071. return
  5072. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  5073. except Exception as e:
  5074. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  5075. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  5076. """The global low-stock percentage, defaulting to the schema's 20.0."""
  5077. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  5078. if raw is None or raw.value is None:
  5079. return 20.0
  5080. try:
  5081. value = float(raw.value)
  5082. except (TypeError, ValueError):
  5083. return 20.0
  5084. return value if 0 < value <= 100 else 20.0
  5085. async def _filament_low_slots_spoolman(
  5086. self, db: AsyncSession, global_threshold: float
  5087. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  5088. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  5089. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  5090. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  5091. so the global threshold is the only one that applies here. That matches
  5092. what the Inventory page already does in this mode.
  5093. One ``get_all_spools`` call covers every slot rather than a request per
  5094. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  5095. without ``allow_archived`` -- which is the behaviour the internal path
  5096. has to ask for explicitly.
  5097. An unreachable Spoolman returns no slots rather than raising. It is an
  5098. ordinary state for a third-party service, not an error in this pass: the
  5099. caller's "nothing resolvable" branch already leaves the notified set
  5100. alone, which is exactly right here, whereas letting it reach the broad
  5101. ``except`` would write a full traceback every time the check runs.
  5102. """
  5103. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5104. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5105. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  5106. if not assignments:
  5107. return {}
  5108. client = await get_spoolman_client()
  5109. if client is None:
  5110. return {}
  5111. try:
  5112. all_spools = await client.get_all_spools()
  5113. except SpoolmanUnavailableError as e:
  5114. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  5115. return {}
  5116. by_id: dict[int, dict] = {}
  5117. for raw in all_spools:
  5118. raw_id = raw.get("id")
  5119. if isinstance(raw_id, int):
  5120. by_id[raw_id] = raw
  5121. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5122. for assignment in assignments:
  5123. raw = by_id.get(assignment.spoolman_spool_id)
  5124. if raw is None:
  5125. continue
  5126. try:
  5127. mapped = _map_spoolman_spool(raw)
  5128. except ValueError:
  5129. continue
  5130. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  5131. if pct is None:
  5132. continue
  5133. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  5134. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  5135. return slots
  5136. async def _emit_filament_low(
  5137. self,
  5138. db: AsyncSession,
  5139. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  5140. *,
  5141. notify: bool = True,
  5142. relay: bool = False,
  5143. ) -> None:
  5144. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  5145. printers: dict[int, Printer] = {}
  5146. for key, (pct, threshold, color) in slots.items():
  5147. printer_id, ams_id, tray_id, spool_id = key
  5148. if pct >= threshold:
  5149. # Back above the line: re-arm rather than expire on a timer, so a
  5150. # refilled slot can alert again and a spool sitting just under the
  5151. # threshold stays quiet.
  5152. self._notified_filament_low.discard(key)
  5153. self._relayed_filament_low.discard(key)
  5154. continue
  5155. send_notification = notify and key not in self._notified_filament_low
  5156. # Only while connected, so a crossing the relay missed reaches it
  5157. # after the reconnect.
  5158. send_relay = relay and key not in self._relayed_filament_low
  5159. if not send_notification and not send_relay:
  5160. continue
  5161. # Marked before sending, which is a choice rather than the only
  5162. # option, and it is the opposite failure mode from the one the
  5163. # debounce argues against: one transient provider failure loses this
  5164. # alert until the spool goes back above the threshold and crosses it
  5165. # again. Marking after a successful send would trade that for
  5166. # re-alerting on every pass while a provider is down -- which is the
  5167. # repetition the whole debounce exists to prevent, and the louder of
  5168. # the two failures. A spool that is low stays low, so the next real
  5169. # signal is not far away; a provider stuck retrying is a signal that
  5170. # never stops.
  5171. if send_notification:
  5172. self._notified_filament_low.add(key)
  5173. if send_relay:
  5174. self._relayed_filament_low.add(key)
  5175. if printer_id not in printers:
  5176. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5177. if printer is None:
  5178. continue
  5179. printers[printer_id] = printer
  5180. printer = printers[printer_id]
  5181. slot = _ams_slot_label(ams_id, tray_id)
  5182. if send_notification:
  5183. try:
  5184. await notification_service.on_filament_low(
  5185. printer_id,
  5186. printer.name,
  5187. slot,
  5188. int(pct),
  5189. db,
  5190. color=color,
  5191. )
  5192. except Exception as e:
  5193. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5194. if send_relay:
  5195. try:
  5196. await mqtt_relay.on_filament_low(
  5197. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5198. )
  5199. except Exception as e:
  5200. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5201. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5202. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5203. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5204. a schema field, a template and a UI toggle, and nothing that computes the
  5205. condition -- the Forecast panel does it in the browser, so with no page
  5206. open nothing could ever alert. This runs the same arithmetic
  5207. (``stock_forecast``) from the scheduler loop.
  5208. An alert is sent when a SKU *moves into* a condition, once, and again
  5209. after the condition has cleared. A SKU that worsens from reorder to break
  5210. alerts again as a break, because the panel treats the two as exclusive; one
  5211. that eases from break back to reorder does not alert again.
  5212. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5213. while it is still low tells you.
  5214. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5215. loop runs every 3 s while an upload is in flight, and the whole spool
  5216. collection is read over HTTP in Spoolman mode. Both events default to off
  5217. on every provider, so nothing is read unless a provider wants one.
  5218. """
  5219. now = time.monotonic()
  5220. if now < self._stock_forecast_next_check:
  5221. return
  5222. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5223. try:
  5224. if self._stock_alerts_persisted is None:
  5225. await self._load_stock_alerts(db)
  5226. wanted = {
  5227. "reorder": bool(
  5228. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5229. ),
  5230. "break": bool(
  5231. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5232. ),
  5233. }
  5234. if not any(wanted.values()):
  5235. # Nobody wants either event. Forget what was sent, so whoever
  5236. # switches one on is told about the SKUs that are low now.
  5237. self._notified_stock_alerts.clear()
  5238. await self._save_stock_alerts(db)
  5239. return
  5240. forecasts = await self._stock_forecasts(db)
  5241. if forecasts is None:
  5242. # Spoolman unreachable. Deliberately not clearing the notified
  5243. # set: a brief outage would otherwise re-alert every SKU when it
  5244. # came back.
  5245. return
  5246. await self._emit_stock_alerts(db, forecasts, wanted)
  5247. await self._save_stock_alerts(db)
  5248. except Exception as e:
  5249. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5250. def _serialize_stock_alerts(self) -> str:
  5251. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5252. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5253. return json.dumps(rows)
  5254. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5255. """Read the notified set saved by the last run, once per process.
  5256. A missing or unreadable row is an empty set: the worst that does is one
  5257. repeat of what a restart used to cause every time.
  5258. """
  5259. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5260. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5261. if raw and raw.value:
  5262. try:
  5263. for key, kind, events in json.loads(raw.value):
  5264. if len(key) == 4 and kind in ("reorder", "break"):
  5265. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5266. except (ValueError, TypeError):
  5267. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5268. loaded = {}
  5269. self._notified_stock_alerts = loaded
  5270. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5271. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5272. """Write the notified set to its settings row if it changed since it was last read or written."""
  5273. serialized = self._serialize_stock_alerts()
  5274. if serialized == self._stock_alerts_persisted:
  5275. return
  5276. from backend.app.core.db_dialect import upsert_setting
  5277. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5278. await db.commit()
  5279. self._stock_alerts_persisted = serialized
  5280. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5281. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5282. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5283. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5284. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5285. sku_settings = {
  5286. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5287. lead_time_days=row.lead_time_days,
  5288. safety_margin_value=row.safety_margin_value,
  5289. safety_margin_unit=row.safety_margin_unit,
  5290. alerts_snoozed=bool(row.alerts_snoozed),
  5291. )
  5292. for row in sku_rows
  5293. }
  5294. if await self._get_bool_setting(db, "spoolman_enabled"):
  5295. spools = await self._stock_spools_spoolman()
  5296. if spools is None:
  5297. return None
  5298. # The Spoolman spools' own rows (#3407), keyed by Spoolman id. Never
  5299. # the built-in ones: a Spoolman id that matches a local spool id
  5300. # (left over from before Spoolman was switched on) would borrow an
  5301. # unrelated spool's history (#3406).
  5302. history = await self._stock_usage_history(db, spoolman=True)
  5303. history = {
  5304. spool.id: stock_forecast.own_records(spool, history[spool.id])
  5305. for spool in spools
  5306. if spool.id in history
  5307. }
  5308. else:
  5309. spools = await self._stock_spools_internal(db)
  5310. history = await self._stock_usage_history(db)
  5311. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5312. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5313. from backend.app.models.spool import Spool
  5314. # Every spool: stock, the recently archived ones that count towards the
  5315. # rate, and the older ones that tell it the SKU was in use before its
  5316. # window (#3407). stock_forecast.forecast_all sorts them.
  5317. rows = (await db.execute(select(Spool))).scalars().all()
  5318. return [
  5319. stock_forecast.StockSpool(
  5320. id=spool.id,
  5321. material=spool.material,
  5322. subtype=spool.subtype,
  5323. brand=spool.brand,
  5324. color_name=spool.color_name,
  5325. label_weight=float(spool.label_weight or 0),
  5326. weight_used=float(spool.weight_used or 0),
  5327. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5328. created_at=spool.created_at,
  5329. archived_at=spool.archived_at,
  5330. last_used_at=spool.last_used,
  5331. )
  5332. for spool in rows
  5333. ]
  5334. async def _stock_usage_history(
  5335. self, db: AsyncSession, *, spoolman: bool = False
  5336. ) -> dict[int, list[stock_forecast.UsageRecord]]:
  5337. """Usage rows by spool id, for one inventory: its own ids, as the forecast
  5338. panel reads them from the usage endpoint."""
  5339. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5340. spool_id = SpoolUsageHistory.spoolman_spool_id if spoolman else SpoolUsageHistory.spool_id
  5341. rows = (
  5342. await db.execute(
  5343. select(spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5344. .where(
  5345. SpoolUsageHistory.spoolman_spool_id.is_not(None)
  5346. if spoolman
  5347. else SpoolUsageHistory.spoolman_spool_id.is_(None)
  5348. )
  5349. .order_by(SpoolUsageHistory.created_at.desc())
  5350. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5351. )
  5352. ).all()
  5353. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5354. for spool_id, created_at, weight_used in rows:
  5355. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5356. # filtered before the limit, so the window matches the forecast panel's.
  5357. if created_at is None or spool_id is None:
  5358. continue
  5359. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5360. return history
  5361. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5362. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5363. Archived ones too: a recently used-up spool counts towards its SKU's
  5364. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5365. page (and so the panel) reads; it dates archiving by the spool's last
  5366. use, as Spoolman records no archive date.
  5367. """
  5368. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5369. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5370. client = await get_spoolman_client()
  5371. if client is None:
  5372. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5373. return None
  5374. try:
  5375. raw_spools = await client.get_all_spools(allow_archived=True)
  5376. except SpoolmanUnavailableError as e:
  5377. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5378. return None
  5379. spools: list[stock_forecast.StockSpool] = []
  5380. for raw in raw_spools:
  5381. try:
  5382. mapped = _map_spoolman_spool(raw)
  5383. except ValueError:
  5384. continue
  5385. created_at = _spoolman_time(mapped.get("created_at"))
  5386. archived_at = None
  5387. if raw.get("archived"):
  5388. # Archived without a date to tell when: not stock, and too old to
  5389. # count towards the rate.
  5390. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5391. spools.append(
  5392. stock_forecast.StockSpool(
  5393. id=mapped["id"],
  5394. material=mapped["material"],
  5395. subtype=mapped.get("subtype"),
  5396. brand=mapped.get("brand"),
  5397. color_name=mapped.get("color_name"),
  5398. label_weight=float(mapped.get("label_weight") or 0),
  5399. weight_used=float(mapped.get("weight_used") or 0),
  5400. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5401. created_at=created_at,
  5402. archived_at=archived_at,
  5403. first_used_at=_spoolman_time(mapped.get("first_used")),
  5404. last_used_at=_spoolman_time(mapped.get("last_used")),
  5405. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5406. )
  5407. )
  5408. return spools
  5409. async def _emit_stock_alerts(
  5410. self,
  5411. db: AsyncSession,
  5412. forecasts: stock_forecast.ForecastMap,
  5413. wanted: dict[str, bool],
  5414. ) -> None:
  5415. """Send the notifications for each SKU that has moved into a stock alert condition.
  5416. A SKU in break has also reached its reorder point, so both events apply to
  5417. it: the break event goes to providers that have it on, and the reorder event
  5418. to the providers that have only that one on. A provider with both on gets the
  5419. break and no second message.
  5420. What is remembered per SKU is the condition and which events had a
  5421. subscriber when it was sent. An event with no subscriber is forgotten, so
  5422. switching it on later reports the SKUs already in that condition.
  5423. """
  5424. active_events = {event for event, on in wanted.items() if on}
  5425. for key, (forecast, spool) in forecasts.items():
  5426. kind: str | None = None
  5427. if not forecast.snoozed:
  5428. if forecast.stock_break_alert:
  5429. kind = "break"
  5430. elif forecast.reorder_alert:
  5431. kind = "reorder"
  5432. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5433. events = applicable & active_events
  5434. if not events:
  5435. self._notified_stock_alerts.pop(key, None)
  5436. continue
  5437. previous = self._notified_stock_alerts.get(key)
  5438. told = (previous[1] & active_events) if previous else frozenset()
  5439. # Trimmed to the events this condition can send. That is what makes easing from
  5440. # break back to reorder silent (the reorder event was told with the break) and
  5441. # worsening again news again (the break event is no longer remembered).
  5442. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5443. # Recorded before sending, for the reason _emit_filament_low gives: a
  5444. # provider that is down should lose this alert, not repeat it every hour.
  5445. to_send = events - told
  5446. # Both flags imply a positive rate and so a day count.
  5447. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5448. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5449. color = None if spool.color_name_is_synthesized else spool.color_name
  5450. try:
  5451. if "break" in to_send:
  5452. await notification_service.on_stock_break_alert(
  5453. spool.material,
  5454. spool.brand,
  5455. forecast.remaining_g,
  5456. rate,
  5457. days_left,
  5458. forecast.effective_lead_time_days,
  5459. db,
  5460. subtype=spool.subtype,
  5461. color=color,
  5462. )
  5463. if "reorder" in to_send:
  5464. await notification_service.on_stock_reorder_alert(
  5465. spool.material,
  5466. spool.brand,
  5467. forecast.remaining_g,
  5468. rate,
  5469. days_left,
  5470. db,
  5471. subtype=spool.subtype,
  5472. color=color,
  5473. skip_break_subscribers=kind == "break",
  5474. )
  5475. except Exception as e:
  5476. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5477. # A SKU with no spools left is no longer alerting.
  5478. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5479. del self._notified_stock_alerts[key]
  5480. @staticmethod
  5481. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5482. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5483. from backend.app.core.auth import is_auth_enabled
  5484. if user_id is None or not await is_auth_enabled(db):
  5485. return ALL_PRINTERS
  5486. return await resolve_user_id_printer_scope(db, user_id)
  5487. async def _model_job_printer_ids(
  5488. self,
  5489. db: AsyncSession,
  5490. item: PrintQueueItem,
  5491. scope: PrinterScope,
  5492. cache: dict[tuple[str, str | None, int | None], set[int]],
  5493. ) -> set[int]:
  5494. """Every printer an "Any <model>" job could land on: the active printers
  5495. of each of its candidate models, in its location, that its creator may use.
  5496. ``cache`` holds one lookup per model, location and creator for the pass,
  5497. so a long queue of model jobs does not query once per job."""
  5498. printer_ids: set[int] = set()
  5499. for candidate in _candidates_for(item):
  5500. if not candidate.target_model:
  5501. continue
  5502. key = (candidate.target_model, item.target_location, item.created_by_id)
  5503. if key not in cache:
  5504. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5505. cache[key] = {printer.id for printer in printers}
  5506. printer_ids |= cache[key]
  5507. return printer_ids
  5508. async def _check_auto_drying(
  5509. self,
  5510. db: AsyncSession,
  5511. queue_items: list[PrintQueueItem],
  5512. dispatching_printers: set[int],
  5513. ):
  5514. """Start drying on idle printers based on humidity.
  5515. Three modes (can all be enabled independently):
  5516. - queue_drying_enabled: Dry between scheduled queue prints
  5517. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5518. - print_drying_enabled: Also evaluate printers that are currently printing,
  5519. when model+firmware supports "Print While Drying" (gated by
  5520. supports_drying_while_printing). Drying temperature is capped at
  5521. max(40, preset_temp - 5) to protect spools mid-print.
  5522. """
  5523. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5524. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5525. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5526. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5527. # The wait belongs to ambient drying: the settings UI only shows it while
  5528. # ambient drying is on, so a value left behind when ambient is turned off
  5529. # must not keep delaying the one path that still reaches the wait gate
  5530. # without it (a mid-print start under print_drying).
  5531. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5532. # Clear every streak as soon as the wait is inactive. An early return (or
  5533. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5534. # a quick toggle-on inherit an old streak.
  5535. if not sustained_wait_active:
  5536. self._auto_dry_above.clear()
  5537. if not queue_drying_enabled and not ambient_drying_enabled:
  5538. # Stop active drying on all printers if both features disabled
  5539. if self._drying_in_progress:
  5540. for pid in list(self._drying_in_progress):
  5541. if pid in self._scheduled_drying_printer_ids:
  5542. continue
  5543. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5544. await self._stop_drying(pid)
  5545. return
  5546. # Update drying state from printer status (handles backend restart)
  5547. self._sync_drying_state()
  5548. # Find printers with scheduled items (for queue drying mode)
  5549. # An "Any <model>" job counts for every printer it could land on.
  5550. printers_with_scheduled: set[int] = set()
  5551. # Printers with a job that could start now: the ones block mode keeps
  5552. # a new cycle off. A job waiting for its start time is what queue
  5553. # drying dries ahead of.
  5554. printers_with_ready_items: set[int] = set()
  5555. now_utc = datetime.now(timezone.utc)
  5556. creator_scopes: dict[int | None, PrinterScope] = {}
  5557. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5558. for item in queue_items:
  5559. if item.printer_id:
  5560. item_printers = {item.printer_id}
  5561. elif item.target_model or item.variants:
  5562. if item.created_by_id not in creator_scopes:
  5563. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5564. item_printers = await self._model_job_printer_ids(
  5565. db, item, creator_scopes[item.created_by_id], model_printers
  5566. )
  5567. else:
  5568. continue
  5569. if item.scheduled_time and not item.manual_start:
  5570. printers_with_scheduled |= item_printers
  5571. sched = item.scheduled_time
  5572. if sched is not None and sched.tzinfo is None:
  5573. sched = sched.replace(tzinfo=timezone.utc)
  5574. if sched is None or sched <= now_utc:
  5575. printers_with_ready_items |= item_printers
  5576. # If only queue mode is on and no printers have scheduled items, stop drying
  5577. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5578. # may still be eligible for mid-print drying regardless of queue state).
  5579. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5580. for pid in list(self._drying_in_progress):
  5581. if pid in self._scheduled_drying_printer_ids:
  5582. continue
  5583. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5584. await self._stop_drying(pid)
  5585. return
  5586. # Get humidity threshold (global fallback)
  5587. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5588. setting = result.scalar_one_or_none()
  5589. global_humidity_threshold = int(setting.value) if setting else 60
  5590. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5591. # to the global threshold for every AMS unit.
  5592. per_type_thresholds = await self._get_humidity_thresholds(db)
  5593. # Get drying presets
  5594. presets = await self._get_drying_presets(db)
  5595. # Determine if drying should be skipped for printers with pending items
  5596. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5597. # Get all active printers
  5598. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5599. for printer in all_printers.scalars():
  5600. pid = printer.id
  5601. # Resolve model+firmware up front — needed to decide whether this printer
  5602. # qualifies for mid-print drying (busy printer on capable hardware).
  5603. state = printer_manager.get_status(pid)
  5604. if not state:
  5605. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5606. continue
  5607. model = printer_manager.get_model(pid)
  5608. firmware = state.firmware_version
  5609. # "Mid-print" has to mean the printer is actually printing (#2801).
  5610. # It used to be inferred from the dispatch set, which also holds
  5611. # printers that merely could not be dispatched to -- so a printer
  5612. # sitting in FINISH behind an unacknowledged plate was treated as
  5613. # printing, had its drying temperature capped by the mid-print
  5614. # spool protection, and was logged as (mid-print) while idle.
  5615. is_printing = state.state in _ACTIVE_PRINT_STATES
  5616. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5617. # A printer whose print is running or imminent is left alone unless
  5618. # it can dry through it. `dispatching_printers` is deliberately the
  5619. # narrow set: running, held post-dispatch, or mid-upload.
  5620. if (is_printing or pid in dispatching_printers) and not mid_print:
  5621. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5622. continue
  5623. if not mid_print:
  5624. # In queue-only mode, only dry printers that have scheduled prints
  5625. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5626. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5627. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5628. await self._stop_drying(pid)
  5629. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5630. continue
  5631. # When block mode is on, don't START new drying on printers with
  5632. # a job that could start now: the cycle would hold it. One
  5633. # scheduled for later may pre-dry; if the cycle is still running
  5634. # at its time, the hold applies then. Already-drying printers go
  5635. # through so humidity auto-stop logic still runs.
  5636. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5637. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5638. continue
  5639. if not printer_manager.is_connected(pid):
  5640. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5641. continue
  5642. # Plate-clear is deliberately ignored here (#2801). It answers
  5643. # "is the bed ready for the next job", which says nothing about
  5644. # whether the AMS may heat -- and the gap between a finished print
  5645. # and the acknowledgment is exactly when drying is most useful,
  5646. # because the printer is free and nobody is waiting on it. Leaving
  5647. # the plate unacknowledged is also how people hold the queue by
  5648. # hand, and that hold should not cost them their drying.
  5649. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5650. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5651. continue
  5652. # Check drying capability. For mid-print path, supports_drying_while_printing
  5653. # was already verified when computing mid_print above.
  5654. if not mid_print and not supports_drying(model, firmware):
  5655. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5656. continue
  5657. # Check each AMS unit from raw_data
  5658. ams_list = state.raw_data.get("ams", [])
  5659. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5660. for ams_data in ams_list:
  5661. module_type = str(ams_data.get("module_type") or "")
  5662. ams_id = int(ams_data.get("id", 0))
  5663. # Only n3f/n3s support drying
  5664. if module_type not in ("n3f", "n3s"):
  5665. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5666. continue
  5667. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5668. # Most-restrictive of all loaded tray types; falls back to the
  5669. # global threshold when no overrides are configured.
  5670. trays = ams_data.get("tray", []) or []
  5671. humidity_threshold = self.resolve_humidity_threshold(
  5672. trays, per_type_thresholds, global_humidity_threshold
  5673. )
  5674. dry_time = int(ams_data.get("dry_time") or 0)
  5675. # Read humidity as a percentage. The 1-5 index is never
  5676. # substituted: it is inverted, and being unable to exceed any
  5677. # threshold it would read as "dry" forever (#3140). ``None``
  5678. # already means "skip this unit" everywhere below.
  5679. humidity_pct = ams_humidity_percent(ams_data)
  5680. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5681. unit_key = (pid, ams_id)
  5682. unit_state = self._auto_dry_units.get(unit_key)
  5683. # Already drying — let it run to its configured duration (#1892).
  5684. #
  5685. # We deliberately do NOT stop drying from a humidity re-check here.
  5686. # Relative humidity drops steeply in heated air, so the AMS sensor
  5687. # reads ~15-20% within minutes of the dryer starting even while the
  5688. # filament is still saturated. A humidity-based early-stop therefore
  5689. # always fires at the minimum-time floor, truncating both user-started
  5690. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5691. # The firmware stops when the configured duration elapses; scheduling
  5692. # stops (print takes priority, queue no longer needs drying) are
  5693. # handled separately via _stop_drying().
  5694. #
  5695. # A parked countdown is not a running cycle (#3478): the firmware
  5696. # took the command and left the heater off, so dry_time sits at
  5697. # its full duration and never reaches 0 on its own. Treating it
  5698. # as running blocked auto-drying on that unit for days. A sample
  5699. # the stall detector has not classified yet (its first 150 s)
  5700. # still counts as running.
  5701. parked = is_countdown_parked(ams_data)
  5702. if dry_time > 0 and not parked:
  5703. if pid not in self._drying_in_progress:
  5704. # Drying we didn't start (manual or from before restart) —
  5705. # track it so scheduling stops still apply; never auto-stop it.
  5706. self._drying_in_progress[pid] = time.monotonic()
  5707. if unit_state is not None:
  5708. unit_state["running"] = True
  5709. logger.debug(
  5710. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5711. pid,
  5712. ams_id,
  5713. dry_time,
  5714. humidity,
  5715. )
  5716. continue
  5717. # Nothing is drying. Close out a cycle we armed ourselves and
  5718. # judge whether it achieved anything (#2770).
  5719. #
  5720. # "Achieved anything" is measured against the LOWEST reading any
  5721. # cycle on this unit has ended at, not against the threshold and
  5722. # not against the previous cycle. A spool that is genuinely wet
  5723. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5724. # allowed to keep going for as long as it is still coming down,
  5725. # however far it still is from the threshold. What must not
  5726. # continue is a cycle that ends exactly where the last one did,
  5727. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5728. # Comparing against the running minimum rather than the previous
  5729. # end is what stops a sensor oscillating by one point between two
  5730. # values from reading as progress every other cycle.
  5731. if unit_state is not None and unit_state.pop("running", False):
  5732. unit_state["ended_at"] = time.monotonic()
  5733. # The streak that armed this cycle is spent; the next one
  5734. # starts fresh (and accumulates through the re-arm cooldown
  5735. # below, so the wait overlaps the cooldown, never stacks on
  5736. # top of it).
  5737. self._auto_dry_above.pop(unit_key, None)
  5738. if parked:
  5739. # The timer stood still (never started, or paused by the
  5740. # power limit or the print), so the cycle says nothing
  5741. # about humidity: count it apart from the unproductive
  5742. # cycles below (#3478).
  5743. never_heated = _never_heated(unit_state) + 1
  5744. unit_state["never_heated"] = never_heated
  5745. logger.warning(
  5746. "Auto-drying: printer %d AMS %d — drying cycle not running: the timer stands "
  5747. "still at %dm with the status Off, %d in a row",
  5748. pid,
  5749. ams_id,
  5750. dry_time,
  5751. never_heated,
  5752. )
  5753. else:
  5754. # A cycle that counted down ran; the parked streak is over.
  5755. unit_state.pop("never_heated", None)
  5756. if not parked and humidity is not None and humidity > humidity_threshold:
  5757. best = unit_state.get("best_end_humidity")
  5758. if isinstance(best, int) and humidity < best:
  5759. # Still coming down. Keep going, however far the
  5760. # threshold still is.
  5761. unproductive = 0
  5762. else:
  5763. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5764. if not isinstance(best, int) or humidity < best:
  5765. unit_state["best_end_humidity"] = humidity
  5766. unit_state["unproductive"] = unproductive
  5767. logger.info(
  5768. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5769. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5770. pid,
  5771. ams_id,
  5772. humidity,
  5773. humidity_threshold,
  5774. unit_state.get("best_end_humidity"),
  5775. unproductive,
  5776. )
  5777. # A cycle that ended at or below the threshold needs no
  5778. # counter reset here: the branch below drops the whole entry.
  5779. # Humidity below threshold — no need to start drying. This is
  5780. # also the only thing that lifts a suspension: the reading we
  5781. # gave up on has come down, so auto-drying works again and the
  5782. # unit goes back to having no history at all.
  5783. if humidity is None or humidity <= humidity_threshold:
  5784. if unit_state is not None and unit_state.get("suspended"):
  5785. logger.info(
  5786. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5787. "threshold, resuming automatic drying",
  5788. pid,
  5789. ams_id,
  5790. humidity,
  5791. humidity_threshold,
  5792. )
  5793. # Clear the judgement, keep the clock (#2801). Dropping the
  5794. # whole entry also dropped `ended_at`, and with it the
  5795. # 30-minute cooldown -- so a reading that dips to the
  5796. # threshold as the AMS cools and comes back above it once
  5797. # warm wiped its own history and re-armed immediately. That
  5798. # oscillation is the very thing #2770's cooldown exists to
  5799. # ride out, and it is worst at exactly the margin that makes
  5800. # a unit dry repeatedly: a point or two above the threshold.
  5801. if unit_state is not None:
  5802. unit_state.pop("suspended", None)
  5803. unit_state.pop("unproductive", None)
  5804. unit_state.pop("best_end_humidity", None)
  5805. unit_state.pop("never_heated", None)
  5806. # A real below-threshold reading ends any sustained-wait
  5807. # streak (#2518) -- "continuously above" means exactly that.
  5808. # An absent reading (humidity is None) is no-information and
  5809. # leaves the streak alone; the observation-gap guard handles
  5810. # a prolonged sensor silence.
  5811. if humidity is not None:
  5812. _above = self._auto_dry_above.pop(unit_key, None)
  5813. if _above is not None and sustained_wait_active:
  5814. logger.info(
  5815. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5816. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5817. pid,
  5818. ams_id,
  5819. humidity,
  5820. time.monotonic() - _above["since"],
  5821. sustained_minutes,
  5822. humidity_threshold,
  5823. )
  5824. logger.debug(
  5825. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5826. pid,
  5827. ams_id,
  5828. humidity,
  5829. humidity_threshold,
  5830. )
  5831. continue
  5832. # Sustained-humidity streak (#2518): updated on every pass that
  5833. # observes the reading above the threshold, BEFORE the
  5834. # suspension/cooldown gates below -- a suspended or cooling-down
  5835. # unit still accumulates streak time, so the wait overlaps those
  5836. # gates instead of stacking after them. Inert when the feature
  5837. # is off: no entries are written, and an entry left over from a
  5838. # toggle-off is dropped so it cannot seed a stale streak later.
  5839. if sustained_wait_active:
  5840. _now = time.monotonic()
  5841. # Four missed scheduler passes, floored: a single slow pass
  5842. # must not void a streak, but the ceiling has to scale with
  5843. # the cadence or a slow loop silently restarts every streak.
  5844. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5845. _above = self._auto_dry_above.get(unit_key)
  5846. if _above is None:
  5847. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5848. elif _now - _above["last"] > _gap_ceiling:
  5849. # Restart, and say so at the same level as the dip
  5850. # reset: a silent restart voids the streak invisibly,
  5851. # and a user who set a long wait and never gets a dry
  5852. # has no way to see why.
  5853. logger.info(
  5854. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5855. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5856. pid,
  5857. ams_id,
  5858. _now - _above["last"],
  5859. _gap_ceiling,
  5860. sustained_minutes,
  5861. )
  5862. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5863. else:
  5864. _above["last"] = _now
  5865. else:
  5866. self._auto_dry_above.pop(unit_key, None)
  5867. if unit_state is not None:
  5868. if unit_state.get("suspended"):
  5869. logger.debug(
  5870. "Auto-drying: printer %d AMS %d skipped — suspended until humidity is back at "
  5871. "or below the %d%% threshold",
  5872. pid,
  5873. ams_id,
  5874. humidity_threshold,
  5875. )
  5876. continue
  5877. never_heated = _never_heated(unit_state)
  5878. if never_heated >= AUTO_DRY_MAX_NEVER_HEATED_CYCLES:
  5879. unit_state["suspended"] = True
  5880. logger.warning(
  5881. "Auto-drying: printer %d AMS %d — suspending automatic drying. The printer "
  5882. "accepted %d drying commands in a row, but each time the timer stood still and "
  5883. "the unit did not heat. Clear the timer with Stop on the printer card and check "
  5884. "the AMS power; automatic drying resumes once humidity is back at or below the "
  5885. "%d%% threshold.",
  5886. pid,
  5887. ams_id,
  5888. never_heated,
  5889. humidity_threshold,
  5890. )
  5891. await self._notify_auto_drying_suspended(
  5892. db, printer, ams_id, humidity, humidity_threshold, never_heated, never_heated=True
  5893. )
  5894. continue
  5895. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5896. unit_state["suspended"] = True
  5897. logger.warning(
  5898. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5899. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5900. "higher while it is warm, so a threshold in that range can never be reached and "
  5901. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5902. pid,
  5903. ams_id,
  5904. int(unit_state.get("unproductive", 0)),
  5905. humidity,
  5906. humidity_threshold,
  5907. )
  5908. await self._notify_auto_drying_suspended(
  5909. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5910. )
  5911. continue
  5912. ended_at = unit_state.get("ended_at")
  5913. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5914. logger.debug(
  5915. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5916. "cycle before the humidity reading is worth acting on",
  5917. pid,
  5918. ams_id,
  5919. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5920. )
  5921. continue
  5922. # Check cannot-dry reasons (power constraints etc.). Sits
  5923. # ahead of the sustained wait so a unit the firmware refuses
  5924. # to dry never logs a wait it was never going to cash in.
  5925. sf_reasons = ams_data.get("dry_sf_reason", [])
  5926. if sf_reasons:
  5927. logger.debug(
  5928. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5929. pid,
  5930. ams_id,
  5931. sf_reasons,
  5932. )
  5933. continue
  5934. # Sustained-humidity wait (#2518): ambient-triggered starts
  5935. # wait; only a printer with a scheduled queue item pending
  5936. # keeps the instant behavior, because that drying has a real
  5937. # deadline. Mid-print is deliberately NOT exempt while ambient
  5938. # drying is on: a humidity start on a printer that happens to be
  5939. # printing is as vulnerable to a lid-open spike as one on an idle
  5940. # printer (proven live: a 2-point threshold crossing mid-print
  5941. # bought a parked 12h command). Inactive when ambient drying is
  5942. # off: print_drying then still starts mid-print cycles on its own
  5943. # (#1816, "regardless of queue state"), and those stay instant.
  5944. if sustained_wait_active and pid not in printers_with_scheduled:
  5945. _above = self._auto_dry_above.get(unit_key)
  5946. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5947. if _waited < sustained_minutes * 60:
  5948. logger.debug(
  5949. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5950. "threshold for %.0fs of the required %dm",
  5951. pid,
  5952. ams_id,
  5953. humidity,
  5954. humidity_threshold,
  5955. _waited,
  5956. sustained_minutes,
  5957. )
  5958. continue
  5959. # Get conservative drying params for mixed filaments
  5960. params = self._get_conservative_drying_params(trays, module_type, presets)
  5961. if not params:
  5962. logger.debug(
  5963. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5964. )
  5965. continue
  5966. temp, duration_hours, filament_type = params
  5967. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5968. # "drying temperature must not exceed the filament's softening temperature"
  5969. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5970. # ineffective and firmware will reject anyway.
  5971. if mid_print:
  5972. temp = max(40, temp - 5)
  5973. # Start drying
  5974. logger.info(
  5975. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5976. "starting %s drying at %d°C for %dh%s",
  5977. pid,
  5978. ams_id,
  5979. humidity,
  5980. humidity_threshold,
  5981. filament_type,
  5982. temp,
  5983. duration_hours,
  5984. " (mid-print)" if mid_print else "",
  5985. )
  5986. success = printer_manager.send_drying_command(
  5987. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5988. )
  5989. if success:
  5990. self._drying_in_progress[pid] = time.monotonic()
  5991. armed = self._auto_dry_units.setdefault(
  5992. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5993. )
  5994. armed["running"] = True
  5995. async def _notify_auto_drying_suspended(
  5996. self,
  5997. db: AsyncSession,
  5998. printer: Printer,
  5999. ams_id: int,
  6000. humidity: int,
  6001. threshold: int,
  6002. cycles: int,
  6003. *,
  6004. never_heated: bool = False,
  6005. ) -> None:
  6006. """Tell the user auto-drying has given up on one AMS unit (#2770).
  6007. ``never_heated`` picks the message for cycles the printer accepted but
  6008. never ran (#3478) instead of cycles that left humidity high.
  6009. Fires once per suspension — the caller sets ``suspended`` before calling
  6010. and every later pass short-circuits on it — because the whole point is
  6011. that Bambuddy has stopped acting. Somebody whose printer sits in another
  6012. building needs that to reach them, and the hourly humidity alarm they
  6013. are already getting says the opposite of what happened here.
  6014. Never raises: a notification provider being down must not stop the
  6015. suspension itself from taking effect.
  6016. """
  6017. ams_label = unit_label(ams_id, printer_tray_layout(printer.id, printer_manager).ams_type(ams_id))
  6018. try:
  6019. await notification_service.on_ams_drying_suspended(
  6020. printer.id,
  6021. printer.name,
  6022. ams_label,
  6023. float(humidity),
  6024. float(threshold),
  6025. cycles,
  6026. db,
  6027. never_heated=never_heated,
  6028. )
  6029. except Exception as e:
  6030. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  6031. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  6032. """Stop judging the drying cycle currently on this AMS unit (#2770).
  6033. The unproductive-cycle counter exists to notice that *drying* is not
  6034. moving the humidity reading. A cycle that ended because somebody sent a
  6035. stop says nothing about that — it was cut short before it had a chance —
  6036. so counting it would suspend auto-drying for a reason that has nothing to
  6037. do with the loop the counter is there to break.
  6038. Two callers, both of them a stop Bambuddy is responsible for: the
  6039. print-takes-priority stop below, and the manual Stop button. Left
  6040. uncalled, an install that dries between queue jobs would suspend its own
  6041. auto-drying after two prints interrupted a dry — exactly the install
  6042. queue-drying exists for.
  6043. The rest of the unit's history is kept: the cooldown before re-arming
  6044. still applies, and an earlier count still stands.
  6045. """
  6046. state = self._auto_dry_units.get((printer_id, ams_id))
  6047. if state is not None:
  6048. state.pop("running", None)
  6049. state["ended_at"] = time.monotonic()
  6050. # A stopped cycle spends the streak that armed it, same as a completed
  6051. # one (#2518).
  6052. self._auto_dry_above.pop((printer_id, ams_id), None)
  6053. def _sync_drying_state(self):
  6054. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  6055. One direction only: it prunes, it never adds. A printer drying without an
  6056. entry here — because the user started the cycle from Studio, the printer's
  6057. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  6058. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  6059. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  6060. That is deliberate for now rather than an oversight: populating this from
  6061. telemetry would hand the scheduler authority to stop drying a user started
  6062. by hand. It also means the backend-restart case this used to claim to
  6063. handle is not handled.
  6064. """
  6065. to_remove = []
  6066. for pid in self._drying_in_progress:
  6067. state = printer_manager.get_status(pid)
  6068. if not state:
  6069. to_remove.append(pid)
  6070. continue
  6071. # Check if any AMS unit is still drying
  6072. ams_list = state.raw_data.get("ams", [])
  6073. # A parked timer is not drying (#3478): it never ends on its own,
  6074. # so it would keep the printer in here for good.
  6075. any_drying = any(int(a.get("dry_time") or 0) > 0 and not is_countdown_parked(a) for a in ams_list)
  6076. if not any_drying:
  6077. to_remove.append(pid)
  6078. for pid in to_remove:
  6079. self._drying_in_progress.pop(pid, None)
  6080. # A printer that has gone away entirely takes its per-AMS auto-drying
  6081. # history with it (#2770), so a printer deleted and re-added does not
  6082. # inherit a suspension it never earned.
  6083. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  6084. self._auto_dry_units.pop(key, None)
  6085. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  6086. # printer starts a fresh wait, and vanished printers do not leak
  6087. # entries.
  6088. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  6089. self._auto_dry_above.pop(key, None)
  6090. @staticmethod
  6091. def _drying_is_only_parked(printer_id: int) -> bool:
  6092. """True when every AMS unit with a drying timer on this printer is parked.
  6093. A parked timer (#2896: the command was taken but the countdown never
  6094. runs) does not end on its own, so nothing may wait on it. False when no
  6095. unit reports a timer yet -- a command just sent that the firmware has not
  6096. reported back is real drying about to begin.
  6097. """
  6098. state = printer_manager.get_status(printer_id)
  6099. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  6100. timed = []
  6101. for unit in units:
  6102. try:
  6103. if int(unit.get("dry_time") or 0) > 0:
  6104. timed.append(unit)
  6105. except (TypeError, ValueError):
  6106. continue
  6107. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  6108. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  6109. """True when a running cycle can be left alone while the next print runs.
  6110. Some hardware dries happily through a print and #2758 settled that we
  6111. should not tear those cycles down: the X2D there was refusing to
  6112. *start* a job, which is a different problem, and stopping drying before
  6113. every dispatch would throw away cycles the printer was content to run.
  6114. Where the model cannot do it, or the user has not enabled it, the print
  6115. takes priority and the cycle stops -- which is what the queue_drying_block
  6116. setting has always promised in its off position.
  6117. """
  6118. if not await self._get_bool_setting(db, "print_drying_enabled"):
  6119. return False
  6120. status = printer_manager.get_status(printer_id)
  6121. return supports_drying_while_printing(
  6122. printer_manager.get_model(printer_id),
  6123. status.firmware_version if status else None,
  6124. )
  6125. async def _stop_drying(self, printer_id: int):
  6126. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  6127. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  6128. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  6129. enough to kill a cycle the user had started by hand on a *different*
  6130. unit of the same printer (#2801). That contradicted the contract
  6131. ``_sync_drying_state`` already documents -- the entry gate deliberately
  6132. only knows about cycles Bambuddy began, so the action must not reach
  6133. past them either.
  6134. """
  6135. state = printer_manager.get_status(printer_id)
  6136. if not state:
  6137. self._drying_in_progress.pop(printer_id, None)
  6138. return
  6139. ams_list = state.raw_data.get("ams", [])
  6140. for ams_data in ams_list:
  6141. dry_time = int(ams_data.get("dry_time") or 0)
  6142. if dry_time > 0:
  6143. ams_id = int(ams_data.get("id", 0))
  6144. if (printer_id, ams_id) not in self._auto_dry_units:
  6145. logger.debug(
  6146. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  6147. printer_id,
  6148. ams_id,
  6149. )
  6150. continue
  6151. logger.info(
  6152. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  6153. printer_id,
  6154. ams_id,
  6155. )
  6156. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  6157. self.forget_auto_dry_cycle(printer_id, ams_id)
  6158. self._drying_in_progress.pop(printer_id, None)
  6159. # Scheduled manual drying (#2638) -----------------------------------
  6160. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  6161. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  6162. async def _check_scheduled_dryings(self, db: AsyncSession):
  6163. """Dispatch due scheduled drying runs and track running ones."""
  6164. now = utcnow_naive()
  6165. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  6166. # Monotonic, so a clock adjustment cannot park the prune for hours.
  6167. since_prune = time.monotonic()
  6168. if (
  6169. self._last_scheduled_drying_prune is None
  6170. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  6171. ):
  6172. self._last_scheduled_drying_prune = since_prune
  6173. await db.execute(
  6174. delete(ScheduledDrying).where(
  6175. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  6176. ScheduledDrying.completed_at.is_not(None),
  6177. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  6178. )
  6179. )
  6180. # Same order as the list route: with two rows due on one printer the
  6181. # earliest scheduled wins rather than whatever the DB hands back first.
  6182. result = await db.execute(
  6183. select(ScheduledDrying)
  6184. .where(ScheduledDrying.status.in_(("pending", "running")))
  6185. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  6186. )
  6187. rows = list(result.scalars().all())
  6188. # Rebuild from the DB every tick so route-side cancels and completions
  6189. # show up. Auto-drying's stop-all branches check this set before
  6190. # stopping anything (#2638).
  6191. # Kept from the previous pass so a run that ended between passes — a
  6192. # cancel through the route, say — can still be released below.
  6193. previously_running = self._scheduled_drying_printer_ids
  6194. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6195. running_printer_ids = set(self._scheduled_drying_printer_ids)
  6196. # Model and firmware come from the printer row, not the live state.
  6197. printer_ids = {row.printer_id for row in rows}
  6198. printers_by_id: dict[int, Printer] = {}
  6199. if printer_ids:
  6200. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  6201. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  6202. for row in rows:
  6203. if row.status == "running":
  6204. self._update_running_scheduled_drying(row, now)
  6205. continue
  6206. if row.start_after is not None and row.start_after > now:
  6207. continue
  6208. state = printer_manager.get_status(row.printer_id)
  6209. if not state:
  6210. row.waiting_reason = "printer_offline"
  6211. continue
  6212. # Same preflight the immediate endpoint runs. Without it the publish
  6213. # succeeds, the row goes to running, the printer ignores the command
  6214. # and the run silently cancels itself after the grace window.
  6215. printer = printers_by_id.get(row.printer_id)
  6216. unsupported = drying_preflight.check_drying_supported(
  6217. printer.model if printer else None, state.firmware_version
  6218. )
  6219. if unsupported:
  6220. row.status = "failed"
  6221. row.error_message = unsupported
  6222. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6223. row.completed_at = now
  6224. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6225. continue
  6226. if (
  6227. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6228. ) or row.printer_id in running_printer_ids:
  6229. row.waiting_reason = "already_drying"
  6230. continue
  6231. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6232. row.waiting_reason = "printer_busy"
  6233. continue
  6234. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6235. if target is None:
  6236. row.waiting_reason = "ams_not_found"
  6237. continue
  6238. blocking = drying_preflight.blocking_reason_codes(target)
  6239. if blocking:
  6240. # Keep the power case distinct; it needs the user to act, so the
  6241. # card can say so instead of waiting silently.
  6242. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6243. continue
  6244. filament = drying_preflight.resolve_filament(target, row.filament)
  6245. logger.info(
  6246. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6247. row.id,
  6248. row.printer_id,
  6249. row.ams_id,
  6250. row.temp,
  6251. row.duration_hours,
  6252. )
  6253. success = printer_manager.send_drying_command(
  6254. row.printer_id,
  6255. row.ams_id,
  6256. row.temp,
  6257. row.duration_hours,
  6258. mode=1,
  6259. filament=filament,
  6260. rotate_tray=row.rotate_tray,
  6261. )
  6262. if success:
  6263. row.status = "running"
  6264. row.started_at = now
  6265. row.waiting_reason = None
  6266. row.filament = filament
  6267. self._drying_in_progress[row.printer_id] = time.monotonic()
  6268. self._scheduled_drying_printer_ids.add(row.printer_id)
  6269. running_printer_ids.add(row.printer_id)
  6270. else:
  6271. row.waiting_reason = "printer_offline"
  6272. # Release the printers whose run has ended. `_drying_in_progress` is
  6273. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6274. # but that call sits behind the auto-drying enabled check, and this
  6275. # method is the one writer that runs whether auto-drying is on or not.
  6276. # With it off, nothing would ever drop the entry short of a print being
  6277. # dispatched to the same printer, so the next scheduled run would wait
  6278. # on "already_drying" forever and `queue_drying_block` would hold the
  6279. # printer's prints too. Covers a run that ended during this pass and one
  6280. # cancelled through the route between passes.
  6281. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6282. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6283. self._drying_in_progress.pop(printer_id, None)
  6284. await db.commit()
  6285. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6286. """Detect completion or interruption of a running scheduled drying.
  6287. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6288. drying. Within the grace window after start we ignore dry_time==0
  6289. (the status lags the command). After that, dry_time==0 near the end
  6290. of the configured duration means completed. Much earlier means the
  6291. run was stopped: re-queue it if a print preempted the dryer, but a
  6292. stop while the printer is idle was deliberate, so cancel the row
  6293. rather than restart drying the user just stopped.
  6294. """
  6295. if row.started_at is None:
  6296. row.started_at = now
  6297. return
  6298. elapsed = (now - row.started_at).total_seconds()
  6299. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6300. return
  6301. state = printer_manager.get_status(row.printer_id)
  6302. if not state:
  6303. return # offline mid-dry; resolve when it reconnects
  6304. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6305. # throw on a malformed id would cost the whole pass including print
  6306. # dispatch, every tick.
  6307. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6308. try:
  6309. dry_time = int(target.get("dry_time") or 0) if target else 0
  6310. except (TypeError, ValueError):
  6311. dry_time = 0
  6312. if dry_time > 0 and is_countdown_parked(target):
  6313. # The printer took the command but the countdown is not running
  6314. # (#2896) and will never reach 0, so the run would stay "running"
  6315. # forever. A print in progress is the likely cause (the power budget
  6316. # is spent), so re-queue it like any interruption; the next start
  6317. # waits for the printer to be idle. Parked on an idle printer is a
  6318. # refusal, not something a retry fixes. The timer itself is left on
  6319. # the printer: it may yet start once power frees up.
  6320. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6321. logger.info(
  6322. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6323. row.id,
  6324. row.ams_id,
  6325. )
  6326. row.status = "pending"
  6327. row.started_at = None
  6328. row.waiting_reason = "interrupted"
  6329. else:
  6330. logger.warning(
  6331. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6332. row.id,
  6333. row.ams_id,
  6334. )
  6335. row.status = "failed"
  6336. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6337. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6338. row.completed_at = now
  6339. return
  6340. if dry_time > 0:
  6341. return
  6342. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6343. row.status = "completed"
  6344. row.completed_at = now
  6345. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6346. row.status = "pending"
  6347. row.started_at = None
  6348. row.waiting_reason = "interrupted"
  6349. else:
  6350. row.status = "cancelled"
  6351. row.completed_at = now
  6352. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6353. """Get all smart plugs associated with a printer."""
  6354. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6355. return list(result.scalars().all())
  6356. @staticmethod
  6357. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6358. """Pick the plug to power-cycle a printer back online with (#2629).
  6359. Only a plug flagged ``controls_printer_power`` can actually bring the
  6360. printer back; waiting for a boot on an accessory (filter fan, lights)
  6361. just burns the power-on timeout and fails the dispatch. Falls back to
  6362. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6363. Callers must pass a non-empty list.
  6364. """
  6365. for plug in auto_on_plugs:
  6366. if plug.controls_printer_power:
  6367. return plug
  6368. return auto_on_plugs[0]
  6369. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6370. # chamber-temperature recommendations BambuStudio ships for the matching
  6371. # filament profile; users can override via Settings → Workflow → Preheat
  6372. # card. "default" applies when a loaded tray's normalised type isn't in
  6373. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6374. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6375. "PLA": 0,
  6376. "PETG": 0,
  6377. "PETG-CF": 40,
  6378. "ABS": 45,
  6379. "ASA": 45,
  6380. "PA": 50,
  6381. "PA-CF": 55,
  6382. "PC": 50,
  6383. "PC-FR": 50,
  6384. "TPU": 0,
  6385. "PVA": 0,
  6386. "default": 0,
  6387. }
  6388. @classmethod
  6389. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6390. """The bundled map under the same key casing a parsed one gets.
  6391. The constant is declared with a lowercase ``default`` because that is
  6392. the key the Settings editor writes and displays. Every read of the map
  6393. happens after ``str(key).upper()``, so handing the constant back as
  6394. declared broke the contract the parser documents: an install that had
  6395. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6396. and the resolution loop's fallback silently found nothing. It read the
  6397. right number only because the bundled default happens to be 0 -- change
  6398. that constant and every unconfigured install would keep preheating to
  6399. zero with no way to tell why.
  6400. """
  6401. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6402. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6403. """Parse the user-configured filament→chamber-target map, falling back
  6404. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6405. are uppercased and the 'default' fallback is always present in the
  6406. returned dict so the resolution loop can index it unconditionally."""
  6407. raw = await self._get_setting(db, "preheat_filament_targets")
  6408. if not raw:
  6409. return self._bundled_preheat_targets()
  6410. try:
  6411. parsed = json.loads(raw)
  6412. if not isinstance(parsed, dict):
  6413. raise ValueError("not an object")
  6414. except (json.JSONDecodeError, ValueError) as exc:
  6415. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6416. return self._bundled_preheat_targets()
  6417. # Coerce values to int; drop unparseable rows so a stray string
  6418. # doesn't crash the loop.
  6419. out: dict[str, int] = {}
  6420. for key, value in parsed.items():
  6421. try:
  6422. out[str(key).upper()] = int(value)
  6423. except (TypeError, ValueError):
  6424. continue
  6425. if "DEFAULT" not in out:
  6426. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6427. return out
  6428. @staticmethod
  6429. def _normalize_filament_type(tray_type: str) -> str:
  6430. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6431. existing drying-preset normalisation (split-at-space, upper-case) so
  6432. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6433. "PA-CF" (no space to split on).
  6434. This is the first stage of ``_resolve_filament_key``, which goes on to
  6435. drop the suffix and consult the alias map; on its own it only decides
  6436. what the tray is called, not which row answers for it.
  6437. Indexing the split rather than testing the input: a tray_type of spaces
  6438. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6439. it through to an IndexError.
  6440. """
  6441. words = (tray_type or "").split()
  6442. return words[0].upper() if words else ""
  6443. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6444. """Per-filament chamber target for one tray's reported type, or 0 when
  6445. the tray is empty / RFID-less and reports no type at all.
  6446. A filled or foamed variant wants its base material's chamber when the
  6447. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6448. not the 0 an unknown type falls to. The specific type is still tried
  6449. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6450. (#2902).
  6451. That lookup is now the shared one, which adds the polyamide aliases on
  6452. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6453. too, rather than the catch-all it was landing on (#3067).
  6454. """
  6455. if not self._normalize_filament_type(tray_type or ""):
  6456. return 0
  6457. key = self._resolve_filament_key(tray_type, targets)
  6458. if key is not None:
  6459. return targets[key]
  6460. # A type the map does not list at all, which is not the same as a tray
  6461. # with nothing in it -- that already returned 0 above.
  6462. return targets.get("DEFAULT", 0)
  6463. def _derive_chamber_target(
  6464. self,
  6465. printer: Printer,
  6466. targets: dict[str, int],
  6467. item: PrintQueueItem | None = None,
  6468. ) -> int:
  6469. """Chamber target for the trays this print actually loads: the max of
  6470. their per-filament targets. Returns 0 when there is nothing to read (no
  6471. status, no AMS telemetry — e.g. external-spool prints) or when every
  6472. tray considered maps to 0, and the chamber phase then short-circuits in
  6473. the main loop.
  6474. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6475. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6476. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6477. plus soak burned ahead of each upload, on a printer whose chamber never
  6478. reaches the target anyway (#2886). An item with no usable mapping falls
  6479. back to scanning every loaded tray: that is the only signal left, and
  6480. narrowing to nothing would skip preheat on prints that genuinely need
  6481. it.
  6482. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6483. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6484. less slots have empty `tray_type` and contribute nothing. The external
  6485. spool is consulted only when the mapping names it (>= 254); it stays
  6486. out of the unnarrowed scan, so an item without a mapping derives from
  6487. the AMS alone exactly as before.
  6488. """
  6489. state = printer_manager.get_status(printer.id)
  6490. if state is None:
  6491. return 0
  6492. raw_data = state.raw_data or {}
  6493. used = _used_global_tray_ids(item)
  6494. ams_list = raw_data.get("ams")
  6495. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6496. if isinstance(ams_list, dict):
  6497. ams_list = ams_list.get("ams") or []
  6498. if not isinstance(ams_list, list):
  6499. ams_list = []
  6500. best = 0
  6501. layout = TrayLayout.from_state(state)
  6502. for ams in ams_list:
  6503. if not isinstance(ams, dict):
  6504. continue
  6505. ams_id = _int_or(ams.get("id"), 0)
  6506. for tray in ams.get("tray") or []:
  6507. # A non-dict entry has never been seen from real firmware, but
  6508. # `.get` on one raises, and nothing between here and
  6509. # `_dispatch_one`'s try/finally catches it — the item would be
  6510. # left holding its dispatch claim. Preheat is best-effort by
  6511. # contract, so step over it instead.
  6512. if not isinstance(tray, dict):
  6513. continue
  6514. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0), layout) not in used:
  6515. continue
  6516. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6517. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN or layout.is_external(t) for t in used):
  6518. for vt in raw_data.get("vt_tray") or []:
  6519. if not isinstance(vt, dict):
  6520. continue
  6521. # `_build_loaded_filaments` addresses external feeds by the id
  6522. # the firmware reports — 255 main, 254 deputy — defaulting to
  6523. # 254 when the field is absent. Same expression here so the two
  6524. # agree on which entry a mapping's 254/255 refers to.
  6525. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6526. continue
  6527. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6528. return best
  6529. def _release_keep_warm(self, pid: int) -> None:
  6530. """Release keep-warm on a printer that left the candidate set.
  6531. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6532. reports the target we set (``entry.held_target``), so a user or
  6533. subsequent print that changed the bed target since is not clobbered.
  6534. Best-effort, never raises.
  6535. The entry is kept, not dropped, when the printer cannot be reached
  6536. right now: a printer that is briefly offline still has a hot bed, and
  6537. holding the entry is what keeps the max-duration timeout applying and
  6538. lets a later tick retry the release. Only a printer that has left the
  6539. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6540. """
  6541. entry = self._keep_warm.get(pid)
  6542. if entry is None:
  6543. return
  6544. state = printer_manager.get_status(pid)
  6545. client = printer_manager.get_client(pid)
  6546. if state is None or client is None:
  6547. logger.debug(
  6548. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6549. pid,
  6550. )
  6551. return
  6552. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6553. if int(cur_bed_target) != entry.held_target:
  6554. # Someone else owns the bed now, so there is nothing of ours to
  6555. # undo and nothing left to track.
  6556. logger.info(
  6557. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6558. pid,
  6559. int(cur_bed_target),
  6560. entry.held_target,
  6561. )
  6562. self._keep_warm.pop(pid, None)
  6563. return
  6564. try:
  6565. client.set_bed_temperature(0)
  6566. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6567. self._keep_warm.pop(pid, None)
  6568. except Exception as exc:
  6569. # Keep the entry so the next tick tries again rather than leaving
  6570. # the bed hot with nothing tracking it.
  6571. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6572. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6573. """Release printers that dropped out of the keep-warm candidate set.
  6574. Called from ``_apply_keep_warm`` on every tick (with the current
  6575. candidate set), and from ``check_queue``'s no-pending-items early
  6576. return (with an empty candidate set) so orphaned holds still get
  6577. released when the queue empties. Also called with an empty candidate
  6578. set when any of the three gate settings toggles off, so a printer
  6579. whose feature was disabled mid-hold gets its bed released.
  6580. Printers being dispatched this tick are excluded from the bed-off
  6581. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6582. transient 0 in between would just churn against preheat. Ownership of
  6583. the hot bed transfers to the preheat rollback pin instead — if the
  6584. dispatch aborts before the print starts (failed upload, cancelled
  6585. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6586. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6587. is the ONLY thing standing between an aborted dispatch and a bed
  6588. left hot with no owner. A successful print start clears the pin and
  6589. the print's own gcode takes over, as usual.
  6590. """
  6591. for _pid in list(self._keep_warm):
  6592. if _pid in active_candidates:
  6593. continue
  6594. if _pid in dispatched:
  6595. handed_over = self._keep_warm.pop(_pid, None)
  6596. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6597. if handed_over is not None:
  6598. self._preheat_pin_bed[_pid] = handed_over.held_target
  6599. continue
  6600. self._release_keep_warm(_pid)
  6601. async def _apply_keep_warm(
  6602. self,
  6603. db: AsyncSession,
  6604. items: list[PrintQueueItem],
  6605. dispatch_ids: list[int] | set[int],
  6606. busy_printers: set[int],
  6607. require_plate_clear: bool,
  6608. ) -> None:
  6609. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6610. When a printer just finished a job (FINISH state) and the next queued
  6611. item needs chamber heating, hold the bed hot so the chamber stays warm
  6612. during the bed-clearing window. The bed is the chamber's heating
  6613. element here, not a print surface — nothing is printing during the
  6614. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6615. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6616. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6617. aftermarket chamber heaters), raised to the item's own parsed
  6618. bed_temperature when that is higher. Items whose archive metadata has
  6619. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6620. get a hold — chamber need is what gates the feature, not metadata.
  6621. Skips entirely for filaments that map to a 0°C chamber target
  6622. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6623. names, so a hot-chamber spool it never touches does not hold the bed of
  6624. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6625. whole unit, as every item was before. Printers being dispatched this
  6626. cycle are excluded:
  6627. ``_preheat_and_soak`` already handles their bed temperature.
  6628. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6629. released to 0 and the entry is latched ``expired=True`` so
  6630. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6631. MQTT: publish is skipped when firmware already has the target.
  6632. The release sweep runs BEFORE the engagement gate so a printer that
  6633. was owned by keep-warm still gets its bed released when any of the
  6634. three gate settings is toggled off mid-hold. The
  6635. ``check_queue`` early-return-when-no-items path also calls
  6636. ``_sweep_keep_warm`` directly to release orphaned holds.
  6637. """
  6638. dispatch_set = set(dispatch_ids)
  6639. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6640. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6641. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6642. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6643. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6644. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6645. # Release sweep first — must run even when gate_open is False so a
  6646. # printer owned by keep-warm when a gate toggles off gets released.
  6647. self._sweep_keep_warm(
  6648. active_candidates=warm_candidates if gate_open else set(),
  6649. dispatched=dispatched_printers,
  6650. )
  6651. if not gate_open:
  6652. return
  6653. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6654. max_hold_seconds = (
  6655. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6656. )
  6657. now_mono = time.monotonic()
  6658. filament_targets: dict[str, int] | None = None
  6659. for pid in warm_candidates:
  6660. entry = self._keep_warm.get(pid)
  6661. # Latched-expired: max-duration timeout already fired for this
  6662. # printer. Skip until the release sweep drops the entry (i.e.
  6663. # until the printer leaves the candidate set).
  6664. if entry is not None and entry.expired:
  6665. continue
  6666. # These two guards sit ahead of the max-duration check below, so an
  6667. # engaged hold only ages out while its printer is still reachable
  6668. # and still in FINISH. That is deliberate rather than a hole: with
  6669. # no status or no client there is no M140 to send anyway, and the
  6670. # elapsed check runs off `entry.started` so it fires on the first
  6671. # tick after the printer comes back. Leaving FINISH means the plate
  6672. # was cleared, which drops the printer out of `warm_candidates` and
  6673. # hands it to `_release_keep_warm` instead. The invariant worth
  6674. # preserving if this is ever reordered: every path out of an
  6675. # engaged hold ends in a bed-off, whether by timeout or release.
  6676. state = printer_manager.get_status(pid)
  6677. if state is None or state.state != "FINISH":
  6678. continue
  6679. client = printer_manager.get_client(pid)
  6680. if client is None:
  6681. continue
  6682. next_item = next((it for it in items if it.printer_id == pid), None)
  6683. if next_item is None:
  6684. continue
  6685. # Hold temperature: the configured keep-warm temp, raised to the
  6686. # item's own bed temp when the metadata reports a higher one. A
  6687. # missing bed_temperature (Orca gcode.3mf exports parse without
  6688. # one) does NOT skip the hold — chamber need gates the feature.
  6689. archive = next_item.archive
  6690. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6691. bed_target = max(item_bed, hold_temp)
  6692. if bed_target <= 0:
  6693. continue
  6694. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6695. if explicit is not None:
  6696. chamber_needed = int(explicit) > 0
  6697. else:
  6698. if filament_targets is None:
  6699. filament_targets = await self._get_preheat_filament_targets(db)
  6700. printer_obj = await self._get_printer(db, pid)
  6701. chamber_needed = (
  6702. printer_obj is not None
  6703. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6704. )
  6705. if not chamber_needed:
  6706. continue
  6707. # Seed the timer on first engagement; keep it on subsequent ticks
  6708. # (never re-seed — that would defeat the max-duration cap).
  6709. if entry is None:
  6710. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6711. self._keep_warm[pid] = entry
  6712. elapsed = now_mono - entry.started
  6713. if elapsed > max_hold_seconds:
  6714. # Timeout: publish bed → 0 once (if firmware still holds our
  6715. # target) and latch expired. The entry stays until the release
  6716. # sweep drops it, preventing the next tick from re-seeding.
  6717. logger.warning(
  6718. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6719. pid,
  6720. elapsed,
  6721. )
  6722. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6723. if int(cur_bed_target) == entry.held_target:
  6724. try:
  6725. client.set_bed_temperature(0)
  6726. except Exception as exc:
  6727. logger.warning(
  6728. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6729. pid,
  6730. exc,
  6731. )
  6732. else:
  6733. logger.info(
  6734. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6735. pid,
  6736. int(cur_bed_target),
  6737. entry.held_target,
  6738. )
  6739. entry.expired = True
  6740. continue
  6741. # Idempotence: skip publish when firmware already has our target.
  6742. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6743. if int(cur_bed_target) == bed_target:
  6744. entry.held_target = bed_target
  6745. continue
  6746. try:
  6747. client.set_bed_temperature(bed_target)
  6748. entry.held_target = bed_target
  6749. logger.info(
  6750. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6751. bed_target,
  6752. pid,
  6753. )
  6754. except Exception as exc:
  6755. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6756. def _sample_chamber_temps(self) -> None:
  6757. """Record a chamber temperature sample for every connected printer.
  6758. Called once per scheduler tick (every 3–30 s). Entries older than
  6759. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6760. Also evicts per-printer state whose printer_id is no longer registered
  6761. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6762. """
  6763. now = time.monotonic()
  6764. cutoff = now - self._chamber_history_ttl
  6765. statuses = printer_manager.get_all_statuses()
  6766. known_pids = set(statuses.keys())
  6767. for pid, status in statuses.items():
  6768. if status is None or not status.connected:
  6769. continue
  6770. temps = status.temperatures or {}
  6771. chamber = temps.get("chamber")
  6772. if chamber is None:
  6773. continue
  6774. hist = self._chamber_history.setdefault(pid, deque())
  6775. hist.append((now, float(chamber)))
  6776. while hist and hist[0][0] < cutoff:
  6777. hist.popleft()
  6778. # Evict state for printers that are no longer registered with the manager.
  6779. # This is the one place a keep-warm entry is dropped without releasing
  6780. # the bed: the printer is gone from the manager, so there is no client
  6781. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6782. # for printers that are merely unreachable, which is what makes this
  6783. # the terminal case rather than a silent leak.
  6784. for pid in list(self._chamber_history):
  6785. if pid not in known_pids:
  6786. self._chamber_history.pop(pid, None)
  6787. for pid in list(self._keep_warm):
  6788. if pid not in known_pids:
  6789. logger.info(
  6790. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6791. pid,
  6792. )
  6793. self._keep_warm.pop(pid, None)
  6794. for pid in list(self._preheat_pin):
  6795. if pid not in known_pids:
  6796. self._preheat_pin.pop(pid, None)
  6797. self._preheat_pin_bed.pop(pid, None)
  6798. def _chamber_soak_remaining(
  6799. self,
  6800. printer_id: int,
  6801. chamber_target: float,
  6802. soak_seconds: int,
  6803. tolerance: float = 2.0,
  6804. ) -> int:
  6805. """Return how many seconds of soak time are still needed.
  6806. Credits the time the chamber has already spent at temperature against
  6807. the configured soak. The credit may not start earlier than any of:
  6808. * **The newest sample.** Nothing recent means the printer stopped
  6809. reporting mid-observation and the chamber may have cooled unseen, so
  6810. the full soak is required. (A 2 h history whose last reading is half
  6811. an hour old is not evidence of anything — the measured cooling rate
  6812. is fast enough to cross the threshold in that time.)
  6813. * **The most recent contiguous run of samples.** A gap wider than
  6814. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6815. far side is not evidence of temperature.
  6816. * **The end of the most recent real dip below the threshold.**
  6817. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6818. — see that constant for the thermal reasoning. A stray low reading is
  6819. an artifact, and treating it as cooling would discard a soak that
  6820. actually happened.
  6821. Returns ``soak_seconds`` when nothing can be credited (no history,
  6822. stale history, or the chamber is below the threshold right now) and 0
  6823. once the credited time covers the whole soak.
  6824. """
  6825. hist = self._chamber_history.get(printer_id)
  6826. if not hist:
  6827. return soak_seconds
  6828. now = time.monotonic()
  6829. newest_ts, newest_temp = hist[-1]
  6830. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6831. return soak_seconds # stale — no fresh evidence to credit
  6832. threshold = chamber_target - tolerance
  6833. if newest_temp < threshold:
  6834. return soak_seconds # below target right now; nothing is soaked
  6835. samples = list(hist)
  6836. # Earliest point we have unbroken observations for.
  6837. credit_from = samples[-1][0]
  6838. for i in range(len(samples) - 1, 0, -1):
  6839. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6840. break
  6841. credit_from = samples[i - 1][0]
  6842. # Pull the credit forward to the end of the last significant dip. Each
  6843. # excursion is measured between the in-range readings that bracket it,
  6844. # so a lone stray sample is charged one sampling interval rather than
  6845. # zero, and the comparison errs towards calling a dip real.
  6846. i = 0
  6847. while i < len(samples):
  6848. if samples[i][1] >= threshold:
  6849. i += 1
  6850. continue
  6851. j = i
  6852. while j < len(samples) and samples[j][1] < threshold:
  6853. j += 1
  6854. # `newest_temp >= threshold` was checked above, so j is in range.
  6855. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6856. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6857. # Credit resumes at the last below-threshold sample rather than
  6858. # the first good one after it, so a recovered dip over-credits
  6859. # by up to one sampling interval — the opposite lean to the
  6860. # bracketing above. Both are bounded by the sample cadence and
  6861. # dwarfed by the grace period, so neither is worth the extra
  6862. # arithmetic to remove.
  6863. credit_from = max(credit_from, samples[j - 1][0])
  6864. i = j
  6865. return max(0, soak_seconds - int(now - credit_from))
  6866. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6867. """Tell an in-flight dispatch that its item no longer wants to print.
  6868. Called by the queue's cancel and delete routes. Those only write to the
  6869. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6870. observe — so preheat would keep heating for the rest of max_wait + soak
  6871. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6872. blocking every other queued item behind a print that is not happening.
  6873. Signalling in memory rather than re-reading the row keeps this off the
  6874. database entirely: no second session, no transaction held across a long
  6875. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6876. Bambuddy serves from a single uvicorn process with one scheduler task,
  6877. so the route and the dispatch always share this object. The flag is
  6878. advisory — dropping it (e.g. after a restart) only costs a wasted
  6879. preheat, never a wrongly-abandoned print.
  6880. Only ids with a dispatch actually in flight are recorded, so the set
  6881. stays bounded by the upload pool rather than growing once per cancelled
  6882. item for the life of the process. Skipping the rest loses nothing: an
  6883. item that is not in flight cannot start heating later either, because
  6884. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6885. the caller has already committed a terminal status (or deleted the row)
  6886. before calling this.
  6887. """
  6888. if item_id in self._inflight:
  6889. self._cancelled_dispatches.add(item_id)
  6890. # A print sent for it earlier that never started is not one any more.
  6891. self._forget_unstarted_print(item_id, unless_printing=False)
  6892. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6893. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6894. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6895. while it is parked, so the wait is chopped into
  6896. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6897. """
  6898. remaining = float(seconds)
  6899. while remaining > 0:
  6900. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6901. await asyncio.sleep(slice_secs)
  6902. remaining -= slice_secs
  6903. if item_id in self._cancelled_dispatches:
  6904. return False
  6905. return True
  6906. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6907. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6908. The full preheat stage does this as part of its own dispatch: an H2D
  6909. left in heating mode by the ABS job before it would otherwise cook the
  6910. PLA that follows. The skip path never reaches that code, so it calls
  6911. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6912. add to the rollback pin, because a flap set to cooling for a print that
  6913. needs no heat is where it should have been either way.
  6914. Best-effort like everything else in the stage: a refused command logs
  6915. and the dispatch carries on.
  6916. """
  6917. model = printer.model or ""
  6918. if not supports_airduct(model):
  6919. return
  6920. state = printer_manager.get_status(printer.id)
  6921. current = getattr(state, "airduct_mode", None) if state else None
  6922. if current == _AIRDUCT_MODE_COOLING:
  6923. return
  6924. client = printer_manager.get_client(printer.id)
  6925. if client is None:
  6926. return
  6927. try:
  6928. client.set_airduct_mode("cooling")
  6929. except Exception as exc:
  6930. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6931. async def _preheat_and_soak(
  6932. self,
  6933. db: AsyncSession,
  6934. item: PrintQueueItem,
  6935. printer: Printer,
  6936. archive: PrintArchive | None,
  6937. ) -> bool:
  6938. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6939. Returns True when the dispatch should carry on to the upload — including
  6940. every case where preheat is skipped, since a skipped preheat is not a
  6941. reason to abandon the print. Returns False only when the item stopped
  6942. wanting to be printed while the stage was waiting (cancelled or
  6943. deleted); the caller must then abandon the dispatch, and
  6944. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6945. Resolution order:
  6946. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6947. to the global `preheat_enabled` setting; 'on' forces the stage on
  6948. even if the global is off.
  6949. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6950. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6951. across the trays `item.ams_mapping` names (every loaded slot when
  6952. it names none).
  6953. 3. A target of 0 off the filament map skips the whole stage: the
  6954. materials this print loads want no chamber, so there is nothing to
  6955. soak for and the bed phase would only delay the upload (#3041).
  6956. An explicit 0 typed into the per-item override, or a per-item
  6957. 'on', still runs the bed phase and the soak — both are the user
  6958. asking for a warm bed in so many words.
  6959. 4. Three hardware tiers branch the wait loop:
  6960. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6961. send M141 to the resolved target, then wait for the chamber sensor
  6962. to reach it (or the max-wait timeout to elapse).
  6963. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6964. no M141; the bed is the only heat source, so we wait for the chamber
  6965. sensor to rise via bed radiation OR fall through on timeout.
  6966. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6967. temperature; the function just heats the bed and holds for the
  6968. configured soak duration.
  6969. The bed target comes from the archive's parsed metadata
  6970. (`bed_temperature`); if missing the preheat stage logs and returns
  6971. without dispatching anything, rather than guessing at a default that
  6972. might wreck filament setup.
  6973. Failures are logged but never re-raised — preheat is best-effort. A
  6974. printer that goes offline mid-soak, a refused gcode command, or a
  6975. missing temperature reading must not turn into a failed queue item; the
  6976. normal upload + start path runs immediately after this method returns.
  6977. """
  6978. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6979. if override == "off":
  6980. return True
  6981. if override == "inherit":
  6982. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6983. if not enabled:
  6984. return True
  6985. # override == "on" forces the stage on regardless of the global setting.
  6986. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6987. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6988. # Chamber target resolution:
  6989. # 1. Explicit per-item override beats everything (user knows best).
  6990. # 2. Otherwise derive from the filament types this print loads, via
  6991. # the per-filament target map. A PLA-only print derives 0 and the
  6992. # block below skips the stage without the user touching anything,
  6993. # even when an ASA spool is sitting in another slot of the same
  6994. # AMS (#2886).
  6995. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6996. if explicit_target is not None and explicit_target > 0:
  6997. chamber_target = int(explicit_target)
  6998. chamber_source = "item-override"
  6999. elif explicit_target == 0:
  7000. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  7001. chamber_source = "item-override-zero"
  7002. else:
  7003. targets = await self._get_preheat_filament_targets(db)
  7004. chamber_target = self._derive_chamber_target(printer, targets, item)
  7005. chamber_source = "filament-map"
  7006. # Nothing to preheat *for*. A zero that came out of the filament map is
  7007. # the map saying this print's materials want no chamber conditioning --
  7008. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  7009. # anyway heated the bed and then held it for the full soak, which
  7010. # delayed every PLA dispatch by minutes and bought nothing: the print's
  7011. # own G-code sets the bed the moment it starts, so preheating it here
  7012. # only moves that heating ahead of the upload instead of overlapping
  7013. # with it, and the soak has no chamber to condition (#3041).
  7014. #
  7015. # An explicit statement from the user still runs the stage. Forcing the
  7016. # per-item override to 'on', or typing a chamber target of exactly 0,
  7017. # both mean "preheat the bed for this print" -- the second is
  7018. # documented as doing precisely that. Only the automatic path, the
  7019. # global toggle plus the filament map, short-circuits here.
  7020. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  7021. logger.info(
  7022. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  7023. "target, so there is nothing to soak for (override=%s model=%s)",
  7024. item.id,
  7025. override,
  7026. printer.model or "",
  7027. )
  7028. self._preheat_flap_to_cooling(item.id, printer)
  7029. return True
  7030. bed_target = await _queued_plate_bed_temperature(item, archive)
  7031. if bed_target <= 0:
  7032. # No bed temperature in the slicer metadata. When the print needs a
  7033. # hot chamber the bed is simply how we heat it, so fall back to the
  7034. # configured chamber-heating bed temperature rather than skipping
  7035. # the whole stage — otherwise the print starts with a cold chamber,
  7036. # which is exactly what preheat exists to prevent. Without a chamber
  7037. # requirement there is nothing to preheat *for*, so skip as before
  7038. # rather than guess a bed temperature for the print itself.
  7039. if chamber_target <= 0:
  7040. logger.info(
  7041. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  7042. item.id,
  7043. )
  7044. return True
  7045. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  7046. logger.info(
  7047. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  7048. "%d°C to drive the chamber to %d°C",
  7049. item.id,
  7050. bed_target,
  7051. chamber_target,
  7052. )
  7053. client = printer_manager.get_client(printer.id)
  7054. if client is None:
  7055. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  7056. return True
  7057. model = printer.model or ""
  7058. has_heater = supports_chamber_heater(model)
  7059. has_sensor = supports_chamber_temp(model)
  7060. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  7061. # Fast path: if the chamber has been continuously above target for at
  7062. # least soak_seconds and the bed is already at temperature, skip the
  7063. # entire preheat stage. Typical case: keep-warm held the bed between
  7064. # consecutive same-material prints and the chamber never dropped.
  7065. if do_chamber and has_sensor and soak_seconds > 0:
  7066. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7067. if remaining == 0:
  7068. cur = printer_manager.get_status(printer.id)
  7069. if cur:
  7070. cur_temps = cur.temperatures or {}
  7071. if (
  7072. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  7073. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  7074. ):
  7075. logger.info(
  7076. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  7077. "and bed is already at temperature (chamber history fast-path)",
  7078. item.id,
  7079. chamber_target,
  7080. soak_seconds,
  7081. )
  7082. # Still set targets to prevent cooling during the 3MF upload window.
  7083. # Register each successful set in the preheat pin so `_dispatch_one`
  7084. # unwinds them on any non-success exit.
  7085. pin = self._preheat_pin.setdefault(printer.id, set())
  7086. try:
  7087. client.set_bed_temperature(bed_target)
  7088. pin.add("bed")
  7089. self._preheat_pin_bed[printer.id] = bed_target
  7090. except Exception as exc:
  7091. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  7092. if supports_airduct(model):
  7093. cur_airduct = getattr(cur, "airduct_mode", None)
  7094. if cur_airduct != _AIRDUCT_MODE_HEATING:
  7095. try:
  7096. client.set_airduct_mode("heating")
  7097. # Only undo what we can see we replaced. `None`
  7098. # means no mode has been observed yet, and
  7099. # rolling that back to cooling would assert a
  7100. # state the printer never reported.
  7101. if cur_airduct == _AIRDUCT_MODE_COOLING:
  7102. pin.add("airduct")
  7103. except Exception as exc:
  7104. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  7105. if has_heater:
  7106. try:
  7107. client.set_chamber_temperature(chamber_target)
  7108. pin.add("chamber")
  7109. except Exception as exc:
  7110. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  7111. return True
  7112. logger.info(
  7113. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  7114. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  7115. item.id,
  7116. bed_target,
  7117. chamber_target if do_chamber else 0,
  7118. chamber_source,
  7119. override,
  7120. model,
  7121. has_heater,
  7122. has_sensor,
  7123. max_wait,
  7124. soak_seconds,
  7125. )
  7126. # Preheat rollback registry: everything we set below is recorded here so
  7127. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  7128. # (bed off, chamber off, airduct back to cooling) on any non-success
  7129. # exit. Populated as each command succeeds; consumed and cleared by
  7130. # `_dispatch_one`.
  7131. pin = self._preheat_pin.setdefault(printer.id, set())
  7132. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  7133. # cache the target locally so the polling reads below see consistent
  7134. # state (firmware MQTT echoes lag by ~1s).
  7135. try:
  7136. client.set_bed_temperature(bed_target)
  7137. pin.add("bed")
  7138. self._preheat_pin_bed[printer.id] = bed_target
  7139. except Exception as exc:
  7140. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  7141. return True
  7142. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  7143. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  7144. # left it on, regardless of M141. Default cooling actively vents the
  7145. # chamber, so a `chamber_target > 0` print with the flap stuck in
  7146. # cooling never converges — the heater fights the open exhaust. We
  7147. # flip the flap BEFORE M141 to "heating" when the preheat wants
  7148. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  7149. # on an H2D that was previously running ABS would otherwise stay in
  7150. # heating mode and overheat PLA). The current-state read keeps the
  7151. # command idempotent — no MQTT chatter when the flap is already where
  7152. # we want it.
  7153. if supports_airduct(model):
  7154. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  7155. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  7156. current_state = printer_manager.get_status(printer.id)
  7157. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  7158. if current_airduct != desired_id:
  7159. try:
  7160. client.set_airduct_mode(desired_airduct)
  7161. # As in the fast path: only pin a rollback for a flap we
  7162. # saw in cooling. `current_airduct` of None means no mode
  7163. # has been observed, so there is nothing to restore to.
  7164. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  7165. pin.add("airduct")
  7166. except Exception as exc:
  7167. logger.warning(
  7168. "Queue item %s: preheat airduct %s mode failed: %s",
  7169. item.id,
  7170. desired_airduct,
  7171. exc,
  7172. )
  7173. if do_chamber and has_heater:
  7174. try:
  7175. client.set_chamber_temperature(chamber_target)
  7176. pin.add("chamber")
  7177. except Exception as exc:
  7178. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  7179. # Release the pooled DB connection before the (potentially many-minute)
  7180. # heat-soak wait below (#2572). Every setting this method needs is read
  7181. # above; the wait/soak loop only polls printer_manager state and sleeps —
  7182. # it never touches the DB. Without this the caller's transaction sat
  7183. # "idle in transaction" for the whole soak, pinning one pooled connection
  7184. # per preheating printer. expire_on_commit=False keeps item/printer
  7185. # readable afterwards; there are no pending writes to lose here.
  7186. await db.commit()
  7187. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  7188. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  7189. # Poll every 3s — frequent enough for responsive logging without
  7190. # spamming the MQTT state stream. The "converged" predicate is:
  7191. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  7192. # AND
  7193. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  7194. BED_TOLERANCE = 2.0
  7195. CHAMBER_TOLERANCE = 2.0
  7196. POLL_INTERVAL = 3.0
  7197. deadline = asyncio.get_event_loop().time() + max_wait
  7198. while True:
  7199. state = printer_manager.get_status(printer.id)
  7200. if state is None:
  7201. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  7202. break
  7203. temps = state.temperatures or {}
  7204. bed_now = float(temps.get("bed", 0) or 0)
  7205. chamber_now = float(temps.get("chamber", 0) or 0)
  7206. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  7207. if not do_chamber:
  7208. chamber_ok = True # phase disabled or model has neither sensor nor heater
  7209. elif not has_sensor:
  7210. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  7211. else:
  7212. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  7213. if bed_ok and chamber_ok:
  7214. logger.info(
  7215. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  7216. item.id,
  7217. bed_now,
  7218. chamber_now,
  7219. )
  7220. break
  7221. if asyncio.get_event_loop().time() >= deadline:
  7222. logger.info(
  7223. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7224. item.id,
  7225. bed_now,
  7226. bed_target,
  7227. chamber_now,
  7228. chamber_target if do_chamber else 0,
  7229. )
  7230. break
  7231. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7232. logger.info(
  7233. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7234. item.id,
  7235. )
  7236. return False
  7237. if soak_seconds > 0:
  7238. if do_chamber and has_sensor:
  7239. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7240. else:
  7241. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7242. if remaining > 0:
  7243. logger.info(
  7244. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7245. "has been above target for ~%ds already)",
  7246. item.id,
  7247. remaining,
  7248. soak_seconds,
  7249. soak_seconds - remaining,
  7250. )
  7251. if not await self._preheat_sleep(item.id, remaining):
  7252. logger.info(
  7253. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7254. item.id,
  7255. )
  7256. return False
  7257. else:
  7258. logger.info(
  7259. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7260. item.id,
  7261. chamber_target,
  7262. soak_seconds,
  7263. )
  7264. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7265. return True
  7266. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7267. """Turn on smart plug and wait for printer to connect.
  7268. Returns True if printer connected successfully within timeout.
  7269. """
  7270. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7271. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7272. # Check current plug state
  7273. status = await service.get_status(plug)
  7274. if not status.get("reachable"):
  7275. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7276. return False
  7277. # Turn on if not already on
  7278. if status.get("state") != "ON":
  7279. success = await service.turn_on(plug)
  7280. if not success:
  7281. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7282. return False
  7283. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7284. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7285. # Get printer from database for connection
  7286. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7287. printer = result.scalar_one_or_none()
  7288. if not printer:
  7289. logger.error("Printer %s not found in database", printer_id)
  7290. return False
  7291. # End the pass's transaction before waiting up to minutes for the boot:
  7292. # held open, it pins a pooled connection idle in transaction
  7293. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7294. # through it.
  7295. await db.commit()
  7296. # Wait for printer to boot (give it some time before trying to connect)
  7297. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7298. await asyncio.sleep(30)
  7299. # Try to connect to the printer periodically
  7300. elapsed = 30 # Already waited 30s
  7301. while elapsed < self._power_on_wait_time:
  7302. # Try to connect
  7303. logger.info("Attempting to connect to printer %s...", printer_id)
  7304. try:
  7305. connected = await printer_manager.connect_printer(printer)
  7306. if connected:
  7307. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7308. # Give it a moment to stabilize and get status
  7309. await asyncio.sleep(5)
  7310. return True
  7311. except Exception as e:
  7312. logger.debug("Connection attempt failed: %s", e)
  7313. await asyncio.sleep(self._power_on_check_interval)
  7314. elapsed += self._power_on_check_interval
  7315. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7316. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7317. return False
  7318. async def _check_previous_success(
  7319. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7320. ) -> bool:
  7321. """Check if the previous print on this printer succeeded.
  7322. ``printer_id`` names the printer to look at when the item has none yet
  7323. (a job for any printer of a model, checked against the one offered).
  7324. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7325. deliberate action, not a failure, so subsequent items should still
  7326. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7327. a skip isn't an actual print attempt, so it must not gate downstream
  7328. items — counting it as a failed predecessor was the cascade bug that
  7329. let a single cancellation block 18 items over 3 days for the reporter.
  7330. Only `failed` and `aborted` — real print-attempt failures — block.
  7331. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7332. action — #1818) are also excluded from the lookback so the user can
  7333. clear the gate after fixing the physical issue without having to
  7334. re-queue every downstream job.
  7335. """
  7336. result = await db.execute(
  7337. select(PrintQueueItem)
  7338. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7339. .where(PrintQueueItem.id != item.id)
  7340. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7341. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7342. # A row ended without a completion time must not count as the
  7343. # latest: PostgreSQL sorts NULL first in a descending order.
  7344. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7345. .limit(1)
  7346. )
  7347. prev_item = result.scalar_one_or_none()
  7348. # If no previous item, assume success (first in queue)
  7349. if not prev_item:
  7350. return True
  7351. return prev_item.status in ("completed", "cancelled")
  7352. def _hold_archive(self, item_id: int, archive_id: int) -> None:
  7353. """Hold the archive a dispatch prints into until it ends (archive_work)."""
  7354. from backend.app.services import archive_work
  7355. self._release_held_archive(item_id)
  7356. archive_work.hold(archive_id)
  7357. self._held_archives[item_id] = archive_id
  7358. def _release_held_archive(self, item_id: int) -> None:
  7359. from backend.app.services import archive_work
  7360. if (archive_id := self._held_archives.pop(item_id, None)) is not None:
  7361. archive_work.release(archive_id)
  7362. @staticmethod
  7363. async def _printing_elsewhere(db: AsyncSession, archive_id: int) -> bool:
  7364. """Whether a print of the archive is running (its run open)."""
  7365. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7366. return (
  7367. await db.scalar(
  7368. select(PrintLogEntry.id)
  7369. .where(PrintLogEntry.archive_id == archive_id, PrintLogEntry.status == RUN_OPEN)
  7370. .limit(1)
  7371. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7372. )
  7373. is not None
  7374. )
  7375. @staticmethod
  7376. async def _vp_prefers_filename(db: AsyncSession, library_file: LibraryFile) -> bool:
  7377. """Whether a virtual printer's upload names its archive after the file.
  7378. Settings > Virtual Printer chooses between the file name and the title
  7379. in the 3MF for the archives of uploads; other files keep the default.
  7380. """
  7381. from backend.app.api.routes.settings import get_setting
  7382. from backend.app.services.virtual_printer.library_store import SOURCE_TYPE
  7383. if library_file.source_type != SOURCE_TYPE:
  7384. return False
  7385. return (await get_setting(db, "virtual_printer_archive_name_source")) == "filename"
  7386. async def _claim_reusable_archive(
  7387. self, db: AsyncSession, item: PrintQueueItem, file_path: Path
  7388. ) -> PrintArchive | None:
  7389. """The archive a library dispatch adds its run to, or None for a new one.
  7390. The same file of the same owner, in the same project, archived from
  7391. this library file or from none (one since deleted, or a print started
  7392. elsewhere), with its copy of the file still on disk. Also while it is
  7393. printing, queued or finishing elsewhere: each print of an archive is
  7394. its own run, with its own start, end, charge, energy, outcome,
  7395. timelapse and photos (archive redesign), as for the copies of a batch.
  7396. """
  7397. from backend.app.services.archive import ArchiveService
  7398. # Off the file as it is now: the stored hash is not refreshed when the
  7399. # file changes on disk (an external folder, overwritten in place).
  7400. content_hash = await asyncio.to_thread(ArchiveService.compute_file_hash, file_path)
  7401. owner = (
  7402. PrintArchive.created_by_id.is_(None)
  7403. if item.created_by_id is None
  7404. else PrintArchive.created_by_id == item.created_by_id
  7405. )
  7406. project = (
  7407. PrintArchive.project_id.is_(None) if item.project_id is None else PrintArchive.project_id == item.project_id
  7408. )
  7409. candidates = (
  7410. await db.scalars(
  7411. select(PrintArchive)
  7412. .where(
  7413. PrintArchive.content_hash == content_hash,
  7414. owner,
  7415. project,
  7416. or_(PrintArchive.library_file_id == item.library_file_id, PrintArchive.library_file_id.is_(None)),
  7417. PrintArchive.deleted_at.is_(None),
  7418. )
  7419. .order_by(PrintArchive.id.desc())
  7420. )
  7421. ).all()
  7422. from backend.app.services import archive_work
  7423. for candidate in candidates:
  7424. # Not one a merge is moving into another archive right now; held
  7425. # from here, with no await between, until the dispatch ends.
  7426. if archive_work.is_merging(candidate.id):
  7427. continue
  7428. if candidate.file_path and (settings.base_dir / candidate.file_path).is_file():
  7429. self._hold_archive(item.id, candidate.id)
  7430. return candidate
  7431. return None
  7432. async def _repoint_siblings_at_archive(
  7433. self,
  7434. db: AsyncSession,
  7435. *,
  7436. consumed_library_file_id: int,
  7437. archive_id: int,
  7438. dispatched_item_id: int,
  7439. ) -> int:
  7440. """Move the other queue items off a library row that is about to be deleted (#2819).
  7441. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7442. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7443. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7444. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7445. clones, so the first dispatch could pull the file out from under rows that
  7446. had not run yet. What those rows did next depended on the database, and
  7447. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7448. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7449. they were left pointing at a row that no longer existed, failing with
  7450. "Library file not found" whenever someone started them -- or sitting
  7451. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7452. constraint, so there the rows were deleted outright and the queued copies
  7453. simply vanished, with no error and no history.
  7454. The archive holds its own copy of the 3MF, so the remaining copies can print
  7455. from it instead. Two things happen here, and both must happen *before* the
  7456. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7457. * every row still naming the file has ``library_file_id`` cleared, which is
  7458. what takes it out of the cascade's reach. That covers rows this cannot
  7459. re-point as well -- a copy already printing from its own archive, and the
  7460. finished ones, which are not spare parts but the record a batch order
  7461. counts its progress from.
  7462. * the rows that still need something to print are pointed at the archive.
  7463. Returns how many items were re-pointed.
  7464. """
  7465. variant_item_ids = (
  7466. (
  7467. await db.execute(
  7468. select(PrintQueueVariant.queue_item_id).where(
  7469. PrintQueueVariant.library_file_id == consumed_library_file_id
  7470. )
  7471. )
  7472. )
  7473. .scalars()
  7474. .all()
  7475. )
  7476. # Candidate rows naming the consumed file have to go rather than be
  7477. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7478. # one out of the cascade. This is what PostgreSQL already does, and
  7479. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7480. # outcome changes -- the two backends simply stop disagreeing about
  7481. # whether the row is still there.
  7482. #
  7483. # It also has to happen before the re-point below: a cross-model item
  7484. # (#671) picks a variant every pass and folds it onto the row, and
  7485. # _resolve_variant clears archive_id as it does so, which would undo the
  7486. # re-point on the very next lap.
  7487. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7488. # An item left with other candidates still has somewhere to go, and those
  7489. # carry their own target model -- pointing it at this archive would print a
  7490. # file the matcher never chose. It is excluded from the re-point and simply
  7491. # re-resolves against what is left.
  7492. surviving_variant_item_ids = set(
  7493. (
  7494. await db.execute(
  7495. select(PrintQueueVariant.queue_item_id).where(
  7496. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7497. )
  7498. )
  7499. )
  7500. .scalars()
  7501. .all()
  7502. )
  7503. repoint_ids = set(
  7504. (
  7505. await db.execute(
  7506. select(PrintQueueItem.id)
  7507. .where(PrintQueueItem.id != dispatched_item_id)
  7508. .where(PrintQueueItem.archive_id.is_(None))
  7509. # "skipped" belongs here with the two live states: it is not
  7510. # terminal. Clearing a printer's previous-success gate puts
  7511. # every item skipped by it back to "pending"
  7512. # (resume_after_failure), and one restored onto a deleted
  7513. # file is the same orphan by a slower route. "failed",
  7514. # "cancelled", "aborted" and "completed" never return.
  7515. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7516. .where(
  7517. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7518. )
  7519. .where(
  7520. or_(
  7521. PrintQueueItem.library_file_id == consumed_library_file_id,
  7522. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7523. )
  7524. )
  7525. )
  7526. )
  7527. .scalars()
  7528. .all()
  7529. )
  7530. if repoint_ids:
  7531. await db.execute(
  7532. update(PrintQueueItem)
  7533. .where(PrintQueueItem.id.in_(repoint_ids))
  7534. .values(
  7535. archive_id=archive_id,
  7536. library_file_id=None,
  7537. # The file this flag named is already consumed. Leaving it set
  7538. # would arm every re-pointed copy to delete whatever library
  7539. # row it is next given.
  7540. cleanup_library_after_dispatch=False,
  7541. )
  7542. )
  7543. logger.info(
  7544. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7545. sorted(repoint_ids),
  7546. archive_id,
  7547. consumed_library_file_id,
  7548. dispatched_item_id,
  7549. )
  7550. # Everything else that still names the file: taken out of the cascade's
  7551. # reach without touching what it prints. The file is gone either way; what
  7552. # this preserves is the row.
  7553. await db.execute(
  7554. update(PrintQueueItem)
  7555. .where(PrintQueueItem.id != dispatched_item_id)
  7556. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7557. .values(library_file_id=None)
  7558. )
  7559. return len(repoint_ids)
  7560. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7561. """Schedule power-off if the queue item enabled auto_off_after.
  7562. Delegates to the smart-plug manager so the off honours each plug's
  7563. configured strategy (time delay or temperature threshold), is cancelled
  7564. if the printer starts printing again, and never cuts power on a loaded
  7565. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7566. powered off on the timeout regardless of print state.
  7567. """
  7568. if not item.auto_off_after:
  7569. return
  7570. try:
  7571. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7572. except Exception as e:
  7573. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7574. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7575. """Get a human-readable name for a queue item."""
  7576. if item.archive_id:
  7577. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7578. archive = result.scalar_one_or_none()
  7579. if archive:
  7580. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7581. if item.library_file_id:
  7582. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7583. library_file = result.scalar_one_or_none()
  7584. if library_file:
  7585. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7586. # A cross-model item (#671) holds no file of its own until a printer is
  7587. # picked, so name it after its first candidate — otherwise every waiting
  7588. # notification for one reads "Job #12". Queried rather than read off
  7589. # item.variants because callers outside the selection loop have not
  7590. # eager-loaded them, and a lazy load raises in async.
  7591. first_variant_name = (
  7592. await db.execute(
  7593. select(LibraryFile.filename)
  7594. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7595. .where(PrintQueueVariant.queue_item_id == item.id)
  7596. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7597. .limit(1)
  7598. )
  7599. ).scalar_one_or_none()
  7600. if first_variant_name:
  7601. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7602. return f"Job #{item.id}"
  7603. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7604. """Get printer by ID."""
  7605. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7606. return result.scalar_one_or_none()
  7607. async def _notify_dispatch_gave_up(
  7608. self,
  7609. queue_item_id: int,
  7610. printer_id: int,
  7611. created_by_id: int | None,
  7612. reason: str = "Printer accepted the file but never started printing",
  7613. ) -> None:
  7614. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7615. Called from the watchdog, which is a background task with no session of
  7616. its own — hence the fresh one here. Best-effort throughout: the row is
  7617. already marked failed and that is the load-bearing part; a notification
  7618. provider being down must not resurrect the retry loop we just stopped.
  7619. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7620. path passes its own, because "accepted the file but never started" is the
  7621. opposite of what happened there — the printer refused it outright (#2732).
  7622. """
  7623. try:
  7624. async with async_session() as db:
  7625. item = await db.get(PrintQueueItem, queue_item_id)
  7626. if not item:
  7627. return
  7628. job_name = await self._get_job_name(db, item)
  7629. printer = await self._get_printer(db, printer_id)
  7630. await notification_service.on_queue_job_failed(
  7631. job_name=job_name,
  7632. printer_id=printer_id,
  7633. printer_name=printer.name if printer else "Unknown",
  7634. reason=reason,
  7635. db=db,
  7636. )
  7637. except Exception as e:
  7638. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7639. try:
  7640. await ws_manager.send_queue_item_failed(
  7641. user_id=created_by_id,
  7642. queue_item_id=queue_item_id,
  7643. printer_id=printer_id,
  7644. reason="never_started",
  7645. )
  7646. except Exception:
  7647. pass # toast is best-effort
  7648. async def _filament_short_on(
  7649. self,
  7650. db: AsyncSession,
  7651. item: PrintQueueItem,
  7652. printer_id: int,
  7653. *,
  7654. require_known: bool = False,
  7655. ) -> bool:
  7656. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7657. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7658. assigned there, with the mapping the item would get there, but changes
  7659. nothing. The model-based matcher uses it to prefer a printer whose
  7660. spools can finish the job.
  7661. False whenever the gate would let the item through: "Print Anyway",
  7662. no mapping, or a check that fails. With ``require_known`` all three of
  7663. those, and any printed slot whose remaining amount is unknown, count
  7664. as short instead: releasing a held job starts it with nobody asked, so
  7665. it needs the amount on record, not merely nothing against it.
  7666. """
  7667. if item.skip_filament_check:
  7668. return False
  7669. try:
  7670. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7671. if not mapping:
  7672. return require_known
  7673. deficit = await compute_deficit_for_queue_item(
  7674. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7675. )
  7676. except Exception as e:
  7677. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7678. return require_known
  7679. return bool(deficit)
  7680. async def _release_short_model_hold(
  7681. self,
  7682. db: AsyncSession,
  7683. item: PrintQueueItem,
  7684. unavailable: set[int],
  7685. require_plate_clear: bool,
  7686. printer_scope: PrinterScope,
  7687. ) -> bool:
  7688. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7689. The deficit gate holds a model-based job on the printer the matcher
  7690. gave it, because "Print Anyway" needs a printer to print on. When
  7691. another idle printer of the job's model has the filament, the job is
  7692. moved to that printer and its hold lifted, and the fixed-printer
  7693. branch dispatches it in this same pass, through the same checks a
  7694. held job meets when the user presses Start. It is moved rather than
  7695. put back in the pool because the model-based branch would pick again
  7696. without requiring the amounts on record (below), and could pick a
  7697. different printer. Only the deficit gate sets ``filament_short``, so a
  7698. job held for any other reason stays held.
  7699. The printer it is held on is left out: a spool loaded there is started
  7700. with Start, as before, rather than while someone may still be loading
  7701. the next one. Each job is checked at most every
  7702. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7703. on each idle printer again.
  7704. Cross-model jobs (#671) stay held: checking a variant writes its file
  7705. onto the item, which would leave a job that is not moved holding
  7706. another variant's file for the printer it waits on.
  7707. A printer qualifies only on a positive finding: every slot the plate
  7708. prints mapped to a spool whose remaining amount is on record and
  7709. enough. A printer whose spools Bambuddy does not track is not one.
  7710. Returns True when the job was moved. A check that fails keeps the hold
  7711. rather than stopping the queue pass.
  7712. """
  7713. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7714. return False
  7715. if not item.target_model or item.variants:
  7716. return False
  7717. now = time.monotonic()
  7718. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7719. return False
  7720. self._short_hold_checked_at[item.id] = now
  7721. try:
  7722. candidates = _candidates_for(item)
  7723. if not candidates:
  7724. return False
  7725. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7726. async def is_short(pid: int) -> bool:
  7727. return await self._filament_short_on(db, item, pid, require_known=True)
  7728. async def unmatched_on(pid: int) -> list[str]:
  7729. return await self._unmatched_on(db, item, pid)
  7730. match_id, _ = await self._find_idle_printer_for_model(
  7731. db,
  7732. item.target_model,
  7733. unavailable | {item.printer_id},
  7734. effective_types,
  7735. item.target_location,
  7736. filament_overrides=filament_overrides,
  7737. require_plate_clear=require_plate_clear,
  7738. printer_scope=printer_scope,
  7739. is_short=is_short,
  7740. unmatched_on=unmatched_on,
  7741. )
  7742. # Every idle printer short comes back as the first of them.
  7743. if match_id is None or await is_short(match_id):
  7744. return False
  7745. except Exception as e:
  7746. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7747. return False
  7748. logger.info(
  7749. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7750. item.id,
  7751. match_id,
  7752. item.printer_id,
  7753. )
  7754. self._short_hold_checked_at.pop(item.id, None)
  7755. item.printer_id = match_id
  7756. # Resolved against the printer it leaves (#3239): the tray mapping and
  7757. # the nozzle positions.
  7758. drop_printer_resolved(item)
  7759. item.manual_start = False
  7760. item.filament_short = False
  7761. item.waiting_reason = None
  7762. await db.commit()
  7763. try:
  7764. printer = await self._get_printer(db, match_id)
  7765. await notification_service.on_queue_job_assigned(
  7766. job_name=await self._get_job_name(db, item),
  7767. printer_id=match_id,
  7768. printer_name=printer.name if printer else "Unknown",
  7769. target_model=item.target_model,
  7770. db=db,
  7771. )
  7772. except Exception as e:
  7773. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7774. return True
  7775. async def _block_on_filament_deficit(
  7776. self,
  7777. db: AsyncSession,
  7778. item: PrintQueueItem,
  7779. ) -> bool:
  7780. """Promote the item to manual_start when the assigned spool is short (#1496).
  7781. Returns True when this dispatch attempt was blocked, False when the
  7782. item is clear to start. A previously-flagged item whose spool has
  7783. since been swapped to one with enough material clears the flag here
  7784. so the next scheduler tick dispatches it.
  7785. """
  7786. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7787. # don't re-flag, don't even compute. Without this short-circuit the
  7788. # scheduler bounces between "user said anyway" (route clears
  7789. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7790. # on identical spool state) (#1698-followup).
  7791. if item.skip_filament_check:
  7792. # #1762 diagnostic: surface the short-circuit at INFO so a
  7793. # future "Print Anyway didn't work" report (e.g. issue #1762
  7794. # comment 3) has actionable evidence in the support bundle
  7795. # without needing DEBUG enabled.
  7796. logger.info(
  7797. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7798. item.id,
  7799. )
  7800. return False
  7801. try:
  7802. deficit = await compute_deficit_for_queue_item(db, item)
  7803. except Exception as e:
  7804. # Never let a flaky deficit check wedge the queue — log and let
  7805. # dispatch proceed. The PrintModal-side check still runs on the
  7806. # manual paths.
  7807. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7808. return False
  7809. if deficit:
  7810. item.filament_short = True
  7811. item.manual_start = True
  7812. await db.commit()
  7813. job_name = await self._get_job_name(db, item)
  7814. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7815. logger.info(
  7816. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7817. item.id,
  7818. len(deficit),
  7819. )
  7820. try:
  7821. await notification_service.on_queue_job_waiting(
  7822. job_name=job_name,
  7823. target_model=(printer.model if printer else "") or "",
  7824. waiting_reason="filament_short",
  7825. db=db,
  7826. printer_id=item.printer_id,
  7827. )
  7828. except Exception as e:
  7829. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7830. return True
  7831. # No deficit — clear any stale flag from a previous tick.
  7832. if item.filament_short:
  7833. item.filament_short = False
  7834. await db.commit()
  7835. return False
  7836. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7837. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7838. Compared the way the matcher compares, so the same hex or a similar one
  7839. is a match. Only slots the plate prints, mapped to a tray the printer
  7840. reports, with a colour on both sides: anything else is not a colour the
  7841. job printed in.
  7842. """
  7843. by_tray = {f["global_tray_id"]: f for f in loaded}
  7844. found = []
  7845. for req in required:
  7846. slot_id = req.get("slot_id") or 0
  7847. if slot_id <= 0 or slot_id > len(mapping):
  7848. continue
  7849. tray_id = mapping[slot_id - 1]
  7850. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7851. if tray is not None and tray.get("color_known") is False:
  7852. # A spool without a colour set is not a different colour.
  7853. continue
  7854. wanted = self._normalize_color_for_compare(req.get("color"))
  7855. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7856. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7857. continue
  7858. found.append(
  7859. {
  7860. "slot_id": slot_id,
  7861. "type": req.get("type") or "",
  7862. "wanted": f"#{wanted.upper()}",
  7863. "got": f"#{got.upper()}",
  7864. "tray": tray_id,
  7865. }
  7866. )
  7867. return found
  7868. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7869. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7870. Read from the mapping the job is about to be sent with, whoever made
  7871. it: the matcher's same-material fallback, a preset match in another
  7872. colour, or a slot picked by hand. The file's colour is the one after
  7873. overrides, so a colour swapped on purpose is not one. None whenever
  7874. there is nothing to compare, and on any failure: a missing note must
  7875. never stop a print.
  7876. """
  7877. try:
  7878. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7879. if not isinstance(mapping, list) or not item.printer_id:
  7880. return None
  7881. status = printer_manager.get_status(item.printer_id)
  7882. if status is None:
  7883. return None
  7884. required = await self._get_filament_requirements(db, item)
  7885. if not required:
  7886. return None
  7887. self._apply_filament_overrides(item, required)
  7888. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7889. except Exception as e:
  7890. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7891. return None
  7892. if found:
  7893. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7894. return json.dumps(found) if found else None
  7895. async def _unmatched_requirements(
  7896. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7897. ) -> list[dict]:
  7898. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7899. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7900. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7901. on why an empty list is not one.
  7902. """
  7903. if mapping is None:
  7904. status = printer_manager.get_status(printer_id)
  7905. if status is None or not self._build_loaded_filaments(status):
  7906. return []
  7907. # Every required slot reads unresolved against an empty mapping.
  7908. mapping = []
  7909. required = await self._get_filament_requirements(db, item)
  7910. if required:
  7911. self._apply_filament_overrides(item, required)
  7912. else:
  7913. # An unreadable 3MF still has its forced colours to go by: they are
  7914. # what the mapping was built from (#3280).
  7915. required = _forced_override_requirements(item)
  7916. return _unresolved_required(required, mapping) if required else []
  7917. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7918. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7919. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7920. Choosing a printer for an "any model" job only checked that each type
  7921. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7922. the spool on the other nozzle, or one spool asked for twice, passes. The
  7923. hold then gave the printer back, and the next pass chose it again.
  7924. Empty when the hold would let the item through, including "Print
  7925. Anyway" and a match that fails: the printer is then chosen as before.
  7926. """
  7927. if item.skip_filament_check:
  7928. return []
  7929. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7930. if key in self._unmatched_memo:
  7931. return list(self._unmatched_memo[key])
  7932. try:
  7933. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7934. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7935. except Exception as e:
  7936. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7937. return []
  7938. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7939. self._unmatched_memo[key] = described
  7940. return list(described)
  7941. async def _block_on_unmatched_filament(
  7942. self,
  7943. db: AsyncSession,
  7944. item: PrintQueueItem,
  7945. release_assignment: bool = False,
  7946. ) -> bool:
  7947. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7948. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7949. goes ahead, letting the printer choose — which is how a job prints in the
  7950. wrong material without anyone being asked. Holding is the same answer the
  7951. deficit gate already gives for "the spool is too light", so it reuses the
  7952. same promote-and-notify machinery.
  7953. Keyed off unresolved slots in the *computed* mapping intersected with the
  7954. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7955. read: on its own it also pads slots this plate does not print, so the
  7956. array alone would hold perfectly good jobs. Reading the mapping rather
  7957. than the printer's loaded filament types also inherits the matcher's
  7958. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7959. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7960. type-only scan would wave that through.
  7961. A mapping that resolved *nothing* is the same finding arriving as an
  7962. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7963. could not replace, and dispatch then goes out as ``use_ams`` with no
  7964. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7965. That is held too, but only once live status positively reports loaded
  7966. trays: #2589's mapping is bogus precisely because the AMS was not known
  7967. yet, and its empty loaded list is that ignorance rather than a miss.
  7968. ``release_assignment`` is for the model-based path, which commits its
  7969. printer choice before the gates run. Holding an "any P2S" job would
  7970. otherwise pin it to the one P2S that could not run it.
  7971. Returns True when this dispatch attempt was blocked.
  7972. """
  7973. if item.skip_filament_check or not item.printer_id:
  7974. return False
  7975. mapping: list | None = None
  7976. if item.ams_mapping:
  7977. try:
  7978. mapping = json.loads(item.ams_mapping)
  7979. except (json.JSONDecodeError, TypeError):
  7980. return False
  7981. if not isinstance(mapping, list):
  7982. return False
  7983. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7984. if not unmatched:
  7985. # No cleanup needed here: once start is pressed the item is no
  7986. # longer staged, and whichever exit runs next overwrites the reason
  7987. # (`hold_item` on the fixed-printer branch, the assignment on the
  7988. # model-based one), as does dispatch.
  7989. return False
  7990. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7991. held_by = item.printer_id
  7992. item.manual_start = True
  7993. # Human-readable: this renders on the queue row.
  7994. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7995. if release_assignment:
  7996. # "Any P2S" means any, so the job returns to the pool rather than
  7997. # waiting on the printer that could not take it. The mapping goes
  7998. # with the assignment: its tray IDs were resolved against the
  7999. # printer being released and mean nothing on the next one (#2799),
  8000. # and keeping them would hold the job again even on a printer that
  8001. # has the filament, since an unresolved slot is deliberately not a
  8002. # conflict worth recomputing over.
  8003. item.printer_id = None
  8004. drop_printer_resolved(item)
  8005. await db.commit()
  8006. job_name = await self._get_job_name(db, item)
  8007. printer = await self._get_printer(db, held_by)
  8008. logger.info(
  8009. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  8010. item.id,
  8011. held_by,
  8012. wanted,
  8013. )
  8014. try:
  8015. await notification_service.on_queue_job_waiting(
  8016. job_name=job_name,
  8017. target_model=(printer.model if printer else "") or "",
  8018. waiting_reason=f"needs {wanted}",
  8019. db=db,
  8020. # Released to the pool: no printer holds it any more.
  8021. printer_id=None if release_assignment else held_by,
  8022. )
  8023. except Exception as e:
  8024. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  8025. return True
  8026. @staticmethod
  8027. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  8028. """The queue item's owner as the row has it now.
  8029. item.created_by_id was read before preheat and upload, which can take
  8030. minutes; deleting the user clears the row, not this session's copy.
  8031. """
  8032. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  8033. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  8034. """Hand the queue item's owner to printer_manager so the
  8035. print-complete callback can credit the user in PrintLogEntry (#1670).
  8036. No-ops when the item has no `created_by_id` or the referenced user
  8037. row is missing (e.g. user deleted between queue-add and dispatch —
  8038. in that case the print log row falls back to the existing un-credited
  8039. behaviour rather than crashing the dispatch).
  8040. """
  8041. from backend.app.models.user import User
  8042. # Read from the row, not item.created_by_id or db.get: both can still
  8043. # hold a user deleted during the upload, after delete_user forgot them
  8044. # (on SQLite the id may be someone new's by the time the print ends).
  8045. # Joined with the printer too: one deleted during the upload was
  8046. # forgotten as well, and this would write the owner back under its id.
  8047. owner = (
  8048. await db.execute(
  8049. select(User.id, User.username)
  8050. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  8051. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  8052. .where(PrintQueueItem.id == item.id)
  8053. )
  8054. ).first()
  8055. if owner:
  8056. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  8057. if item.printer_id is not None:
  8058. self._unconfirmed_print_user[item.id] = item.printer_id
  8059. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  8060. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  8061. A cancel lands in another session while the upload runs (the edit route
  8062. even tells users to cancel a job that is being sent). An unconditional
  8063. write here would turn that cancellation into a failure, with a failure
  8064. notification, and block the next job that needs the previous print to
  8065. have succeeded. Returns whether the item was marked failed.
  8066. """
  8067. result = cast(
  8068. CursorResult,
  8069. await db.execute(
  8070. update(PrintQueueItem)
  8071. .where(PrintQueueItem.id == item.id)
  8072. .where(PrintQueueItem.status.in_(("pending", "printing")))
  8073. # Failed before the print started: no slot printed in any colour (#3279).
  8074. .values(
  8075. status="failed",
  8076. error_message=message,
  8077. completed_at=datetime.now(timezone.utc),
  8078. color_substitutions=None,
  8079. )
  8080. .execution_options(synchronize_session=False)
  8081. ),
  8082. )
  8083. await db.commit()
  8084. if result.rowcount == 0:
  8085. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  8086. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  8087. return False
  8088. await db.refresh(item)
  8089. from backend.app.services.print_batch import refresh_batches_after
  8090. await refresh_batches_after([item.id])
  8091. return True
  8092. @staticmethod
  8093. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  8094. """Put a job whose printer turned busy before the start back in the queue.
  8095. Only if it is still printing: a stop that landed meanwhile stands.
  8096. """
  8097. await db.execute(
  8098. update(PrintQueueItem)
  8099. .where(PrintQueueItem.id == item.id)
  8100. .where(PrintQueueItem.status == "printing")
  8101. .values(status="pending", started_at=None, color_substitutions=None)
  8102. .execution_options(synchronize_session=False)
  8103. )
  8104. await db.commit()
  8105. @staticmethod
  8106. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  8107. """Close the dispatch toast of an item the user cancelled while it was sent."""
  8108. try:
  8109. await ws_manager.send_queue_item_failed(
  8110. user_id=toast_uid,
  8111. queue_item_id=item.id,
  8112. printer_id=item.printer_id,
  8113. reason="cancelled_mid_dispatch",
  8114. )
  8115. except Exception:
  8116. pass # toast is best-effort
  8117. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  8118. """Upload file and start print for a queue item.
  8119. Supports two sources:
  8120. - archive_id: Print from an existing archive
  8121. - library_file_id: Print from a library file (file manager)
  8122. """
  8123. logger.info("Starting queue item %s", item.id)
  8124. # Also covers a reservation left active by a process interruption
  8125. # during an earlier attempt. `_dispatch_one` releases this marker on
  8126. # every exit unless start_print() confirms that the command was sent.
  8127. self._unconfirmed_budget_reservations.add(item.id)
  8128. try:
  8129. from backend.app.models.user import User
  8130. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  8131. # Recompute at the final authorization boundary as well as enqueue
  8132. # time. This covers rows created before the server-side estimate
  8133. # migration and prevents any alternate write path from weakening
  8134. # the budget reservation.
  8135. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  8136. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  8137. item.estimated_cost = await estimate_queue_source_cost(
  8138. db,
  8139. archive=archive,
  8140. library_file=library_file,
  8141. plate_id=item.plate_id,
  8142. ams_mapping=item.ams_mapping,
  8143. printer_id=item.printer_id,
  8144. )
  8145. await validate_print_budget(
  8146. db,
  8147. cost_center_id=item.cost_center_id,
  8148. estimated_cost=item.estimated_cost,
  8149. current_user=queue_user,
  8150. exclude_queue_item_id=item.id,
  8151. exclude_reservation_source_type="print_queue",
  8152. exclude_reservation_source_id=item.id,
  8153. )
  8154. budget_reservation = await create_budget_reservation(
  8155. db,
  8156. cost_center_id=item.cost_center_id,
  8157. estimated_cost=item.estimated_cost,
  8158. current_user=queue_user,
  8159. source_type="print_queue",
  8160. source_id=item.id,
  8161. print_archive_id=item.archive_id,
  8162. exclude_queue_item_id=item.id,
  8163. )
  8164. await db.commit()
  8165. except HTTPException as exc:
  8166. if not await self._fail_dispatch(db, item, str(exc.detail)):
  8167. return
  8168. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  8169. await self._power_off_if_needed(db, item)
  8170. return
  8171. # Get printer first (needed for both paths)
  8172. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  8173. printer = result.scalar_one_or_none()
  8174. if not printer:
  8175. if not await self._fail_dispatch(db, item, "Printer not found"):
  8176. return
  8177. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  8178. await self._power_off_if_needed(db, item)
  8179. return
  8180. # Check printer is connected
  8181. if not printer_manager.is_connected(item.printer_id):
  8182. if not await self._fail_dispatch(db, item, "Printer not connected"):
  8183. return
  8184. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  8185. await self._power_off_if_needed(db, item)
  8186. return
  8187. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  8188. # `items` was taken at the top of check_queue, but the user can /cancel
  8189. # any pending row in the gap before we reach this point. Re-read the
  8190. # row and bail out cleanly instead of starting an FTP upload for a row
  8191. # that's already cancelled. The atomic CAS at the pending→printing
  8192. # transition (below, before start_print) is the load-bearing guard;
  8193. # this is the early-exit optimisation that avoids wasted FTP I/O.
  8194. await db.refresh(item)
  8195. if item.status != "pending":
  8196. logger.info(
  8197. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  8198. item.id,
  8199. item.status,
  8200. )
  8201. return
  8202. # Busy-printer guard (#2598). check_queue gates dispatch on
  8203. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  8204. # keep reporting FINISH for tens of seconds *after* it accepted a
  8205. # project_file (see the watchdog's phase-B note). A watchdog revert
  8206. # (#2555) also releases the dispatch hold, so a re-selected item can
  8207. # reach here while its printer has actually started printing. Uploading
  8208. # and dispatching then collides with the live job — the firmware answers
  8209. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  8210. # live state right before the expensive FTP upload: if the printer is
  8211. # busy, leave the item pending and let a later tick dispatch it once the
  8212. # printer is genuinely idle. No wasted upload, no collision.
  8213. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8214. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  8215. logger.info(
  8216. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  8217. "leaving item pending for a later tick (#2598)",
  8218. item.id,
  8219. item.printer_id,
  8220. pre_dispatch_state,
  8221. )
  8222. return
  8223. # Determine source: archive or library file
  8224. archive = None
  8225. library_file = None
  8226. file_path = None
  8227. filename = None
  8228. cleanup_disk_paths: list[Path] = []
  8229. # Set when a dispatch consumes its library file, so the photos can be
  8230. # carried over after the commit that removes the row (#3077).
  8231. consumed_library_file_id: int | None = None
  8232. consumed_photos: list[str] = []
  8233. if item.archive_id:
  8234. # Print from archive
  8235. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  8236. archive = result.scalar_one_or_none()
  8237. if archive is not None and archive.deleted_at is not None:
  8238. # Merged into another archive since it was queued (archive
  8239. # redesign P2): print that one, whose file it now holds.
  8240. from backend.app.services.archive_merge import resolve_alias
  8241. if (into := await resolve_alias(db, archive.id)) is not None:
  8242. archive = await db.get(PrintArchive, into)
  8243. if archive is not None:
  8244. item.archive_id = archive.id
  8245. if not archive:
  8246. if not await self._fail_dispatch(db, item, "Archive not found"):
  8247. return
  8248. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  8249. await self._power_off_if_needed(db, item)
  8250. return
  8251. # Persist the queue item's selected plate onto the archive so Print
  8252. # History can show the actual plate after cancel/fail/complete (#2603).
  8253. # The archive shows its latest run's plate; each run keeps its own
  8254. # on its print log entry.
  8255. if item.plate_id is not None:
  8256. archive.plate_id = item.plate_id
  8257. # Ask-for-outcome opt-in rides from the queue item to the archive
  8258. # the same way (#1898); never cleared here so a reprint of an
  8259. # archive that already asked keeps asking.
  8260. if item.confirm_outcome:
  8261. archive.confirm_requested = True
  8262. file_path = settings.base_dir / archive.file_path
  8263. filename = archive.filename
  8264. elif item.library_file_id:
  8265. # Print from library file (file manager)
  8266. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  8267. library_file = result.scalar_one_or_none()
  8268. if not library_file:
  8269. # "Not found" covers two different situations and only one of
  8270. # them is recoverable, so say which. A trashed file is still
  8271. # there and restoring it makes a re-queued job work; a file that
  8272. # is really gone needs a different one. Neither is knowable from
  8273. # the queue, which is the whole complaint about this message.
  8274. trashed = (
  8275. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  8276. ).scalar_one_or_none()
  8277. if not await self._fail_dispatch(
  8278. db,
  8279. item,
  8280. (
  8281. f"'{trashed}' is in the library trash — restore it and queue the print again"
  8282. if trashed
  8283. else "Library file not found — it was deleted after this job was queued"
  8284. ),
  8285. ):
  8286. return
  8287. logger.error(
  8288. "Queue item %s: library file %s is %s",
  8289. item.id,
  8290. item.library_file_id,
  8291. "in the trash" if trashed else "gone",
  8292. )
  8293. await self._power_off_if_needed(db, item)
  8294. return
  8295. # Library files store absolute paths
  8296. lib_path = Path(library_file.file_path)
  8297. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  8298. filename = library_file.filename
  8299. # Create archive from library file so usage tracking has access to the 3MF
  8300. queue_item_id = item.id
  8301. # Held separately: a cleanup dispatch clears item.library_file_id
  8302. # below, and the log line at the end of this block reported that
  8303. # cleared field -- so every consumed print logged "from library
  8304. # file None", which is the one case worth being able to trace.
  8305. source_library_file_id = item.library_file_id
  8306. reused_archive = False
  8307. try:
  8308. from backend.app.services.archive import ArchiveService
  8309. # The file printed before: this run joins its archive rather
  8310. # than archiving the same file a second time.
  8311. archive = await self._claim_reusable_archive(db, item, file_path)
  8312. if archive is not None:
  8313. reused_archive = True
  8314. if archive.library_file_id is None:
  8315. archive.library_file_id = item.library_file_id
  8316. # This run's, as a new archive would have them: the
  8317. # archive shows its latest run's plate, and a print
  8318. # without a queue item falls back to the archive's plate
  8319. # and cost centre. Not while another print of it runs: they
  8320. # are that print's (this one's run has its own, from the
  8321. # dispatch), and the archive takes the latest run's plate
  8322. # once none prints (print_log.mirror_latest_run).
  8323. if not await self._printing_elsewhere(db, archive.id):
  8324. if item.plate_id is not None:
  8325. archive.plate_id = item.plate_id
  8326. archive.cost_center_id = item.cost_center_id
  8327. if (slicer_pick := slicer_ams_pick.unpack(item.slicer_ams_mapping)) is not None:
  8328. archive.extra_data = {
  8329. **(archive.extra_data or {}),
  8330. "slicer_ams_mapping": {"mapping": slicer_pick[0], "printer_id": slicer_pick[1]},
  8331. }
  8332. else:
  8333. # A virtual printer's upload: its name setting, and the
  8334. # slicer's AMS pick kept for reprints (#2700). Passed only
  8335. # when set, as for every other file nothing changes.
  8336. vp_extras: dict = {}
  8337. if await self._vp_prefers_filename(db, library_file):
  8338. vp_extras["prefer_filename_for_name"] = True
  8339. if (slicer_pick := slicer_ams_pick.unpack(item.slicer_ams_mapping)) is not None:
  8340. # The printer the slicer resolved it on, not the
  8341. # job's: the job may have been moved since.
  8342. vp_extras["slicer_ams_mapping"], vp_extras["slicer_ams_mapping_printer_id"] = slicer_pick
  8343. archive_service = ArchiveService(db)
  8344. archive = await archive_service.archive_print(
  8345. printer_id=item.printer_id,
  8346. source_file=file_path,
  8347. original_filename=filename,
  8348. created_by_id=item.created_by_id,
  8349. project_id=item.project_id,
  8350. cost_center_id=item.cost_center_id,
  8351. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8352. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8353. **vp_extras,
  8354. )
  8355. if archive:
  8356. self._hold_archive(item.id, archive.id)
  8357. item.archive_id = archive.id
  8358. if item.confirm_outcome:
  8359. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8360. if budget_reservation is not None:
  8361. budget_reservation.print_archive_id = archive.id
  8362. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8363. consumed_library_file_id = library_file.id
  8364. item.library_file_id = None
  8365. cleanup_disk_paths.append(file_path)
  8366. if library_file.thumbnail_path:
  8367. thumb_path = Path(library_file.thumbnail_path)
  8368. if not thumb_path.is_absolute():
  8369. thumb_path = settings.base_dir / library_file.thumbnail_path
  8370. cleanup_disk_paths.append(thumb_path)
  8371. # Before the delete, not after: on PostgreSQL the FK
  8372. # cascade would already have taken these rows (#2819).
  8373. await self._repoint_siblings_at_archive(
  8374. db,
  8375. consumed_library_file_id=consumed_library_file_id,
  8376. archive_id=archive.id,
  8377. dispatched_item_id=item.id,
  8378. )
  8379. # Read while the row is still here; the photos move
  8380. # below, once the delete has actually committed.
  8381. consumed_photos = list(library_file.photos or [])
  8382. # The delete clears the link on the earlier archives of
  8383. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8384. # SQLite). This one is loaded, so set it here too, or it
  8385. # keeps the stale id in the session.
  8386. archive.library_file_id = None
  8387. await db.delete(library_file)
  8388. file_path = settings.base_dir / archive.file_path
  8389. filename = archive.filename
  8390. # Commit, not flush — flush opens the SQLite write
  8391. # transaction (item.archive_id update + library_file
  8392. # delete) and would hold the WAL writer lock through the
  8393. # FTP upload below, causing "database is locked" cascades
  8394. # for sensor history + concurrent cancels (#1853).
  8395. await db.commit()
  8396. logger.info(
  8397. "Queue item %s: %s archive %s from library file %s",
  8398. item.id,
  8399. "Reused" if reused_archive else "Created",
  8400. archive.id,
  8401. source_library_file_id,
  8402. )
  8403. except Exception as e:
  8404. logger.warning(
  8405. "Queue item %s: Failed to create archive from library file: %s",
  8406. queue_item_id,
  8407. e,
  8408. exc_info=True,
  8409. )
  8410. await db.rollback()
  8411. item = await db.get(PrintQueueItem, queue_item_id)
  8412. if item:
  8413. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8414. return
  8415. await self._power_off_if_needed(db, item)
  8416. return
  8417. if not archive:
  8418. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8419. return
  8420. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8421. await self._power_off_if_needed(db, item)
  8422. return
  8423. # The photos follow the file into the archive that replaces it, for
  8424. # the same reason the siblings do (#3077). After the commit above,
  8425. # never before it: that commit can fail ("database is locked",
  8426. # #1853) and roll the library row back, and photos already moved
  8427. # would leave it naming a directory that no longer exists. The
  8428. # file and thumbnail unlinks are deferred for the same reason.
  8429. if consumed_library_file_id is not None and consumed_photos:
  8430. # Held as a plain int, read here while the session is still
  8431. # healthy, because the handler below may not touch an ORM
  8432. # instance at all. The commit it exists for fails inside the
  8433. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8434. # first DML statement, so a busy writer surfaces as "database
  8435. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8436. # internally through safe_reraise before re-raising, which
  8437. # expires every loaded instance and leaves the session in
  8438. # pending-rollback state -- so `archive.id` inside the except
  8439. # would itself raise PendingRollbackError and the rollback
  8440. # below would never be reached.
  8441. archive_id = archive.id
  8442. try:
  8443. carried_photos = move_library_photos(
  8444. consumed_library_file_id,
  8445. consumed_photos,
  8446. archive_photos_dir(archive),
  8447. )
  8448. if carried_photos:
  8449. archive.photos = list(archive.photos or []) + carried_photos
  8450. await db.commit()
  8451. except Exception as e:
  8452. # The archive and the delete are already committed; the
  8453. # print goes ahead either way. Worst case the pictures sit
  8454. # unnamed in the archive's own directory.
  8455. #
  8456. # Ints only until the rollback has run, per the note above,
  8457. # which is why this logs queue_item_id and not item.id --
  8458. # the sibling handler forty lines up does the same.
  8459. logger.warning(
  8460. "Queue item %s: failed to carry library photos into archive %s: %s",
  8461. queue_item_id,
  8462. archive_id,
  8463. e,
  8464. )
  8465. await db.rollback()
  8466. # rollback() expires every loaded instance, and in async
  8467. # SQLAlchemy the next plain attribute read is lazy IO
  8468. # outside the greenlet -- MissingGreenlet, which would turn
  8469. # this cosmetic failure into a dispatch crash in exactly the
  8470. # "database is locked" case the block exists for (#1853).
  8471. # The nozzle guard, the upload and the start all keep
  8472. # reading item, archive and printer, so all three go back
  8473. # into the session before falling through.
  8474. item = await db.get(PrintQueueItem, queue_item_id)
  8475. archive = await db.get(PrintArchive, archive_id)
  8476. printer = await db.get(Printer, item.printer_id) if item else None
  8477. if not item or not archive or not printer:
  8478. logger.error(
  8479. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8480. queue_item_id,
  8481. archive_id,
  8482. )
  8483. return
  8484. else:
  8485. # Neither archive nor library file specified
  8486. if not await self._fail_dispatch(db, item, "No source file specified"):
  8487. return
  8488. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8489. await self._power_off_if_needed(db, item)
  8490. return
  8491. # Check file exists on disk
  8492. if not file_path.exists():
  8493. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8494. return
  8495. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8496. await self._power_off_if_needed(db, item)
  8497. return
  8498. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8499. # size dispatched to a printer with a different nozzle installed is
  8500. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8501. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8502. # gives the user no idea what went wrong. Catch it here, before we spend
  8503. # time preheating and uploading, and fail with an actionable message.
  8504. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8505. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8506. # the printer hasn't reported its nozzles yet, we fall through and let the
  8507. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8508. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8509. # as one of the two hotends is a 0.6.
  8510. #
  8511. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8512. # (#2885): the printer fetches one as part of starting the print, so the
  8513. # set to test against is "reachable", not "currently mounted". This runs
  8514. # well before the rack picker at the bottom of this method, so without
  8515. # the rack in scope here that picker never got the chance to run.
  8516. sliced_nozzle = archive.nozzle_diameter if archive else None
  8517. if sliced_nozzle:
  8518. nozzle_status = printer_manager.get_status(item.printer_id)
  8519. installed = _installed_nozzle_diameters(nozzle_status)
  8520. rack = _rack_nozzle_diameters(nozzle_status)
  8521. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8522. if mismatch_msg:
  8523. if not await self._fail_dispatch(db, item, mismatch_msg):
  8524. return
  8525. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8526. await notification_service.on_queue_job_failed(
  8527. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8528. printer_id=printer.id,
  8529. printer_name=printer.name,
  8530. reason=mismatch_msg,
  8531. db=db,
  8532. )
  8533. try:
  8534. await ws_manager.send_queue_item_failed(
  8535. user_id=item.created_by_id,
  8536. queue_item_id=item.id,
  8537. printer_id=item.printer_id,
  8538. reason="nozzle_mismatch",
  8539. )
  8540. except Exception:
  8541. pass
  8542. await self._power_off_if_needed(db, item)
  8543. return
  8544. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8545. # bed (and chamber, if applicable) is at temperature when the firmware
  8546. # starts the actual print routine. Best-effort: any failure logs and
  8547. # falls through to the normal upload+start path rather than turning a
  8548. # configuration issue into a failed queue item.
  8549. # Returns False only when the item was cancelled or deleted while the
  8550. # stage was holding at temperature. Uploading and starting it anyway
  8551. # would print a job the user has already called off, so abandon the
  8552. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8553. if not await self._preheat_and_soak(db, item, printer, archive):
  8554. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8555. return
  8556. # See `_effective_plate_id` for why this is resolved once here rather
  8557. # than each site below repeating `item.plate_id or 1`.
  8558. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8559. # G-code injection for auto-print systems (#422)
  8560. injected_path = None
  8561. # #2547: tracked separately from `injected_path`, which is also set when
  8562. # only a START snippet was injected. Only an END snippet changes what the
  8563. # camera sees at print completion.
  8564. end_gcode_injected = False
  8565. if item.gcode_injection:
  8566. try:
  8567. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8568. if snippets_raw:
  8569. snippets = json.loads(snippets_raw)
  8570. model_snippets = snippets.get(printer.model, {})
  8571. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8572. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8573. if start_gc or end_gc:
  8574. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8575. injected_path = inject_gcode_into_3mf(
  8576. file_path, effective_plate_id, start_gc or None, end_gc or None
  8577. )
  8578. if injected_path:
  8579. file_path = injected_path
  8580. end_gcode_injected = bool(end_gc)
  8581. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8582. else:
  8583. logger.warning(
  8584. "Queue item %s: G-code injection returned no result, using original", item.id
  8585. )
  8586. except Exception as e:
  8587. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8588. # #2547: the finish-photo path can't learn from telemetry that this print
  8589. # ends with user End G-code — which means the plate may be gone by the
  8590. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8591. # the print once the printer confirms it running.
  8592. if end_gcode_injected:
  8593. print_dispatch_context.mark_pending(printer.id)
  8594. # Upload to root directory (not /cache/) - the start_print command references
  8595. # files by name only (ftp://{filename}), so they must be in the root
  8596. remote_filename = derive_remote_filename(filename)
  8597. remote_path = f"/{remote_filename}"
  8598. # Get FTP retry settings
  8599. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8600. logger.info(
  8601. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8602. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8603. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8604. )
  8605. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8606. # Every read this method needs (printer, archive/library, preheat) is
  8607. # done, and the library-file branch already committed its archive
  8608. # creation. Without this the transaction opened by the first SELECT above
  8609. # stays "idle in transaction" for the entire upload — multiple seconds
  8610. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8611. # a farm dispatching many jobs at once then exhausts the pool. This was
  8612. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8613. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8614. # readable; the status writes below (upload-failure path and the
  8615. # pending->printing CAS) transparently open a fresh transaction.
  8616. # The owner is read here, after preheat, so the commit releases this read too.
  8617. toast_uid = await self._queue_owner_id(db, item)
  8618. await db.commit()
  8619. # Delete existing file if present (avoids 553 error on overwrite)
  8620. try:
  8621. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8622. delete_result = await delete_file_async(
  8623. printer.ip_address,
  8624. printer.access_code,
  8625. remote_path,
  8626. socket_timeout=ftp_timeout,
  8627. printer_model=printer.model,
  8628. # This delete and the upload below are one bounded, user-initiated
  8629. # unit -- at most nine connections -- so neither skips on the
  8630. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8631. # trace this delete took the TLS failure and armed the cool-off,
  8632. # and the upload's four attempts were then spent against it
  8633. # without a socket being opened.
  8634. respect_handshake_cooloff=False,
  8635. )
  8636. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8637. except Exception as e:
  8638. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8639. # Dispatch toast — announce the upload start with the total byte
  8640. # count so the frontend can render an honest progress bar.
  8641. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8642. try:
  8643. total_bytes = file_path.stat().st_size
  8644. except OSError:
  8645. total_bytes = 0
  8646. try:
  8647. await ws_manager.send_queue_item_uploading(
  8648. user_id=toast_uid,
  8649. queue_item_id=item.id,
  8650. printer_id=item.printer_id,
  8651. printer_name=printer.name,
  8652. file_name=toast_file_name,
  8653. total_bytes=total_bytes,
  8654. )
  8655. except Exception:
  8656. pass # toast is best-effort
  8657. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8658. # A deadline expiry gets its own message: "check your SD card" is the
  8659. # wrong advice for a link that was simply too slow to finish (#2529).
  8660. upload_error: str | None = None
  8661. # Why the upload failed, straight from the client rather than inferred.
  8662. # Owned here, so a background fetch for another print cannot overwrite
  8663. # it between the failure and the sentence built from it (#2899).
  8664. upload_failure = FtpFailureReport()
  8665. try:
  8666. if ftp_retry_enabled:
  8667. uploaded = await with_ftp_retry(
  8668. upload_file_async,
  8669. printer.ip_address,
  8670. printer.access_code,
  8671. file_path,
  8672. remote_path,
  8673. socket_timeout=ftp_timeout,
  8674. printer_model=printer.model,
  8675. progress_callback=progress_bridge,
  8676. respect_handshake_cooloff=False,
  8677. failure=upload_failure,
  8678. max_retries=ftp_retry_count,
  8679. retry_delay=ftp_retry_delay,
  8680. operation_name=f"Upload print to {printer.name}",
  8681. )
  8682. else:
  8683. uploaded = await upload_file_async(
  8684. printer.ip_address,
  8685. printer.access_code,
  8686. file_path,
  8687. remote_path,
  8688. socket_timeout=ftp_timeout,
  8689. printer_model=printer.model,
  8690. progress_callback=progress_bridge,
  8691. respect_handshake_cooloff=False,
  8692. failure=upload_failure,
  8693. )
  8694. except UploadCancelled as e:
  8695. uploaded = False
  8696. upload_error = (
  8697. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8698. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8699. )
  8700. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8701. except Exception as e:
  8702. uploaded = False
  8703. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8704. # Clean up injected temp file after upload attempt
  8705. if injected_path and injected_path.exists():
  8706. injected_path.unlink(missing_ok=True)
  8707. # Again after the upload, which can take minutes: an owner deleted
  8708. # meanwhile gets no more toasts, and neither does whoever has their id.
  8709. toast_uid = await self._queue_owner_id(db, item)
  8710. # The printer's copy at this path was replaced (or deleted above): the
  8711. # file browser's previews must not show the old one.
  8712. from backend.app.services.printer_file_cache import printer_file_cache
  8713. printer_file_cache.forget(printer.id, remote_path)
  8714. if not uploaded:
  8715. # This used to be one string for every upload failure, telling
  8716. # everyone to check the SD card. The client knows which of seven
  8717. # things went wrong and logs each one differently; it just had no
  8718. # way to say so here, so the card got named even for a TLS
  8719. # handshake that never reached the printer's filesystem (#2899).
  8720. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8721. failure = upload_failure.failure
  8722. if failure is not None and failure.kind is FtpFailureKind.STORAGE:
  8723. try:
  8724. validate_print_filename(remote_filename)
  8725. except InvalidFilenameError as e:
  8726. # This 553 is the file's name, which no card can hold, not
  8727. # the printer's storage: it would be refused on every retry
  8728. # and every printer, so this item fails and the queue goes on.
  8729. upload_error = f"The printer could not create the file {remote_filename!r}: {e}. Rename the file."
  8730. error_msg = upload_error
  8731. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8732. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid, failure.kind)
  8733. return
  8734. if not await self._fail_dispatch(db, item, error_msg):
  8735. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8736. return
  8737. logger.error(
  8738. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8739. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8740. )
  8741. # Send failure notification
  8742. await notification_service.on_queue_job_failed(
  8743. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8744. printer_id=printer.id,
  8745. printer_name=printer.name,
  8746. # The same sentence the queue shows. A push notification saying
  8747. # something different from the UI is its own small bug (#2899).
  8748. reason=error_msg,
  8749. db=db,
  8750. )
  8751. try:
  8752. await ws_manager.send_queue_item_failed(
  8753. user_id=toast_uid,
  8754. queue_item_id=item.id,
  8755. printer_id=item.printer_id,
  8756. reason="upload_failed",
  8757. )
  8758. except Exception:
  8759. pass
  8760. await self._power_off_if_needed(db, item)
  8761. return
  8762. # The printer took a file, so any run of refused uploads is over: the
  8763. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8764. self._upload_refusals.pop(printer.id, None)
  8765. self._upload_refusal_kind.pop(printer.id, None)
  8766. self._upload_refusal_notified.pop(printer.id, None)
  8767. # Parse AMS mapping if stored
  8768. ams_mapping = None
  8769. if item.ams_mapping:
  8770. try:
  8771. ams_mapping = json.loads(item.ams_mapping)
  8772. except json.JSONDecodeError:
  8773. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8774. # Register as expected print so we don't create a duplicate archive
  8775. # Only applicable for archive-based prints
  8776. if archive:
  8777. from backend.app.main import register_expected_print
  8778. register_expected_print(
  8779. item.printer_id,
  8780. remote_filename,
  8781. archive.id,
  8782. ams_mapping=ams_mapping,
  8783. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8784. # no print-start email, and neither does whoever has their id.
  8785. created_by_id=toast_uid,
  8786. cost_center_id=item.cost_center_id,
  8787. # The plate actually dispatched, not the queue item's raw
  8788. # column: on None, `register_expected_print` stores nothing,
  8789. # and `extract_filament_usage_from_3mf` then books every
  8790. # filament in the file rather than the one plate that printed.
  8791. plate_id=effective_plate_id,
  8792. )
  8793. # Registration happens before the print command by necessity (the
  8794. # printer can report the print before the send returns), so record
  8795. # what to undo if we never get as far as sending. `_dispatch_one`
  8796. # rolls back anything still pending here on every exit — exception,
  8797. # early return, or cancel winning the CAS below.
  8798. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8799. # Propagate the queue item's owner into printer_manager so the
  8800. # print-complete callback can credit the user in the PrintLogEntry
  8801. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8802. # items) or when the user clicks the manual-start button.
  8803. await self._propagate_owner_to_printer_manager(db, item)
  8804. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8805. # This prevents phantom reprints if the backend crashes/restarts after the
  8806. # print command is sent but before the status update is committed.
  8807. # If we crash after this commit but before start_print(), the item will be
  8808. # in "printing" status without actually printing - but that's safer than
  8809. # accidentally reprinting the same file hours later.
  8810. #
  8811. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8812. # initial pending read at the top of check_queue and this point) flips
  8813. # the row to "cancelled" in a separate session. Without the WHERE
  8814. # status='pending' clause, the unconditional update here would silently
  8815. # overwrite that cancellation and we'd ship the MQTT start_print below
  8816. # — printer obeys, user sees "I pressed cancel and the print started".
  8817. # rowcount==0 means the user won the race; bail out, best-effort delete
  8818. # the file we just uploaded, do NOT send start_print.
  8819. now_utc = datetime.now(timezone.utc)
  8820. billing_run_id = str(uuid.uuid4())
  8821. # Written with the move to printing, so a retried send replaces the
  8822. # last answer and a cancelled one leaves the row alone (#3279).
  8823. color_substitutions = await self._color_substitutions_for(db, item)
  8824. cas = await db.execute(
  8825. update(PrintQueueItem)
  8826. .where(PrintQueueItem.id == item.id)
  8827. .where(PrintQueueItem.status == "pending")
  8828. .values(
  8829. status="printing",
  8830. started_at=now_utc,
  8831. billing_run_id=billing_run_id,
  8832. color_substitutions=color_substitutions,
  8833. )
  8834. )
  8835. await db.commit()
  8836. if cas.rowcount == 0:
  8837. logger.info(
  8838. "Queue item %s no longer pending at print-command time "
  8839. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8840. item.id,
  8841. )
  8842. try:
  8843. await delete_file_async(
  8844. printer.ip_address,
  8845. printer.access_code,
  8846. remote_path,
  8847. socket_timeout=ftp_timeout,
  8848. printer_model=printer.model,
  8849. )
  8850. except Exception as cleanup_err:
  8851. logger.debug(
  8852. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8853. item.id,
  8854. cleanup_err,
  8855. )
  8856. try:
  8857. await ws_manager.send_queue_item_failed(
  8858. user_id=toast_uid,
  8859. queue_item_id=item.id,
  8860. printer_id=item.printer_id,
  8861. reason="cancelled_mid_dispatch",
  8862. )
  8863. except Exception:
  8864. pass
  8865. return
  8866. # Sync the in-memory item so subsequent code that reads item.status /
  8867. # item.started_at sees the values we just persisted.
  8868. item.status = "printing"
  8869. item.started_at = now_utc
  8870. item.billing_run_id = billing_run_id
  8871. if archive is not None:
  8872. archive.billing_run_id = billing_run_id
  8873. # Legacy transaction deletion used an archive-wide skip flag.
  8874. # A newly dispatched run has its own UUID/tombstone, so it must be
  8875. # billable independently of any older deleted run on this archive.
  8876. archive.wallet_charge_skipped = False
  8877. # Persist before MQTT send so completion and restart recovery can
  8878. # always recover the internal billing identity.
  8879. await db.commit()
  8880. for cleanup_path in cleanup_disk_paths:
  8881. try:
  8882. if cleanup_path.exists():
  8883. cleanup_path.unlink()
  8884. except OSError as cleanup_err:
  8885. logger.warning(
  8886. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8887. json.dumps(
  8888. {
  8889. "queue_item_id": item.id,
  8890. "path": str(cleanup_path),
  8891. "error": str(cleanup_err),
  8892. },
  8893. sort_keys=True,
  8894. ),
  8895. )
  8896. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8897. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8898. # #1898: with the opt-in default-good setting, moving on to the next
  8899. # print resolves the previous print's unanswered outcome prompt as
  8900. # "good" — this path also covers the camera-based plate detection,
  8901. # which releases the gate by allowing dispatch rather than by an
  8902. # explicit acknowledgment. Rides on the dispatch transaction.
  8903. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8904. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8905. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8906. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8907. # Capture state before dispatch so the watchdog can detect whether the
  8908. # printer actually transitioned (#967). Also capture subtask_id so the
  8909. # watchdog can recognise "command landed but state hasn't flipped yet"
  8910. # on slow H2D transitions (#1078).
  8911. pre_status = printer_manager.get_status(item.printer_id)
  8912. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8913. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8914. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8915. # #1721: respect the user's explicit timelapse choice. The #1397
  8916. # force-on at dispatch was removed because it caused per-layer nozzle
  8917. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8918. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8919. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8920. # FINISH-state fallback — no need to force a video.
  8921. effective_timelapse = bool(item.timelapse)
  8922. # Nozzle-rack fallback (#2800). A job that never passed through the
  8923. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8924. # dispatches with no nozzle field at all and chooses for itself — which
  8925. # is how a print levelled on one hotend and then printed on another,
  8926. # millimetres above the plate. Derive the per-slot extruder assignment
  8927. # from the file being dispatched.
  8928. #
  8929. # Done here rather than at queue time because this is the first point
  8930. # that knows both the actual printer and the actual file: an item can
  8931. # be created without a printer (model-based assignment), reassigned
  8932. # afterwards, or have its file swapped for a G-code-injected copy just
  8933. # above. Every queue-creation path — the print dialog, a bulk library
  8934. # add, the webhook, a pipeline run — is covered by the one call.
  8935. # Skipped when the item already carries a Bambu Studio capture: that
  8936. # one wins downstream anyway, so reading the 3MF again would be work
  8937. # thrown away on every dispatch.
  8938. # Rack position resolution (#1784), tried before the #2800 fallback
  8939. # below because it can express what that one cannot: a plate wanting a
  8940. # *different* hotend off the rack per filament group. The position per
  8941. # group is the operator's pick — the 3MF states it nowhere, proven by
  8942. # sending one plate twice with different picks and finding the two
  8943. # files identical bar float noise — so it is resolved here against the
  8944. # rack as it stands right now, after the upload, not at queue time.
  8945. resolved_nozzle_mapping = None
  8946. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8947. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8948. if rack_plan is not None:
  8949. try:
  8950. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8951. except (json.JSONDecodeError, TypeError):
  8952. stored_choice = {}
  8953. logger.warning(
  8954. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8955. item.id,
  8956. item.nozzle_rack_choice,
  8957. )
  8958. # JSON object keys are strings; the groups are ints.
  8959. choice: dict[int, int] = {}
  8960. for key, value in (stored_choice or {}).items():
  8961. try:
  8962. choice[int(key)] = int(value)
  8963. except (TypeError, ValueError):
  8964. continue
  8965. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8966. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8967. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8968. )
  8969. if resolved_nozzle_mapping is None and choice:
  8970. # An explicit pick that no longer holds stops the print. The
  8971. # operator named a hotend; printing from a different one is
  8972. # how a plate gets levelled on one nozzle and drawn with
  8973. # another, millimetres above the bed. Nothing has been sent
  8974. # to the printer yet, so failing here costs only the upload.
  8975. # The file is already on the SD card by this point, and a
  8976. # 3MF left there is a phantom print waiting to be started
  8977. # from the touchscreen. Same cleanup the start_print
  8978. # failure path below does, for the same reason.
  8979. try:
  8980. await delete_file_async(
  8981. printer.ip_address,
  8982. printer.access_code,
  8983. remote_path,
  8984. printer_model=printer.model,
  8985. )
  8986. except Exception:
  8987. pass # Best-effort — don't fail the error handler
  8988. if not await self._fail_dispatch(
  8989. db,
  8990. item,
  8991. (
  8992. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8993. "Edit the item to choose another position."
  8994. ),
  8995. ):
  8996. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8997. return
  8998. logger.warning(
  8999. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  9000. item.id,
  9001. printer.name,
  9002. rack_error,
  9003. choice,
  9004. [slot.get("id") for slot in live_rack],
  9005. )
  9006. await notification_service.on_queue_job_failed(
  9007. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9008. printer_id=printer.id,
  9009. printer_name=printer.name,
  9010. reason=item.error_message,
  9011. db=db,
  9012. )
  9013. try:
  9014. await ws_manager.send_queue_item_failed(
  9015. user_id=toast_uid,
  9016. queue_item_id=item.id,
  9017. printer_id=item.printer_id,
  9018. reason="nozzle_rack_pick_stale",
  9019. )
  9020. except Exception:
  9021. pass # Best-effort — don't fail the error handler
  9022. return
  9023. if resolved_nozzle_mapping is None:
  9024. # Nothing was picked and nothing could be assigned. Falls
  9025. # through to the #2800 path, which is what ran before this
  9026. # existed — strictly not worse than today.
  9027. logger.info(
  9028. "Queue item %s: no rack positions assignable (%s); falling back",
  9029. item.id,
  9030. rack_error,
  9031. )
  9032. else:
  9033. logger.info(
  9034. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  9035. item.id,
  9036. resolved_nozzle_mapping,
  9037. rack_plan.slot_groups,
  9038. choice or "auto",
  9039. )
  9040. nozzle_slot_extruders = None
  9041. if (
  9042. not item.nozzle_mapping
  9043. and resolved_nozzle_mapping is None
  9044. and file_path is not None
  9045. and is_nozzle_rack_model(printer.model)
  9046. ):
  9047. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  9048. if slot_extruders:
  9049. nozzle_slot_extruders = json.dumps(slot_extruders)
  9050. # Every filament this plate prints is on the external spool -> the print
  9051. # must go out with use_ams=False. The firmware answers use_ams=true plus
  9052. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  9053. # table", which is what held the reporter's P1S at Heatbed preheating
  9054. # for ten minutes before it gave up (#3087). The MQTT command builder
  9055. # already downgrades a mapping that is *only* external ([254]), but a
  9056. # multi-filament project pads the slots this plate does not print with
  9057. # -1 — BambuStudio's own convention — and down there a -1 is
  9058. # indistinguishable from a slot that never resolved, which must never be
  9059. # sent to the spool holder (#2589). Here the plate's filament list says
  9060. # which is which, so the answer is exact rather than a guess.
  9061. #
  9062. # Deliberately narrow: this fires only when every consumed slot is an
  9063. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  9064. # alone and the firmware still rejects the print, exactly as today. And
  9065. # only for single-nozzle printers, mirroring the builder's own reconcile
  9066. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  9067. # whether to use the AMS, so it is not ours to rewrite.
  9068. effective_use_ams = item.use_ams
  9069. plate_uses_only_external = False
  9070. if (
  9071. ams_mapping
  9072. and file_path is not None
  9073. # Cheap gate before opening the file: with nothing on the spool
  9074. # holder anywhere in the mapping, no subset of it can be all
  9075. # external, so most dispatches never pay for the parse. The
  9076. # isinstance also keeps a malformed stored mapping (a bare number
  9077. # from a hand-edited row) failing where it always failed, in the
  9078. # command builder, rather than here.
  9079. and isinstance(ams_mapping, list)
  9080. and any(_is_external_tray(t, TrayLayout.from_state(pre_status).rack) for t in ams_mapping)
  9081. and not _might_be_dual_nozzle(printer.model, pre_status)
  9082. ):
  9083. from backend.app.services.filament_requirements import extract_filament_requirements
  9084. consumed = _consumed_mapping_entries(
  9085. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  9086. )
  9087. if consumed and all(_is_external_tray(t, TrayLayout.from_state(pre_status).rack) for t in consumed):
  9088. # Exact for this plate: the command builder must not turn the
  9089. # AMS back on for a real tray another plate of the file uses,
  9090. # whether the job asked for the AMS or already had it off.
  9091. plate_uses_only_external = True
  9092. if plate_uses_only_external and effective_use_ams:
  9093. effective_use_ams = False
  9094. logger.info(
  9095. "Queue item %s: every filament plate %s prints is on the external spool "
  9096. "(mapping %s) — dispatching with use_ams=False (#3087)",
  9097. item.id,
  9098. effective_plate_id,
  9099. ams_mapping,
  9100. )
  9101. # A slot that lost its K-profile selection (a power cycle resets every
  9102. # slot to the default K) would print on the default. The idle check in
  9103. # the status handler normally restores it first, but nothing guarantees
  9104. # it ran before this dispatch (#3219). Unthrottled: once per job.
  9105. # Never allowed to stop the print it is protecting.
  9106. try:
  9107. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  9108. except Exception:
  9109. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  9110. # Start the print with AMS mapping, plate_id and print options.
  9111. # nozzle_mapping rides through verbatim — JSON string captured from
  9112. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  9113. # parses + injects it only for dual-nozzle models so a null on every
  9114. # other model is a transparent pass-through. The rack fallback is
  9115. # resolved down there too, where the live rack position is known.
  9116. started = printer_manager.start_print(
  9117. item.printer_id,
  9118. remote_filename,
  9119. plate_id=effective_plate_id,
  9120. ams_mapping=ams_mapping,
  9121. bed_levelling=item.bed_levelling,
  9122. flow_cali=item.flow_cali,
  9123. vibration_cali=item.vibration_cali,
  9124. layer_inspect=item.layer_inspect,
  9125. timelapse=effective_timelapse,
  9126. use_ams=effective_use_ams,
  9127. plate_uses_only_external=plate_uses_only_external,
  9128. nozzle_offset_cali=item.nozzle_offset_cali,
  9129. nozzle_mapping=item.nozzle_mapping
  9130. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  9131. nozzle_slot_extruders=nozzle_slot_extruders,
  9132. )
  9133. if started:
  9134. # The command is away, so the expectation is now legitimate and must
  9135. # survive. Anything still in this dict when _dispatch_one exits gets
  9136. # rolled back.
  9137. self._unconfirmed_expected_print.pop(item.id, None)
  9138. self._unconfirmed_budget_reservations.discard(item.id)
  9139. self._unconfirmed_print_user.pop(item.id, None)
  9140. if item.printer_id is not None:
  9141. self._sent_unstarted_print[item.id] = (
  9142. item.printer_id,
  9143. remote_filename if archive else None,
  9144. archive.id if archive else None,
  9145. )
  9146. # Handoff to the print's own gcode: keep whatever preheat set (bed
  9147. # target, chamber target, airduct heating) — the gcode owns
  9148. # heater/flap control from here. Clearing the pin prevents
  9149. # `_dispatch_one`'s finally from unwinding a live print.
  9150. self._preheat_pin.pop(item.printer_id, None)
  9151. self._preheat_pin_bed.pop(item.printer_id, None)
  9152. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  9153. # No dispatch-toast event here: the legacy bg-dispatch path kept
  9154. # status='processing' from upload start until the printer acked
  9155. # (or timed out). The frontend derives "Awaiting printer…" purely
  9156. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  9157. # event would push the status chip out of 'PROCESSING' prematurely
  9158. # — which is exactly what the screenshot at #1625-followup
  9159. # complained about.
  9160. # Register the local 3MF in the cover-cache so /cover skips FTP
  9161. # (#1166 follow-up). file_path was resolved earlier from either the
  9162. # archive or the library file row.
  9163. if file_path is not None:
  9164. cache_3mf_download(item.printer_id, remote_filename, file_path)
  9165. # Hold the printer against further dispatches until the watchdog
  9166. # confirms the printer transitioned (or until the hard timeout).
  9167. # Prevents multi-plate batches from triple-dispatching onto the
  9168. # same H2D Pro while it digests the first project_file (#1157).
  9169. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  9170. # Watchdog: if the printer never transitions out of pre_state AND
  9171. # never advances subtask_id, the MQTT publish was accepted locally but
  9172. # didn't reach the printer (half-broken session — same shape as
  9173. # #887/#936). Revert the queue item so the next dispatch can pick it
  9174. # up instead of leaving it stuck in "printing" (#967). subtask_id
  9175. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  9176. # that would otherwise cause the item to re-dispatch as a reprint
  9177. # of the just-finished job (#1078).
  9178. if pre_state:
  9179. spawn_background_task(
  9180. self._watchdog_print_start(
  9181. item.id,
  9182. item.printer_id,
  9183. pre_state,
  9184. pre_subtask_id,
  9185. pre_gcode_file,
  9186. created_by_id=toast_uid,
  9187. ),
  9188. name=f"watchdog-print-start-{item.id}",
  9189. )
  9190. # Get estimated time for notification.
  9191. #
  9192. # This used to fall back to `library_file.print_time_seconds`, a column
  9193. # LibraryFile does not have — the print time it knows about lives in
  9194. # `file_metadata`. So a library print whose archive carried no parseable
  9195. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  9196. # AttributeError right here, *after* the printer had already been sent
  9197. # the job: the started-notification never fired, and the exception
  9198. # unwound the whole queue pass, so every other printer still waiting to
  9199. # be dispatched on that tick silently missed its turn.
  9200. #
  9201. # The queue item caches the print time at creation ("Cached from
  9202. # archive/library"), which is the value this was reaching for.
  9203. # The item's is its plate's; the archive's adds every plate of the
  9204. # file up (#3375).
  9205. estimated_time = None
  9206. if item.print_time_seconds:
  9207. estimated_time = item.print_time_seconds
  9208. elif archive and archive.print_time_seconds:
  9209. estimated_time = archive.print_time_seconds
  9210. # Send job started notification
  9211. await notification_service.on_queue_job_started(
  9212. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9213. printer_id=printer.id,
  9214. printer_name=printer.name,
  9215. db=db,
  9216. estimated_time=estimated_time,
  9217. )
  9218. # MQTT relay - publish queue job started
  9219. try:
  9220. await mqtt_relay.on_queue_job_started(
  9221. job_id=item.id,
  9222. filename=filename,
  9223. printer_id=printer.id,
  9224. printer_name=printer.name,
  9225. printer_serial=printer.serial_number,
  9226. )
  9227. except Exception:
  9228. pass # Don't fail if MQTT fails
  9229. else:
  9230. # Clean up uploaded file from SD card to prevent phantom prints
  9231. try:
  9232. await delete_file_async(
  9233. printer.ip_address,
  9234. printer.access_code,
  9235. remote_path,
  9236. printer_model=printer.model,
  9237. )
  9238. except Exception:
  9239. pass # Best-effort — don't fail the error handler
  9240. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  9241. # state can flip from idle to active in the window between the
  9242. # pre-dispatch check above and this publish (the FTP upload takes
  9243. # seconds); start_print() then refuses to send project_file to the
  9244. # now-busy printer and returns False. Failing the item here would be
  9245. # wrong — the printer is fine, it is simply busy — so revert to
  9246. # pending and let a later tick dispatch it once the printer is idle,
  9247. # exactly like the pre-dispatch guard. Only a start_print() False on
  9248. # an idle/unknown printer is a genuine command failure.
  9249. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  9250. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  9251. logger.info(
  9252. "Queue item %s: printer %s became busy (state=%s) before the start "
  9253. "command was sent — deferring, reverting item to pending (#2598)",
  9254. item.id,
  9255. item.printer_id,
  9256. post_dispatch_state,
  9257. )
  9258. await self._defer_until_printer_idle(db, item)
  9259. return
  9260. # Print command failed - revert status
  9261. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  9262. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9263. return
  9264. logger.error(
  9265. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  9266. f"printer_manager.start_print() returned False. "
  9267. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  9268. f"Check printer status and backend logs for details."
  9269. )
  9270. # Send failure notification
  9271. await notification_service.on_queue_job_failed(
  9272. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9273. printer_id=printer.id,
  9274. printer_name=printer.name,
  9275. reason="Failed to send print command to printer - check printer connection and status",
  9276. db=db,
  9277. )
  9278. try:
  9279. await ws_manager.send_queue_item_failed(
  9280. user_id=toast_uid,
  9281. queue_item_id=item.id,
  9282. printer_id=item.printer_id,
  9283. reason="start_command_failed",
  9284. )
  9285. except Exception:
  9286. pass
  9287. await self._power_off_if_needed(db, item)
  9288. @staticmethod
  9289. async def _watchdog_print_start(
  9290. queue_item_id: int,
  9291. printer_id: int,
  9292. pre_state: str,
  9293. pre_subtask_id: str | None = None,
  9294. pre_gcode_file: str | None = None,
  9295. timeout: float = 90.0,
  9296. phase_b_timeout: float = 180.0,
  9297. poll_interval: float = 3.0,
  9298. created_by_id: int | None = None,
  9299. ) -> None:
  9300. """Revert a queue item if the printer never acknowledges the start command.
  9301. Bambuddy optimistically marks the queue item as "printing" right after the
  9302. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  9303. Phase A (up to ``timeout``): wait for either an active-state transition
  9304. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  9305. primary signal; subtask_id advance handles the H2D case where state can
  9306. sit at FINISH for ~50 s after the printer accepted ``project_file``
  9307. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  9308. was lost on a half-broken session (#887/#936) — revert and force
  9309. reconnect (the #967 recovery path).
  9310. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  9311. alone): keep watching for the active-state transition. subtask_id alone
  9312. proves the file landed but not that the printer started — and a printer
  9313. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  9314. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  9315. used to leave the queue item stuck in 'printing' forever because the
  9316. old watchdog returned success as soon as subtask_id advanced. If Phase
  9317. B times out, revert the queue item so the user can retry without
  9318. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  9319. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9320. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  9321. transitions that also don't emit an early subtask_id tick.
  9322. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  9323. refuses to verify our commands will never start this job or any other,
  9324. so waiting out the full 270 s and re-uploading the 3MF twice more only
  9325. burns an upload slot the rest of the farm is queued behind — that path
  9326. is for a printer that might still come good, which this one cannot
  9327. (#2732). It fails the item on the spot with the actual reason instead.
  9328. """
  9329. last_status = None
  9330. landed_on_subtask = False
  9331. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  9332. # every push carrying an `hms` key, so the fault can come and go between
  9333. # 3-second polls. Seeing it once inside the dispatch window is enough.
  9334. command_rejected = False
  9335. # Latched for the same reason as command_rejected: drying can finish, or
  9336. # be stopped by the user, part-way through the dispatch window. Seeing it
  9337. # once is what matters — it is the state the printer was in when it
  9338. # declined to start (#2758).
  9339. drying_ams_ids: list[int] = []
  9340. # The printer answered the start with a refusal: nothing will start,
  9341. # and the command was not lost, so no reconnect either.
  9342. start_refusal: tuple[str, str | None] | None = None
  9343. deadline = time.monotonic() + timeout
  9344. while time.monotonic() < deadline:
  9345. await asyncio.sleep(poll_interval)
  9346. status = printer_manager.get_status(printer_id)
  9347. if not status:
  9348. # Printer disconnected — don't mess with the DB. Drop the
  9349. # in-memory dispatch hold too so a fresh dispatch can retry
  9350. # once the printer comes back; the hard timeout would
  9351. # otherwise hold the printer unnecessarily.
  9352. scheduler._release_dispatch_hold(printer_id)
  9353. return
  9354. last_status = status
  9355. if status.state in _ACTIVE_PRINT_STATES:
  9356. # Printer is actively processing the job — release the
  9357. # post-dispatch hold so the next pending item for this printer
  9358. # can be evaluated normally. We do NOT accept arbitrary state
  9359. # transitions: a printer going FINISH -> IDLE (user dismissed
  9360. # the post-print prompt without accepting our project_file)
  9361. # would otherwise look like "command landed" and leave the
  9362. # queue item stuck in 'printing' forever (#1370).
  9363. scheduler._release_dispatch_hold(printer_id)
  9364. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9365. try:
  9366. await ws_manager.send_queue_item_acked(
  9367. user_id=created_by_id,
  9368. queue_item_id=queue_item_id,
  9369. printer_id=printer_id,
  9370. )
  9371. except Exception:
  9372. pass
  9373. return
  9374. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9375. # Checked only after the active-state exit above: a stale HMS left
  9376. # over from an earlier job must never abort a print that is visibly
  9377. # running. An actually-refused command leaves the printer idle, so
  9378. # this ordering costs the detection nothing.
  9379. if _mqtt_commands_rejected(status):
  9380. command_rejected = True
  9381. break
  9382. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9383. if isinstance(refusal, tuple):
  9384. start_refusal = refusal
  9385. break
  9386. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9387. # Phase A exit — printer accepted the file (subtask_id flipped
  9388. # to our submission id). Don't return yet: the printer may
  9389. # have accepted the command but never actually start (e.g.
  9390. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9391. # B watches for the active-state transition.
  9392. landed_on_subtask = True
  9393. break
  9394. if landed_on_subtask and not command_rejected:
  9395. phase_b_deadline = time.monotonic() + phase_b_timeout
  9396. while time.monotonic() < phase_b_deadline:
  9397. await asyncio.sleep(poll_interval)
  9398. status = printer_manager.get_status(printer_id)
  9399. if not status:
  9400. scheduler._release_dispatch_hold(printer_id)
  9401. return
  9402. last_status = status
  9403. if status.state in _ACTIVE_PRINT_STATES:
  9404. scheduler._release_dispatch_hold(printer_id)
  9405. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9406. try:
  9407. await ws_manager.send_queue_item_acked(
  9408. user_id=created_by_id,
  9409. queue_item_id=queue_item_id,
  9410. printer_id=printer_id,
  9411. )
  9412. except Exception:
  9413. pass
  9414. return
  9415. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9416. # Same ordering rule as Phase A: a running print wins over a
  9417. # lingering HMS.
  9418. if _mqtt_commands_rejected(status):
  9419. command_rejected = True
  9420. break
  9421. # No active-state transition. Revert the item so the scheduler can retry.
  9422. # Drop the in-memory hold so the retry isn't blocked by it.
  9423. scheduler._release_dispatch_hold(printer_id)
  9424. # Logged on every failed dispatch window, not just the last one, so a
  9425. # support bundle shows the correlation from the first attempt rather than
  9426. # only after the retry budget is spent (#2758).
  9427. if drying_ams_ids:
  9428. logger.info(
  9429. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9430. queue_item_id,
  9431. printer_id,
  9432. ", ".join(str(i) for i in drying_ams_ids),
  9433. )
  9434. # Four outcomes from the revert attempt, each routed differently:
  9435. # "reverted": row flipped from printing -> pending, run recovery
  9436. # "gave_up": same, but the retry budget is spent — row failed
  9437. # rather than pending, so it stops going round again
  9438. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9439. # on_print_complete or user). Skip recovery entirely
  9440. # — the print clearly landed somewhere even if the
  9441. # watchdog didn't see the active-state transition.
  9442. # "revert_failed": SQLite contention exhausted retries. Still run
  9443. # recovery so the MQTT session gets a fresh client_id
  9444. # on the half-broken-session path.
  9445. #
  9446. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9447. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9448. # the watchdog again. For a printer that is genuinely wedged that loop never
  9449. # ends — the reporter had one printer "since this morning still not launch"
  9450. # — and each lap also consumes an upload slot that the other printers in the
  9451. # farm are waiting on. Retrying is right; retrying forever is not.
  9452. async def _do_revert(db):
  9453. item = await db.get(PrintQueueItem, queue_item_id)
  9454. if not item or item.status != "printing":
  9455. return "already_moved_on"
  9456. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9457. item.started_at = None
  9458. # The print never started: no slot printed in any colour (#3279).
  9459. item.color_substitutions = None
  9460. # Charge the attempt to the candidate that was actually dispatched, so
  9461. # a cross-model item (#671) reaches for its other file next lap instead
  9462. # of retrying the printer that just failed to start. Matched by file
  9463. # because that is what the resolver copied onto the row.
  9464. if item.library_file_id is not None:
  9465. await db.execute(
  9466. update(PrintQueueVariant)
  9467. .where(PrintQueueVariant.queue_item_id == item.id)
  9468. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9469. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9470. )
  9471. if command_rejected:
  9472. # No retry budget for this one: the printer refused to verify the
  9473. # command, and re-uploading the same 3MF to the same printer will
  9474. # be refused the same way. Fail now with the fix rather than after
  9475. # three laps of a message about SD cards (#2732).
  9476. item.status = "failed"
  9477. item.error_message = (
  9478. "The printer rejected the print command: MQTT command verification failed "
  9479. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9480. "then start the job again."
  9481. )
  9482. item.completed_at = datetime.now(timezone.utc)
  9483. await db.commit()
  9484. return "command_rejected"
  9485. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9486. item.status = "failed"
  9487. if drying_ams_ids:
  9488. # #2758: the generic message below sent the reporter looking
  9489. # at the SD card while the actual obstacle — AMS units in a
  9490. # drying cycle — was on screen the whole time. Name what we
  9491. # observed and let the user judge it; Bambuddy does not stop
  9492. # the cycle itself, because on this hardware drying can run
  9493. # alongside a print and stopping it may not be the fix.
  9494. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9495. item.error_message = (
  9496. f"The printer accepted the file but never started printing, after "
  9497. f"{item.dispatch_attempts} attempts. {units} "
  9498. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9499. f"some printers refuse to begin a print while an AMS is in a drying "
  9500. f"cycle, and an AMS drying without its external power supply can also "
  9501. f"leave too little power for the start-of-print calibration. Stop the "
  9502. f"drying, or connect the AMS power supply, and start the job again."
  9503. )
  9504. else:
  9505. item.error_message = (
  9506. f"The printer accepted the file but never started printing, after "
  9507. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9508. f"prompt or error, confirm its SD card is readable, and start the job again."
  9509. )
  9510. item.completed_at = datetime.now(timezone.utc)
  9511. await release_budget_reservation(
  9512. db,
  9513. source_type="print_queue",
  9514. source_id=item.id,
  9515. status="released",
  9516. )
  9517. await db.commit()
  9518. return "gave_up"
  9519. item.status = "pending"
  9520. await db.commit()
  9521. return "reverted"
  9522. try:
  9523. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9524. except Exception as e:
  9525. logger.warning(
  9526. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9527. "scheduler may keep treating this item as in-flight",
  9528. queue_item_id,
  9529. printer_id,
  9530. e,
  9531. )
  9532. revert_outcome = "revert_failed"
  9533. if revert_outcome in ("command_rejected", "gave_up"):
  9534. # The item is failed: its print user and expected print must not
  9535. # pass the printer's next print off as Bambuddy's.
  9536. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9537. from backend.app.services.print_batch import refresh_batches_after
  9538. await refresh_batches_after([queue_item_id])
  9539. elif revert_outcome == "reverted":
  9540. # Another try claims the printer again. Until then no print on it
  9541. # is vouched for as this item's, except a late start of its file.
  9542. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9543. elif revert_outcome == "already_moved_on":
  9544. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9545. if revert_outcome == "already_moved_on":
  9546. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9547. # other path) already moved the item past 'printing', don't run the
  9548. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9549. # session breaks ongoing prints on the same printer.
  9550. return
  9551. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9552. if revert_outcome == "command_rejected":
  9553. logger.error(
  9554. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9555. "failed) — the print command was rejected, not lost. Failing the item "
  9556. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9557. queue_item_id,
  9558. printer_id,
  9559. HMS_MQTT_VERIFY_FAILED,
  9560. )
  9561. await scheduler._notify_dispatch_gave_up(
  9562. queue_item_id,
  9563. printer_id,
  9564. created_by_id,
  9565. reason="Printer rejected the print command (MQTT command verification failed)",
  9566. )
  9567. # Same reasoning as the landed_on_subtask path below: the file is on
  9568. # the printer and a forced reconnect would only add 0500_4003 to a
  9569. # problem that has nothing to do with the MQTT session (#1150).
  9570. return
  9571. if revert_outcome == "gave_up":
  9572. logger.error(
  9573. "Queue item %s: printer %d never started the print after %d dispatch "
  9574. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9575. "re-uploading it again (#2555)",
  9576. queue_item_id,
  9577. printer_id,
  9578. DISPATCH_MAX_ATTEMPTS,
  9579. total_timeout,
  9580. )
  9581. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9582. elif revert_outcome == "reverted":
  9583. if start_refusal is not None:
  9584. logger.warning(
  9585. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9586. "reverted to 'pending' for retry",
  9587. queue_item_id,
  9588. printer_id,
  9589. start_refusal[0],
  9590. start_refusal[1],
  9591. )
  9592. elif landed_on_subtask:
  9593. logger.warning(
  9594. "Queue item %s: printer %d accepted project_file (subtask_id "
  9595. "advanced) but never transitioned to an active state within "
  9596. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9597. "for retry (#1678)",
  9598. queue_item_id,
  9599. printer_id,
  9600. total_timeout,
  9601. )
  9602. else:
  9603. logger.warning(
  9604. "Queue item %s: printer %d did not respond to print command within "
  9605. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9606. "for retry (#967)",
  9607. queue_item_id,
  9608. printer_id,
  9609. timeout,
  9610. pre_state,
  9611. pre_subtask_id,
  9612. )
  9613. # Phase B was entered iff subtask_id advanced, which means the
  9614. # project_file landed on the printer. A forced reconnect at this point
  9615. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9616. # skip the recovery entirely.
  9617. if landed_on_subtask or start_refusal is not None:
  9618. return
  9619. # Phase A timeout path: if the printer's gcode_file changed since
  9620. # pre-dispatch, the project_file command landed and the printer is
  9621. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9622. # If gcode_file is unchanged, the publish was silently swallowed
  9623. # (#887/#936) and force_reconnect recovery is what we want.
  9624. client = printer_manager.get_client(printer_id)
  9625. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9626. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9627. if publish_landed:
  9628. logger.warning(
  9629. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9630. "received the command and is parsing slowly. Skipping forced "
  9631. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9632. queue_item_id,
  9633. current_gcode_file,
  9634. pre_gcode_file,
  9635. )
  9636. elif client and hasattr(client, "force_reconnect_stale_session"):
  9637. client.force_reconnect_stale_session(
  9638. f"queue print command unacknowledged after {timeout:.0f}s "
  9639. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9640. )
  9641. # Global scheduler instance
  9642. scheduler = PrintScheduler()