print_scheduler.py 504 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import derive_remote_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. plate_bed_temperature,
  90. select_plate_gcode_name,
  91. )
  92. logger = logging.getLogger(__name__)
  93. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  94. """Human slot name for an assignment tuple, in the spelling already in use.
  95. Composed from the notification side's own pair rather than spelled out again
  96. here. The hand-rolled version this replaces got three real slot kinds wrong:
  97. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  98. ``chr(191)``; both externals collapsed to one label, because an external
  99. assignment stores ams_id 255 with tray_id picking left or right
  100. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  101. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  102. Naming the same slot two ways is its own defect once an alert and the
  103. Inventory page are meant to be talking about the same tray, so this defers
  104. rather than adding a fifth spelling.
  105. """
  106. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  107. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  108. # interval: the fast path runs every 3 s while an upload is in flight, and a
  109. # low spool does not need answering at that resolution (#2913).
  110. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  111. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  112. # days, so a finer check would only repeat the same answer.
  113. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  114. # The settings row that holds which stock alerts have already been sent (#2955).
  115. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  116. # The Inventory page asks for this many usage records and the forecast panel
  117. # builds its rates from them; the alert reads the same window so the two agree.
  118. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  119. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  120. """Remaining filament as a percentage of the label weight.
  121. The same arithmetic the Inventory page's Low Stock count uses, and it works
  122. unchanged in both inventory modes: internal spools store ``weight_used``
  123. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  124. ``remaining_weight`` so the shape matches. Returns None when there is no
  125. label weight to be a percentage of -- a spool that cannot say how full it
  126. started cannot say how empty it is.
  127. """
  128. if not label_weight or label_weight <= 0:
  129. return None
  130. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  131. return remaining / float(label_weight) * 100.0
  132. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  133. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  134. # byte gate) from before the scheduler unification. Time gate keeps small
  135. # files from going silent (a single 8 KB chunk fires once and that's it);
  136. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  137. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  138. # sub-200 ms files.
  139. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  140. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  141. # How far back chamber temperature samples are retained. 2h comfortably spans
  142. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  143. # before the next print.
  144. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  145. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  146. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  147. # who clear plates promptly will want far less than this; it is deliberately
  148. # the cautious end, since the cost of it being too short is only a re-soak.
  149. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  150. # Max acceptable gap between two consecutive chamber samples before we treat
  151. # the older one as belonging to a separate observation run (printer went
  152. # offline and came back). Above ~30s cadence with a safety margin.
  153. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  154. # How long the chamber must read below target before we accept that it really
  155. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  156. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  157. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  158. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  159. # sub-target readings are therefore a door opening or noise, not lost soak,
  160. # and a plate swap (exactly when keep-warm is running) produces one. Six
  161. # minutes clears the longest such artifact observed (~5 min once bracketed by
  162. # its neighbouring samples) and still sits far below the 23-minute floor for
  163. # real cooling.
  164. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  165. # How often the preheat stage re-checks that the item it is heating for still
  166. # wants to be printed. Cancelling only writes `status` to the database — it
  167. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  168. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  169. # and the printer stays in `busy_printers`, blocking every other queued item
  170. # behind a print that is not happening.
  171. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  172. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  173. _AIRDUCT_MODE_COOLING = 0
  174. _AIRDUCT_MODE_HEATING = 1
  175. # How long a queue row may stay 'printing' while its printer sits in a terminal
  176. # state before the scheduler closes it itself (#2829).
  177. #
  178. # A real completion arrives within seconds of the printer going terminal, so
  179. # five minutes is far outside the normal path — this only ever sees a row whose
  180. # completion was refused or never delivered. It is the whole cost of the
  181. # failure to the user, though: a stranded row blocks every later job for that
  182. # printer, so it should not be raised without reason.
  183. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  184. # gcode_state values that mean the print is over, mapped to the queue status
  185. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  186. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  187. # which the queue calls cancelled) so a recovered row cannot disagree with one
  188. # closed by the normal path.
  189. _TERMINAL_STATE_QUEUE_STATUS = {
  190. "FINISH": "completed",
  191. "FAILED": "failed",
  192. "IDLE": "cancelled",
  193. }
  194. def _terminal_queue_status(state) -> str | None:
  195. """Queue status implied by *state*, or None if the print is not over.
  196. None for a disconnected printer as well as a busy one: a printer we are not
  197. talking to has a stale ``state`` field that proves nothing about what it is
  198. doing now.
  199. """
  200. if state is None or not getattr(state, "connected", False):
  201. return None
  202. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  203. @dataclass
  204. class _KeepWarmEntry:
  205. """Per-printer keep-warm state.
  206. - ``started``: monotonic time when keep-warm first fired for this printer.
  207. Used by the max-duration timeout.
  208. - ``held_target``: last bed target we successfully published. On release
  209. we only send bed-off when firmware still reports this value, so a user
  210. or subsequent print that changed the target isn't clobbered.
  211. - ``expired``: latched True when the max-duration timeout fires. Prevents
  212. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  213. release sweep drops the entry entirely once the printer leaves the
  214. candidate set.
  215. """
  216. started: float
  217. held_target: int
  218. expired: bool = False
  219. # Auto-drying re-arm guards (#2770).
  220. #
  221. # An AMS reports HIGHER relative humidity while it is warm than once it has
  222. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  223. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  224. # threshold set inside that band therefore cannot be satisfied while the box is
  225. # hot, and the firmware is free to end a cycle whenever it decides the filament
  226. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  227. # the threshold and arms another cycle. The reporter's log has five 12-hour
  228. # cycles armed inside four hours, one of them six seconds after the previous
  229. # ended.
  230. #
  231. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  232. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  233. # manual or firmware-run dry is untouched.
  234. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  235. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  236. # Sustained-humidity wait (#2518): an above-threshold streak is only
  237. # "continuous" if some pass observed it within the gap ceiling. A unit that
  238. # goes unobserved longer (print running, printer disconnected, sensor silent)
  239. # restarts its streak rather than inheriting a stale one. The ceiling is
  240. # derived from the scheduler cadence — four missed passes — with this floor so
  241. # a fast-polling configuration does not void streaks on a single hiccup.
  242. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  243. # How long a finished scheduled drying row is kept before it is pruned.
  244. SCHEDULED_DRYING_RETENTION_DAYS = 7
  245. # How often that prune actually runs. The check itself is called on every queue
  246. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  247. # write transaction, which SQLite serialises against every other writer. Rows
  248. # only become prunable a week after they finish, so anything short of hourly is
  249. # paying that cost for nothing.
  250. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  251. class _UploadProgressBridge:
  252. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  253. ``upload_file_async`` runs the FTP transfer in an executor thread and
  254. invokes its ``progress_callback`` from that thread, so the callback
  255. body cannot ``await`` directly. This bridge captures the asyncio loop
  256. at construction (on the scheduler thread) and uses
  257. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  258. matches the legacy background_dispatch.py path 1:1 so the toast feels
  259. identical to the pre-#1625 experience.
  260. Failures inside the emit are swallowed — progress is a UX nicety, the
  261. upload itself must not fail because of a WS hiccup.
  262. """
  263. def __init__(self, user_id: int | None, queue_item_id: int):
  264. self._user_id = user_id
  265. self._queue_item_id = queue_item_id
  266. try:
  267. self._loop = asyncio.get_running_loop()
  268. except RuntimeError:
  269. self._loop = None
  270. self._last_emit_bytes = 0
  271. self._last_emit_monotonic = 0.0
  272. self._has_emitted = False
  273. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  274. if self._loop is None or total_bytes <= 0:
  275. return
  276. now = time.monotonic()
  277. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  278. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  279. # the four matter most: first-call so the user sees something even
  280. # for sub-chunk-size files; uploaded >= total so the bar locks at
  281. # 100% even when the throttle would otherwise eat it.
  282. should_emit = (
  283. not self._has_emitted
  284. or bytes_transferred >= total_bytes
  285. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  286. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  287. )
  288. if not should_emit:
  289. return
  290. self._has_emitted = True
  291. self._last_emit_bytes = bytes_transferred
  292. self._last_emit_monotonic = now
  293. try:
  294. asyncio.run_coroutine_threadsafe(
  295. ws_manager.send_queue_item_upload_progress(
  296. user_id=self._user_id,
  297. queue_item_id=self._queue_item_id,
  298. bytes_transferred=bytes_transferred,
  299. total_bytes=total_bytes,
  300. ),
  301. self._loop,
  302. )
  303. except Exception:
  304. pass # progress is best-effort, never block the upload
  305. # Bambu firmware states that mean the project_file has actually been accepted
  306. # and the printer is now processing / running / paused mid-print. Used by the
  307. # dispatch watchdog (#1370): a transition into one of these states means the
  308. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  309. # a post-print prompt) is NOT a valid "command landed" signal even though the
  310. # state value did change. SLICING is included because some firmwares park
  311. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  312. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  313. # How many times the start-watchdog may revert an item to 'pending' before it
  314. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  315. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  316. # both never recovers and starves the other printers of dispatch slots. Three
  317. # is chosen to clear the transient causes the watchdog already recovers from —
  318. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  319. # force-reconnect on the very next attempt — while still bounding the loop.
  320. DISPATCH_MAX_ATTEMPTS = 3
  321. # Upload failures that mean the file never reached the printer's storage: the
  322. # file service refused or never answered (#3210). These put the item back in
  323. # the queue instead of failing it, because nothing about the job is wrong --
  324. # and failing it left the printer idle, so the next pass handed it the next
  325. # item, which failed the same way. One P2S whose file service was out of
  326. # connection slots ate 43 queued jobs in ten minutes that way.
  327. #
  328. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  329. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  330. # and an upload that overran its deadline -- each of those would fail the same
  331. # way on every retry.
  332. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  333. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  334. )
  335. # How long a printer whose upload was put back stays out of dispatch (#3210).
  336. # The first window matches the FTP client's own handshake cool-off, so the
  337. # retry lands after the client would talk to the printer again anyway. Each
  338. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  339. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  340. # five connection attempts and a page of log. A successful upload resets it.
  341. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  342. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  343. def _upload_backoff_seconds(refusals: int) -> int:
  344. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  345. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  346. @dataclass(slots=True)
  347. class _ModelCandidate:
  348. """One (file, printer model) pair the model-based matcher may try.
  349. Model-based assignment used to have exactly one of these per item, held
  350. directly in the item's own columns. Cross-model queue items (#671) have
  351. several, held in ``print_queue_variants``. Both shapes are normalised into
  352. this so the matching, the cross-model gate and the waiting-reason handling
  353. are written once and an item without variants provably takes the same path
  354. it took before variants existed.
  355. ``variant`` is None for the item's own columns and set for a real variant
  356. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  357. item once that candidate wins.
  358. """
  359. target_model: str | None
  360. sliced_for: str | None
  361. required_filament_types: str | None
  362. filament_overrides: str | None
  363. variant: "PrintQueueVariant | None" = None
  364. def _sliced_for_model(archive, library_file) -> str | None:
  365. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  366. if archive is not None:
  367. return archive.sliced_for_model
  368. if library_file is not None and library_file.file_metadata:
  369. return library_file.file_metadata.get("sliced_for_model")
  370. return None
  371. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  372. """The filament a candidate needs, as ``(types, overrides)``.
  373. Both columns are JSON text written by the slicer step. Malformed content is
  374. treated as no constraint rather than as an error: a job whose overrides
  375. cannot be parsed still prints, it just gets no filament-based narrowing.
  376. Overrides carry their own types, so the returned type list is the union of
  377. the two — an override on one slot must not drop the requirements of the
  378. slots it says nothing about.
  379. Shared by the matcher and by the smart-plug wake step so both ask a printer
  380. for the same filament (#2876). Waking a printer the matcher would then
  381. reject on colour is the bug this exists to prevent.
  382. """
  383. required_types = None
  384. if candidate.required_filament_types:
  385. try:
  386. required_types = json.loads(candidate.required_filament_types)
  387. except json.JSONDecodeError:
  388. pass
  389. filament_overrides = None
  390. if candidate.filament_overrides:
  391. try:
  392. filament_overrides = json.loads(candidate.filament_overrides)
  393. except json.JSONDecodeError:
  394. pass
  395. effective_types = required_types
  396. if filament_overrides:
  397. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  398. if override_types:
  399. effective_types = sorted(set(required_types or []) | set(override_types))
  400. return effective_types, filament_overrides
  401. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  402. """Whether ``item`` was competing for the printer another item just took.
  403. The SJF starvation guard marks a job as jumped when a shorter one lower in
  404. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  405. compete for the same printer, so the guard has to look across both lanes
  406. (#3200); looking only inside the dispatched item's own lane let a stream of
  407. short model-based jobs hold a longer pinned job back indefinitely.
  408. Location filters are not checked: over-marking only lifts an item that was
  409. going to wait anyway, while under-marking is the starvation this prevents.
  410. """
  411. if item.printer_id is not None:
  412. return item.printer_id == printer_id
  413. if not printer_model:
  414. return False
  415. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  416. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  417. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  418. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  419. """Candidate files for ``item``, best first.
  420. An item with no variant rows yields exactly one candidate built from its own
  421. columns — the pre-#671 behaviour, unchanged.
  422. Variants come back least-attempted first, ties broken by the user's
  423. ``position``. On the first pass every count is zero, so this is purely the
  424. user's priority order. After a start-watchdog bounce the printer that failed
  425. drops behind, so the next lap tries the other machine rather than spending the
  426. item's whole retry budget on the one that is wedged. Once every candidate has
  427. been tried equally often they cycle again, which keeps the item-level
  428. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  429. still gives up, it just does not give up without trying them.
  430. """
  431. if not item.variants:
  432. if not item.archive_id and not item.library_file_id:
  433. # Nothing to print at all. Dispatching would fail deep in the upload
  434. # on "No archive_id or library_file_id"; the caller holds the item
  435. # with an explanation instead.
  436. return []
  437. return [
  438. _ModelCandidate(
  439. target_model=item.target_model,
  440. sliced_for=_sliced_for_model(item.archive, item.library_file),
  441. required_filament_types=item.required_filament_types,
  442. filament_overrides=item.filament_overrides,
  443. )
  444. ]
  445. # Drop candidates whose file is gone or in the trash. Both are reachable and
  446. # neither is covered by the schema: library deletes are soft (the row lives
  447. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  448. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  449. # fires there and a hard delete leaves the variant row pointing at nothing.
  450. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  451. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  452. return [
  453. _ModelCandidate(
  454. target_model=v.target_model,
  455. sliced_for=_sliced_for_model(None, v.library_file),
  456. required_filament_types=v.required_filament_types,
  457. filament_overrides=v.filament_overrides,
  458. variant=v,
  459. )
  460. for v in ordered
  461. ]
  462. # Why a job for any printer of a model waits when every free one's last print
  463. # failed. The queue page matches it to offer Resume for the model.
  464. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  465. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  466. """Fold one waiting reason per candidate into a single line for the item.
  467. A cross-model item produces a reason per candidate, and pasting them
  468. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  469. — on which machine?). Each reason is prefixed with its model, except in the
  470. single-candidate case where the item already displays its target model and
  471. the prefix would be noise.
  472. Identical reasons collapse rather than repeat, so three idle-less models
  473. read as one clause.
  474. When *every* candidate is merely busy the parts are joined with the ``" | "``
  475. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  476. unprefixed. That case must keep testing busy-only: a fleet that is simply
  477. printing needs no user action, and labelling the clauses would turn each pass
  478. over a two-model item into a "job waiting" notification.
  479. """
  480. reasons = [(model, reason) for model, reason in per_model if reason]
  481. if not reasons:
  482. return None
  483. if len(reasons) == 1:
  484. return reasons[0][1]
  485. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  486. if len(distinct) == 1:
  487. return distinct[0]
  488. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  489. return " | ".join(distinct)
  490. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  491. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  492. """Human label for the models an item is waiting on ("H2S or H2C").
  493. Notifications take a single target model. For a cross-model item the item's
  494. own ``target_model`` is whichever variant happens to be first, which reads as
  495. a lie once it is the H2C that actually runs — so name all of them.
  496. """
  497. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  498. if not models:
  499. return None
  500. return " or ".join(models)
  501. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  502. """True if ``mapping`` is a non-empty list whose every entry is the
  503. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  504. Such a mapping is a bug artifact: a frontend status-load race can serialize
  505. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  506. recomputed from live status at dispatch rather than trusted, otherwise it
  507. reaches the print command and is silently downgraded to external-spool mode.
  508. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  509. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  510. explicit external selection (``>= 254``) is NOT unresolved either — those
  511. keep their meaning.
  512. """
  513. if not isinstance(mapping, list) or not mapping:
  514. return False
  515. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  516. def _is_tray_id(value: object) -> bool:
  517. """True when ``value`` can be read as a global tray ID.
  518. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  519. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  520. against whatever happens to be loaded there.
  521. """
  522. return isinstance(value, int) and not isinstance(value, bool)
  523. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  524. # stages an item (#2799). The manual_start branch clears every other reason on
  525. # a staged item (#3074); this one is the reason it was staged, so it stays.
  526. _UNMATCHED_HOLD_PREFIX = "Needs "
  527. # How often an "any model" job held for low filament looks for another printer
  528. # of its model that has enough (#3137). Each look matches its filament on every
  529. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  530. _SHORT_HOLD_RECHECK_SECONDS = 120
  531. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  532. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  533. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  534. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  535. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  536. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  537. for a filament this plate does not use. A slot past the end of the mapping
  538. is unresolved too.
  539. """
  540. unresolved = []
  541. for req in required:
  542. slot_id = req.get("slot_id") or 0
  543. if slot_id <= 0:
  544. continue
  545. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  546. if not _is_tray_id(tray) or tray < 0:
  547. unresolved.append(req)
  548. return unresolved
  549. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  550. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  551. # on `_mapping_is_all_unresolved`.
  552. _EXTERNAL_TRAY_ID_MIN = 254
  553. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  554. """The ``mapping`` entries for the slots this plate actually prints.
  555. ``required`` comes from ``extract_filament_requirements``, which drops any
  556. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  557. consumes, and one absent from it is padding. That distinction is why this
  558. decision lives here and not in the MQTT command builder: a ``-1`` in the
  559. mapping means either "this plate does not print filament N" or "we never
  560. worked out which tray", and only the plate's own filament list separates
  561. them. The builder sees both as the same byte, which is how a plate whose one
  562. printed filament sat on the external spool went out as `use_ams=true` with a
  563. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  564. with 07FF_8012 (#3087).
  565. Returns None whenever the two cannot be lined up — no mapping, no parsed
  566. requirements, or a requirement the mapping is too short to cover — so every
  567. caller falls back to existing behaviour rather than acting on a guess.
  568. """
  569. if not isinstance(mapping, list) or not mapping or not required:
  570. return None
  571. entries = []
  572. for filament in required:
  573. slot_id = filament.get("slot_id")
  574. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  575. # The mapping and the requirements disagree about how many filaments
  576. # the file has. They came from different reads, so judge nothing.
  577. return None
  578. entries.append(mapping[slot_id - 1])
  579. return entries or None
  580. def _is_external_tray(tray_id) -> bool:
  581. """True for an explicit external-spool selection (254/255), not for an
  582. unresolved slot and not for an AMS tray."""
  583. if tray_id is None:
  584. return False
  585. try:
  586. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  587. except (TypeError, ValueError):
  588. return False
  589. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  590. """Whether this printer could have two extruders, judged generously.
  591. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  592. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  593. why the MQTT command builder skips its own use_ams reconcile there. Anything
  594. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  595. with, external spools or not.
  596. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  597. behaviour it has always had, while a wrong "no" would rewrite a field that
  598. steers which nozzle prints. The model name is the first answer (it is what
  599. the command builder falls back to as well), then the same live evidence the
  600. dispatcher's extruder annotation uses — a second nozzle reporting a
  601. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  602. since a single-nozzle printer has exactly one.
  603. """
  604. if is_dual_nozzle_model(printer_model):
  605. return True
  606. nozzles = getattr(status, "nozzles", None) or []
  607. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  608. return True
  609. raw = getattr(status, "raw_data", None) or {}
  610. if raw.get("ams_extruder_map"):
  611. return True
  612. vt_trays = raw.get("vt_tray") or []
  613. return isinstance(vt_trays, list) and len(vt_trays) > 1
  614. def _int_or(value, default: int) -> int:
  615. """``int(value)``, or ``default`` when the field is missing or junk.
  616. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  617. the next — and a tray id that fails to parse must not take the whole
  618. derivation down with it.
  619. """
  620. try:
  621. return int(value)
  622. except (TypeError, ValueError):
  623. return default
  624. # What a queue job's dispatch is worked out from, and an edit can change.
  625. _DISPATCH_INPUTS = (
  626. "printer_id",
  627. "status",
  628. "ams_mapping",
  629. "plate_id",
  630. "filament_overrides",
  631. "skip_filament_check",
  632. "target_model",
  633. "target_location",
  634. )
  635. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  636. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  637. The pass works on the jobs as loaded at its start, and it may have waited
  638. since: a plug powering a printer on takes minutes. A job edited meanwhile
  639. (moved to another printer, given a mapping or another plate, cancelled)
  640. is left to the next pass, which reads it fresh: deciding from the stale
  641. copy would overwrite the edit, or send the job where it no longer goes.
  642. The query flushes the pass's own pending changes first, so those don't
  643. count as edits.
  644. """
  645. row = (
  646. await db.execute(
  647. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  648. )
  649. ).one_or_none()
  650. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  651. return False
  652. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  653. return True
  654. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  655. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  656. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  657. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  658. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  659. agree or a mapping cannot be read back against live tray telemetry.
  660. """
  661. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  662. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  663. """The global tray ids ``item`` actually prints from, or None if unknown.
  664. ``ams_mapping`` is the array the print command carries: position = filament
  665. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  666. not use. None means "no usable statement" — no mapping, unparseable JSON,
  667. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  668. documents), or one that resolves to no tray at all. Callers must treat None
  669. as "consider every loaded tray" rather than "consider none": narrowing on
  670. an absent mapping would silently drop requirements the print really has.
  671. """
  672. raw = getattr(item, "ams_mapping", None)
  673. if not raw:
  674. return None
  675. if isinstance(raw, str):
  676. try:
  677. mapping = json.loads(raw)
  678. except (json.JSONDecodeError, TypeError):
  679. return None
  680. else:
  681. mapping = raw
  682. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  683. return None
  684. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  685. return used or None
  686. def _mqtt_commands_rejected(status) -> bool:
  687. """True when the printer is currently reporting that it refused a command.
  688. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  689. a control command it could not verify. Queries still answer, so the printer
  690. looks connected and idle while project_file, gcode_line and
  691. ams_change_filament are all dropped — no amount of waiting or re-uploading
  692. changes that (#2732).
  693. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  694. ``print_error`` path builds HMSError differently), so this is safe to call on
  695. every watchdog poll.
  696. """
  697. for err in getattr(status, "hms_errors", None) or []:
  698. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  699. return True
  700. return False
  701. def _drying_ams_ids(status) -> list[int]:
  702. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  703. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  704. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  705. started (#2758) — it is a diagnostic, not a gate.
  706. Deliberately not used to block or stop drying before dispatch. This printer
  707. class supports drying concurrently with an active print
  708. (``supports_drying_while_printing``), so drying is not incompatible with
  709. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  710. while two AMS units were drying, one of them without its external PSU. Until
  711. it is known whether the blocker is drying itself or the power budget
  712. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  713. hardware is perfectly happy to continue.
  714. """
  715. ids: list[int] = []
  716. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  717. if not isinstance(unit, dict):
  718. continue
  719. try:
  720. if int(unit.get("dry_time") or 0) > 0:
  721. ids.append(int(unit.get("id", 0)))
  722. except (TypeError, ValueError):
  723. continue
  724. return ids
  725. def _parse_diameter(raw) -> float | None:
  726. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  727. try:
  728. value = float(raw)
  729. except (TypeError, ValueError):
  730. return None
  731. return value if value > 0 else None
  732. def _nozzle_info_by_id(status) -> dict[int, dict]:
  733. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  734. The field name is historical: on the H2 series ``nozzle_info`` carries an
  735. entry for *every* nozzle the printer knows about — the L/R hotends under
  736. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  737. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  738. :func:`_installed_nozzle_diameters` each take the half they need.
  739. """
  740. by_id: dict[int, dict] = {}
  741. for entry in getattr(status, "nozzle_rack", None) or []:
  742. if not isinstance(entry, dict):
  743. continue
  744. try:
  745. by_id[int(entry.get("id"))] = entry
  746. except (TypeError, ValueError):
  747. continue
  748. return by_id
  749. # What the firmware puts in a nozzle's serial number when the carriage or dock
  750. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  751. # its nozzle back in the rack (#2885).
  752. _EMPTY_NOZZLE_SERIAL = "N/A"
  753. def _nozzle_is_mounted(entry: dict | None) -> bool:
  754. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  755. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  756. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  757. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  758. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  759. the dock. So the diameter is not a presence signal (#2885).
  760. Emptiness has to be stated, not merely unstated. The serial must be the
  761. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  762. absent — an empty serial only means the printer didn't say, and a firmware
  763. that reports neither field normalises to exactly that. Treating "didn't
  764. say" as "empty" would silently switch the #1899 guard off on any such
  765. machine, so everything we cannot positively call empty counts as mounted.
  766. """
  767. if entry is None:
  768. return True
  769. serial = str(entry.get("serial_number") or "").strip().upper()
  770. if serial != _EMPTY_NOZZLE_SERIAL:
  771. return True
  772. try:
  773. max_temp = float(entry.get("max_temp") or 0)
  774. except (TypeError, ValueError):
  775. return True
  776. return max_temp > 0
  777. def _installed_nozzle_diameters(status) -> list[float]:
  778. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  779. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  780. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  781. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  782. told us its nozzle hardware" — callers must treat that as unknown, not as a
  783. mismatch, so we never block a print on missing data.
  784. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  785. though ``nozzles`` still carries a diameter for it: that value is stale, and
  786. counting it would let a slice match a nozzle the machine does not have
  787. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  788. """
  789. info = _nozzle_info_by_id(status)
  790. diameters: list[float] = []
  791. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  792. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  793. try:
  794. value = float(raw)
  795. except (TypeError, ValueError):
  796. continue
  797. if value > 0 and _nozzle_is_mounted(info.get(index)):
  798. diameters.append(value)
  799. return diameters
  800. def _rack_nozzle_diameters(status) -> list[float]:
  801. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  802. Keyed off the nozzle ids themselves rather than the printer model: only a
  803. rack machine ever reports ids 16-21, so there is no model registry to keep
  804. in sync. An empty dock is simply absent from the payload — measured on an
  805. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  806. present — so appearing here already means "a nozzle is in that dock".
  807. ``stat`` is deliberately not interpreted: its values aren't known, and
  808. reading it wrongly could hide a nozzle the printer would happily fetch.
  809. """
  810. diameters: list[float] = []
  811. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  812. if nozzle_id not in _RACK_NOZZLE_IDS:
  813. continue
  814. # PrinterState spells it "diameter"; the REST schema renames it to
  815. # "nozzle_diameter". Accept either so a caller holding the serialised
  816. # shape gets the same answer.
  817. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  818. if value is not None:
  819. diameters.append(value)
  820. return diameters
  821. def _format_diameters(diameters: list[float]) -> str:
  822. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  823. Deduplicated because a loaded rack holds several nozzles of the same size,
  824. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  825. short form doesn't. Matching still runs over the full list.
  826. """
  827. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  828. def _nozzle_mismatch_message(
  829. sliced_nozzle: float | None,
  830. installed: list[float],
  831. rack: list[float] | None = None,
  832. ) -> str | None:
  833. """Return an actionable error message when the sliced nozzle can't be
  834. printed on any nozzle the machine can reach, else None (#1899).
  835. Fail-safe: returns None whenever we lack the data to judge — no sliced
  836. diameter, or the printer reported no nozzles — so a print is only ever
  837. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  838. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  839. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  840. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  841. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  842. as reachable: the printer fetches one as part of starting the print, so a
  843. slice that matches a docked nozzle is not a mismatch. Without this the
  844. guard blocked every job whose nozzle happened not to be on a hotend at
  845. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  846. diameter already mounted could ever print, and the user had to fetch the
  847. nozzle by hand on the printer's own UI first (#2885).
  848. """
  849. reachable = [*installed, *(rack or [])]
  850. if not sliced_nozzle or not reachable:
  851. return None
  852. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  853. return None
  854. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  855. if rack:
  856. where += f" and {_format_diameters(rack)} in the nozzle rack"
  857. return (
  858. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  859. f"{where}. Re-slice for an available nozzle, or fit the matching "
  860. f"nozzle before printing."
  861. )
  862. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  863. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  864. Shared by the required and loaded sides, which name their extruder
  865. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  866. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  867. 1 the left/deputy — and both are absent on single-nozzle printers, where
  868. naming a nozzle would be noise.
  869. """
  870. parts = [(entry.get("type") or "filament").upper()]
  871. if entry.get("color"):
  872. parts.append(str(entry["color"]))
  873. nozzle = entry.get(nozzle_key)
  874. if nozzle == 0:
  875. parts.append("(right nozzle)")
  876. elif nozzle == 1:
  877. parts.append("(left nozzle)")
  878. return " ".join(parts)
  879. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  880. """Explain that nothing loaded matches what the file needs (#2771).
  881. Only ever built for a printer with no AMS, where the loaded list is short
  882. enough to quote in full and there is no "load another spool and hit Resume"
  883. recovery — the external spool holder is all there is, so the user needs to
  884. be told which filament to put on it.
  885. """
  886. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  887. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  888. return (
  889. f"No filament loaded on this printer matches the file. It needs {want}; "
  890. f"the printer has {have} and no AMS. Load the required filament on the "
  891. f"external spool holder, or send this job to a printer that has it."
  892. )
  893. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  894. """Bed temperature for the plate a queued job prints, 0 when unknown.
  895. The archive stores the highest bed temperature of any filament in the
  896. project, while the job may print another plate than the one archived: a
  897. PLA plate of a project that also holds PETG is heated for PLA. Read from
  898. the archive's file for the job's own plate, falling back to the stored
  899. value when the file can't be read.
  900. """
  901. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  902. if archive is None or not archive.file_path:
  903. return stored
  904. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  905. return temperature or stored
  906. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  907. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  908. every call site below it: G-code injection, usage registration, rack-plan
  909. lookup, slot-extruder lookup, the external-spool check, and the actual
  910. print command.
  911. A positive explicit ``plate_id`` on the queue item always wins. A
  912. non-positive one is treated as "not set" and resolved from the archive,
  913. the way the rest of the queue code already reads it (``if item.plate_id:``
  914. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  915. field, and passing a 0 straight through would build a print command for
  916. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  917. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  918. Falling back to a bare ``1`` instead of reading the archive assumes a
  919. single-plate file's one G-code is numbered 1, which only holds for a
  920. plate exported on its own: one cut out of a larger project keeps its
  921. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  922. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  923. the file, throws an HMS error, and sits wedged in IDLE until
  924. power-cycled (#2947).
  925. The call sites agreed on a fallback only by accident before this:
  926. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  927. the archive's own default plate internally whenever the plate id it's
  928. handed isn't in the file, so it could silently inject into a different
  929. plate than the one the print command itself asked for.
  930. Falls back to 1 when the archive can't be read, holds no G-code member at
  931. all, or its default member doesn't follow the ``plate_N`` naming
  932. convention (a slicer that doesn't use it has no number to dispatch).
  933. An explicit plate the archive doesn't hold is logged and then sent
  934. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  935. to a plate that is in the file would print a model nobody asked for,
  936. which is the worse of the two.
  937. """
  938. try:
  939. with zipfile.ZipFile(file_path, "r") as zf:
  940. names = zf.namelist()
  941. except (OSError, zipfile.BadZipFile) as exc:
  942. logger.warning(
  943. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  944. "is unavailable; dispatching plate %s",
  945. file_path,
  946. exc,
  947. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  948. )
  949. names = None
  950. if explicit_plate_id is not None and explicit_plate_id > 0:
  951. if (
  952. names is not None
  953. and default_plate_number(names) is not None
  954. and select_plate_gcode_name(names, explicit_plate_id) is None
  955. ):
  956. logger.warning(
  957. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  958. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  959. "file, since printing a different plate would print the wrong model (#2947)",
  960. file_path,
  961. explicit_plate_id,
  962. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  963. explicit_plate_id,
  964. )
  965. return explicit_plate_id
  966. resolved = default_plate_number(names) if names is not None else None
  967. return resolved if resolved is not None else 1
  968. class PrintScheduler:
  969. """Background scheduler that processes the print queue."""
  970. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  971. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  972. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  973. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  974. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  975. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  976. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  977. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  978. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  979. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  980. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  981. }
  982. def __init__(self):
  983. self._running = False
  984. self._check_interval = 30 # seconds
  985. # After a pass that actually dispatched something, loop again almost
  986. # immediately instead of sleeping the full interval (#2555). A dispatch
  987. # changes printer state — a batch launch fans out over several passes as
  988. # printers free up, a wedged head-of-line job reverts to pending, an
  989. # upload slot opens — and the next batch of ready work should not have to
  990. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  991. # pending items are behind printers that are genuinely busy printing),
  992. # there is nothing to react to, so we fall back to the normal interval;
  993. # that also means this can never tight-loop, since fast ticks only
  994. # continue while dispatches keep happening and the queue is draining.
  995. self._fast_check_interval = 3 # seconds
  996. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  997. self._power_on_check_interval = 10 # seconds between connection checks
  998. # Printers whose class-target power-on failed, mapped to the monotonic
  999. # time their cool-off expires (#2786).
  1000. #
  1001. # Without this, one printer with an unreachable plug starves every
  1002. # sibling of its model forever: the wake step walks candidates in id
  1003. # order, spends the pass's single attempt on the same broken printer
  1004. # every time, and the healthy one two slots down is never reached. It
  1005. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1006. # which delays the whole queue, not just this job.
  1007. #
  1008. # Entries expire on read rather than being cleared on success: a printer
  1009. # inside its cool-off is skipped before the power-on is reached, so a
  1010. # live entry can never be overwritten by a success anyway. A printer
  1011. # that comes back by any other route stops being a wake candidate the
  1012. # moment it connects.
  1013. self._wake_failures: dict[int, float] = {}
  1014. self._wake_failure_cooloff = 600 # seconds
  1015. # Printers whose last upload never reached them, mapped to the monotonic
  1016. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1017. # as `_wake_failures`. Without it, a printer that cannot take files is
  1018. # idle on every pass, so it is picked on every pass.
  1019. self._upload_backoff: dict[int, float] = {}
  1020. # Refused uploads in a row per printer, which sets the next backoff
  1021. # window. Cleared by a successful upload to that printer.
  1022. self._upload_refusals: dict[int, int] = {}
  1023. # Printers whose current run of refusals has already sent its one
  1024. # "job waiting" notification. Each retry clears the item's waiting
  1025. # reason and the next refusal sets it again, which `hold_item` reads as
  1026. # a new reason; without this, every retry would notify. Cleared with
  1027. # `_upload_refusals`.
  1028. self._upload_refusal_notified: set[int] = set()
  1029. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1030. self._drying_in_progress: dict[int, float] = {}
  1031. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1032. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1033. # cycle and the humidity finally coming down, so the normal steady
  1034. # state is an empty dict. Fields:
  1035. # running — a cycle we armed is (or should be) on the firmware
  1036. # ended_at — monotonic when we observed that cycle end
  1037. # unproductive — consecutive armed cycles that ended with the reading
  1038. # still above the threshold
  1039. # suspended — we have stopped arming this unit and said so
  1040. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1041. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1042. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1043. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1044. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1045. # arming setdefault all act on that meaning -- a unit that is merely
  1046. # waiting out its streak must not become stoppable or judgeable.
  1047. # since -- monotonic stamp when the current continuous above-threshold
  1048. # streak began
  1049. # last -- monotonic stamp of the last pass that observed the streak
  1050. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1051. # Slots already notified as low on filament:
  1052. # {(printer_id, ams_id, tray_id, spool_id)}.
  1053. # Cleared when the slot goes back above its threshold rather than on a
  1054. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1055. # boundary must not produce an alert on every pass, and a slot that has
  1056. # been refilled has to be able to alert again. See #2913.
  1057. #
  1058. # The spool id is part of the key because the slot alone cannot clear
  1059. # itself. Pull a low spool and put a different part-used one in the same
  1060. # slot: the key survives the pass where the slot resolves to nothing --
  1061. # deliberately, so a brief Spoolman outage does not re-alert everything
  1062. # when it returns -- and the replacement never goes above the threshold,
  1063. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1064. # different key and the stale one is inert.
  1065. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1066. # The same, for the MQTT relay's filament/low event: its own record, so
  1067. # one channel having been told never silences the other.
  1068. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1069. # Earliest monotonic time the next low-filament check may run (#2913).
  1070. self._filament_low_next_check: float = 0.0
  1071. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1072. # condition is "reorder" or "break", the events are those that had a
  1073. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1074. # condition clears, so it can alert again, and when nobody wants either
  1075. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1076. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1077. # re-send one message per SKU that is still low.
  1078. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1079. # The JSON last read from or written to that row; None until it has been read.
  1080. self._stock_alerts_persisted: str | None = None
  1081. # Earliest monotonic time the next stock forecast check may run (#2955).
  1082. self._stock_forecast_next_check: float = 0.0
  1083. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1084. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1085. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1086. # both features share _drying_in_progress.
  1087. self._scheduled_drying_printer_ids: set[int] = set()
  1088. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1089. # the first pass after a restart reaps anything left behind.
  1090. self._last_scheduled_drying_prune: float | None = None
  1091. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1092. # a project_file command must not get a second dispatch until either it
  1093. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1094. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1095. # during that window the DB busy_printers seed is empirically unreliable
  1096. # (multi-plate batches double-/triple-dispatched onto the same printer
  1097. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1098. # or revert.
  1099. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1100. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1101. # Minimum cooldown between dispatches to the same printer (covers the
  1102. # H2D's project_file digestion window).
  1103. self._dispatch_min_cooldown = 60.0
  1104. # Hard timeout — drop the hold even if we never observed a transition,
  1105. # so a lost MQTT session can't lock a printer out of the queue forever.
  1106. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1107. # watchdog runs first on the unhappy path.
  1108. self._dispatch_max_hold = 180.0
  1109. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1110. # an earlier pass and is still running. `_start_print` flips the row
  1111. # pending -> printing only *after* the upload completes, so until then
  1112. # the row stays `pending`: each tick, check_queue excludes these
  1113. # item_ids from re-selection and their printers from new dispatch /
  1114. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1115. # freed slots refill on the next fast tick. check_queue is the sole,
  1116. # sequential caller and the prune done-callbacks run in the same
  1117. # event-loop thread, so this dict needs no lock.
  1118. # item_id -> (task, printer_id)
  1119. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1120. # Expected prints registered by `_start_print` that have not yet had a
  1121. # print command sent. Populated at registration, dropped once
  1122. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1123. # other exit. Same threading argument as `_inflight` above: one
  1124. # sequential caller, callbacks on the same loop, so no lock.
  1125. # item_id -> (printer_id, remote_filename, archive_id)
  1126. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1127. # Budget reservations created for a dispatch whose print command has
  1128. # not been confirmed yet. `_dispatch_one` releases these on every
  1129. # unsuccessful exit; a successful start removes the item id and leaves
  1130. # the reservation for finance_billing to consume with the archive.
  1131. self._unconfirmed_budget_reservations: set[int] = set()
  1132. # The print user `_start_print` handed to printer_manager for an item
  1133. # whose print command has not been sent yet (item_id -> printer_id).
  1134. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1135. # expected print above: it marks the printer's next print as Bambuddy's.
  1136. self._unconfirmed_print_user: dict[int, int] = {}
  1137. # Prints whose command went out but which the printer has not been
  1138. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1139. # the file and archive None for a library print. The watchdog drops the
  1140. # entry once the print runs, and withdraws what it stands for when the
  1141. # print never starts (see `_forget_unstarted_print`).
  1142. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1143. # Chamber temperature history for smart soak-time reduction.
  1144. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1145. # Entries older than _chamber_history_ttl are pruned on write.
  1146. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1147. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1148. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1149. # Populated on engagement in `_apply_keep_warm`, cleared by
  1150. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1151. # when a gate setting toggles off mid-hold — the release publishes
  1152. # bed → 0 first).
  1153. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1154. # Preheat rollback registry: printer_id -> subset of
  1155. # {"bed", "chamber", "airduct"} listing which preheat commands
  1156. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1157. # every entry still present at exit unless the print successfully
  1158. # started, so a failed upload / cancel / exception never leaves the
  1159. # printer heating for a job that isn't happening.
  1160. self._preheat_pin: dict[int, set[str]] = {}
  1161. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1162. # rollback can tell its own target from one someone else has since
  1163. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1164. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1165. self._preheat_pin_bed: dict[int, int] = {}
  1166. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1167. # its preheat was still holding at temperature. Set by
  1168. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1169. # `_preheat_sleep`, and cleared when the dispatch exits.
  1170. self._cancelled_dispatches: set[int] = set()
  1171. # printer_id -> monotonic time it was first seen terminal while one of
  1172. # its queue rows was still 'printing'. Reset by any non-terminal
  1173. # observation, so it measures an unbroken run rather than a total.
  1174. # In-memory on purpose: a restart re-arms the grace period, which only
  1175. # delays a recovery that is already the exceptional path (#2829).
  1176. self._terminal_since: dict[int, float] = {}
  1177. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1178. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1179. # across idle printers repeats that for every one of them in a single
  1180. # pass. Cleared at the top of each pass so a re-sliced file is never
  1181. # served from a previous tick.
  1182. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1183. # When each "any model" job held for low filament last looked for
  1184. # another printer (#3137), by queue item id.
  1185. self._short_hold_checked_at: dict[int, float] = {}
  1186. async def run(self):
  1187. """Main loop - check queue every interval."""
  1188. self._running = True
  1189. logger.info("Print scheduler started")
  1190. await self._clear_stale_dispatch_claims(at_startup=True)
  1191. while self._running:
  1192. dispatched = False
  1193. try:
  1194. self._sample_chamber_temps()
  1195. # No-op while any upload is in flight; on a quiet tick it releases
  1196. # a claim whose best-effort clear failed (e.g. the database was
  1197. # briefly unreachable), instead of leaving the row wedged until
  1198. # the next restart.
  1199. await self._clear_stale_dispatch_claims()
  1200. await self._close_stranded_printing_items()
  1201. dispatched = await self.check_queue()
  1202. except Exception as e:
  1203. logger.error("Scheduler error: %s", e)
  1204. # Re-check quickly after a productive pass so a draining batch does
  1205. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1206. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1207. async def _close_stranded_printing_items(self) -> None:
  1208. """Close a ``printing`` row the completion event never closed (#2829).
  1209. ``on_print_complete`` refuses to close a row when the completion's
  1210. subtask name disagrees with the file the row was dispatched with, so a
  1211. completion meant for something else (the printer's own
  1212. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1213. The refusal has no way back, though: nothing else ever closes the row,
  1214. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1215. one bad comparison wedges that printer's queue until a human presses
  1216. cancel. That is what #2829's reporters hit, and the guard's own
  1217. docstring already called stranding the worse of the two failures.
  1218. This is the way back. When a row has been ``printing`` while its
  1219. printer sat in a terminal state for the whole grace period, the print
  1220. is over however the event was read, and the row is closed with the
  1221. status the printer's own state implies.
  1222. Deliberately conservative:
  1223. * Only a connected printer counts. A disconnected one has a stale
  1224. ``state`` and proves nothing.
  1225. * The clock is reset by any non-terminal observation, so this cannot
  1226. fire on a printer that is merely between stages.
  1227. * The grace period is far longer than the gap between a printer
  1228. finishing and its completion arriving, so the normal path always
  1229. wins the race and this only ever sees genuine strandings.
  1230. What it does *not* do is replay the completion's side effects --
  1231. notifications, billing, auto-off. It restores the queue, which is the
  1232. harm being undone; the archive was updated by the normal path
  1233. regardless, since only the queue block refuses. A recovery that
  1234. silently re-fired notifications minutes late would be its own bug.
  1235. """
  1236. try:
  1237. async with async_session() as db:
  1238. result = await db.execute(
  1239. select(PrintQueueItem)
  1240. .where(PrintQueueItem.status == "printing")
  1241. .where(PrintQueueItem.printer_id.is_not(None))
  1242. )
  1243. items = list(result.scalars().all())
  1244. if not items:
  1245. self._terminal_since.clear()
  1246. return
  1247. now = time.monotonic()
  1248. seen_printers: set[int] = set()
  1249. closed = False
  1250. for item in items:
  1251. printer_id = item.printer_id
  1252. seen_printers.add(printer_id)
  1253. state = printer_manager.get_status(printer_id)
  1254. status = _terminal_queue_status(state)
  1255. if status is None:
  1256. self._terminal_since.pop(printer_id, None)
  1257. continue
  1258. since = self._terminal_since.setdefault(printer_id, now)
  1259. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1260. continue
  1261. item.status = status
  1262. item.completed_at = datetime.now(timezone.utc)
  1263. closed = True
  1264. # The printer is idle: nothing it prints next is this item's.
  1265. self._forget_unstarted_print(item.id, unless_printing=True)
  1266. logger.warning(
  1267. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1268. "closing it as %s. Its completion event was never matched to it, which blocks "
  1269. "every later job for this printer (#2829).",
  1270. item.id,
  1271. printer_id,
  1272. getattr(state, "state", None),
  1273. now - since,
  1274. status,
  1275. )
  1276. if closed:
  1277. await db.commit()
  1278. from backend.app.services.print_batch import refresh_batches_after
  1279. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1280. for printer_id in list(self._terminal_since):
  1281. if printer_id not in seen_printers:
  1282. del self._terminal_since[printer_id]
  1283. except Exception as e:
  1284. # Best-effort, same as the claim sweep beside it: a recovery path
  1285. # that can itself break the scheduler loop is worse than the strand.
  1286. logger.error("Stranded-item sweep failed: %s", e)
  1287. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1288. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1289. A claim is only ever held by a live dispatch coroutine, so when this
  1290. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1291. is stale. At startup that is trivially true — no coroutine survives a
  1292. restart. It is equally true on any later tick where no upload is running,
  1293. which is what makes this safe to repeat rather than only run once.
  1294. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1295. the database is briefly unreachable at exactly the moment dispatch ends,
  1296. the claim survives and the row is wedged out of the selection query. That
  1297. used to last until the next restart (#2702 follow-up, seen when
  1298. PostgreSQL refused a connection mid-dispatch).
  1299. ``_inflight`` is populated when the task is spawned, before the coroutine
  1300. claims its row, and pruned by a done-callback that cannot run before the
  1301. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1302. race window and needs no age threshold. A size-derived upload deadline
  1303. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1304. """
  1305. if self._inflight:
  1306. return
  1307. try:
  1308. async with async_session() as db:
  1309. res = await db.execute(
  1310. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1311. )
  1312. await db.commit()
  1313. if res.rowcount:
  1314. logger.info(
  1315. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1316. res.rowcount,
  1317. " at startup" if at_startup else "",
  1318. )
  1319. except Exception as exc:
  1320. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1321. def stop(self):
  1322. """Stop the scheduler."""
  1323. self._running = False
  1324. logger.info("Print scheduler stopped")
  1325. def forget_printer(self, printer_id: int) -> None:
  1326. """Drop what is kept for a deleted printer, so the next printer given its
  1327. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1328. would keep it out of dispatch for up to an hour.
  1329. A dispatch already in flight keeps its own state (_inflight, the preheat
  1330. pins, unconfirmed prints): it unwinds that when it ends.
  1331. """
  1332. for keyed in (
  1333. self._upload_backoff,
  1334. self._upload_refusals,
  1335. self._wake_failures,
  1336. self._drying_in_progress,
  1337. self._dispatch_holds,
  1338. self._chamber_history,
  1339. self._keep_warm,
  1340. self._terminal_since,
  1341. ):
  1342. keyed.pop(printer_id, None)
  1343. self._upload_refusal_notified.discard(printer_id)
  1344. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1345. for key in [key for key in keyed if key[0] == printer_id]:
  1346. del keyed[key]
  1347. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1348. del self._sent_unstarted_print[item_id]
  1349. async def check_queue(self) -> bool:
  1350. """Check for prints ready to start.
  1351. Returns True if this pass dispatched at least one item, so the caller
  1352. can loop again quickly instead of sleeping the full interval (#2555).
  1353. """
  1354. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1355. self._filament_req_memo.clear()
  1356. async with async_session() as db:
  1357. # Check if shortest-job-first scheduling is enabled
  1358. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1359. # Get all pending items in the one order the queue page shows them
  1360. # in (#3200). The first eligible item takes a printer, so this order
  1361. # decides who wins a printer that a pinned job and an "Any <model>"
  1362. # job both want. It used to start with ``printer_id``, which made the
  1363. # lane outrank the position: SQLite sorts NULL first, so model-based
  1364. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1365. # Neither is what the user dragged into place.
  1366. if sjf_enabled:
  1367. # SJF: items already jumped get top priority (starvation guard),
  1368. # then sort by print_time ascending. Items with no print time go
  1369. # last, and position breaks ties.
  1370. result = await db.execute(
  1371. select(PrintQueueItem)
  1372. .where(PrintQueueItem.status == "pending")
  1373. # Never re-select a row a dispatch worker has already claimed
  1374. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1375. # below, and the guard that lets an orphaned claim be ignored
  1376. # until startup reconciliation clears it.
  1377. .where(PrintQueueItem.dispatching_at.is_(None))
  1378. # archive/library_file are read by the cross-model gate
  1379. # (#2578); eager-load once per pass instead of a lazy-load
  1380. # (which would raise in async) per item.
  1381. .options(
  1382. selectinload(PrintQueueItem.archive),
  1383. selectinload(PrintQueueItem.library_file),
  1384. # Cross-model candidates (#671), plus each candidate's file
  1385. # for the same cross-model gate. Lazy-loading either would
  1386. # raise in async.
  1387. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1388. )
  1389. .order_by(
  1390. PrintQueueItem.been_jumped.desc(),
  1391. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1392. PrintQueueItem.position,
  1393. PrintQueueItem.id,
  1394. )
  1395. )
  1396. else:
  1397. result = await db.execute(
  1398. select(PrintQueueItem)
  1399. .where(PrintQueueItem.status == "pending")
  1400. # Skip rows already claimed by a dispatch worker (#2615).
  1401. .where(PrintQueueItem.dispatching_at.is_(None))
  1402. .options(
  1403. selectinload(PrintQueueItem.archive),
  1404. selectinload(PrintQueueItem.library_file),
  1405. # Cross-model candidates (#671), plus each candidate's file
  1406. # for the same cross-model gate. Lazy-loading either would
  1407. # raise in async.
  1408. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1409. )
  1410. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1411. )
  1412. items = list(result.scalars().all())
  1413. # Drop rows whose upload is still in flight from an earlier pass
  1414. # (#2602). They stay `pending` until the upload finishes, so without
  1415. # this a fast tick would re-select and re-dispatch the same row.
  1416. # Belt-and-suspenders with the printer exclusion below.
  1417. if self._inflight:
  1418. inflight_ids = set(self._inflight)
  1419. items = [it for it in items if it.id not in inflight_ids]
  1420. # Read plate-clear setting once per queue check. Default MUST be
  1421. # False to match the schema (SettingsSchema.require_plate_clear
  1422. # defaults False) and the frontend (toggle + card badge both treat a
  1423. # missing value as off). When no settings row exists, a True default
  1424. # here re-enabled the plate-clear gate the UI showed as disabled,
  1425. # blocking dispatch to FINISH-state printers forever with no UI path
  1426. # to clear it (#1865).
  1427. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1428. # Dispatch and track scheduled drying runs (#2638)
  1429. await self._check_scheduled_dryings(db)
  1430. if not items:
  1431. # No dispatchable pending items — still check auto-drying on idle
  1432. # printers, but keep any printer with an upload still in flight
  1433. # from an earlier pass out of it (#2602): its print is imminent,
  1434. # so it must not be auto-dried in the gap before the row flips to
  1435. # printing. Report the pass as productive while uploads run so the
  1436. # loop stays on the fast interval.
  1437. #
  1438. # Also release any keep-warm holds that got orphaned by the queue
  1439. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1440. # this early return, so call it directly with an empty candidate
  1441. # set. Without this, a printer whose queued item was cancelled or
  1442. # deleted would keep its bed at target until the max-duration
  1443. # timeout expired.
  1444. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1445. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1446. await self._check_auto_drying(db, [], inflight_printers)
  1447. await self._check_filament_low(db)
  1448. await self._check_stock_forecast(db)
  1449. return bool(self._inflight)
  1450. logger.info(
  1451. "Queue check: found %d pending items: %s",
  1452. len(items),
  1453. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1454. )
  1455. # Forget jobs that left the queue since they were last checked.
  1456. pending_ids = {i.id for i in items}
  1457. self._short_hold_checked_at = {
  1458. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1459. }
  1460. # Seed busy_printers with printers that already have an item in 'printing'
  1461. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1462. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1463. # lag several seconds behind the print command, so the next check_queue
  1464. # tick still sees IDLE and would double-dispatch onto the same printer.
  1465. # Without this guard, two pending items targeting the same printer
  1466. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1467. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1468. busy_result = await db.execute(
  1469. select(PrintQueueItem.printer_id)
  1470. .where(PrintQueueItem.status == "printing")
  1471. .where(PrintQueueItem.printer_id.is_not(None))
  1472. )
  1473. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1474. # Why each printer left this pass, recorded where the decision is
  1475. # made rather than re-derived when the summary is logged. #3018's
  1476. # bundle shows what the old summary produced: "printer 1 not
  1477. # available -- connected=True, state=IDLE" immediately followed by a
  1478. # dispatch to printer 1. Two things went wrong at once. The line read
  1479. # live state at log time, which by then no longer matched the state
  1480. # the decision was made on; and `busy_printers` holds both printers
  1481. # that cannot take work and printers this pass has claimed for it,
  1482. # which are opposite facts. It is the first line anyone greps for
  1483. # "why did my item not go out", so it has to say which.
  1484. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1485. # Printers this pass is dispatching to. They are in busy_printers so
  1486. # nothing else in the pass targets them -- that is a reservation, not
  1487. # an obstruction, and the summary says so.
  1488. claimed_printers: set[int] = set()
  1489. def mark_busy(printer_id: int, reason: str) -> None:
  1490. """Take ``printer_id`` out of this pass, recording why.
  1491. First reason wins: a printer already excluded by a stronger fact
  1492. -- a print running on it -- must not be relabelled by a weaker
  1493. check that ran later and would have excluded it anyway.
  1494. """
  1495. busy_printers.add(printer_id)
  1496. busy_reasons.setdefault(printer_id, reason)
  1497. def claim_printer(printer_id: int) -> None:
  1498. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1499. claimed_printers.add(printer_id)
  1500. mark_busy(printer_id, "selected for dispatch in this pass")
  1501. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1502. # worded for a different audience: the log wants "still inside its
  1503. # post-dispatch hold window", the queue row wants to know the printer
  1504. # is taken and nothing is broken. Only the cases that would read wrong
  1505. # as a plain "Busy" are recorded here; the rest fall back to it.
  1506. item_hold_reasons: dict[int, str] = {}
  1507. # Names and models for the printers this pass may have to write a
  1508. # waiting reason about, read once rather than per skip per tick. The
  1509. # model-based branch already has its names from `_printers_for_model`.
  1510. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1511. pinned_printers: dict[int, tuple[str, str]] = {}
  1512. if pinned_printer_ids:
  1513. pinned_rows = await db.execute(
  1514. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1515. )
  1516. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1517. def printer_label(printer_id: int) -> str:
  1518. """What to call this printer in a queue row."""
  1519. entry = pinned_printers.get(printer_id)
  1520. return (entry[0] if entry else "") or f"printer {printer_id}"
  1521. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1522. """Record why *item* is not going out, in the words the queue row shows.
  1523. The fixed-printer branch's single writer for ``waiting_reason``
  1524. (#3074). Before this, the sensor interlock was the only thing that
  1525. wrote the field there, so an item pinned to a printer that was
  1526. merely printing sat at `pending` with nothing to show for it —
  1527. indistinguishable from a queue that had stopped working — while
  1528. the same job queued as "Any <model>" explained itself.
  1529. Every exit from that branch now calls this, which is also what
  1530. replaced the interlock's old habit of clearing the field up front:
  1531. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1532. because whichever exit runs next overwrites it and the dispatch
  1533. path clears it.
  1534. A notification goes out when this item starts asking for
  1535. something, and only then: the new reason needs the user, and what
  1536. it replaced did not. "What it replaced did not" has to include a
  1537. busy-only reason, not just an empty one. The sequence this branch
  1538. actually produces is a print running (``Busy: X1C-01``) and then
  1539. the plate it left behind (``Waiting for plate confirmation``), and
  1540. testing "was the field empty" would call that no transition at all
  1541. and stay quiet through the one case worth saying out loud.
  1542. The cost is that a printer dropping offline, coming back busy and
  1543. dropping again asks twice rather than once. That is the honest
  1544. reading — it went wrong twice — and the alternative was a rule
  1545. that never fired for the case this was built for.
  1546. *notify* is how a caller opts out. The sensor interlock does: it
  1547. has never sent this notification, and a change about what the
  1548. queue *displays* is not the place to start (#1148).
  1549. """
  1550. if item.waiting_reason == reason:
  1551. return
  1552. # Busy-only and empty are the same thing here: neither is the
  1553. # queue asking the user for anything.
  1554. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1555. item.waiting_reason = reason
  1556. await db.commit()
  1557. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1558. return
  1559. try:
  1560. job_name = await self._get_job_name(db, item)
  1561. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1562. await notification_service.on_queue_job_waiting(
  1563. job_name=job_name,
  1564. target_model=(entry[1] if entry else "") or "",
  1565. waiting_reason=reason,
  1566. db=db,
  1567. printer_id=item.printer_id,
  1568. )
  1569. except Exception as e:
  1570. # A queue that cannot say why it is waiting is the bug being
  1571. # fixed here; a queue that stops dispatching because a
  1572. # notification provider is down would be a worse one.
  1573. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1574. async def hold_for_printer(
  1575. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1576. ) -> None:
  1577. """Take *printer_id* out of this pass and tell the item's owner why."""
  1578. mark_busy(printer_id, log_reason)
  1579. item_hold_reasons.setdefault(printer_id, item_reason)
  1580. await hold_item(item, item_reason)
  1581. # Defense-in-depth (#1157): augment busy_printers with any printer
  1582. # still in its post-dispatch hold window. Empirically, the DB seed
  1583. # above can miss in-flight items in a multi-plate batch — same-file
  1584. # plates were being dispatched 30 s apart while the H2D was still
  1585. # digesting the first project_file. The hold is keyed in-memory and
  1586. # released by the watchdog on the success path, so it adds a layer
  1587. # that doesn't depend on DB row visibility or completion-callback
  1588. # timing.
  1589. for held_printer_id in list(self._dispatch_holds.keys()):
  1590. if self._printer_in_dispatch_hold(held_printer_id):
  1591. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1592. # Exclude printers whose upload is still in flight from an earlier
  1593. # pass (#2602). The row is `pending` until the upload finishes and
  1594. # the printing-state seed / dispatch hold above only arm once the
  1595. # upload completes, so this is what holds the printer (and, via
  1596. # busy_printers, its auto-drying) out of the pass during the upload.
  1597. for _task, inflight_pid in self._inflight.values():
  1598. if inflight_pid is not None:
  1599. mark_busy(inflight_pid, "an upload to it is still in flight")
  1600. # Snapshot taken here, before the item loop adds anything (#2801).
  1601. #
  1602. # The three sources above all mean the same thing: a print on this
  1603. # printer is running or imminent. Everything the loop adds below
  1604. # means only "the queue could not dispatch to it this pass", which
  1605. # is a different statement -- a printer waiting on a plate-clear
  1606. # acknowledgment, an offline printer, one with no matching file.
  1607. #
  1608. # Auto-drying must only see the first kind. Reading the whole set
  1609. # as "is currently printing" is what put a plate-held printer down
  1610. # the mid-print path: it capped the drying temperature, logged the
  1611. # cycle as (mid-print), and skipped the very gate that was supposed
  1612. # to hold it. The interlock block below already documents the same
  1613. # hazard and works around it by staying out of busy_printers; this
  1614. # generalises that workaround instead of repeating it per case.
  1615. dispatching_printers: set[int] = set(busy_printers)
  1616. # Printers whose last upload never reached them (#3210). After the
  1617. # snapshot above on purpose: such a printer is idle, not about to
  1618. # print, and auto-drying must keep treating it as idle.
  1619. now_mono = time.monotonic()
  1620. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1621. # can leave them out: there is no print to keep a bed warm for.
  1622. backoff_printers: set[int] = set()
  1623. # In backoff, and the "job waiting" notification for this run of
  1624. # refusals has gone out already. Their holds are written silently.
  1625. silent_hold_printers: set[int] = set()
  1626. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1627. if now_mono >= retry_at:
  1628. del self._upload_backoff[backoff_pid]
  1629. continue
  1630. backoff_printers.add(backoff_pid)
  1631. if backoff_pid in self._upload_refusal_notified:
  1632. silent_hold_printers.add(backoff_pid)
  1633. else:
  1634. self._upload_refusal_notified.add(backoff_pid)
  1635. mark_busy(
  1636. backoff_pid,
  1637. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1638. )
  1639. item_hold_reasons.setdefault(
  1640. backoff_pid,
  1641. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1642. )
  1643. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1644. # enclosure door left open, say. The fixed-printer branch turns
  1645. # this into a waiting_reason the user can act on; the model-based
  1646. # branch hides these printers from the matcher so an "Any <model>"
  1647. # job runs on a sibling instead of queueing behind the held one.
  1648. #
  1649. # Deliberately NOT merged into busy_printers, even though that set
  1650. # already means "unavailable this pass". _check_auto_drying reads
  1651. # it as "is currently printing" and would put an idle-but-held
  1652. # printer down the mid-print drying path, which caps the drying
  1653. # temperature and skips the queue-only gating. A held printer is
  1654. # idle; it should dry exactly as it did before.
  1655. #
  1656. # Only sensors we actually read and found alerting appear here; see
  1657. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1658. # holds nothing.
  1659. interlocked: dict[int, str] = {}
  1660. try:
  1661. interlocked = await ha_sensor_manager.blocked_printers(db)
  1662. except Exception as e:
  1663. # Never let the interlock stop the queue running. A broken
  1664. # lookup means no holds, not no dispatches.
  1665. logger.warning("Home Assistant interlock check failed: %s", e)
  1666. interlocked = {}
  1667. # Printers a smart plug can bring back, read once for the whole pass
  1668. # (#2786). Used by the model-based branch both to word "Offline" in
  1669. # the waiting reason and to decide what the wake step may switch on.
  1670. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1671. # At most one power-on per queue check. Each one blocks this loop
  1672. # for the boot wait, so a queue of ten class-targeted jobs must not
  1673. # switch on ten printers inside a single pass — the next pass wakes
  1674. # the next one (#2786).
  1675. power_on_attempted = False
  1676. # Log skip reasons once per queue check (not per item)
  1677. skip_reasons: dict[str, int] = {}
  1678. # Items selected for dispatch in this pass, one per printer. The
  1679. # loop below only *decides* — the uploads happen afterwards, in
  1680. # parallel (#2555). See _dispatch_selected().
  1681. dispatch_ids: list[int] = []
  1682. # Library rows queued with `cleanup_library_after_dispatch` (the
  1683. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1684. # that prints them: the row is deleted and the 3MF is unlinked from
  1685. # disk. That was safe only because dispatch was serial. Run two of
  1686. # them against the same row at once and the second DELETE matches no
  1687. # row (StaleDataError), and the winner's unlink can pull the file out
  1688. # from under the loser's in-flight upload.
  1689. #
  1690. # Only the cleanup flag mutates the row. An ordinary library print
  1691. # just reads it, so the common fan-out — one file, many printers,
  1692. # which is exactly the reporter's workload — still goes out fully in
  1693. # parallel. Narrow the guard to the mutating case; do not serialise
  1694. # the case the whole fix exists for.
  1695. dispatch_libs: set[int] = set()
  1696. consumed_libs: set[int] = set()
  1697. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1698. """True if dispatching `candidate` now would race another item's cleanup."""
  1699. lib_id = candidate.library_file_id
  1700. if lib_id is None:
  1701. return False
  1702. if candidate.cleanup_library_after_dispatch:
  1703. # We would delete a row someone else in this pass is reading.
  1704. return lib_id in dispatch_libs
  1705. # Someone else in this pass will delete the row out from under us.
  1706. return lib_id in consumed_libs
  1707. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1708. lib_id = candidate.library_file_id
  1709. if lib_id is None:
  1710. return
  1711. dispatch_libs.add(lib_id)
  1712. if candidate.cleanup_library_after_dispatch:
  1713. consumed_libs.add(lib_id)
  1714. # Printer scope of each job's creator (#1727), so an "any <model>"
  1715. # job only lands on a printer its creator may use. Loaded lazily,
  1716. # once per creator per pass.
  1717. from backend.app.core.auth import is_auth_enabled
  1718. scope_auth_enabled = await is_auth_enabled(db)
  1719. creator_scopes: dict[int, PrinterScope] = {}
  1720. # Printers a model job passes over while drying blocks the queue,
  1721. # as a pinned job waits for its own. A parked timer never ends,
  1722. # so it does not hold (#2896).
  1723. drying_held: set[int] = (
  1724. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1725. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1726. else set()
  1727. )
  1728. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1729. if not scope_auth_enabled or user_id is None:
  1730. return ALL_PRINTERS
  1731. if user_id not in creator_scopes:
  1732. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1733. return creator_scopes[user_id]
  1734. for item in items:
  1735. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1736. if item.scheduled_time:
  1737. sched = item.scheduled_time
  1738. if sched.tzinfo is None:
  1739. sched = sched.replace(tzinfo=timezone.utc)
  1740. if sched > datetime.now(timezone.utc):
  1741. # Waiting on the clock, not on a printer.
  1742. await hold_item(item, None)
  1743. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1744. continue
  1745. # Skip items that require manual start, except an "any model"
  1746. # job held for low filament that another idle printer can now
  1747. # run: that one is moved there and carries on below (#3137).
  1748. if item.manual_start and not (
  1749. item.filament_short
  1750. and await self._release_short_model_hold(
  1751. db,
  1752. item,
  1753. busy_printers | interlocked.keys() | drying_held,
  1754. require_plate_clear,
  1755. await _creator_scope(item.created_by_id),
  1756. )
  1757. ):
  1758. # Waiting on the user, not on a printer. Cleared here because
  1759. # this is the last pass that will look at the row: a staged
  1760. # item never reaches the branches below again, so a reason
  1761. # left from before it was staged would stand forever (#3074).
  1762. # The one exception is the unmatched-filament hold, whose
  1763. # reason was written at staging and is why the item waits:
  1764. # it names the filament to load (#2799). Pressing start
  1765. # clears manual_start, and the branches below overwrite it.
  1766. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1767. await hold_item(item, keep)
  1768. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1769. continue
  1770. if item.printer_id and item.printer_id not in pinned_printers:
  1771. # Moved by the release above to a printer no row named when
  1772. # the labels were read.
  1773. moved_to = await self._get_printer(db, item.printer_id)
  1774. if moved_to is not None:
  1775. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1776. if item.printer_id:
  1777. # Its creator may no longer use this printer (#1727): an
  1778. # admin took it away from their group after the job was
  1779. # queued, say to keep it free for a training session. Held,
  1780. # not failed, so it starts if access comes back or the user
  1781. # moves it to a printer they still have.
  1782. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1783. await hold_item(
  1784. item,
  1785. "Its owner no longer has access to this printer — move it to another printer",
  1786. notify=False,
  1787. )
  1788. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1789. continue
  1790. # Held by a sensor interlock (#1148). Checked before the
  1791. # busy_printers test that would otherwise swallow it
  1792. # silently — "waiting for a printer" and "waiting for you
  1793. # to shut the enclosure" need to read differently, and only
  1794. # one of them is something the user can fix.
  1795. #
  1796. # It used to be the only thing that wrote a waiting_reason on
  1797. # this branch, and it cleared the field up front so a lifted
  1798. # hold could not leave a shut door reading "Waiting on
  1799. # Enclosure Door". `hold_item` carries that guarantee now —
  1800. # every exit below writes — so the clear is gone and the
  1801. # interlock is an ordinary hold like the rest (#3074).
  1802. interlock_reason = interlocked.get(item.printer_id)
  1803. if interlock_reason:
  1804. # Silent, exactly as it has always been. #1148 built this
  1805. # as a hold that shows on the row, never as an alert, and
  1806. # routing it through the shared writer must not quietly
  1807. # turn every open door into a notification.
  1808. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1809. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1810. continue
  1811. # Specific printer assignment (existing behavior)
  1812. if item.printer_id in busy_printers:
  1813. # Whatever took the printer out of this pass — a print
  1814. # already running on it, a post-dispatch hold, an upload
  1815. # still in flight, an item ahead of this one in the same
  1816. # pass — reads the same way from the queue: the printer is
  1817. # taken and this item is in line for it. The exceptions
  1818. # that do not (an offline printer, say) recorded their own
  1819. # wording in `item_hold_reasons` when they held it.
  1820. await hold_item(
  1821. item,
  1822. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1823. notify=item.printer_id not in silent_hold_printers,
  1824. )
  1825. continue
  1826. # Check if printer is idle
  1827. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1828. printer_connected = printer_manager.is_connected(item.printer_id)
  1829. # If printer not connected, try to power on via smart plug
  1830. if not printer_connected:
  1831. plugs = await self._get_smart_plugs(db, item.printer_id)
  1832. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1833. if auto_on_plugs:
  1834. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1835. # Power on using the plug that actually feeds the printer, and
  1836. # wait for it to boot on that one only (#2629).
  1837. primary_plug = self._pick_power_plug(auto_on_plugs)
  1838. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1839. if powered_on:
  1840. # Also turn on any remaining auto_on plugs (e.g., filter)
  1841. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1842. try:
  1843. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1844. if await service.turn_on(extra_plug):
  1845. await publish_plug_state(
  1846. extra_plug.id,
  1847. extra_plug.name,
  1848. extra_plug.printer_id,
  1849. on=True,
  1850. ha_entity_id=extra_plug.ha_entity_id,
  1851. )
  1852. logger.info(
  1853. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1854. )
  1855. except Exception as e:
  1856. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1857. printer_connected = True
  1858. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1859. else:
  1860. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1861. await hold_for_printer(
  1862. item,
  1863. item.printer_id,
  1864. "smart-plug power-on failed",
  1865. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1866. )
  1867. continue
  1868. else:
  1869. # No plug or auto_on disabled. Worded exactly as the
  1870. # model-based branch words it (#2786): this is the one
  1871. # entry on that list the user has to act on, because
  1872. # Bambuddy will never switch this printer on itself.
  1873. await hold_for_printer(
  1874. item,
  1875. item.printer_id,
  1876. "offline, with no smart plug to power it on",
  1877. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1878. )
  1879. continue
  1880. # Check if printer is idle (busy with another print)
  1881. if not printer_idle:
  1882. await hold_for_printer(
  1883. item,
  1884. item.printer_id,
  1885. "not idle",
  1886. self._pinned_hold_reason(
  1887. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1888. ),
  1889. )
  1890. continue
  1891. # Drying blocks the queue, if the user asked it to. A hold
  1892. # is a skip like any other, so it belongs here with the
  1893. # rest of the availability checks.
  1894. # A parked timer (#2896) never ends, so it must not hold the
  1895. # queue; it stays tracked so the stop paths still reach it.
  1896. if (
  1897. self._drying_in_progress.get(item.printer_id)
  1898. and not self._drying_is_only_parked(item.printer_id)
  1899. and await self._get_bool_setting(db, "queue_drying_block")
  1900. ):
  1901. # Busy-shaped on purpose: the cycle ends on its own and
  1902. # the job goes out, so there is nothing to alert about.
  1903. await hold_for_printer(
  1904. item,
  1905. item.printer_id,
  1906. "drying, and drying is set to block the queue",
  1907. f"Busy: {printer_label(item.printer_id)} (drying)",
  1908. )
  1909. continue
  1910. # Check condition (previous print success)
  1911. if item.require_previous_success:
  1912. if not await self._check_previous_success(db, item):
  1913. item.status = "skipped"
  1914. item.error_message = "Previous print failed or was aborted"
  1915. item.completed_at = datetime.now(timezone.utc)
  1916. # Not pending any more, so not waiting for anything.
  1917. item.waiting_reason = None
  1918. await db.commit()
  1919. logger.info("Skipped queue item %s - previous print failed", item.id)
  1920. # Send notification
  1921. job_name = await self._get_job_name(db, item)
  1922. printer = await self._get_printer(db, item.printer_id)
  1923. await notification_service.on_queue_job_skipped(
  1924. job_name=job_name,
  1925. printer_id=item.printer_id,
  1926. printer_name=printer.name if printer else "Unknown",
  1927. reason="Previous print failed or was aborted",
  1928. db=db,
  1929. )
  1930. continue
  1931. # Resolve the AMS mapping when it's missing OR unresolved
  1932. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1933. # frontend status-load race can persist [-1] (#2589) — and
  1934. # must be recomputed from live trays rather than trusted.
  1935. if await _edited_since_loaded(db, item):
  1936. continue
  1937. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1938. if unmappable:
  1939. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1940. continue
  1941. # Filament-deficit pre-dispatch check (#1496). If the
  1942. # assigned spool can't satisfy any required slot grams,
  1943. # promote the item to manual_start so the user must
  1944. # acknowledge via the ▶ button (which re-checks live).
  1945. if await self._block_on_filament_deficit(db, item):
  1946. # Now staged for the user to start by hand, and the row
  1947. # shows the filament-short badge instead. Cleared because
  1948. # a staged item never reaches this branch again.
  1949. await hold_item(item, None)
  1950. continue
  1951. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1952. # than let the printer pick a substitute for a slot the
  1953. # matcher could not resolve on this printer.
  1954. if await self._block_on_unmatched_filament(db, item):
  1955. continue
  1956. # Hold this item back for the next pass rather than racing
  1957. # another dispatch over the same transient library row. The
  1958. # printer is still marked busy so a later item does not jump
  1959. # its place in this printer's queue.
  1960. if _library_row_conflict(item):
  1961. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1962. await hold_for_printer(
  1963. item,
  1964. item.printer_id,
  1965. "holding its place while another item releases a library row",
  1966. f"Busy: {printer_label(item.printer_id)}",
  1967. )
  1968. continue
  1969. # Print takes priority: stop a cycle Bambuddy armed, now
  1970. # that this item is definitely going out.
  1971. #
  1972. # Placement is the whole point (#2801). This used to sit up
  1973. # with the availability checks, inside the not-idle branch
  1974. # -- so it fired only on the passes where the print was NOT
  1975. # going to start, and never on the ones where it was.
  1976. # Drying is not one of the things `_is_printer_idle` looks
  1977. # at, so a stop could never have unblocked that printer
  1978. # anyway; the cycle was spent for nothing, auto-drying
  1979. # re-armed on the next tick, and a plate left
  1980. # unacknowledged turned that into a loop on the scheduler
  1981. # interval. Every skip between there and here -- a failed
  1982. # previous print, an unmappable item, a filament deficit, a
  1983. # contested library row -- is another way to lose a cycle
  1984. # for a print that never happens, which is why this waits
  1985. # until the decision is actually made.
  1986. if self._drying_in_progress.get(
  1987. item.printer_id
  1988. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1989. await self._stop_drying(item.printer_id)
  1990. # Queue the dispatch instead of running it here — see
  1991. # _dispatch_selected(). busy_printers still gets the printer
  1992. # immediately, so nothing else in this pass can target it.
  1993. #
  1994. # The reason goes first: this item is not waiting for anything
  1995. # any more, and the model-based branch clears its own at the
  1996. # equivalent moment (#3074).
  1997. await hold_item(item, None)
  1998. _claim_library_row(item)
  1999. dispatch_ids.append(item.id)
  2000. claim_printer(item.printer_id)
  2001. # SJF starvation guard: mark items that were jumped
  2002. if sjf_enabled and item.print_time_seconds is not None:
  2003. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2004. for other in items:
  2005. if (
  2006. other.id != item.id
  2007. and other.id not in dispatch_ids
  2008. and other.status == "pending"
  2009. and _could_take_printer(other, item.printer_id, pinned_model)
  2010. and not other.been_jumped
  2011. and other.position < item.position
  2012. and (
  2013. other.print_time_seconds is None
  2014. or other.print_time_seconds > item.print_time_seconds
  2015. )
  2016. ):
  2017. other.been_jumped = True
  2018. await db.commit()
  2019. elif item.target_model or item.variants:
  2020. # Model-based assignment - find any idle printer of matching model.
  2021. # A plain model-based item has exactly one candidate, built from
  2022. # its own columns. A cross-model item (#671) has one per sliced
  2023. # variant and takes the first that matches, walking them in the
  2024. # user's priority order so the pick is reproducible when more
  2025. # than one printer is free in the same pass.
  2026. candidates = _candidates_for(item)
  2027. item_scope = await _creator_scope(item.created_by_id)
  2028. printer_id = None
  2029. chosen: _ModelCandidate | None = None
  2030. per_model_reasons: list[tuple[str | None, str]] = []
  2031. # Candidates that cleared the cross-model gate below. The
  2032. # smart-plug wake step may only consider these — waking a
  2033. # printer for a file that can never legally run on it is
  2034. # worse than not waking at all (#2786).
  2035. wakeable_candidates: list[_ModelCandidate] = []
  2036. # Printers passed over because their last print failed.
  2037. gate_blocked: set[int] = set()
  2038. if not candidates:
  2039. # Every candidate file has been deleted or trashed out from
  2040. # under this item. Hold it with something the user can act
  2041. # on rather than letting it look dispatchable forever.
  2042. per_model_reasons.append(
  2043. (
  2044. item.target_model,
  2045. "Every file for this job has been deleted — add a file back or remove the item",
  2046. )
  2047. )
  2048. for candidate in candidates:
  2049. effective_types, filament_overrides = _filament_constraints(candidate)
  2050. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2051. # for an incompatible model to a printer, no matter how the
  2052. # row got into the DB (old rows, direct API writes). Held
  2053. # as pending with an actionable waiting_reason — the user
  2054. # fixes it by editing the item's target model.
  2055. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2056. per_model_reasons.append(
  2057. (
  2058. candidate.target_model,
  2059. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2060. f"{candidate.target_model} — edit the item and fix its target model",
  2061. )
  2062. )
  2063. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2064. continue
  2065. wakeable_candidates.append(candidate)
  2066. async def is_short(
  2067. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2068. ) -> bool:
  2069. # The check reads the file and plate off the item,
  2070. # so it must hold this candidate's. Resolving is
  2071. # safe to repeat, and the winner is resolved again
  2072. # below.
  2073. self._resolve_variant(item, candidate)
  2074. return await self._filament_short_on(db, item, pid)
  2075. while True:
  2076. match_id, match_reason = await self._find_idle_printer_for_model(
  2077. db,
  2078. candidate.target_model,
  2079. # Sensor-held printers are unavailable to the
  2080. # matcher but stay out of busy_printers itself
  2081. # (#1148) — see where `interlocked` is built.
  2082. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2083. effective_types,
  2084. item.target_location,
  2085. filament_overrides=filament_overrides,
  2086. require_plate_clear=require_plate_clear,
  2087. wakeable_ids=wakeable_printer_ids,
  2088. printer_scope=item_scope,
  2089. is_short=is_short,
  2090. drying_ids=drying_held,
  2091. )
  2092. # "Only if the previous print succeeded" is about the
  2093. # printer the job lands on: one whose last print failed
  2094. # is passed over for another of the model.
  2095. if (
  2096. match_id
  2097. and item.require_previous_success
  2098. and not await self._check_previous_success(db, item, printer_id=match_id)
  2099. ):
  2100. gate_blocked.add(match_id)
  2101. continue
  2102. break
  2103. if match_id:
  2104. printer_id = match_id
  2105. chosen = candidate
  2106. break
  2107. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2108. # Nothing is available and nothing has been woken this pass:
  2109. # switch one matching printer on. Assignment is left to the
  2110. # next pass, which sees the booted printer's live state
  2111. # instead of guessing at it seconds after connect (#2786).
  2112. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2113. woken_id, attempted_id = await self._wake_printer_for_model(
  2114. db,
  2115. wakeable_candidates,
  2116. item.target_location,
  2117. busy_printers | interlocked.keys(),
  2118. wakeable_printer_ids,
  2119. require_plate_clear,
  2120. printer_scope=item_scope,
  2121. )
  2122. # An attempt spends the pass's one wake whether or not
  2123. # it worked: it has already blocked the queue loop for
  2124. # the boot wait. A failed printer is held out of later
  2125. # passes by its own cool-off, deliberately NOT by
  2126. # busy_printers — it is off, not busy, and labelling it
  2127. # busy would both misdescribe it in every later item's
  2128. # waiting reason and suppress the notification, since
  2129. # an all-busy reason is treated as needing no action.
  2130. power_on_attempted = attempted_id is not None
  2131. if woken_id is not None:
  2132. # Hold this item back rather than dispatching onto a
  2133. # printer whose AMS has not reported yet.
  2134. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2135. continue
  2136. if printer_id is None and gate_blocked:
  2137. # The matcher reports the printers passed over as busy;
  2138. # what holds the job is their failed last print.
  2139. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2140. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2141. # Fold the winning variant's file and settings onto the item
  2142. # before anything else looks at them — the guards below and
  2143. # every step of the dispatch read the item's own columns.
  2144. if chosen is not None:
  2145. self._resolve_variant(item, chosen)
  2146. # Update waiting_reason if changed and send notification when first waiting
  2147. if item.waiting_reason != waiting_reason:
  2148. was_waiting = item.waiting_reason is not None
  2149. previous_reason = item.waiting_reason
  2150. item.waiting_reason = waiting_reason
  2151. await db.commit()
  2152. # Send waiting notification only when transitioning to waiting state
  2153. # and the reason requires user action (not just "all printers busy")
  2154. # Also when a job that only waited for a busy printer
  2155. # now waits on something the user has to do.
  2156. if (
  2157. waiting_reason
  2158. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2159. and not self._is_busy_only(waiting_reason)
  2160. ):
  2161. job_name = await self._get_job_name(db, item)
  2162. await notification_service.on_queue_job_waiting(
  2163. job_name=job_name,
  2164. target_model=_candidate_model_label(candidates) or item.target_model,
  2165. waiting_reason=waiting_reason,
  2166. db=db,
  2167. )
  2168. if printer_id:
  2169. # Before claiming the printer: hold back rather than race
  2170. # another dispatch over the same transient library row.
  2171. # Checked here so a held item does not get a printer
  2172. # assigned and then sit on it. See _library_row_conflict().
  2173. #
  2174. # No busy_printers.add() here, unlike the fixed-printer
  2175. # branch above: that one protects its printer's own queue
  2176. # ordering, but this item was never assigned to `printer_id`
  2177. # — the matcher merely offered it. Marking it busy would
  2178. # strand an idle printer for the rest of the pass.
  2179. if _library_row_conflict(item):
  2180. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2181. continue
  2182. if await _edited_since_loaded(db, item):
  2183. continue
  2184. # Assign printer and start - clear waiting reason
  2185. item.printer_id = printer_id
  2186. item.waiting_reason = None
  2187. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2188. # Send assignment notification
  2189. job_name = await self._get_job_name(db, item)
  2190. printer = await self._get_printer(db, printer_id)
  2191. await notification_service.on_queue_job_assigned(
  2192. job_name=job_name,
  2193. printer_id=printer_id,
  2194. printer_name=printer.name if printer else "Unknown",
  2195. target_model=item.target_model,
  2196. db=db,
  2197. )
  2198. # A mapping on this item was not made for the printer just
  2199. # picked: it came with a job moved here from a fixed
  2200. # printer, or from a variant. Its tray IDs can name a
  2201. # tray of the right type in another colour here, which
  2202. # the fit check lets through (#3239). Match afresh, by
  2203. # type and colour.
  2204. if item.ams_mapping:
  2205. logger.info(
  2206. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2207. item.id,
  2208. item.ams_mapping,
  2209. printer_id,
  2210. )
  2211. item.ams_mapping = None
  2212. # On a nozzle-rack printer its own nozzle mapping likewise
  2213. # (set through the API or an order's plate spec): it names
  2214. # rack positions, and the dispatch sends a stored one as-is
  2215. # instead of resolving this printer's rack. Elsewhere it
  2216. # holds extruder indices, the same on every printer of the
  2217. # model (an H2D VP keeps the slicer's for that reason), and
  2218. # one that came with the chosen variant belongs to that
  2219. # variant's file: both stay.
  2220. if (
  2221. (chosen is None or chosen.variant is None)
  2222. and printer is not None
  2223. and is_nozzle_rack_model(printer.model)
  2224. ):
  2225. item.nozzle_mapping = None
  2226. # Resolve the AMS mapping for the assigned printer. It is
  2227. # always missing here, so this computes it, and it also
  2228. # self-heals a bogus stored [-1] (#2589).
  2229. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2230. if unmappable:
  2231. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2232. continue
  2233. # Filament-deficit pre-dispatch check (#1496).
  2234. if await self._block_on_filament_deficit(db, item):
  2235. continue
  2236. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2237. # selection already filters on filament type, so this is a
  2238. # backstop for an AMS that changed between assignment and
  2239. # dispatch, and for a type loaded on the wrong nozzle.
  2240. # The assignment made above is released with the hold —
  2241. # this item asked for a model, not this printer.
  2242. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2243. continue
  2244. # As for a pinned job: drying stops once the print is
  2245. # decided, unless it may run through it.
  2246. if self._drying_in_progress.get(
  2247. printer_id
  2248. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2249. await self._stop_drying(printer_id)
  2250. _claim_library_row(item)
  2251. dispatch_ids.append(item.id)
  2252. claim_printer(printer_id)
  2253. # SJF starvation guard: mark items that were jumped
  2254. if sjf_enabled and item.print_time_seconds is not None:
  2255. for other in items:
  2256. if (
  2257. other.id != item.id
  2258. and other.id not in dispatch_ids
  2259. and other.status == "pending"
  2260. and _could_take_printer(other, printer_id, item.target_model)
  2261. and not other.been_jumped
  2262. and other.position < item.position
  2263. and (
  2264. other.print_time_seconds is None
  2265. or other.print_time_seconds > item.print_time_seconds
  2266. )
  2267. ):
  2268. other.been_jumped = True
  2269. await db.commit()
  2270. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2271. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2272. # skip summary that only lands after the transfers have finished is
  2273. # useless for working out why an item did not go out.
  2274. if skip_reasons:
  2275. logger.info("Queue skip summary: %s", skip_reasons)
  2276. for pid in sorted(busy_printers):
  2277. reason = busy_reasons.get(pid, "no reason recorded")
  2278. if pid in claimed_printers:
  2279. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2280. continue
  2281. # The three live fields stay, because they are what someone
  2282. # reading a bundle wants next -- but they are labelled as read
  2283. # now, not as the state the decision was made on, which is what
  2284. # made the old line contradict itself.
  2285. state = printer_manager.get_status(pid)
  2286. logger.info(
  2287. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2288. pid,
  2289. reason,
  2290. printer_manager.is_connected(pid),
  2291. state.state if state else "NO_STATUS",
  2292. printer_manager.is_awaiting_plate_clear(pid),
  2293. )
  2294. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2295. # selection and `_launch_uploads`, so anything raising here would
  2296. # discard this tick's selections — computed AMS mappings and all —
  2297. # and, on a persistent fault, stop the queue dispatching entirely.
  2298. # Same reasoning as the deficit check's guard below: never let an
  2299. # auxiliary check wedge the queue. The bed simply stays wherever it
  2300. # was, and the next tick tries again.
  2301. try:
  2302. await self._apply_keep_warm(
  2303. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2304. )
  2305. except Exception as e:
  2306. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2307. # Read the concurrency limit BEFORE the commit below, not inside
  2308. # _dispatch_selected(). A SELECT on this session after the commit
  2309. # implicitly opens a fresh transaction that nothing then closes, and
  2310. # it would stay open for the whole dispatch — minutes of "idle in
  2311. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2312. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2313. # checkpointed while every dispatch is writing to it.
  2314. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2315. # Selection is done; every decision above is recorded on `db`
  2316. # (model-based printer assignment, computed ams_mapping). Flush it
  2317. # before the dispatch tasks open their own sessions, or they will
  2318. # read a row that still says printer_id=None. This also releases the
  2319. # connection back to the pool for the duration of the dispatch.
  2320. await db.commit()
  2321. if dispatch_ids:
  2322. item_printers = {it.id: it.printer_id for it in items}
  2323. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2324. # Auto-drying: start drying on idle printers that have no pending queue items
  2325. await self._check_auto_drying(db, items, dispatching_printers)
  2326. # Low filament: alert on assigned spools that have crossed their
  2327. # low-stock threshold (#2913). Runs on both paths out of this method
  2328. # for the same reason auto-drying does — an empty queue does not mean
  2329. # the spools in the printers stopped mattering.
  2330. await self._check_filament_low(db)
  2331. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2332. # is about to run out before a replenishment could arrive (#2955).
  2333. await self._check_stock_forecast(db)
  2334. # Keep the loop on the fast interval while any upload is in flight so
  2335. # a slot freed mid-tick refills within seconds rather than after the
  2336. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2337. # deferred because the pool was full) also counts as productive.
  2338. return bool(dispatch_ids) or bool(self._inflight)
  2339. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2340. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2341. Dispatch used to happen inline in the selection loop: ``await
  2342. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2343. performs the FTP upload, that serialized every printer behind every
  2344. other printer's transfer even though the printers are independent
  2345. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2346. gather was awaited before ``check_queue`` returned, so the run loop
  2347. stayed blocked until the *slowest* upload in the batch finished — a
  2348. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2349. 93-printer farm even as other printers came free (#2602).
  2350. Each upload now runs as an independent background task tracked in
  2351. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2352. `pending` until their upload completes) and their printers from the
  2353. next pass's selection, and this method launches at most
  2354. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2355. the next fast tick instead of waiting out the whole batch. The bound
  2356. exists because the printers are independent but the host is not: each
  2357. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2358. file handle.
  2359. The no-overlapping-dispatch invariant the batch-await used to provide
  2360. is now carried by the in-flight exclusion in check_queue. Everything
  2361. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2362. per-printer hold, and each item's independent failure handling — still
  2363. lives in ``_start_print`` and runs per task exactly as before.
  2364. Synchronous on purpose: it registers every launched task into
  2365. ``self._inflight`` before returning, so the next (sequential) tick sees
  2366. an accurate in-flight count with no interleaving await.
  2367. """
  2368. free = limit - len(self._inflight)
  2369. if free <= 0:
  2370. logger.info(
  2371. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2372. len(self._inflight),
  2373. limit,
  2374. len(item_ids),
  2375. item_ids,
  2376. )
  2377. return
  2378. to_launch = item_ids[:free]
  2379. deferred = item_ids[free:]
  2380. logger.info(
  2381. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2382. len(to_launch),
  2383. len(self._inflight),
  2384. limit,
  2385. f" — deferring {deferred} to a later tick" if deferred else "",
  2386. )
  2387. for item_id in to_launch:
  2388. task = spawn_background_task(
  2389. self._dispatch_one(item_id, item_printers.get(item_id)),
  2390. name=f"queue-upload-{item_id}",
  2391. )
  2392. self._inflight[item_id] = (task, item_printers.get(item_id))
  2393. # Prune on completion so the freed slot is refillable next tick.
  2394. # spawn_background_task already logs any uncaught exception; this
  2395. # only reclaims the pool slot (fires on success, failure, or cancel).
  2396. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2397. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2398. """Upload + start one queue item in its own session (pool worker, #2602).
  2399. Its own session: pool workers run concurrently and an AsyncSession is
  2400. not safe to share across tasks; it also keeps a slow upload from pinning
  2401. the scheduler's session (and, on SQLite, its transaction) open for the
  2402. transfer's duration.
  2403. ``selected_printer_id`` is the printer this item was selected for, taken
  2404. from the same snapshot the caller used. It exists so the preheat pin can
  2405. be unwound on the paths that never reach the ``finally`` below — see the
  2406. claim failure a few lines down. Optional so the direct-call tests keep
  2407. working; when it is absent those paths simply behave as they did before.
  2408. """
  2409. async with async_session() as item_db:
  2410. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2411. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2412. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2413. # routes reject reassignment (409), so printer_id can't change out from
  2414. # under the in-flight upload and split the queue row from the
  2415. # archive/expected-print/physical command.
  2416. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2417. logger.info(
  2418. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2419. item_id,
  2420. )
  2421. # This return is outside the try/finally below, so the rollback
  2422. # has to happen here. Selecting this item already handed any
  2423. # keep-warm hold on its printer over to the preheat pin
  2424. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2425. # unwind it. Bailing without doing so leaves the bed hot with
  2426. # nothing tracking it: the keep-warm entry is gone, so the
  2427. # max-duration cap no longer applies, and if this was the
  2428. # printer's last pending item nothing else will ever turn it
  2429. # off. Reachable whenever a cancel or delete lands between
  2430. # selection and the claim.
  2431. if selected_printer_id is not None:
  2432. self._rollback_preheat_pin(item_id, selected_printer_id)
  2433. return
  2434. # Seeded from the caller's snapshot so the `item vanished` return
  2435. # below still unwinds the pin; overwritten with the row's own
  2436. # printer_id as soon as we have it.
  2437. item_printer_id: int | None = selected_printer_id
  2438. try:
  2439. item = await item_db.get(PrintQueueItem, item_id)
  2440. if not item:
  2441. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2442. return
  2443. item_printer_id = item.printer_id
  2444. await self._start_print(item_db, item)
  2445. finally:
  2446. # Undo an expected-print registration whose print command never
  2447. # went out. One choke point covers every way `_start_print` can
  2448. # end without sending: a raised exception (a DB failure mid-
  2449. # dispatch is the reported case), an early return, a cancel
  2450. # winning the #1853 CAS, or `start_print()` returning False.
  2451. # A confirmed send removes the entry itself, so this is a no-op
  2452. # on the happy path.
  2453. self._rollback_unconfirmed_expected_print(item_id)
  2454. # Likewise the print user it set: the printer's next print is
  2455. # not this item's.
  2456. self._rollback_unconfirmed_print_user(item_id)
  2457. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2458. # reservation survives only after start_print() accepted the
  2459. # command. Failure, cancellation, deferral, and exceptions all
  2460. # release it here.
  2461. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2462. # Unwind preheat state (bed/chamber/airduct) if the
  2463. # dispatch aborted before the print's own gcode took over.
  2464. # `_start_print` clears the pin on successful `start_print()`;
  2465. # anything still present here is by definition an aborted
  2466. # dispatch and gets rolled back so the printer isn't left
  2467. # heating for a job that isn't happening.
  2468. if item_printer_id is not None:
  2469. self._rollback_preheat_pin(item_id, item_printer_id)
  2470. # The cancellation flag only has meaning while this dispatch is
  2471. # running; drop it so the set cannot grow without bound and a
  2472. # re-queued item never inherits a stale cancellation.
  2473. self._cancelled_dispatches.discard(item_id)
  2474. # Release the claim on every exit. Once dispatch has finished the
  2475. # row's status carries the lock (printing/failed/cancelled are all
  2476. # != pending), so the token is only needed for the duration of the
  2477. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2478. # dispatchable again on the next tick.
  2479. await self._clear_dispatch_claim(item_db, item_id)
  2480. async def _requeue_after_upload_refused(
  2481. self,
  2482. db: AsyncSession,
  2483. item: PrintQueueItem,
  2484. printer: Printer,
  2485. error_msg: str,
  2486. toast_uid: int | None,
  2487. ) -> None:
  2488. """Put an item back in the queue after its file never reached the printer (#3210).
  2489. The item keeps its printer. Its AMS mapping was computed against that
  2490. printer's trays, and nothing on the row says whether a mapping was
  2491. computed or set by the user, so moving it to a sibling could print from
  2492. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2493. keeps every other item away from it; this one waits there and is the
  2494. only thing that knocks again, once per backoff window. The window
  2495. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2496. `dispatch_attempts` is not charged: that budget bounds a printer that
  2497. takes the file and then never starts, which this is not.
  2498. """
  2499. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2500. self._upload_refusals[printer.id] = refusals
  2501. backoff = _upload_backoff_seconds(refusals)
  2502. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2503. # The row is still `pending` -- it only moves to `printing` after a
  2504. # successful upload -- so there is no status to write back. Writing one
  2505. # anyway would undo a cancel that landed during the upload.
  2506. if item.error_message:
  2507. item.error_message = None
  2508. await db.commit()
  2509. logger.warning(
  2510. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2511. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2512. item.id,
  2513. printer.id,
  2514. printer.name,
  2515. error_msg,
  2516. refusals,
  2517. backoff,
  2518. )
  2519. try:
  2520. # Closes the dispatch toast for this attempt. Without it the toast
  2521. # keeps spinning on an upload that has ended.
  2522. await ws_manager.send_queue_item_failed(
  2523. user_id=toast_uid,
  2524. queue_item_id=item.id,
  2525. printer_id=item.printer_id,
  2526. reason="upload_failed",
  2527. )
  2528. except Exception:
  2529. pass # toast is best-effort
  2530. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2531. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2532. if printer_id is not None:
  2533. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2534. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2535. """Withdraw the expected print and print user of a sent print that never started.
  2536. Both tell the rest of Bambuddy that the printer's next print is this
  2537. item's: left behind, a print started by hand later is taken for it.
  2538. With ``unless_printing``, a printer that is printing after all keeps
  2539. them, as that print is most likely this one starting late.
  2540. ``keep_expected`` withdraws only the print user, which vouches for any
  2541. print on the printer. The expected print names this item's file, so a
  2542. late start of it is still matched to its archive.
  2543. """
  2544. sent = self._sent_unstarted_print.get(item_id)
  2545. if sent is None:
  2546. return
  2547. printer_id, remote_filename, archive_id = sent
  2548. if unless_printing:
  2549. status = printer_manager.get_status(printer_id)
  2550. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2551. return
  2552. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2553. if keep_expected:
  2554. return
  2555. del self._sent_unstarted_print[item_id]
  2556. if remote_filename is not None and archive_id is not None:
  2557. try:
  2558. from backend.app.main import unregister_expected_print
  2559. unregister_expected_print(printer_id, remote_filename, archive_id)
  2560. except Exception:
  2561. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2562. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2563. """Drop an expectation for a print command that was never sent.
  2564. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2565. where the interesting exception is usually the one already propagating.
  2566. """
  2567. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2568. if pending is None:
  2569. return
  2570. printer_id, remote_filename, archive_id = pending
  2571. try:
  2572. from backend.app.main import unregister_expected_print
  2573. unregister_expected_print(printer_id, remote_filename, archive_id)
  2574. except Exception:
  2575. logger.warning(
  2576. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2577. item_id,
  2578. printer_id,
  2579. remote_filename,
  2580. archive_id,
  2581. exc_info=True,
  2582. )
  2583. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2584. """Release a queue reservation without touching the dispatch session."""
  2585. if item_id not in self._unconfirmed_budget_reservations:
  2586. return
  2587. for attempt in range(1, 4):
  2588. async with async_session() as cleanup_db:
  2589. try:
  2590. await release_budget_reservation(
  2591. cleanup_db,
  2592. source_type="print_queue",
  2593. source_id=item_id,
  2594. status="released",
  2595. )
  2596. await cleanup_db.commit()
  2597. self._unconfirmed_budget_reservations.discard(item_id)
  2598. return
  2599. except Exception as exc:
  2600. try:
  2601. await cleanup_db.rollback()
  2602. except Exception:
  2603. pass
  2604. if attempt == 3:
  2605. logger.error(
  2606. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2607. item_id,
  2608. attempt,
  2609. exc,
  2610. )
  2611. return
  2612. await asyncio.sleep(0.5 * attempt)
  2613. @staticmethod
  2614. def _reported_bed_target(printer_id: int) -> int | None:
  2615. """The bed target firmware currently reports, or None if it can't be read.
  2616. None means "no evidence", not "zero" — callers must not treat it as a
  2617. temperature. Deliberately total: this feeds cleanup paths that run in a
  2618. ``finally``, where a malformed status must not become the exception the
  2619. caller sees.
  2620. """
  2621. try:
  2622. state = printer_manager.get_status(printer_id)
  2623. if state is None:
  2624. return None
  2625. temps = state.temperatures
  2626. if not isinstance(temps, dict):
  2627. return None
  2628. return int(float(temps.get("bed_target", 0) or 0))
  2629. except (TypeError, ValueError, AttributeError):
  2630. return None
  2631. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2632. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2633. Turns the bed heater off, the chamber heater off, and opens the
  2634. airduct flap back to cooling — for whichever of those preheat
  2635. actually applied. `_start_print` clears the pin on successful
  2636. `start_print()`; anything still present when `_dispatch_one` exits
  2637. is by definition an aborted dispatch and gets rolled back here.
  2638. The bed is the one action that can be declined: if firmware has since
  2639. been given a target other than the one we pinned, it belongs to someone
  2640. else and is left alone. See the comment at that branch.
  2641. Also called directly from `_dispatch_one`'s claim-failure return, which
  2642. never reaches the ``finally``.
  2643. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2644. """
  2645. pin = self._preheat_pin.pop(printer_id, set())
  2646. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2647. if not pin:
  2648. return
  2649. client = printer_manager.get_client(printer_id)
  2650. if client is None:
  2651. logger.info(
  2652. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2653. item_id,
  2654. printer_id,
  2655. )
  2656. return
  2657. if "bed" in pin:
  2658. # Only undo our own target. If firmware reports something else, the
  2659. # user or another writer owns the bed now and zeroing it would
  2660. # clobber their choice -- the same guard `_release_keep_warm`
  2661. # applies to a keep-warm hold.
  2662. #
  2663. # Every uncertain case switches the bed off rather than leaving it:
  2664. # no recorded target (a pin written before this bookkeeping, or a
  2665. # setter that raised after pinning) and an unreadable status both
  2666. # fall through. A bed left hot with no owner is the worse failure,
  2667. # and this runs in a `finally` where raising would mask the real
  2668. # exception.
  2669. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2670. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2671. logger.info(
  2672. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2673. item_id,
  2674. printer_id,
  2675. cur_bed_target,
  2676. pinned_bed,
  2677. )
  2678. else:
  2679. try:
  2680. client.set_bed_temperature(0)
  2681. except Exception as exc:
  2682. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2683. if "chamber" in pin:
  2684. try:
  2685. client.set_chamber_temperature(0)
  2686. except Exception as exc:
  2687. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2688. if "airduct" in pin:
  2689. try:
  2690. client.set_airduct_mode("cooling")
  2691. except Exception as exc:
  2692. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2693. logger.info(
  2694. "Dispatch item %s (printer %d): preheat rollback → %s",
  2695. item_id,
  2696. printer_id,
  2697. sorted(pin),
  2698. )
  2699. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2700. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2701. Returns True if this call won the claim, False if the row was already
  2702. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2703. the load-bearing guard against reassign-during-dispatch (#2615).
  2704. ``printer_id`` is the printer the item was selected for: a row moved to
  2705. another printer since is not claimed, and the next pass selects it for
  2706. that one."""
  2707. query = (
  2708. update(PrintQueueItem)
  2709. .where(PrintQueueItem.id == item_id)
  2710. .where(PrintQueueItem.status == "pending")
  2711. .where(PrintQueueItem.dispatching_at.is_(None))
  2712. )
  2713. if printer_id is not None:
  2714. query = query.where(PrintQueueItem.printer_id == printer_id)
  2715. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2716. await db.commit()
  2717. return res.rowcount > 0
  2718. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2719. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2720. mask the dispatch outcome.
  2721. Retried, because the failure mode in practice is transient and narrow: a
  2722. database that is momentarily unreachable — PostgreSQL out of connection
  2723. slots is the observed case — refuses this write for a second or two while
  2724. the dispatch that just ended is still holding the row out of the selection
  2725. query. One attempt was enough to wedge the item; a couple of spaced
  2726. attempts clear it. Each attempt rolls back first, since a failed write
  2727. leaves the session needing it before it can be reused.
  2728. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2729. on the next quiet tick.
  2730. """
  2731. for attempt in range(1, 4):
  2732. try:
  2733. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2734. await db.commit()
  2735. return
  2736. except Exception as exc:
  2737. try:
  2738. await db.rollback()
  2739. except Exception:
  2740. pass
  2741. if attempt == 3:
  2742. logger.warning(
  2743. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2744. "— a later quiet tick will release it",
  2745. item_id,
  2746. attempt,
  2747. exc,
  2748. )
  2749. return
  2750. await asyncio.sleep(0.5 * attempt)
  2751. async def _printers_for_model(
  2752. self,
  2753. db: AsyncSession,
  2754. model: str,
  2755. target_location: str | None = None,
  2756. printer_scope: PrinterScope = ALL_PRINTERS,
  2757. ) -> list[Printer]:
  2758. """Active printers of *model*, optionally narrowed to one location.
  2759. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2760. answer "which printers can this job run on" from one query — a job can
  2761. only be woken onto a printer the matcher would also have considered.
  2762. ``printer_scope`` is the job creator's (#1727).
  2763. """
  2764. normalized_model = normalize_printer_model(model) or model
  2765. query = (
  2766. select(Printer)
  2767. .where(func.lower(Printer.model) == normalized_model.lower())
  2768. .where(Printer.is_active == True) # noqa: E712
  2769. )
  2770. if target_location:
  2771. query = query.where(Printer.location == target_location)
  2772. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2773. query = query.where(clause)
  2774. result = await db.execute(query)
  2775. return list(result.scalars().all())
  2776. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2777. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2778. Read once per queue check rather than per printer: it decides both
  2779. whether the wake step has anything to do and how an offline printer is
  2780. worded in the waiting reason — "Offline" and "offline with no Auto On
  2781. plug" are different problems, and the second is the one the user has to
  2782. fix themselves (#2786).
  2783. """
  2784. result = await db.execute(
  2785. select(SmartPlug.printer_id)
  2786. .where(SmartPlug.printer_id.is_not(None))
  2787. .where(SmartPlug.enabled == True) # noqa: E712
  2788. .where(SmartPlug.auto_on == True) # noqa: E712
  2789. )
  2790. return {pid for (pid,) in result.all() if pid is not None}
  2791. def _wake_recently_failed(self, printer_id: int) -> bool:
  2792. """True while this printer's failed power-on is still cooling off (#2786)."""
  2793. deadline = self._wake_failures.get(printer_id)
  2794. if deadline is None:
  2795. return False
  2796. if time.monotonic() >= deadline:
  2797. del self._wake_failures[printer_id]
  2798. return False
  2799. return True
  2800. async def _wake_printer_for_model(
  2801. self,
  2802. db: AsyncSession,
  2803. candidates: list[_ModelCandidate],
  2804. target_location: str | None,
  2805. exclude_ids: set[int],
  2806. wakeable_ids: set[int],
  2807. require_plate_clear: bool,
  2808. printer_scope: PrinterScope = ALL_PRINTERS,
  2809. ) -> tuple[int | None, int | None]:
  2810. """Power on one offline printer a model-based item could run on (#2786).
  2811. The fixed-printer branch has powered a printer on since smart plugs
  2812. existed. The model-based branch never could: its matcher drops an
  2813. offline printer into the "Offline:" waiting reason and nothing looks at
  2814. its plugs, so a class-targeted job with every matching printer switched
  2815. off sat pending forever. The reporter's log is the controlled
  2816. experiment — the same item, same plug, same Auto On setting, dispatched
  2817. the moment they edited it onto a specific printer.
  2818. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2819. power-on was actually tried, so the caller can tell "nothing here was
  2820. wakeable" (both None — cheap, other items may still find something)
  2821. from "we tried and it did not come up" (only ``attempted_id`` — the
  2822. boot timeout has already been spent).
  2823. A printer whose last known trays cannot satisfy the job is passed over
  2824. rather than woken (#2876): the colours are readable while it is off, so
  2825. switching a farm on one machine at a time to discover them wakes
  2826. printers that could never have taken the job.
  2827. Deliberately does NOT go on to match the job once a printer is up: AMS
  2828. trays arrive with the first status push after connect, so a filament
  2829. check against a printer that booted seconds ago can reject the printer
  2830. we just woke. The next queue pass matches it with live state.
  2831. At most one printer per pass. Each wake blocks the queue loop for the
  2832. boot wait, and a queue of ten class-targeted jobs must not switch on
  2833. ten printers inside one check.
  2834. """
  2835. for candidate in candidates:
  2836. if not candidate.target_model:
  2837. continue
  2838. required_types, filament_overrides = _filament_constraints(candidate)
  2839. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2840. for printer in sorted(printers, key=lambda p: p.id):
  2841. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2842. continue
  2843. if printer_manager.is_connected(printer.id):
  2844. continue
  2845. if self._wake_recently_failed(printer.id):
  2846. # Its plug did not bring it back a moment ago. Move on to a
  2847. # sibling instead of spending this pass — and every pass —
  2848. # on the same printer.
  2849. continue
  2850. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2851. # Waking this one buys nothing: it would boot into IDLE and
  2852. # then be held by the plate-clear gate, which is exactly
  2853. # what the reporter's log shows happening for 80 minutes
  2854. # after a fixed-printer wake. The flag is Bambuddy-side and
  2855. # persisted, so it is readable while the printer is off.
  2856. logger.info(
  2857. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2858. printer.id,
  2859. candidate.target_model,
  2860. )
  2861. continue
  2862. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2863. if shortfall:
  2864. logger.info(
  2865. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2866. printer.id,
  2867. candidate.target_model,
  2868. ", ".join(shortfall),
  2869. )
  2870. continue
  2871. plugs = await self._get_smart_plugs(db, printer.id)
  2872. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2873. if not auto_on_plugs:
  2874. # wakeable_ids said otherwise — the plug changed under us
  2875. # mid-pass. Nothing to do but move on.
  2876. continue
  2877. logger.info(
  2878. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2879. candidate.target_model,
  2880. printer.id,
  2881. )
  2882. primary_plug = self._pick_power_plug(auto_on_plugs)
  2883. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2884. logger.warning(
  2885. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2886. printer.id,
  2887. self._wake_failure_cooloff,
  2888. )
  2889. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2890. return None, printer.id
  2891. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2892. try:
  2893. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2894. if await service.turn_on(extra_plug):
  2895. await publish_plug_state(
  2896. extra_plug.id,
  2897. extra_plug.name,
  2898. extra_plug.printer_id,
  2899. on=True,
  2900. ha_entity_id=extra_plug.ha_entity_id,
  2901. )
  2902. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2903. except Exception as e:
  2904. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2905. return printer.id, printer.id
  2906. return None, None
  2907. async def _find_idle_printer_for_model(
  2908. self,
  2909. db: AsyncSession,
  2910. model: str,
  2911. exclude_ids: set[int],
  2912. required_filament_types: list[str] | None = None,
  2913. target_location: str | None = None,
  2914. filament_overrides: list[dict] | None = None,
  2915. require_plate_clear: bool = True,
  2916. wakeable_ids: set[int] | None = None,
  2917. printer_scope: PrinterScope = ALL_PRINTERS,
  2918. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2919. drying_ids: set[int] | None = None,
  2920. ) -> tuple[int | None, str | None]:
  2921. """Find an idle, connected printer matching the model with compatible filaments.
  2922. Args:
  2923. db: Database session
  2924. model: Printer model to match (e.g., "X1C", "P1S")
  2925. exclude_ids: Printer IDs to exclude (already busy)
  2926. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2927. If provided, only printers with all required types loaded will match.
  2928. target_location: Optional location filter. If provided, only printers in this location are considered.
  2929. filament_overrides: Optional list of override dicts. Each entry may include
  2930. ``force_color_match: true`` to require an exact type+color match
  2931. on the printer for that slot. Without the flag the existing
  2932. colour-preference logic applies.
  2933. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2934. offline printer is worded: one Bambuddy will switch on reads
  2935. differently from one the user has to go and switch on themselves.
  2936. is_short: Says whether a printer's spools are too light for the job (#3137).
  2937. A printer it flags is passed over while another eligible one
  2938. is not. When every eligible printer is short, the first is
  2939. returned all the same, so the deficit gate holds the job there
  2940. and "Print Anyway" still has a printer to print on.
  2941. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  2942. in the reason, as a pinned job's wait is.
  2943. Returns:
  2944. Tuple of (printer_id, waiting_reason):
  2945. - (printer_id, None) if a matching printer was found
  2946. - (None, reason) if no printer is available, with explanation
  2947. """
  2948. normalized_model = normalize_printer_model(model) or model
  2949. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2950. location_suffix = f" in {target_location}" if target_location else ""
  2951. if not printers:
  2952. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2953. # Separate force-matched overrides from preference-only overrides
  2954. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2955. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2956. # Track reasons for skipping printers
  2957. printers_busy = []
  2958. printers_offline = []
  2959. printers_offline_no_plug = []
  2960. printers_missing_filament: list[tuple[str, list[str]]] = []
  2961. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2962. # The first eligible printer that is short on filament, kept in case
  2963. # every eligible printer is (#3137).
  2964. short_fallback: int | None = None
  2965. for printer in printers:
  2966. if printer.id in exclude_ids:
  2967. # Printer is already claimed by another job in this scheduling run.
  2968. # For force-color jobs, still check if the color would match — if not,
  2969. # report it as a color mismatch rather than plain "Busy" so the user
  2970. # knows the job needs a filament change, not just to wait for availability.
  2971. if force_overrides and not pref_overrides:
  2972. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2973. if missing_colors:
  2974. printers_missing_filament.append((printer.name, missing_colors))
  2975. continue
  2976. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  2977. continue
  2978. is_connected = printer_manager.is_connected(printer.id)
  2979. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2980. if not is_connected:
  2981. # An offline printer whose last known filament cannot run this
  2982. # job is reported as needing filament rather than as offline
  2983. # (#2876). It is also the printer the smart-plug step will now
  2984. # decline to switch on, and "Offline:" on its own would leave
  2985. # that decision looking like nothing happening at all.
  2986. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2987. if shortfall:
  2988. printers_missing_filament.append((printer.name, shortfall))
  2989. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2990. printers_offline_no_plug.append(printer.name)
  2991. else:
  2992. printers_offline.append(printer.name)
  2993. continue
  2994. if not is_idle:
  2995. # Printer is currently printing. For force-color jobs, check whether the
  2996. # loaded color would satisfy the requirement — if not, surface it as a
  2997. # color-mismatch reason rather than plain "Busy" so the user understands
  2998. # that the job is waiting for a filament change, not just printer availability.
  2999. if force_overrides and not pref_overrides:
  3000. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3001. if missing_colors:
  3002. printers_missing_filament.append((printer.name, missing_colors))
  3003. logger.debug(
  3004. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3005. printer.id,
  3006. printer.name,
  3007. missing_colors,
  3008. )
  3009. continue
  3010. printers_busy.append(printer.name)
  3011. continue
  3012. # Validate filament compatibility if required types are specified
  3013. if required_filament_types:
  3014. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3015. if missing:
  3016. # When force_overrides are present, enrich missing entries with color info
  3017. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3018. if force_overrides:
  3019. force_color_map = {
  3020. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3021. for o in force_overrides
  3022. }
  3023. missing_enriched = [
  3024. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3025. for t in missing
  3026. ]
  3027. printers_missing_filament.append((printer.name, missing_enriched))
  3028. else:
  3029. printers_missing_filament.append((printer.name, missing))
  3030. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3031. continue
  3032. # Force color match: ALL flagged slots must have an exact type+color match
  3033. if force_overrides:
  3034. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3035. if missing_colors:
  3036. printers_missing_filament.append((printer.name, missing_colors))
  3037. logger.debug(
  3038. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3039. printer.id,
  3040. printer.name,
  3041. missing_colors,
  3042. )
  3043. continue
  3044. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3045. if pref_overrides:
  3046. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3047. if color_matches > 0:
  3048. candidates.append((printer.id, color_matches))
  3049. else:
  3050. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3051. printers_missing_filament.append((printer.name, override_colors))
  3052. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3053. continue
  3054. else:
  3055. # No preference ordering needed: the first eligible printer
  3056. # wins, unless its spools are too light for the job (#3137).
  3057. if is_short is not None and await is_short(printer.id):
  3058. if short_fallback is None:
  3059. short_fallback = printer.id
  3060. logger.info(
  3061. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3062. printer.id,
  3063. printer.name,
  3064. )
  3065. continue
  3066. return printer.id, None
  3067. # If we have candidates from preference override matching, pick the one with most color matches
  3068. if candidates:
  3069. candidates.sort(key=lambda c: c[1], reverse=True)
  3070. if is_short is not None:
  3071. for candidate_id, _ in candidates:
  3072. if not await is_short(candidate_id):
  3073. return candidate_id, None
  3074. logger.info(
  3075. "Model-based assignment: passing over printer %s, not enough filament",
  3076. candidate_id,
  3077. )
  3078. return candidates[0][0], None
  3079. if short_fallback is not None:
  3080. return short_fallback, None
  3081. # Build waiting reason from what we found
  3082. reasons = []
  3083. if printers_missing_filament:
  3084. # Filament/color mismatch is most actionable - show first
  3085. if force_overrides and not pref_overrides:
  3086. # All mismatches are force-color failures — use descriptive message only;
  3087. # but only if there are no busy printers that DO have the matching color.
  3088. # If a printer has the right color but is busy, surface "Busy" instead so
  3089. # the user knows the job will start automatically once that printer is free.
  3090. # Same for a printer that is merely offline: Bambuddy switches that one on
  3091. # by itself, so the job is not actually waiting on anybody to change a
  3092. # spool (#2876 — offline printers reach this list now that a switched-off
  3093. # printer's own filament is read).
  3094. if not printers_busy and not printers_offline:
  3095. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3096. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3097. # else: fall through — the self-resolving entries are appended below
  3098. else:
  3099. names_and_missing = [
  3100. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3101. ]
  3102. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3103. if printers_busy:
  3104. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3105. if printers_offline:
  3106. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3107. if printers_offline_no_plug:
  3108. # Named separately because it is the one entry on this list the
  3109. # user has to act on: no enabled Auto On plug means Bambuddy will
  3110. # never power this printer on for the queue (#2786).
  3111. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3112. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3113. @staticmethod
  3114. def _is_busy_only(waiting_reason: str) -> bool:
  3115. """Check if the waiting reason only contains 'Busy' entries.
  3116. When all matching printers are simply busy printing, the queued job
  3117. will start automatically once a printer finishes — no user action
  3118. is required, so we skip the notification.
  3119. """
  3120. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3121. return all(p.startswith("Busy:") for p in parts)
  3122. def _get_missing_force_color_slots(
  3123. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3124. ) -> list[str]:
  3125. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3126. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3127. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3128. with an exact type+color match.
  3129. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3130. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3131. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3132. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3133. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3134. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3135. setups are unaffected.
  3136. Returns:
  3137. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3138. """
  3139. if raw_data is None:
  3140. status = printer_manager.get_status(printer_id)
  3141. if not status:
  3142. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3143. raw_data = status.raw_data
  3144. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3145. loaded: list[tuple[str, str, str]] = []
  3146. for ams_unit in raw_data.get("ams", []):
  3147. for tray in ams_unit.get("tray", []):
  3148. tray_type = tray.get("tray_type")
  3149. if tray_type:
  3150. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3151. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3152. for vt in raw_data.get("vt_tray") or []:
  3153. vt_type = vt.get("tray_type")
  3154. if vt_type:
  3155. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3156. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3157. missing = []
  3158. for o in force_overrides:
  3159. o_type = canonical_filament_type(o.get("type") or "")
  3160. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3161. o_idx = o.get("tray_info_idx") or ""
  3162. satisfied = any(
  3163. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  3164. for t_type, t_color, t_idx in loaded
  3165. )
  3166. if not satisfied:
  3167. color_label = o.get("color_name") or o.get("color", "?")
  3168. missing.append(f"{o_type} ({color_label})")
  3169. return missing
  3170. def _get_missing_filament_types(
  3171. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3172. ) -> list[str]:
  3173. """Get the list of required filament types that are not loaded on the printer.
  3174. Args:
  3175. printer_id: The printer ID
  3176. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3177. Returns:
  3178. List of missing filament types (empty if all are loaded)
  3179. """
  3180. if raw_data is None:
  3181. status = printer_manager.get_status(printer_id)
  3182. if not status:
  3183. return required_types # Can't determine, assume all missing
  3184. raw_data = status.raw_data
  3185. # Collect all filament types loaded on this printer (AMS units + external spool)
  3186. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3187. loaded_types: set[str] = set()
  3188. # Check AMS units (stored in raw_data["ams"])
  3189. ams_data = raw_data.get("ams", [])
  3190. if ams_data:
  3191. for ams_unit in ams_data:
  3192. for tray in ams_unit.get("tray", []):
  3193. tray_type = tray.get("tray_type")
  3194. if tray_type:
  3195. loaded_types.add(canonical_filament_type(tray_type))
  3196. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3197. for vt in raw_data.get("vt_tray") or []:
  3198. vt_type = vt.get("tray_type")
  3199. if vt_type:
  3200. loaded_types.add(canonical_filament_type(vt_type))
  3201. # Find which required types are missing (using canonical type for equivalence)
  3202. missing = []
  3203. for req_type in required_types:
  3204. if canonical_filament_type(req_type) not in loaded_types:
  3205. missing.append(req_type)
  3206. return missing
  3207. def _count_override_color_matches(
  3208. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3209. ) -> int:
  3210. """Count how many filament overrides have an exact color match on the printer.
  3211. Used to prefer printers that already have the desired override colors loaded.
  3212. """
  3213. if raw_data is None:
  3214. status = printer_manager.get_status(printer_id)
  3215. if not status:
  3216. return 0
  3217. raw_data = status.raw_data
  3218. # Collect loaded filaments' type+color pairs
  3219. loaded: set[tuple[str, str]] = set()
  3220. for ams_unit in raw_data.get("ams", []):
  3221. for tray in ams_unit.get("tray", []):
  3222. tray_type = tray.get("tray_type")
  3223. # `or ""`, not a dict default: a slot can carry the key with a
  3224. # null value, and this now runs against switched-off printers
  3225. # too, where nobody is watching for the AttributeError.
  3226. tray_color = tray.get("tray_color") or ""
  3227. if tray_type:
  3228. color_norm = tray_color.replace("#", "").lower()[:6]
  3229. loaded.add((canonical_filament_type(tray_type), color_norm))
  3230. for vt in raw_data.get("vt_tray") or []:
  3231. vt_type = vt.get("tray_type")
  3232. if vt_type:
  3233. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3234. loaded.add((canonical_filament_type(vt_type), color_norm))
  3235. # Types compared as the type check compares them: a PA12-CF override
  3236. # is met by PA-CF in its colour.
  3237. matches = 0
  3238. for o in overrides:
  3239. o_type = canonical_filament_type(o.get("type") or "")
  3240. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3241. if (o_type, o_color) in loaded:
  3242. matches += 1
  3243. return matches
  3244. @staticmethod
  3245. def _tray_reading(printer_id: int) -> dict:
  3246. """The best tray reading available for a printer that is not printing.
  3247. Live status first: a printer keeps its last status after the power
  3248. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3249. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3250. for when the client itself has been dropped and taken its status with
  3251. it — which is what every power-on attempt does.
  3252. An empty result means "we have never heard", not "nothing is loaded":
  3253. the two are indistinguishable from here, and only the second would be
  3254. safe to act on.
  3255. """
  3256. status = printer_manager.get_status(printer_id)
  3257. raw = (status.raw_data if status else None) or {}
  3258. for ams_unit in raw.get("ams") or []:
  3259. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3260. return raw
  3261. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3262. return raw
  3263. return printer_manager.last_known_trays(printer_id)
  3264. def _cached_filament_shortfall(
  3265. self,
  3266. printer_id: int,
  3267. required_types: list[str] | None,
  3268. filament_overrides: list[dict] | None,
  3269. ) -> list[str]:
  3270. """What a switched-off printer's last known filament cannot provide (#2876).
  3271. The smart-plug wake step used to consider only the model, so a job for a
  3272. colour loaded on the last printer in ID order switched on every earlier
  3273. one in turn, evaluated it, rejected it on colour and left it running.
  3274. Bambuddy knew those colours the whole time. This asks the same three
  3275. questions the matcher asks a live printer — required types, forced
  3276. colours, preferred colours — of the trays it last reported, and returns
  3277. the answers in the same shape the "Waiting for filament" reason uses.
  3278. Empty means the printer may still be able to take the job.
  3279. Fails open, and deliberately: with no tray reading (never connected
  3280. since Bambuddy started, or the cache dropped by a reconnect) this
  3281. returns nothing to report and the printer is treated as it was before.
  3282. A farm restarted while its printers were off must not conclude that
  3283. none of them can print.
  3284. """
  3285. if not required_types and not filament_overrides:
  3286. return []
  3287. raw_data = self._tray_reading(printer_id)
  3288. if not raw_data:
  3289. return []
  3290. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3291. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3292. if required_types:
  3293. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3294. if missing:
  3295. # Same enrichment the live path applies: a bare "PLA" is not
  3296. # much help when what is missing is a particular PLA.
  3297. force_color_map = {
  3298. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3299. }
  3300. return [
  3301. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3302. for t in missing
  3303. ]
  3304. if force_overrides:
  3305. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3306. if missing_colors:
  3307. return missing_colors
  3308. # Preference overrides read as a preference but the matcher treats zero
  3309. # matches as a skip, so a printer with none of the wanted colours is
  3310. # rejected there too. Waking it would only produce that same rejection.
  3311. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3312. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3313. return []
  3314. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3315. """Fold the winning candidate's file and settings onto the queue row (#671).
  3316. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3317. never escapes the selection loop. By the time the pass commits, the row
  3318. looks exactly like an ordinary single-file model-based item, so the upload,
  3319. archive creation, expected-print registration, print history and reprint
  3320. paths need no knowledge that variants exist.
  3321. No-ops for a non-variant candidate, which is already the item's own columns.
  3322. Safe to run and re-run: the item's file columns are only ever *read* when it
  3323. has no variants, so an item that gets resolved and then skipped (library-row
  3324. conflict, previous-print gate) is simply resolved again on the next pass.
  3325. """
  3326. variant = candidate.variant
  3327. if variant is None:
  3328. return
  3329. item.library_file_id = variant.library_file_id
  3330. item.library_file = variant.library_file
  3331. # The dispatcher checks archive_id first and would print that instead of
  3332. # the file we just picked. Creation refuses to combine the two, so this
  3333. # only ever fires on a hand-written row — clear it rather than silently
  3334. # dispatch something the matcher never considered.
  3335. item.archive_id = None
  3336. item.archive = None
  3337. item.target_model = variant.target_model
  3338. item.plate_id = variant.plate_id
  3339. item.ams_mapping = variant.ams_mapping
  3340. item.nozzle_mapping = variant.nozzle_mapping
  3341. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3342. item.filament_overrides = variant.filament_overrides
  3343. item.required_filament_types = variant.required_filament_types
  3344. if variant.print_time_seconds is not None:
  3345. # The row carried the shortest candidate's estimate so SJF could order
  3346. # it before a printer was known; now that one is chosen, record what is
  3347. # actually going to run so history and the ETA agree with reality.
  3348. item.print_time_seconds = variant.print_time_seconds
  3349. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3350. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3351. Recomputes from live printer status when the stored mapping is missing OR
  3352. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3353. frontend status-load race can serialize [-1] before the printer's AMS
  3354. trays are known (#2589) — and must not be trusted: downstream it would be
  3355. silently downgraded to external-spool mode and print against an empty
  3356. feed. A resolved mapping is re-checked against the target printer's
  3357. live trays before it is trusted (#2799) and recomputed when it does not
  3358. fit. When it does fit, its resolved slots are kept as they are and only
  3359. the slots the plate prints that are still unresolved are matched again;
  3360. all of it is left alone when the user has acknowledged it with "Print
  3361. Anyway".
  3362. When recompute cannot resolve it either (no compatible tray loaded), the
  3363. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3364. external selection. On a printer that reported loaded trays,
  3365. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3366. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3367. and the firmware surfaces a clear AMS-mapping error instead of silently
  3368. printing to the empty external feed.
  3369. Returns an actionable message when that firmware error is the only
  3370. possible outcome — the matcher ran, matched nothing, and the printer has
  3371. no AMS to load a different spool into (#2771). The caller fails the item
  3372. on it instead of spending an upload on a print that cannot start.
  3373. Returns None everywhere else, including every case where we simply lack
  3374. the data to judge, so dispatch is only ever blocked on a positive
  3375. finding.
  3376. """
  3377. stored_mapping: list | None = None
  3378. if item.ams_mapping:
  3379. try:
  3380. stored_mapping = json.loads(item.ams_mapping)
  3381. except (json.JSONDecodeError, TypeError):
  3382. stored_mapping = None
  3383. # Present and resolved. Global tray IDs only mean something relative to
  3384. # the printer they were resolved against, so "resolved" is not the same
  3385. # as "resolved *here*" — check the mapping still fits the printer that
  3386. # is about to run this item before trusting it (#2799). "Print anyway"
  3387. # is the user overriding exactly this judgement, so it short-circuits.
  3388. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3389. if item.skip_filament_check:
  3390. return None
  3391. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3392. if conflict is None:
  3393. # It fits, but a slot the plate prints may still be empty: the
  3394. # spool was missing when it was mapped, and has perhaps been
  3395. # loaded since. Nothing else would ever look at that slot again,
  3396. # so a job held for it would be held again on every Start.
  3397. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3398. if filled is not None:
  3399. item.ams_mapping = json.dumps(filled)
  3400. logger.info(
  3401. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3402. item.id,
  3403. stored_mapping,
  3404. printer_id,
  3405. filled,
  3406. )
  3407. await db.commit()
  3408. return None
  3409. logger.warning(
  3410. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3411. item.id,
  3412. stored_mapping,
  3413. printer_id,
  3414. conflict,
  3415. )
  3416. # Drop it before recomputing so a failed recompute cannot fall back
  3417. # to the mapping we just rejected.
  3418. item.ams_mapping = None
  3419. stored_mapping = None
  3420. await db.commit()
  3421. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3422. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3423. item.ams_mapping = json.dumps(computed_mapping)
  3424. logger.info(
  3425. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3426. item.id,
  3427. printer_id,
  3428. computed_mapping,
  3429. )
  3430. await db.commit()
  3431. return None
  3432. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3433. if external_only is not None:
  3434. item.ams_mapping = json.dumps(external_only)
  3435. logger.info(
  3436. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3437. "mapping every filament to it: %s",
  3438. item.id,
  3439. printer_id,
  3440. external_only,
  3441. )
  3442. await db.commit()
  3443. return None
  3444. if _mapping_is_all_unresolved(stored_mapping):
  3445. logger.warning(
  3446. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3447. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3448. item.id,
  3449. stored_mapping,
  3450. printer_id,
  3451. )
  3452. item.ams_mapping = None
  3453. await db.commit()
  3454. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3455. async def _external_spool_only_mapping(
  3456. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3457. ) -> list[int] | None:
  3458. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3459. A printer without an AMS prints from its external spool, and an external
  3460. spool whose filament was never set reports no type, so the matcher has
  3461. nothing to match. Sent without a mapping, the print goes out with the AMS
  3462. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3463. to carry such a job through; a job placed by model or location no longer
  3464. keeps one, and one queued that way never had one.
  3465. Only on a positive report: the printer has said it has no AMS, it has a
  3466. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3467. is not ours to pick), and no feed has a filament set — with one set, the
  3468. matcher has already given its answer. Not for a job that asked for its
  3469. colours to be matched strictly: a spool without a filament set has no
  3470. colour to check. Returns None otherwise.
  3471. """
  3472. if item.filament_overrides:
  3473. try:
  3474. overrides = json.loads(item.filament_overrides)
  3475. except (json.JSONDecodeError, TypeError):
  3476. return None
  3477. if not isinstance(overrides, list) or any(
  3478. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3479. ):
  3480. return None
  3481. status = printer_manager.get_status(printer_id)
  3482. if status is None or not isinstance(status.raw_data, dict):
  3483. return None
  3484. ams_units = status.raw_data.get("ams")
  3485. if not isinstance(ams_units, list) or ams_units:
  3486. return None
  3487. vt_trays = status.raw_data.get("vt_tray")
  3488. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3489. return None
  3490. if self._build_loaded_filaments(status):
  3491. return None
  3492. printer = await self._get_printer(db, printer_id)
  3493. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3494. return None
  3495. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3496. if external < _EXTERNAL_TRAY_ID_MIN:
  3497. return None
  3498. required = await self._get_filament_requirements(db, item)
  3499. slot_ids = [r.get("slot_id") for r in required or []]
  3500. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3501. if not slot_ids:
  3502. return None
  3503. mapping = [-1] * max(slot_ids)
  3504. for slot_id in slot_ids:
  3505. mapping[slot_id - 1] = external
  3506. return mapping
  3507. async def _fill_unresolved_slots(
  3508. self,
  3509. db: AsyncSession,
  3510. printer_id: int,
  3511. item: PrintQueueItem,
  3512. stored_mapping: list | None,
  3513. ) -> list | None:
  3514. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3515. Every resolved entry is kept, so a tray the user picked by hand stays
  3516. picked. Only the plate's unresolved slots are matched, and only against
  3517. trays the mapping does not already use: the matcher never gives two
  3518. slots one tray, and filling a gap with a tray the user assigned to
  3519. another slot would print that slot's filament twice.
  3520. Returns None when there is nothing to fill or nothing could be filled.
  3521. """
  3522. if not isinstance(stored_mapping, list) or not stored_mapping:
  3523. return None
  3524. required = await self._get_filament_requirements(db, item)
  3525. if not required:
  3526. return None
  3527. self._apply_filament_overrides(item, required)
  3528. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3529. if not gaps:
  3530. return None
  3531. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3532. computed = await self._compute_ams_mapping_for_printer(
  3533. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3534. )
  3535. if not computed:
  3536. return None
  3537. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3538. filled = False
  3539. for slot_id in gaps:
  3540. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3541. if _is_tray_id(tray) and tray >= 0:
  3542. merged[slot_id - 1] = tray
  3543. filled = True
  3544. return merged if filled else None
  3545. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3546. """What a staged item would be held for if it were started now (#2799).
  3547. The Start button asks this before releasing an item, so that a job whose
  3548. filament is still not loaded offers "Print Anyway" instead of being
  3549. released, held again by the scheduler and leaving no way past the hold.
  3550. It reaches the same answer the dispatch path would: a stored mapping
  3551. that fits is kept and only its gaps are matched again, and one that
  3552. does not fit (or is missing) is replaced by a fresh match.
  3553. Returns the missing filaments, described the way the queue row
  3554. describes them, or None when nothing is missing or there is not enough
  3555. evidence to say: no printer yet (a model-based item picks one at
  3556. dispatch), no status, no trays reported, or no readable 3MF.
  3557. """
  3558. if item.skip_filament_check or not item.printer_id:
  3559. return None
  3560. status = printer_manager.get_status(item.printer_id)
  3561. if status is None or not self._build_loaded_filaments(status):
  3562. return None
  3563. # Called from a request, not from a pass: drop whatever the last pass
  3564. # memoised so this reads the file as it is now. A pass running at the
  3565. # same time only loses its cache.
  3566. self._filament_req_memo.clear()
  3567. mapping: list | None = None
  3568. if item.ams_mapping:
  3569. try:
  3570. mapping = json.loads(item.ams_mapping)
  3571. except (json.JSONDecodeError, TypeError):
  3572. mapping = None
  3573. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3574. mapping = None
  3575. if mapping is not None:
  3576. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3577. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3578. else:
  3579. mapping = None
  3580. if mapping is None:
  3581. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3582. required = await self._get_filament_requirements(db, item)
  3583. if not required:
  3584. return None
  3585. self._apply_filament_overrides(item, required)
  3586. missing = _unresolved_required(required, mapping)
  3587. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3588. async def _stored_mapping_conflict(
  3589. self,
  3590. db: AsyncSession,
  3591. printer_id: int,
  3592. item: PrintQueueItem,
  3593. stored_mapping: list | None,
  3594. ) -> str | None:
  3595. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3596. A mapping is a list of global tray IDs, and those are only meaningful
  3597. relative to the printer they were resolved against — the same rule
  3598. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3599. arrives at a printer it was not resolved for:
  3600. * the print dialog stamps one mapping onto every selected printer, so a
  3601. mapping computed against the first printer is dispatched verbatim to
  3602. the rest, whose AMS slot order differs;
  3603. * a spool is moved between queueing and dispatch.
  3604. Both end the same way: the slot index still resolves, so nothing looks
  3605. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3606. the firmware's own type check, so a PETG slot happily prints in ASA.
  3607. Returns a short reason when the mapping names a tray this printer does
  3608. not have loaded, points a slot at a tray holding a different filament
  3609. type, or points it at an external spool this printer reports empty while
  3610. its AMS holds that slot's filament (#3239). Returns None when the
  3611. mapping fits, and — deliberately — whenever we lack the evidence to
  3612. judge, so a recompute only ever follows a positive finding.
  3613. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3614. matcher had nothing, not that the mapping belongs to another printer,
  3615. and destroying a partially hand-resolved mapping over it would lose the
  3616. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3617. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3618. item when that finds nothing.
  3619. """
  3620. if not isinstance(stored_mapping, list) or not stored_mapping:
  3621. return None
  3622. status = printer_manager.get_status(printer_id)
  3623. if status is None:
  3624. return None
  3625. loaded = self._build_loaded_filaments(status)
  3626. if not loaded:
  3627. # Nothing reported yet (reconnect, first push pending). Saying
  3628. # "tray not loaded" here would recompute against an AMS we cannot
  3629. # see, which is how #2589 produced a bogus all-[-1] in the first
  3630. # place.
  3631. return None
  3632. by_tray = {f["global_tray_id"]: f for f in loaded}
  3633. # Cheap pass first, on live status alone: every tray the mapping names
  3634. # has to exist here. This catches a foreign mapping without opening the
  3635. # 3MF, which is worth doing because the parse below is neither cached
  3636. # nor free.
  3637. for index, tray in enumerate(stored_mapping):
  3638. if not _is_tray_id(tray) or tray < 0:
  3639. continue
  3640. if tray in by_tray:
  3641. continue
  3642. if tray >= 254:
  3643. # An external feed we have not heard about is absence of
  3644. # evidence about *that slot* — the rest of the mapping is still
  3645. # worth judging, so skip it rather than abandoning the pass.
  3646. continue
  3647. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3648. # Only now is the 3MF worth opening: the type check needs to know what
  3649. # each slot actually asked for. The external spool is checked the same
  3650. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3651. # two printers with different filament in the external feed is the same
  3652. # failure this method exists to catch.
  3653. required = await self._get_filament_requirements(db, item)
  3654. if not required:
  3655. return None
  3656. self._apply_filament_overrides(item, required)
  3657. # External feeds the printer reports and reports as empty. That is
  3658. # evidence, unlike an external feed it says nothing about (#3239).
  3659. empty_external: set[int] = set()
  3660. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3661. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3662. if isinstance(vt, dict) and not vt.get("tray_type"):
  3663. try:
  3664. empty_external.add(int(vt.get("id", 254)))
  3665. except (TypeError, ValueError):
  3666. continue
  3667. for req in required:
  3668. slot_id = req.get("slot_id") or 0
  3669. if slot_id <= 0:
  3670. continue
  3671. if slot_id > len(stored_mapping):
  3672. return f"slot {slot_id} is not covered by the mapping"
  3673. tray = stored_mapping[slot_id - 1]
  3674. if not _is_tray_id(tray) or tray < 0:
  3675. continue
  3676. loaded_tray = by_tray.get(tray)
  3677. if loaded_tray is None:
  3678. # A mapping made for a printer that feeds this slot from its
  3679. # external spool, sent to one whose external spool is empty and
  3680. # whose AMS holds the filament (#3239). Only then: an external
  3681. # spool can be loaded without its filament set, and on a printer
  3682. # with nothing else to offer that job printed before. The colour
  3683. # has to match too: with only another colour in the AMS, the
  3684. # printer asking for the spool beats printing in that colour.
  3685. want = canonical_filament_type(req.get("type"))
  3686. if tray >= 254 and tray in empty_external and want:
  3687. ams_tray = next(
  3688. (
  3689. f
  3690. for f in loaded
  3691. if not f.get("is_external")
  3692. and canonical_filament_type(f.get("type")) == want
  3693. and self._colors_are_similar(f.get("color"), req.get("color"))
  3694. ),
  3695. None,
  3696. )
  3697. if ams_tray is not None:
  3698. return (
  3699. f"slot {slot_id} points at the external spool, which is empty, "
  3700. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3701. )
  3702. continue
  3703. want = canonical_filament_type(req.get("type"))
  3704. have = canonical_filament_type(loaded_tray.get("type"))
  3705. if want and have and want != have:
  3706. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3707. return None
  3708. async def _unmappable_without_ams_message(
  3709. self,
  3710. db: AsyncSession,
  3711. printer_id: int,
  3712. item: PrintQueueItem,
  3713. computed_mapping: list[int] | None,
  3714. ) -> str | None:
  3715. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3716. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3717. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3718. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3719. uploaded several megabytes and burned its dispatch retries. This method
  3720. speaks only for the AMS-less case: there is nothing to resume into — the
  3721. external spool holder is the whole inventory — so the useful answer is to
  3722. say which filament is missing and stop. With an AMS attached it returns
  3723. None: where live status reported loaded trays,
  3724. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3725. reported none the print goes out and the firmware error is the answer —
  3726. the user can load the right spool and press Resume.
  3727. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3728. every branch that lacks the evidence to be sure returns None.
  3729. """
  3730. # None means the matcher never ran (no requirements parsed from the 3MF,
  3731. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3732. # dispatch as they always have.
  3733. if not _mapping_is_all_unresolved(computed_mapping):
  3734. return None
  3735. status = printer_manager.get_status(printer_id)
  3736. if status is None:
  3737. return None
  3738. # "No AMS" has to be a fact the printer stated, not the absence of a
  3739. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3740. # handled and is preserved across partial pushes thereafter, so a missing
  3741. # key means we have not heard yet — most likely a reconnect, where the
  3742. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3743. # empty list is the positive report of a printer with no AMS.
  3744. ams_units = status.raw_data.get("ams")
  3745. if not isinstance(ams_units, list) or ams_units:
  3746. return None
  3747. required = await self._get_filament_requirements(db, item)
  3748. loaded = self._build_loaded_filaments(status)
  3749. if not required or not loaded:
  3750. # Both were non-empty moments ago or the matcher could not have run.
  3751. # If the picture changed under us, say nothing rather than fail an
  3752. # item on stale evidence.
  3753. return None
  3754. self._apply_filament_overrides(item, required)
  3755. return _unmatched_filament_message(required, loaded)
  3756. async def _fail_unmappable_item(
  3757. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3758. ) -> None:
  3759. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3760. This replaces a failure, not a success: without it the item is uploaded,
  3761. rejected by the firmware with 0700_8012, retried twice more and failed
  3762. anyway with "never started the print after N dispatch attempts". So this
  3763. applies on the model-based path too, even though it means an "Any <model>"
  3764. job stops at the first printer offered rather than trying its siblings —
  3765. deferring instead would need the check to move inside
  3766. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3767. re-assigns the same printer on the next tick.
  3768. """
  3769. item.status = "failed"
  3770. item.error_message = message
  3771. item.completed_at = datetime.now(timezone.utc)
  3772. item.waiting_reason = None
  3773. await db.commit()
  3774. from backend.app.services.print_batch import refresh_batches_after
  3775. await refresh_batches_after([item.id])
  3776. logger.warning(
  3777. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3778. item.id,
  3779. printer_id,
  3780. message,
  3781. )
  3782. job_name = await self._get_job_name(db, item)
  3783. printer = await self._get_printer(db, printer_id)
  3784. await notification_service.on_queue_job_failed(
  3785. job_name=job_name,
  3786. printer_id=printer_id,
  3787. printer_name=printer.name if printer else "Unknown",
  3788. reason=message,
  3789. db=db,
  3790. )
  3791. try:
  3792. await ws_manager.send_queue_item_failed(
  3793. user_id=item.created_by_id,
  3794. queue_item_id=item.id,
  3795. printer_id=printer_id,
  3796. reason="filament_unmappable",
  3797. )
  3798. except Exception:
  3799. pass
  3800. async def _compute_ams_mapping_for_printer(
  3801. self,
  3802. db: AsyncSession,
  3803. printer_id: int,
  3804. item: PrintQueueItem,
  3805. *,
  3806. only_slots: set[int] | None = None,
  3807. reserved_trays: set[int] | None = None,
  3808. ) -> list[int] | None:
  3809. """Compute AMS mapping for a printer based on filament requirements.
  3810. Called when a queue item has no ams_mapping set — either for model-based
  3811. items after printer assignment, or printer-specific items (e.g. from VP).
  3812. Args:
  3813. db: Database session
  3814. printer_id: The assigned printer ID
  3815. item: The queue item (contains archive_id or library_file_id)
  3816. only_slots: Match only these filament slots; every other slot comes
  3817. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3818. reserved_trays: Global tray IDs to leave out of the match, because
  3819. the stored mapping already gives them to another slot.
  3820. Returns:
  3821. AMS mapping array or None if no mapping needed/possible
  3822. """
  3823. # Get printer status
  3824. status = printer_manager.get_status(printer_id)
  3825. if not status:
  3826. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3827. return None
  3828. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3829. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3830. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3831. # an AMS on the *other* nozzle, and the matcher falls through to a
  3832. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3833. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3834. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3835. # Get filament requirements from source file
  3836. filament_reqs = await self._get_filament_requirements(db, item)
  3837. if not filament_reqs:
  3838. # When the 3MF can't be read but force-color overrides are present, build a
  3839. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3840. if item.filament_overrides:
  3841. try:
  3842. overrides = json.loads(item.filament_overrides)
  3843. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3844. if force_overrides:
  3845. logger.info(
  3846. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3847. "force-color override(s)",
  3848. item.id,
  3849. len(force_overrides),
  3850. )
  3851. return self._build_override_direct_mapping(force_overrides, status)
  3852. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3853. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3854. logger.debug("No filament requirements found for queue item %s", item.id)
  3855. return None
  3856. self._apply_filament_overrides(item, filament_reqs)
  3857. if only_slots is not None:
  3858. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3859. if not filament_reqs:
  3860. return None
  3861. # Build loaded filaments from printer status
  3862. loaded_filaments = self._build_loaded_filaments(status)
  3863. if reserved_trays:
  3864. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3865. if not loaded_filaments:
  3866. logger.debug("No filaments loaded on printer %s", printer_id)
  3867. return None
  3868. # Check if user prefers lowest remaining filament when multiple spools match
  3869. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3870. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3871. # Without backup, the printer will not switch to a second spool when the
  3872. # picked one runs out — so sorting toward the lowest leaves the print
  3873. # at risk of running dry mid-job. None (unknown: no status report with
  3874. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3875. if prefer_lowest and status.ams_filament_backup is False:
  3876. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3877. prefer_lowest = False
  3878. # When the preference is on, surface Bambuddy's inventory-side
  3879. # remaining for each slot that's bound to a tracked spool, so the
  3880. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3881. # entirely when the preference is off — no behaviour change for
  3882. # users who haven't opted in.
  3883. inventory_remain_overrides: dict[int, float] | None = None
  3884. if prefer_lowest:
  3885. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3886. # Compute mapping: match required filaments to available slots
  3887. return self._match_filaments_to_slots(
  3888. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3889. )
  3890. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3891. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3892. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3893. diagnosis (#2771) describes the filament the matcher actually looked
  3894. for, not the one the 3MF was sliced with — naming the pre-override
  3895. filament in a user-facing error would send the user to load the wrong
  3896. spool.
  3897. """
  3898. if not item.filament_overrides:
  3899. return
  3900. try:
  3901. overrides = json.loads(item.filament_overrides)
  3902. override_map = {o["slot_id"]: o for o in overrides}
  3903. for req in filament_reqs:
  3904. if req["slot_id"] in override_map:
  3905. override = override_map[req["slot_id"]]
  3906. req["type"] = override["type"]
  3907. req["color"] = override["color"]
  3908. # A manual/preference override SWAPS the slot's filament, so the
  3909. # 3MF's original tray_info_idx now points at the old spool and must
  3910. # be cleared — matching then falls back to type+colour. A
  3911. # force_color_match override is not a swap: it carries the 3MF's
  3912. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3913. # it here too, letting the matcher pin the correct variant slot on a
  3914. # printer holding two same-colour spools of different variants (#2650).
  3915. # If that variant isn't loaded the matcher falls back to type+colour,
  3916. # so an eligible printer never fails to map.
  3917. req["tray_info_idx"] = (
  3918. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3919. )
  3920. logger.debug(
  3921. "Queue item %s: Override slot %d -> %s %s",
  3922. item.id,
  3923. req["slot_id"],
  3924. override["type"],
  3925. override["color"],
  3926. )
  3927. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3928. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3929. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3930. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3931. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3932. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3933. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3934. treated as the filament requirement for that slot and matched against the
  3935. current AMS state of the printer.
  3936. Returns the same format as ``_match_filaments_to_slots``, or None when
  3937. the AMS has no loaded filaments.
  3938. """
  3939. loaded = self._build_loaded_filaments(status)
  3940. if not loaded:
  3941. return None
  3942. reqs = [
  3943. {
  3944. "slot_id": o["slot_id"],
  3945. "type": o.get("type", ""),
  3946. "color": o.get("color", ""),
  3947. # These are all force_color_match overrides, so the idx (when the
  3948. # 3MF carried one) is the intended variant, not a stale swap —
  3949. # keep it so the matcher pins the right variant slot, falling back
  3950. # to type+colour when it isn't loaded (#2650).
  3951. "tray_info_idx": o.get("tray_info_idx", ""),
  3952. }
  3953. for o in force_overrides
  3954. ]
  3955. return self._match_filaments_to_slots(reqs, loaded)
  3956. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3957. """Resolve the queue item's source 3MF and parse the per-slot
  3958. filament requirements out of it. Thin DB-resolver wrapper around
  3959. ``filament_requirements.extract_filament_requirements`` so the VP
  3960. queue-mode write path (#1188) can reuse the same parser at upload
  3961. time.
  3962. """
  3963. from backend.app.services.filament_requirements import extract_filament_requirements
  3964. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3965. # so every caller gets its own copy — a shared list would leak one
  3966. # item's overrides into the next item that happens to print the same
  3967. # plate.
  3968. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3969. if memo_key in self._filament_req_memo:
  3970. cached = self._filament_req_memo[memo_key]
  3971. return [dict(r) for r in cached] if cached else None
  3972. file_path: Path | None = None
  3973. if item.archive_id:
  3974. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3975. archive = result.scalar_one_or_none()
  3976. if archive:
  3977. file_path = settings.base_dir / archive.file_path
  3978. elif item.library_file_id:
  3979. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3980. library_file = result.scalar_one_or_none()
  3981. if library_file:
  3982. lib_path = Path(library_file.file_path)
  3983. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3984. if not file_path or not file_path.exists():
  3985. self._filament_req_memo[memo_key] = None
  3986. return None
  3987. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3988. self._filament_req_memo[memo_key] = filaments or None
  3989. return [dict(r) for r in filaments] if filaments else None
  3990. def _build_loaded_filaments(self, status) -> list[dict]:
  3991. """Build list of loaded filaments from printer status.
  3992. Args:
  3993. status: PrinterState from printer_manager
  3994. Returns:
  3995. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3996. """
  3997. filaments = []
  3998. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3999. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4000. # Routes external spools to an extruder (#2771). Mirrors
  4001. # `buildLoadedFilaments` in the frontend.
  4002. vt_trays = status.raw_data.get("vt_tray") or []
  4003. is_dual_nozzle = reports_two_nozzles(status)
  4004. # Parse AMS units from raw_data
  4005. ams_data = status.raw_data.get("ams", [])
  4006. for ams_unit in ams_data:
  4007. ams_id = int(ams_unit.get("id", 0))
  4008. trays = ams_unit.get("tray", [])
  4009. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4010. for tray in trays:
  4011. tray_type = tray.get("tray_type")
  4012. if tray_type:
  4013. tray_id = int(tray.get("id", 0))
  4014. tray_color = tray.get("tray_color", "")
  4015. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4016. tray_info_idx = tray.get("tray_info_idx", "")
  4017. # Normalize color: remove alpha, add hash
  4018. color = self._normalize_color(tray_color)
  4019. # Calculate global tray ID
  4020. # AMS-HT units have IDs starting at 128 with a single tray
  4021. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4022. filaments.append(
  4023. {
  4024. "type": tray_type,
  4025. "color": color,
  4026. "tray_info_idx": tray_info_idx,
  4027. "ams_id": ams_id,
  4028. "tray_id": tray_id,
  4029. "is_ht": is_ht,
  4030. "is_external": False,
  4031. "global_tray_id": global_tray_id,
  4032. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4033. "remain": tray.get("remain", -1),
  4034. }
  4035. )
  4036. # Check external spool(s) (vt_tray is a list)
  4037. for idx, vt in enumerate(vt_trays):
  4038. if vt.get("tray_type"):
  4039. color = self._normalize_color(vt.get("tray_color", ""))
  4040. tray_id = int(vt.get("id", 254))
  4041. filaments.append(
  4042. {
  4043. "type": vt["tray_type"],
  4044. "color": color,
  4045. "tray_info_idx": vt.get("tray_info_idx", ""),
  4046. "ams_id": -1,
  4047. "tray_id": idx,
  4048. "is_ht": False,
  4049. "is_external": True,
  4050. "global_tray_id": tray_id,
  4051. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4052. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4053. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4054. "remain": vt.get("remain", -1),
  4055. }
  4056. )
  4057. return filaments
  4058. def _normalize_color(self, color: str | None) -> str:
  4059. """Normalize color to #RRGGBB format."""
  4060. if not color:
  4061. return "#808080"
  4062. hex_color = color.replace("#", "")[:6]
  4063. return f"#{hex_color}"
  4064. def _normalize_color_for_compare(self, color: str | None) -> str:
  4065. """Normalize color for comparison (lowercase, no hash)."""
  4066. if not color:
  4067. return ""
  4068. return color.replace("#", "").lower()[:6]
  4069. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4070. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4071. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4072. stays the per-channel box that shipped — this only decides which of
  4073. several eligible spools is closest, so nothing becomes usable or
  4074. unusable because of it.
  4075. It ranks by how far apart the colours *look*, not how far apart their
  4076. numbers are. RGB distance overweights blue badly enough to invert the
  4077. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4078. the nearer of two eligible spools by RGB and the further by a factor of
  4079. four once measured perceptually.
  4080. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4081. transparent filament is not a colour the user chose, and counting it
  4082. would stop a transparent filament matching itself.
  4083. """
  4084. return perceptual_color_distance(color1, color2)
  4085. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4086. """Check if two colors are visually similar within a threshold."""
  4087. hex1 = self._normalize_color_for_compare(color1)
  4088. hex2 = self._normalize_color_for_compare(color2)
  4089. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4090. return False
  4091. try:
  4092. r1 = int(hex1[0:2], 16)
  4093. g1 = int(hex1[2:4], 16)
  4094. b1 = int(hex1[4:6], 16)
  4095. r2 = int(hex2[0:2], 16)
  4096. g2 = int(hex2[2:4], 16)
  4097. b2 = int(hex2[4:6], 16)
  4098. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4099. except ValueError:
  4100. return False
  4101. async def _build_inventory_remain_overrides(
  4102. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4103. ) -> dict[int, float]:
  4104. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4105. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4106. The MQTT ``remain`` field on a tray is the printer firmware's
  4107. RFID-decremented value, which has two limitations the "Prefer Lowest
  4108. Remaining Filament" feature has been ignoring (#1508):
  4109. - it's only meaningful for Bambu RFID spools; everything else reports
  4110. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4111. compare equal and the sort collapses to AMS-slot order — the user
  4112. who's curating inventory weights gets the lower-slot pick instead
  4113. of the lower-remaining pick;
  4114. - even when set, it's the *printer's* counter, not Bambuddy's
  4115. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4116. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4117. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4118. When the user has bound a spool to a slot, their own inventory
  4119. tracking is authoritative; this helper surfaces that value so the
  4120. sort can prefer it. Slots without a binding are absent from the
  4121. returned map — the caller then falls back to MQTT ``remain`` for
  4122. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4123. Returns an empty map on any failure (no inventory bindings, DB
  4124. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4125. is a preference, not a guarantee.
  4126. """
  4127. if not loaded:
  4128. return {}
  4129. # External / virtual-tray slots are tracked separately from AMS — skip
  4130. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4131. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4132. # match is fiddly and out of scope for this fix).
  4133. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4134. if not tracked_slots:
  4135. return {}
  4136. is_spoolman = await self._is_spoolman_mode(db)
  4137. overrides: dict[int, float] = {}
  4138. if is_spoolman:
  4139. result = await db.execute(
  4140. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4141. )
  4142. assignments = list(result.scalars().all())
  4143. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4144. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4145. for ams_id, tray_id, gtid in tracked_slots:
  4146. spoolman_id = by_slot.get((ams_id, tray_id))
  4147. if spoolman_id is None:
  4148. continue
  4149. grams = await _spoolman_remaining_grams(spoolman_id)
  4150. if grams is not None:
  4151. overrides[gtid] = grams
  4152. return overrides
  4153. # Internal inventory mode (default). selectinload matches the pattern
  4154. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4155. # plus an eager-loaded relationship rather than an explicit join, so
  4156. # the row-attribute shape is exactly what those routes already rely on.
  4157. result = await db.execute(
  4158. select(SpoolAssignment)
  4159. .options(selectinload(SpoolAssignment.spool))
  4160. .where(SpoolAssignment.printer_id == printer_id)
  4161. )
  4162. assignments = list(result.scalars().all())
  4163. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4164. for ams_id, tray_id, gtid in tracked_slots:
  4165. spool = by_slot.get((ams_id, tray_id))
  4166. if spool is None:
  4167. continue
  4168. label = float(spool.label_weight or 0)
  4169. used = float(spool.weight_used or 0)
  4170. overrides[gtid] = max(0.0, label - used)
  4171. return overrides
  4172. @staticmethod
  4173. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4174. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4175. here to avoid making this module import-dependent on that private
  4176. helper's signature."""
  4177. try:
  4178. from backend.app.api.routes.settings import get_setting
  4179. v = await get_setting(db, "spoolman_enabled")
  4180. return bool(v) and v.lower() == "true"
  4181. except Exception:
  4182. return False
  4183. @staticmethod
  4184. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4185. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4186. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4187. so a tied sort produces the same physical-position order the pre-#1508
  4188. stable sort did (preserves the regression-free baseline):
  4189. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4190. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4191. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4192. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4193. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4194. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4195. """
  4196. if ams_id is None or ams_id < 0:
  4197. return 10_000
  4198. if ams_id >= 128:
  4199. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4200. return ams_id * 4 + (tray_id or 0)
  4201. @staticmethod
  4202. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4203. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4204. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4205. non-tracked spools (the user has told us they care about these
  4206. specifically), then ascending by remaining within each tier, then
  4207. ascending by AMS slot position as the deterministic tie-breaker.
  4208. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4209. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4210. because the tier flag dominates — which is what lets us mix grams
  4211. (inventory) and percent (MQTT) without a unit conversion.
  4212. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4213. spools the printer DOES know something about sort ahead of those
  4214. it knows nothing about — preserves pre-#1508 behaviour for the
  4215. no-inventory-binding case.
  4216. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4217. external on ties, matching the legacy emission-order stable sort.
  4218. """
  4219. gtid = f.get("global_tray_id")
  4220. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4221. if overrides and gtid in overrides:
  4222. return (0, overrides[gtid], slot_order)
  4223. remain = f.get("remain", -1)
  4224. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4225. def _match_filaments_to_slots(
  4226. self,
  4227. required: list[dict],
  4228. loaded: list[dict],
  4229. prefer_lowest: bool = False,
  4230. inventory_remain_overrides: dict[int, float] | None = None,
  4231. fts_installed: bool = False,
  4232. ) -> list[int] | None:
  4233. """Match required filaments to loaded filaments and build AMS mapping.
  4234. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4235. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4236. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4237. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4238. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4239. matching among those trays.
  4240. Args:
  4241. required: List of required filaments with slot_id, type, color, tray_info_idx
  4242. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4243. Returns:
  4244. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4245. """
  4246. if not required:
  4247. return None
  4248. # Track used trays to avoid duplicate assignment
  4249. used_tray_ids: set[int] = set()
  4250. comparisons = []
  4251. for req in required:
  4252. req_type = (req.get("type") or "").upper()
  4253. req_color = req.get("color", "")
  4254. req_tray_info_idx = req.get("tray_info_idx", "")
  4255. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4256. idx_match = None
  4257. exact_match = None
  4258. similar_match = None
  4259. similar_distance = float("inf")
  4260. type_only_match = None
  4261. # Get available trays (not already used)
  4262. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4263. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4264. # Hard filter — cross-nozzle assignment causes print failures
  4265. # ("position of left hotend is abnormal"), so never fall back.
  4266. # Skipped when an FTS is installed: it routes any AMS slot to either
  4267. # extruder, so restricting to one nozzle would wrongly exclude the
  4268. # correct spool sitting in the other nozzle's AMS (#2186).
  4269. req_nozzle_id = req.get("nozzle_id")
  4270. if req_nozzle_id is not None and not fts_installed:
  4271. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4272. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4273. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4274. # _prefer_lowest_sort_key for the full rationale.
  4275. if prefer_lowest:
  4276. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4277. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4278. # One line per filament req so a bug report can be diagnosed
  4279. # without enabling debug logging: shows what the matcher saw
  4280. # (req shape + sorted candidate trays with their remain values
  4281. # and any inventory override that was applied). Mirrored by
  4282. # the picked-match log at the bottom of the loop.
  4283. logger.info(
  4284. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4285. req.get("slot_id"),
  4286. req_type,
  4287. req_color,
  4288. req_tray_info_idx,
  4289. req_nozzle_id,
  4290. [
  4291. {
  4292. "gtid": f.get("global_tray_id"),
  4293. "type": f.get("type"),
  4294. "color": f.get("color"),
  4295. "tii": f.get("tray_info_idx"),
  4296. "remain": f.get("remain"),
  4297. "inv_g": (
  4298. inventory_remain_overrides.get(f.get("global_tray_id"))
  4299. if inventory_remain_overrides
  4300. else None
  4301. ),
  4302. }
  4303. for f in available
  4304. ],
  4305. )
  4306. # Check if tray_info_idx is unique among available trays
  4307. if req_tray_info_idx:
  4308. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4309. if len(idx_matches) == 1:
  4310. # Unique tray_info_idx - use it as definitive match
  4311. idx_match = idx_matches[0]
  4312. logger.debug(
  4313. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4314. f"-> tray {idx_match['global_tray_id']}"
  4315. )
  4316. elif len(idx_matches) > 1:
  4317. # Multiple trays with same tray_info_idx - use color matching among them
  4318. logger.debug(
  4319. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4320. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4321. )
  4322. if prefer_lowest:
  4323. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4324. # Use color matching within this subset
  4325. for f in idx_matches:
  4326. f_color = f.get("color", "")
  4327. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4328. if not exact_match:
  4329. exact_match = f
  4330. elif self._colors_are_similar(f_color, req_color):
  4331. distance = self._color_distance(f_color, req_color)
  4332. if distance is not None and distance < similar_distance:
  4333. similar_match = f
  4334. similar_distance = distance
  4335. elif not type_only_match:
  4336. type_only_match = f
  4337. # If no idx_match yet, do standard type/color matching on all available trays
  4338. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4339. for f in available:
  4340. f_type = (f.get("type") or "").upper()
  4341. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4342. continue
  4343. # Type matches - check color
  4344. f_color = f.get("color", "")
  4345. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4346. if not exact_match:
  4347. exact_match = f
  4348. elif self._colors_are_similar(f_color, req_color):
  4349. # Nearest wins, not first-in-tray-order. `available` is
  4350. # already in the caller's order (slot order, or the
  4351. # prefer-lowest sort), and `<` keeps the earliest of
  4352. # equally close spools — so that order survives as the
  4353. # tie-break (#2804).
  4354. distance = self._color_distance(f_color, req_color)
  4355. if distance is not None and distance < similar_distance:
  4356. similar_match = f
  4357. similar_distance = distance
  4358. elif not type_only_match:
  4359. type_only_match = f
  4360. match = idx_match or exact_match or similar_match or type_only_match
  4361. if match:
  4362. used_tray_ids.add(match["global_tray_id"])
  4363. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4364. else:
  4365. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4366. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4367. # "Why did it pick that spool" is the question every wrong-filament
  4368. # report starts with, and a `similar_color` win is now a ranked
  4369. # choice among several eligible spools rather than whichever tray
  4370. # came first, so it is worth being able to see after the fact.
  4371. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4372. # is on (#1766).
  4373. if match:
  4374. bucket = (
  4375. "idx"
  4376. if idx_match is not None
  4377. else "exact_color"
  4378. if exact_match is not None
  4379. else "similar_color"
  4380. if similar_match is not None
  4381. else "type_only"
  4382. )
  4383. logger.info(
  4384. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4385. match["global_tray_id"],
  4386. bucket,
  4387. req.get("slot_id"),
  4388. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4389. )
  4390. else:
  4391. logger.info(
  4392. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4393. req.get("slot_id"),
  4394. req_type,
  4395. req_color,
  4396. req_tray_info_idx,
  4397. )
  4398. # Build mapping array
  4399. if not comparisons:
  4400. return None
  4401. max_slot_id = max(c["slot_id"] for c in comparisons)
  4402. if max_slot_id <= 0:
  4403. return None
  4404. mapping = [-1] * max_slot_id
  4405. for c in comparisons:
  4406. slot_id = c["slot_id"]
  4407. if slot_id and slot_id > 0:
  4408. mapping[slot_id - 1] = c["global_tray_id"]
  4409. return mapping
  4410. def _mark_printer_dispatched(
  4411. self,
  4412. printer_id: int,
  4413. pre_state: str | None,
  4414. pre_subtask_id: str | None,
  4415. ) -> None:
  4416. """Record that a print command was just sent to ``printer_id``.
  4417. Held until either the watchdog observes a state/subtask transition
  4418. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4419. """
  4420. if not pre_state:
  4421. # No pre_state means we can't detect a transition — fall back to a
  4422. # pure time-based hold using empty string as a sentinel that won't
  4423. # match any real printer state.
  4424. pre_state = ""
  4425. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4426. def _release_dispatch_hold(self, printer_id: int) -> None:
  4427. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4428. self._dispatch_holds.pop(printer_id, None)
  4429. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4430. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4431. Returns False (and clears the hold) once any of these are true:
  4432. - hard timeout (``_dispatch_max_hold``) has elapsed
  4433. - the printer has transitioned out of pre_state and we're past the
  4434. minimum cooldown
  4435. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4436. past the minimum cooldown
  4437. Otherwise the printer is held — caller should treat it as busy.
  4438. """
  4439. entry = self._dispatch_holds.get(printer_id)
  4440. if not entry:
  4441. return False
  4442. started_at, pre_state, pre_subtask_id = entry
  4443. elapsed = time.monotonic() - started_at
  4444. if elapsed >= self._dispatch_max_hold:
  4445. self._dispatch_holds.pop(printer_id, None)
  4446. return False
  4447. # Without a pre_state we can't detect a transition — fall back to the
  4448. # min cooldown alone, then drop the hold.
  4449. if not pre_state:
  4450. if elapsed >= self._dispatch_min_cooldown:
  4451. self._dispatch_holds.pop(printer_id, None)
  4452. return False
  4453. return True
  4454. status = printer_manager.get_status(printer_id)
  4455. current_state = getattr(status, "state", None) if status else None
  4456. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4457. transitioned = (current_state is not None and current_state != pre_state) or (
  4458. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4459. )
  4460. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4461. self._dispatch_holds.pop(printer_id, None)
  4462. return False
  4463. return True
  4464. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4465. """Check if a printer is connected and idle."""
  4466. if not printer_manager.is_connected(printer_id):
  4467. logger.debug("Printer %d: not connected", printer_id)
  4468. return False
  4469. state = printer_manager.get_status(printer_id)
  4470. if not state:
  4471. logger.debug("Printer %d: no status available", printer_id)
  4472. return False
  4473. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4474. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4475. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4476. # printer, it boots back into IDLE with no memory of the previous finish; without
  4477. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4478. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4479. logger.debug(
  4480. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4481. printer_id,
  4482. state.state,
  4483. )
  4484. return False
  4485. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4486. if not idle:
  4487. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4488. return False
  4489. # A print would run from the SD card the firmware is being written to.
  4490. from backend.app.services.firmware_update import upload_in_progress
  4491. if upload_in_progress(printer_id):
  4492. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4493. return False
  4494. return True
  4495. @staticmethod
  4496. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4497. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4498. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4499. and that the fixed-printer branch has already found connected, so the two
  4500. offline cases answer at their own exits and never arrive here.
  4501. The default is the model-based branch's ``Busy:`` wording, which
  4502. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4503. the right answer for the connected-but-no-telemetry second or two after a
  4504. reconnect: the model-based branch has always reported it that way, and it
  4505. is not something to wake anybody up for.
  4506. A plate nobody has confirmed is the one case here that does not resolve
  4507. itself — somebody has to walk over to the printer — so it is worded as
  4508. itself and allowed to notify.
  4509. """
  4510. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4511. return f"Waiting for plate confirmation: {printer_name}"
  4512. return f"Busy: {printer_name}"
  4513. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4514. """Read a setting value from the database."""
  4515. result = await db.execute(select(Settings).where(Settings.key == key))
  4516. setting = result.scalar_one_or_none()
  4517. return setting.value if setting else None
  4518. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4519. """Read a boolean setting from the database."""
  4520. result = await db.execute(select(Settings).where(Settings.key == key))
  4521. setting = result.scalar_one_or_none()
  4522. if setting:
  4523. return setting.value.lower() == "true"
  4524. return default
  4525. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4526. """Read an int setting; falls back to default on missing/unparseable rows."""
  4527. result = await db.execute(select(Settings).where(Settings.key == key))
  4528. setting = result.scalar_one_or_none()
  4529. if setting and setting.value:
  4530. try:
  4531. return int(setting.value)
  4532. except ValueError:
  4533. pass
  4534. return default
  4535. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4536. """Get drying presets (user-configured or built-in defaults)."""
  4537. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4538. setting = result.scalar_one_or_none()
  4539. if setting and setting.value:
  4540. try:
  4541. presets = json.loads(setting.value)
  4542. if isinstance(presets, dict) and presets:
  4543. return presets
  4544. except json.JSONDecodeError:
  4545. pass
  4546. return self.DEFAULT_DRYING_PRESETS
  4547. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4548. """Per-filament humidity thresholds (#1605).
  4549. Returns the user-configured overrides map keyed by normalized filament
  4550. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4551. unknown / unmapped types. Empty / unset → empty dict, in which case
  4552. callers fall back to ``ams_humidity_fair``.
  4553. """
  4554. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4555. setting = result.scalar_one_or_none()
  4556. if not setting or not setting.value:
  4557. return {}
  4558. try:
  4559. data = json.loads(setting.value)
  4560. except json.JSONDecodeError:
  4561. return {}
  4562. if not isinstance(data, dict):
  4563. return {}
  4564. out: dict[str, int] = {}
  4565. for key, value in data.items():
  4566. try:
  4567. out[str(key).upper() if key != "default" else "default"] = int(value)
  4568. except (TypeError, ValueError):
  4569. continue
  4570. return out
  4571. # Materials whose AMS spelling differs from the key the tables above use.
  4572. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4573. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4574. # good PA row (#3067).
  4575. #
  4576. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4577. # The drying popover has resolved these correctly since #2774 and the
  4578. # scheduler never did, which is exactly why #3067's reporter could dry a
  4579. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4580. #
  4581. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4582. # of nylon, so it is the one entry that is a judgement rather than a
  4583. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4584. # way, and PA's row is the hottest the table has. Drying it there is closer
  4585. # to right than not drying it at all, which is what it got before.
  4586. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4587. "NYLON": "PA",
  4588. "PA6": "PA",
  4589. "PA11": "PA",
  4590. "PA12": "PA",
  4591. "PAHT": "PA",
  4592. "PPA": "PA",
  4593. }
  4594. @classmethod
  4595. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4596. """The key in *table* that answers for this tray's material, or None.
  4597. The printer reports the material in ``tray_type``, and it spells filled
  4598. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4599. tables here are keyed by base material, so matching the raw string alone
  4600. found a row for 8 of the 41 types a printer can report and skipped the
  4601. rest -- silently, because every caller reads "no row" as "nothing to do
  4602. for this tray". Auto-drying therefore ignored every composite spool on
  4603. the install (#3067).
  4604. Exact match first, so a table the user has extended with a row of its
  4605. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4606. base material's. Then the suffix is dropped, then the alias map above
  4607. answers for the polyamide spellings.
  4608. Returns None rather than a default: what to do with an unrecognised
  4609. material differs per caller, and only the caller knows whether "no row"
  4610. means skip the tray or fall back to a catch-all. Nothing here invents a
  4611. temperature for a material the table does not list.
  4612. """
  4613. raw = cls._normalize_filament_type(tray_type or "")
  4614. if not raw:
  4615. return None
  4616. for candidate in (raw, raw.split("-")[0]):
  4617. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4618. if key in table:
  4619. return key
  4620. return None
  4621. @staticmethod
  4622. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4623. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4624. For mixed filament types loaded into one AMS, returns the most
  4625. restrictive (lowest) threshold across all loaded tray types — matches
  4626. the conservative-params strategy already used for drying temp/hours.
  4627. Empty / unloaded trays contribute no constraint. Unknown types use the
  4628. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4629. when no per-type map is configured at all.
  4630. """
  4631. default = thresholds.get("default", fallback)
  4632. if not thresholds:
  4633. return fallback
  4634. candidates: list[int] = []
  4635. for tray in trays:
  4636. tray_type = str(tray.get("tray_type") or "").strip()
  4637. if not tray_type:
  4638. continue
  4639. # A composite carries its base material's threshold when it has no
  4640. # row of its own, the same way it takes its drying preset (#3067).
  4641. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4642. candidates.append(thresholds[key] if key is not None else default)
  4643. if not candidates:
  4644. return default
  4645. return min(candidates)
  4646. def _get_conservative_drying_params(
  4647. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4648. ) -> tuple[int, int, str] | None:
  4649. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4650. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4651. """
  4652. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4653. hours_key = f"{temp_key}_hours"
  4654. min_temp = None
  4655. max_hours = None
  4656. filament_type = ""
  4657. for tray in trays:
  4658. tray_type = tray.get("tray_type", "")
  4659. if not tray_type:
  4660. continue
  4661. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4662. # which is what stopped auto-drying on every composite spool (#3067).
  4663. base_type = self._resolve_filament_key(tray_type, presets)
  4664. if base_type is None:
  4665. continue
  4666. # The table is user-editable JSON with no per-row validation, so a
  4667. # row can be present and empty. That has always meant "skip this
  4668. # material", and it has to keep meaning it: the reads below fall
  4669. # back to 55C/12h per missing field, which is a temperature nobody
  4670. # chose and would deform a PLA spool.
  4671. preset = presets[base_type]
  4672. if not preset:
  4673. continue
  4674. temp = preset.get(temp_key, 55)
  4675. hours = preset.get(hours_key, 12)
  4676. # Conservative: lowest temp, longest duration
  4677. if min_temp is None or temp < min_temp:
  4678. min_temp = temp
  4679. if max_hours is None or hours > max_hours:
  4680. max_hours = hours
  4681. if not filament_type:
  4682. filament_type = base_type
  4683. if min_temp is None:
  4684. return None
  4685. return (min_temp, max_hours or 12, filament_type)
  4686. async def _check_filament_low(self, db: AsyncSession) -> None:
  4687. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4688. ``on_filament_low`` has had a column, a schema field, a route, a template
  4689. and a UI toggle since the notification system was built, and no caller --
  4690. so the toggle could be switched on and could never fire. This is the
  4691. producer.
  4692. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4693. ``low_stock_threshold_pct`` override is already exactly this decision:
  4694. already configurable, already surfaced, already driving the Inventory
  4695. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4696. consulted -- it has been measured up to 56 points out against a scale,
  4697. which is not a number to page someone on.
  4698. Only slots with an assigned spool produce an event. A slot Bambuddy
  4699. cannot resolve to a spool has no remaining weight it can stand behind,
  4700. and guessing one is how the remain percentage would have got in.
  4701. """
  4702. from backend.app.models.spool import Spool
  4703. # Time-gated rather than run on every pass. run() sleeps
  4704. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4705. # early-return path counts as productive while an upload is in flight
  4706. # (#2602), so an unthrottled check would re-read the whole spool
  4707. # collection every 3 seconds for the length of a batch drain. In
  4708. # Spoolman mode that is a request storm against a third-party service,
  4709. # which is the thing this producer's design note argues against; and
  4710. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4711. # check_queue holding the scheduler's session, so the outage would
  4712. # throttle the print queue itself. A low spool is not a 3-second
  4713. # concern -- the idle interval is the natural resolution.
  4714. now = time.monotonic()
  4715. if now < self._filament_low_next_check:
  4716. return
  4717. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4718. try:
  4719. # on_filament_low defaults to off on every provider, so on most
  4720. # installs nobody wants this alert. Without this the check would
  4721. # still read every assigned spool each interval -- the whole
  4722. # collection over HTTP in Spoolman mode -- for an event that is
  4723. # switched off. One query against the provider table settles it
  4724. # before any spool work, the same guard the bed-cooled waiter uses.
  4725. # No printer_id: this asks whether any provider wants the event at
  4726. # all; per-printer scoping is applied when the event is sent.
  4727. #
  4728. # While nobody wants it, no pass sees a slot go back above its
  4729. # threshold, so nothing can re-arm; a spool refilled under the same
  4730. # id in that time would stay silenced until a restart. Forgetting
  4731. # what was sent is right anyway: whoever switches the event back on
  4732. # is told about the spools that are low now.
  4733. #
  4734. # The MQTT relay publishes the same event, so a connected relay is
  4735. # reason enough to run the check. Its record is forgotten when the
  4736. # relay is switched off, not when the broker drops: a reconnect must
  4737. # not re-send every low slot.
  4738. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4739. relay = mqtt_relay.enabled and mqtt_relay.connected
  4740. if not notify:
  4741. self._notified_filament_low.clear()
  4742. if not mqtt_relay.enabled:
  4743. self._relayed_filament_low.clear()
  4744. if not notify and not relay:
  4745. return
  4746. global_threshold = await self._get_low_stock_threshold(db)
  4747. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4748. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4749. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4750. if spoolman_on:
  4751. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4752. else:
  4753. rows = (
  4754. await db.execute(
  4755. select(SpoolAssignment, Spool)
  4756. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4757. # An archived spool is not stock. The Inventory page's
  4758. # Low Stock count skips them (InventoryPage.tsx:1089)
  4759. # and get_all_spools without allow_archived already
  4760. # excludes them in Spoolman mode, so without this the
  4761. # internal path is the only one that alerts on them.
  4762. .where(Spool.archived_at.is_(None))
  4763. )
  4764. ).all()
  4765. for assignment, spool in rows:
  4766. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4767. if pct is None:
  4768. continue
  4769. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4770. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4771. pct,
  4772. threshold,
  4773. spool.color_name,
  4774. )
  4775. if not slots:
  4776. # Nothing resolvable this pass. Deliberately not clearing the
  4777. # notified set: a Spoolman that is briefly unreachable would
  4778. # otherwise re-alert on every spool as soon as it came back.
  4779. return
  4780. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4781. except Exception as e:
  4782. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4783. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4784. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4785. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4786. if raw is None or raw.value is None:
  4787. return 20.0
  4788. try:
  4789. value = float(raw.value)
  4790. except (TypeError, ValueError):
  4791. return 20.0
  4792. return value if 0 < value <= 100 else 20.0
  4793. async def _filament_low_slots_spoolman(
  4794. self, db: AsyncSession, global_threshold: float
  4795. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4796. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4797. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4798. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4799. so the global threshold is the only one that applies here. That matches
  4800. what the Inventory page already does in this mode.
  4801. One ``get_all_spools`` call covers every slot rather than a request per
  4802. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4803. without ``allow_archived`` -- which is the behaviour the internal path
  4804. has to ask for explicitly.
  4805. An unreachable Spoolman returns no slots rather than raising. It is an
  4806. ordinary state for a third-party service, not an error in this pass: the
  4807. caller's "nothing resolvable" branch already leaves the notified set
  4808. alone, which is exactly right here, whereas letting it reach the broad
  4809. ``except`` would write a full traceback every time the check runs.
  4810. """
  4811. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4812. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4813. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4814. if not assignments:
  4815. return {}
  4816. client = await get_spoolman_client()
  4817. if client is None:
  4818. return {}
  4819. try:
  4820. all_spools = await client.get_all_spools()
  4821. except SpoolmanUnavailableError as e:
  4822. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4823. return {}
  4824. by_id: dict[int, dict] = {}
  4825. for raw in all_spools:
  4826. raw_id = raw.get("id")
  4827. if isinstance(raw_id, int):
  4828. by_id[raw_id] = raw
  4829. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4830. for assignment in assignments:
  4831. raw = by_id.get(assignment.spoolman_spool_id)
  4832. if raw is None:
  4833. continue
  4834. try:
  4835. mapped = _map_spoolman_spool(raw)
  4836. except ValueError:
  4837. continue
  4838. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4839. if pct is None:
  4840. continue
  4841. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4842. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4843. return slots
  4844. async def _emit_filament_low(
  4845. self,
  4846. db: AsyncSession,
  4847. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4848. *,
  4849. notify: bool = True,
  4850. relay: bool = False,
  4851. ) -> None:
  4852. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4853. printers: dict[int, Printer] = {}
  4854. for key, (pct, threshold, color) in slots.items():
  4855. printer_id, ams_id, tray_id, spool_id = key
  4856. if pct >= threshold:
  4857. # Back above the line: re-arm rather than expire on a timer, so a
  4858. # refilled slot can alert again and a spool sitting just under the
  4859. # threshold stays quiet.
  4860. self._notified_filament_low.discard(key)
  4861. self._relayed_filament_low.discard(key)
  4862. continue
  4863. send_notification = notify and key not in self._notified_filament_low
  4864. # Only while connected, so a crossing the relay missed reaches it
  4865. # after the reconnect.
  4866. send_relay = relay and key not in self._relayed_filament_low
  4867. if not send_notification and not send_relay:
  4868. continue
  4869. # Marked before sending, which is a choice rather than the only
  4870. # option, and it is the opposite failure mode from the one the
  4871. # debounce argues against: one transient provider failure loses this
  4872. # alert until the spool goes back above the threshold and crosses it
  4873. # again. Marking after a successful send would trade that for
  4874. # re-alerting on every pass while a provider is down -- which is the
  4875. # repetition the whole debounce exists to prevent, and the louder of
  4876. # the two failures. A spool that is low stays low, so the next real
  4877. # signal is not far away; a provider stuck retrying is a signal that
  4878. # never stops.
  4879. if send_notification:
  4880. self._notified_filament_low.add(key)
  4881. if send_relay:
  4882. self._relayed_filament_low.add(key)
  4883. if printer_id not in printers:
  4884. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4885. if printer is None:
  4886. continue
  4887. printers[printer_id] = printer
  4888. printer = printers[printer_id]
  4889. slot = _ams_slot_label(ams_id, tray_id)
  4890. if send_notification:
  4891. try:
  4892. await notification_service.on_filament_low(
  4893. printer_id,
  4894. printer.name,
  4895. slot,
  4896. int(pct),
  4897. db,
  4898. color=color,
  4899. )
  4900. except Exception as e:
  4901. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4902. if send_relay:
  4903. try:
  4904. await mqtt_relay.on_filament_low(
  4905. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  4906. )
  4907. except Exception as e:
  4908. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  4909. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4910. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4911. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4912. a schema field, a template and a UI toggle, and nothing that computes the
  4913. condition -- the Forecast panel does it in the browser, so with no page
  4914. open nothing could ever alert. This runs the same arithmetic
  4915. (``stock_forecast``) from the scheduler loop.
  4916. An alert is sent when a SKU *moves into* a condition, once, and again
  4917. after the condition has cleared. A SKU that worsens from reorder to break
  4918. alerts again as a break, because the panel treats the two as exclusive; one
  4919. that eases from break back to reorder does not alert again.
  4920. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4921. while it is still low tells you.
  4922. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4923. loop runs every 3 s while an upload is in flight, and the whole spool
  4924. collection is read over HTTP in Spoolman mode. Both events default to off
  4925. on every provider, so nothing is read unless a provider wants one.
  4926. """
  4927. now = time.monotonic()
  4928. if now < self._stock_forecast_next_check:
  4929. return
  4930. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4931. try:
  4932. if self._stock_alerts_persisted is None:
  4933. await self._load_stock_alerts(db)
  4934. wanted = {
  4935. "reorder": bool(
  4936. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  4937. ),
  4938. "break": bool(
  4939. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  4940. ),
  4941. }
  4942. if not any(wanted.values()):
  4943. # Nobody wants either event. Forget what was sent, so whoever
  4944. # switches one on is told about the SKUs that are low now.
  4945. self._notified_stock_alerts.clear()
  4946. await self._save_stock_alerts(db)
  4947. return
  4948. forecasts = await self._stock_forecasts(db)
  4949. if forecasts is None:
  4950. # Spoolman unreachable. Deliberately not clearing the notified
  4951. # set: a brief outage would otherwise re-alert every SKU when it
  4952. # came back.
  4953. return
  4954. await self._emit_stock_alerts(db, forecasts, wanted)
  4955. await self._save_stock_alerts(db)
  4956. except Exception as e:
  4957. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4958. def _serialize_stock_alerts(self) -> str:
  4959. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4960. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4961. return json.dumps(rows)
  4962. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4963. """Read the notified set saved by the last run, once per process.
  4964. A missing or unreadable row is an empty set: the worst that does is one
  4965. repeat of what a restart used to cause every time.
  4966. """
  4967. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4968. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4969. if raw and raw.value:
  4970. try:
  4971. for key, kind, events in json.loads(raw.value):
  4972. if len(key) == 4 and kind in ("reorder", "break"):
  4973. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4974. except (ValueError, TypeError):
  4975. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4976. loaded = {}
  4977. self._notified_stock_alerts = loaded
  4978. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4979. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4980. """Write the notified set to its settings row if it changed since it was last read or written."""
  4981. serialized = self._serialize_stock_alerts()
  4982. if serialized == self._stock_alerts_persisted:
  4983. return
  4984. from backend.app.core.db_dialect import upsert_setting
  4985. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4986. await db.commit()
  4987. self._stock_alerts_persisted = serialized
  4988. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4989. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4990. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4991. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4992. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4993. sku_settings = {
  4994. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4995. lead_time_days=row.lead_time_days,
  4996. safety_margin_value=row.safety_margin_value,
  4997. safety_margin_unit=row.safety_margin_unit,
  4998. alerts_snoozed=bool(row.alerts_snoozed),
  4999. )
  5000. for row in sku_rows
  5001. }
  5002. if await self._get_bool_setting(db, "spoolman_enabled"):
  5003. spools = await self._stock_spools_spoolman()
  5004. if spools is None:
  5005. return None
  5006. # Spoolman owns the usage in this mode and Bambuddy's own history
  5007. # table holds nothing for those spools, so the rate is always the
  5008. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  5009. # are local spool ids, and a Spoolman id that happens to match one
  5010. # (left over from before Spoolman was switched on) would borrow an
  5011. # unrelated spool's history.
  5012. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5013. else:
  5014. spools = await self._stock_spools_internal(db)
  5015. history = await self._stock_usage_history(db)
  5016. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5017. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5018. from backend.app.models.spool import Spool
  5019. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  5020. return [
  5021. stock_forecast.StockSpool(
  5022. id=spool.id,
  5023. material=spool.material,
  5024. subtype=spool.subtype,
  5025. brand=spool.brand,
  5026. color_name=spool.color_name,
  5027. label_weight=float(spool.label_weight or 0),
  5028. weight_used=float(spool.weight_used or 0),
  5029. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5030. created_at=spool.created_at,
  5031. )
  5032. for spool in rows
  5033. ]
  5034. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  5035. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5036. rows = (
  5037. await db.execute(
  5038. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5039. .order_by(SpoolUsageHistory.created_at.desc())
  5040. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5041. )
  5042. ).all()
  5043. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5044. for spool_id, created_at, weight_used in rows:
  5045. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5046. # filtered before the limit, so the window matches the forecast panel's.
  5047. if created_at is None or spool_id is None:
  5048. continue
  5049. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5050. return history
  5051. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5052. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5053. ``get_all_spools`` leaves archived spools out unless asked, which is the
  5054. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  5055. is the same mapping the Inventory page (and so the panel) reads.
  5056. """
  5057. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5058. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5059. client = await get_spoolman_client()
  5060. if client is None:
  5061. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5062. return None
  5063. try:
  5064. raw_spools = await client.get_all_spools()
  5065. except SpoolmanUnavailableError as e:
  5066. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5067. return None
  5068. spools: list[stock_forecast.StockSpool] = []
  5069. for raw in raw_spools:
  5070. try:
  5071. mapped = _map_spoolman_spool(raw)
  5072. except ValueError:
  5073. continue
  5074. created_at = None
  5075. if mapped.get("created_at"):
  5076. try:
  5077. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  5078. except ValueError:
  5079. created_at = None
  5080. spools.append(
  5081. stock_forecast.StockSpool(
  5082. id=mapped["id"],
  5083. material=mapped["material"],
  5084. subtype=mapped.get("subtype"),
  5085. brand=mapped.get("brand"),
  5086. color_name=mapped.get("color_name"),
  5087. label_weight=float(mapped.get("label_weight") or 0),
  5088. weight_used=float(mapped.get("weight_used") or 0),
  5089. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5090. created_at=created_at,
  5091. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5092. )
  5093. )
  5094. return spools
  5095. async def _emit_stock_alerts(
  5096. self,
  5097. db: AsyncSession,
  5098. forecasts: stock_forecast.ForecastMap,
  5099. wanted: dict[str, bool],
  5100. ) -> None:
  5101. """Send the notifications for each SKU that has moved into a stock alert condition.
  5102. A SKU in break has also reached its reorder point, so both events apply to
  5103. it: the break event goes to providers that have it on, and the reorder event
  5104. to the providers that have only that one on. A provider with both on gets the
  5105. break and no second message.
  5106. What is remembered per SKU is the condition and which events had a
  5107. subscriber when it was sent. An event with no subscriber is forgotten, so
  5108. switching it on later reports the SKUs already in that condition.
  5109. """
  5110. active_events = {event for event, on in wanted.items() if on}
  5111. for key, (forecast, spool) in forecasts.items():
  5112. kind: str | None = None
  5113. if not forecast.snoozed:
  5114. if forecast.stock_break_alert:
  5115. kind = "break"
  5116. elif forecast.reorder_alert:
  5117. kind = "reorder"
  5118. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5119. events = applicable & active_events
  5120. if not events:
  5121. self._notified_stock_alerts.pop(key, None)
  5122. continue
  5123. previous = self._notified_stock_alerts.get(key)
  5124. told = (previous[1] & active_events) if previous else frozenset()
  5125. # Trimmed to the events this condition can send. That is what makes easing from
  5126. # break back to reorder silent (the reorder event was told with the break) and
  5127. # worsening again news again (the break event is no longer remembered).
  5128. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5129. # Recorded before sending, for the reason _emit_filament_low gives: a
  5130. # provider that is down should lose this alert, not repeat it every hour.
  5131. to_send = events - told
  5132. # Both flags imply a positive rate and so a day count.
  5133. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5134. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5135. color = None if spool.color_name_is_synthesized else spool.color_name
  5136. try:
  5137. if "break" in to_send:
  5138. await notification_service.on_stock_break_alert(
  5139. spool.material,
  5140. spool.brand,
  5141. forecast.remaining_g,
  5142. rate,
  5143. days_left,
  5144. forecast.effective_lead_time_days,
  5145. db,
  5146. subtype=spool.subtype,
  5147. color=color,
  5148. )
  5149. if "reorder" in to_send:
  5150. await notification_service.on_stock_reorder_alert(
  5151. spool.material,
  5152. spool.brand,
  5153. forecast.remaining_g,
  5154. rate,
  5155. days_left,
  5156. db,
  5157. subtype=spool.subtype,
  5158. color=color,
  5159. skip_break_subscribers=kind == "break",
  5160. )
  5161. except Exception as e:
  5162. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5163. # A SKU with no spools left is no longer alerting.
  5164. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5165. del self._notified_stock_alerts[key]
  5166. @staticmethod
  5167. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5168. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5169. from backend.app.core.auth import is_auth_enabled
  5170. if user_id is None or not await is_auth_enabled(db):
  5171. return ALL_PRINTERS
  5172. return await resolve_user_id_printer_scope(db, user_id)
  5173. async def _model_job_printer_ids(
  5174. self,
  5175. db: AsyncSession,
  5176. item: PrintQueueItem,
  5177. scope: PrinterScope,
  5178. cache: dict[tuple[str, str | None, int | None], set[int]],
  5179. ) -> set[int]:
  5180. """Every printer an "Any <model>" job could land on: the active printers
  5181. of each of its candidate models, in its location, that its creator may use.
  5182. ``cache`` holds one lookup per model, location and creator for the pass,
  5183. so a long queue of model jobs does not query once per job."""
  5184. printer_ids: set[int] = set()
  5185. for candidate in _candidates_for(item):
  5186. if not candidate.target_model:
  5187. continue
  5188. key = (candidate.target_model, item.target_location, item.created_by_id)
  5189. if key not in cache:
  5190. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5191. cache[key] = {printer.id for printer in printers}
  5192. printer_ids |= cache[key]
  5193. return printer_ids
  5194. async def _check_auto_drying(
  5195. self,
  5196. db: AsyncSession,
  5197. queue_items: list[PrintQueueItem],
  5198. dispatching_printers: set[int],
  5199. ):
  5200. """Start drying on idle printers based on humidity.
  5201. Three modes (can all be enabled independently):
  5202. - queue_drying_enabled: Dry between scheduled queue prints
  5203. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5204. - print_drying_enabled: Also evaluate printers that are currently printing,
  5205. when model+firmware supports "Print While Drying" (gated by
  5206. supports_drying_while_printing). Drying temperature is capped at
  5207. max(40, preset_temp - 5) to protect spools mid-print.
  5208. """
  5209. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5210. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5211. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5212. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5213. # The wait belongs to ambient drying: the settings UI only shows it while
  5214. # ambient drying is on, so a value left behind when ambient is turned off
  5215. # must not keep delaying the one path that still reaches the wait gate
  5216. # without it (a mid-print start under print_drying).
  5217. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5218. # Clear every streak as soon as the wait is inactive. An early return (or
  5219. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5220. # a quick toggle-on inherit an old streak.
  5221. if not sustained_wait_active:
  5222. self._auto_dry_above.clear()
  5223. if not queue_drying_enabled and not ambient_drying_enabled:
  5224. # Stop active drying on all printers if both features disabled
  5225. if self._drying_in_progress:
  5226. for pid in list(self._drying_in_progress):
  5227. if pid in self._scheduled_drying_printer_ids:
  5228. continue
  5229. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5230. await self._stop_drying(pid)
  5231. return
  5232. # Update drying state from printer status (handles backend restart)
  5233. self._sync_drying_state()
  5234. # Find printers with scheduled items (for queue drying mode)
  5235. # An "Any <model>" job counts for every printer it could land on.
  5236. printers_with_scheduled: set[int] = set()
  5237. # Printers with a job that could start now: the ones block mode keeps
  5238. # a new cycle off. A job waiting for its start time is what queue
  5239. # drying dries ahead of.
  5240. printers_with_ready_items: set[int] = set()
  5241. now_utc = datetime.now(timezone.utc)
  5242. creator_scopes: dict[int | None, PrinterScope] = {}
  5243. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5244. for item in queue_items:
  5245. if item.printer_id:
  5246. item_printers = {item.printer_id}
  5247. elif item.target_model or item.variants:
  5248. if item.created_by_id not in creator_scopes:
  5249. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5250. item_printers = await self._model_job_printer_ids(
  5251. db, item, creator_scopes[item.created_by_id], model_printers
  5252. )
  5253. else:
  5254. continue
  5255. if item.scheduled_time and not item.manual_start:
  5256. printers_with_scheduled |= item_printers
  5257. sched = item.scheduled_time
  5258. if sched is not None and sched.tzinfo is None:
  5259. sched = sched.replace(tzinfo=timezone.utc)
  5260. if sched is None or sched <= now_utc:
  5261. printers_with_ready_items |= item_printers
  5262. # If only queue mode is on and no printers have scheduled items, stop drying
  5263. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5264. # may still be eligible for mid-print drying regardless of queue state).
  5265. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5266. for pid in list(self._drying_in_progress):
  5267. if pid in self._scheduled_drying_printer_ids:
  5268. continue
  5269. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5270. await self._stop_drying(pid)
  5271. return
  5272. # Get humidity threshold (global fallback)
  5273. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5274. setting = result.scalar_one_or_none()
  5275. global_humidity_threshold = int(setting.value) if setting else 60
  5276. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5277. # to the global threshold for every AMS unit.
  5278. per_type_thresholds = await self._get_humidity_thresholds(db)
  5279. # Get drying presets
  5280. presets = await self._get_drying_presets(db)
  5281. # Determine if drying should be skipped for printers with pending items
  5282. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5283. # Get all active printers
  5284. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5285. for printer in all_printers.scalars():
  5286. pid = printer.id
  5287. # Resolve model+firmware up front — needed to decide whether this printer
  5288. # qualifies for mid-print drying (busy printer on capable hardware).
  5289. state = printer_manager.get_status(pid)
  5290. if not state:
  5291. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5292. continue
  5293. model = printer_manager.get_model(pid)
  5294. firmware = state.firmware_version
  5295. # "Mid-print" has to mean the printer is actually printing (#2801).
  5296. # It used to be inferred from the dispatch set, which also holds
  5297. # printers that merely could not be dispatched to -- so a printer
  5298. # sitting in FINISH behind an unacknowledged plate was treated as
  5299. # printing, had its drying temperature capped by the mid-print
  5300. # spool protection, and was logged as (mid-print) while idle.
  5301. is_printing = state.state in _ACTIVE_PRINT_STATES
  5302. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5303. # A printer whose print is running or imminent is left alone unless
  5304. # it can dry through it. `dispatching_printers` is deliberately the
  5305. # narrow set: running, held post-dispatch, or mid-upload.
  5306. if (is_printing or pid in dispatching_printers) and not mid_print:
  5307. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5308. continue
  5309. if not mid_print:
  5310. # In queue-only mode, only dry printers that have scheduled prints
  5311. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5312. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5313. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5314. await self._stop_drying(pid)
  5315. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5316. continue
  5317. # When block mode is on, don't START new drying on printers with
  5318. # a job that could start now: the cycle would hold it. One
  5319. # scheduled for later may pre-dry; if the cycle is still running
  5320. # at its time, the hold applies then. Already-drying printers go
  5321. # through so humidity auto-stop logic still runs.
  5322. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5323. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5324. continue
  5325. if not printer_manager.is_connected(pid):
  5326. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5327. continue
  5328. # Plate-clear is deliberately ignored here (#2801). It answers
  5329. # "is the bed ready for the next job", which says nothing about
  5330. # whether the AMS may heat -- and the gap between a finished print
  5331. # and the acknowledgment is exactly when drying is most useful,
  5332. # because the printer is free and nobody is waiting on it. Leaving
  5333. # the plate unacknowledged is also how people hold the queue by
  5334. # hand, and that hold should not cost them their drying.
  5335. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5336. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5337. continue
  5338. # Check drying capability. For mid-print path, supports_drying_while_printing
  5339. # was already verified when computing mid_print above.
  5340. if not mid_print and not supports_drying(model, firmware):
  5341. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5342. continue
  5343. # Check each AMS unit from raw_data
  5344. ams_list = state.raw_data.get("ams", [])
  5345. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5346. for ams_data in ams_list:
  5347. module_type = str(ams_data.get("module_type") or "")
  5348. ams_id = int(ams_data.get("id", 0))
  5349. # Only n3f/n3s support drying
  5350. if module_type not in ("n3f", "n3s"):
  5351. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5352. continue
  5353. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5354. # Most-restrictive of all loaded tray types; falls back to the
  5355. # global threshold when no overrides are configured.
  5356. trays = ams_data.get("tray", []) or []
  5357. humidity_threshold = self.resolve_humidity_threshold(
  5358. trays, per_type_thresholds, global_humidity_threshold
  5359. )
  5360. dry_time = int(ams_data.get("dry_time") or 0)
  5361. # Read humidity as a percentage. The 1-5 index is never
  5362. # substituted: it is inverted, and being unable to exceed any
  5363. # threshold it would read as "dry" forever (#3140). ``None``
  5364. # already means "skip this unit" everywhere below.
  5365. humidity_pct = ams_humidity_percent(ams_data)
  5366. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5367. unit_key = (pid, ams_id)
  5368. unit_state = self._auto_dry_units.get(unit_key)
  5369. # Already drying — let it run to its configured duration (#1892).
  5370. #
  5371. # We deliberately do NOT stop drying from a humidity re-check here.
  5372. # Relative humidity drops steeply in heated air, so the AMS sensor
  5373. # reads ~15-20% within minutes of the dryer starting even while the
  5374. # filament is still saturated. A humidity-based early-stop therefore
  5375. # always fires at the minimum-time floor, truncating both user-started
  5376. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5377. # The firmware stops when the configured duration elapses; scheduling
  5378. # stops (print takes priority, queue no longer needs drying) are
  5379. # handled separately via _stop_drying().
  5380. if dry_time > 0:
  5381. if pid not in self._drying_in_progress:
  5382. # Drying we didn't start (manual or from before restart) —
  5383. # track it so scheduling stops still apply; never auto-stop it.
  5384. self._drying_in_progress[pid] = time.monotonic()
  5385. if unit_state is not None:
  5386. unit_state["running"] = True
  5387. logger.debug(
  5388. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5389. pid,
  5390. ams_id,
  5391. dry_time,
  5392. humidity,
  5393. )
  5394. continue
  5395. # Nothing is drying. Close out a cycle we armed ourselves and
  5396. # judge whether it achieved anything (#2770).
  5397. #
  5398. # "Achieved anything" is measured against the LOWEST reading any
  5399. # cycle on this unit has ended at, not against the threshold and
  5400. # not against the previous cycle. A spool that is genuinely wet
  5401. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5402. # allowed to keep going for as long as it is still coming down,
  5403. # however far it still is from the threshold. What must not
  5404. # continue is a cycle that ends exactly where the last one did,
  5405. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5406. # Comparing against the running minimum rather than the previous
  5407. # end is what stops a sensor oscillating by one point between two
  5408. # values from reading as progress every other cycle.
  5409. if unit_state is not None and unit_state.pop("running", False):
  5410. unit_state["ended_at"] = time.monotonic()
  5411. # The streak that armed this cycle is spent; the next one
  5412. # starts fresh (and accumulates through the re-arm cooldown
  5413. # below, so the wait overlaps the cooldown, never stacks on
  5414. # top of it).
  5415. self._auto_dry_above.pop(unit_key, None)
  5416. if humidity is not None and humidity > humidity_threshold:
  5417. best = unit_state.get("best_end_humidity")
  5418. if isinstance(best, int) and humidity < best:
  5419. # Still coming down. Keep going, however far the
  5420. # threshold still is.
  5421. unproductive = 0
  5422. else:
  5423. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5424. if not isinstance(best, int) or humidity < best:
  5425. unit_state["best_end_humidity"] = humidity
  5426. unit_state["unproductive"] = unproductive
  5427. logger.info(
  5428. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5429. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5430. pid,
  5431. ams_id,
  5432. humidity,
  5433. humidity_threshold,
  5434. unit_state.get("best_end_humidity"),
  5435. unproductive,
  5436. )
  5437. # A cycle that ended at or below the threshold needs no
  5438. # counter reset here: the branch below drops the whole entry.
  5439. # Humidity below threshold — no need to start drying. This is
  5440. # also the only thing that lifts a suspension: the reading we
  5441. # gave up on has come down, so auto-drying works again and the
  5442. # unit goes back to having no history at all.
  5443. if humidity is None or humidity <= humidity_threshold:
  5444. if unit_state is not None and unit_state.get("suspended"):
  5445. logger.info(
  5446. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5447. "threshold, resuming automatic drying",
  5448. pid,
  5449. ams_id,
  5450. humidity,
  5451. humidity_threshold,
  5452. )
  5453. # Clear the judgement, keep the clock (#2801). Dropping the
  5454. # whole entry also dropped `ended_at`, and with it the
  5455. # 30-minute cooldown -- so a reading that dips to the
  5456. # threshold as the AMS cools and comes back above it once
  5457. # warm wiped its own history and re-armed immediately. That
  5458. # oscillation is the very thing #2770's cooldown exists to
  5459. # ride out, and it is worst at exactly the margin that makes
  5460. # a unit dry repeatedly: a point or two above the threshold.
  5461. if unit_state is not None:
  5462. unit_state.pop("suspended", None)
  5463. unit_state.pop("unproductive", None)
  5464. unit_state.pop("best_end_humidity", None)
  5465. # A real below-threshold reading ends any sustained-wait
  5466. # streak (#2518) -- "continuously above" means exactly that.
  5467. # An absent reading (humidity is None) is no-information and
  5468. # leaves the streak alone; the observation-gap guard handles
  5469. # a prolonged sensor silence.
  5470. if humidity is not None:
  5471. _above = self._auto_dry_above.pop(unit_key, None)
  5472. if _above is not None and sustained_wait_active:
  5473. logger.info(
  5474. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5475. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5476. pid,
  5477. ams_id,
  5478. humidity,
  5479. time.monotonic() - _above["since"],
  5480. sustained_minutes,
  5481. humidity_threshold,
  5482. )
  5483. logger.debug(
  5484. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5485. pid,
  5486. ams_id,
  5487. humidity,
  5488. humidity_threshold,
  5489. )
  5490. continue
  5491. # Sustained-humidity streak (#2518): updated on every pass that
  5492. # observes the reading above the threshold, BEFORE the
  5493. # suspension/cooldown gates below -- a suspended or cooling-down
  5494. # unit still accumulates streak time, so the wait overlaps those
  5495. # gates instead of stacking after them. Inert when the feature
  5496. # is off: no entries are written, and an entry left over from a
  5497. # toggle-off is dropped so it cannot seed a stale streak later.
  5498. if sustained_wait_active:
  5499. _now = time.monotonic()
  5500. # Four missed scheduler passes, floored: a single slow pass
  5501. # must not void a streak, but the ceiling has to scale with
  5502. # the cadence or a slow loop silently restarts every streak.
  5503. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5504. _above = self._auto_dry_above.get(unit_key)
  5505. if _above is None:
  5506. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5507. elif _now - _above["last"] > _gap_ceiling:
  5508. # Restart, and say so at the same level as the dip
  5509. # reset: a silent restart voids the streak invisibly,
  5510. # and a user who set a long wait and never gets a dry
  5511. # has no way to see why.
  5512. logger.info(
  5513. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5514. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5515. pid,
  5516. ams_id,
  5517. _now - _above["last"],
  5518. _gap_ceiling,
  5519. sustained_minutes,
  5520. )
  5521. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5522. else:
  5523. _above["last"] = _now
  5524. else:
  5525. self._auto_dry_above.pop(unit_key, None)
  5526. if unit_state is not None:
  5527. if unit_state.get("suspended"):
  5528. logger.debug(
  5529. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5530. "above the %d%% threshold",
  5531. pid,
  5532. ams_id,
  5533. int(unit_state.get("unproductive", 0)),
  5534. humidity_threshold,
  5535. )
  5536. continue
  5537. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5538. unit_state["suspended"] = True
  5539. logger.warning(
  5540. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5541. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5542. "higher while it is warm, so a threshold in that range can never be reached and "
  5543. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5544. pid,
  5545. ams_id,
  5546. int(unit_state.get("unproductive", 0)),
  5547. humidity,
  5548. humidity_threshold,
  5549. )
  5550. await self._notify_auto_drying_suspended(
  5551. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5552. )
  5553. continue
  5554. ended_at = unit_state.get("ended_at")
  5555. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5556. logger.debug(
  5557. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5558. "cycle before the humidity reading is worth acting on",
  5559. pid,
  5560. ams_id,
  5561. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5562. )
  5563. continue
  5564. # Check cannot-dry reasons (power constraints etc.). Sits
  5565. # ahead of the sustained wait so a unit the firmware refuses
  5566. # to dry never logs a wait it was never going to cash in.
  5567. sf_reasons = ams_data.get("dry_sf_reason", [])
  5568. if sf_reasons:
  5569. logger.debug(
  5570. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5571. pid,
  5572. ams_id,
  5573. sf_reasons,
  5574. )
  5575. continue
  5576. # Sustained-humidity wait (#2518): ambient-triggered starts
  5577. # wait; only a printer with a scheduled queue item pending
  5578. # keeps the instant behavior, because that drying has a real
  5579. # deadline. Mid-print is deliberately NOT exempt while ambient
  5580. # drying is on: a humidity start on a printer that happens to be
  5581. # printing is as vulnerable to a lid-open spike as one on an idle
  5582. # printer (proven live: a 2-point threshold crossing mid-print
  5583. # bought a parked 12h command). Inactive when ambient drying is
  5584. # off: print_drying then still starts mid-print cycles on its own
  5585. # (#1816, "regardless of queue state"), and those stay instant.
  5586. if sustained_wait_active and pid not in printers_with_scheduled:
  5587. _above = self._auto_dry_above.get(unit_key)
  5588. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5589. if _waited < sustained_minutes * 60:
  5590. logger.debug(
  5591. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5592. "threshold for %.0fs of the required %dm",
  5593. pid,
  5594. ams_id,
  5595. humidity,
  5596. humidity_threshold,
  5597. _waited,
  5598. sustained_minutes,
  5599. )
  5600. continue
  5601. # Get conservative drying params for mixed filaments
  5602. params = self._get_conservative_drying_params(trays, module_type, presets)
  5603. if not params:
  5604. logger.debug(
  5605. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5606. )
  5607. continue
  5608. temp, duration_hours, filament_type = params
  5609. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5610. # "drying temperature must not exceed the filament's softening temperature"
  5611. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5612. # ineffective and firmware will reject anyway.
  5613. if mid_print:
  5614. temp = max(40, temp - 5)
  5615. # Start drying
  5616. logger.info(
  5617. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5618. "starting %s drying at %d°C for %dh%s",
  5619. pid,
  5620. ams_id,
  5621. humidity,
  5622. humidity_threshold,
  5623. filament_type,
  5624. temp,
  5625. duration_hours,
  5626. " (mid-print)" if mid_print else "",
  5627. )
  5628. success = printer_manager.send_drying_command(
  5629. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5630. )
  5631. if success:
  5632. self._drying_in_progress[pid] = time.monotonic()
  5633. armed = self._auto_dry_units.setdefault(
  5634. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5635. )
  5636. armed["running"] = True
  5637. async def _notify_auto_drying_suspended(
  5638. self,
  5639. db: AsyncSession,
  5640. printer: Printer,
  5641. ams_id: int,
  5642. humidity: int,
  5643. threshold: int,
  5644. cycles: int,
  5645. ) -> None:
  5646. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5647. Fires once per suspension — the caller sets ``suspended`` before calling
  5648. and every later pass short-circuits on it — because the whole point is
  5649. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5650. building needs that to reach them, and the hourly humidity alarm they
  5651. are already getting says the opposite of what happened here.
  5652. Never raises: a notification provider being down must not stop the
  5653. suspension itself from taking effect.
  5654. """
  5655. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5656. try:
  5657. await notification_service.on_ams_drying_suspended(
  5658. printer.id,
  5659. printer.name,
  5660. ams_label,
  5661. float(humidity),
  5662. float(threshold),
  5663. cycles,
  5664. db,
  5665. )
  5666. except Exception as e:
  5667. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5668. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5669. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5670. The unproductive-cycle counter exists to notice that *drying* is not
  5671. moving the humidity reading. A cycle that ended because somebody sent a
  5672. stop says nothing about that — it was cut short before it had a chance —
  5673. so counting it would suspend auto-drying for a reason that has nothing to
  5674. do with the loop the counter is there to break.
  5675. Two callers, both of them a stop Bambuddy is responsible for: the
  5676. print-takes-priority stop below, and the manual Stop button. Left
  5677. uncalled, an install that dries between queue jobs would suspend its own
  5678. auto-drying after two prints interrupted a dry — exactly the install
  5679. queue-drying exists for.
  5680. The rest of the unit's history is kept: the cooldown before re-arming
  5681. still applies, and an earlier count still stands.
  5682. """
  5683. state = self._auto_dry_units.get((printer_id, ams_id))
  5684. if state is not None:
  5685. state.pop("running", None)
  5686. state["ended_at"] = time.monotonic()
  5687. # A stopped cycle spends the streak that armed it, same as a completed
  5688. # one (#2518).
  5689. self._auto_dry_above.pop((printer_id, ams_id), None)
  5690. def _sync_drying_state(self):
  5691. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5692. One direction only: it prunes, it never adds. A printer drying without an
  5693. entry here — because the user started the cycle from Studio, the printer's
  5694. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5695. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5696. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5697. That is deliberate for now rather than an oversight: populating this from
  5698. telemetry would hand the scheduler authority to stop drying a user started
  5699. by hand. It also means the backend-restart case this used to claim to
  5700. handle is not handled.
  5701. """
  5702. to_remove = []
  5703. for pid in self._drying_in_progress:
  5704. state = printer_manager.get_status(pid)
  5705. if not state:
  5706. to_remove.append(pid)
  5707. continue
  5708. # Check if any AMS unit is still drying
  5709. ams_list = state.raw_data.get("ams", [])
  5710. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5711. if not any_drying:
  5712. to_remove.append(pid)
  5713. for pid in to_remove:
  5714. self._drying_in_progress.pop(pid, None)
  5715. # A printer that has gone away entirely takes its per-AMS auto-drying
  5716. # history with it (#2770), so a printer deleted and re-added does not
  5717. # inherit a suspension it never earned.
  5718. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5719. self._auto_dry_units.pop(key, None)
  5720. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5721. # printer starts a fresh wait, and vanished printers do not leak
  5722. # entries.
  5723. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5724. self._auto_dry_above.pop(key, None)
  5725. @staticmethod
  5726. def _drying_is_only_parked(printer_id: int) -> bool:
  5727. """True when every AMS unit with a drying timer on this printer is parked.
  5728. A parked timer (#2896: the command was taken but the countdown never
  5729. runs) does not end on its own, so nothing may wait on it. False when no
  5730. unit reports a timer yet -- a command just sent that the firmware has not
  5731. reported back is real drying about to begin.
  5732. """
  5733. state = printer_manager.get_status(printer_id)
  5734. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5735. timed = []
  5736. for unit in units:
  5737. try:
  5738. if int(unit.get("dry_time") or 0) > 0:
  5739. timed.append(unit)
  5740. except (TypeError, ValueError):
  5741. continue
  5742. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5743. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5744. """True when a running cycle can be left alone while the next print runs.
  5745. Some hardware dries happily through a print and #2758 settled that we
  5746. should not tear those cycles down: the X2D there was refusing to
  5747. *start* a job, which is a different problem, and stopping drying before
  5748. every dispatch would throw away cycles the printer was content to run.
  5749. Where the model cannot do it, or the user has not enabled it, the print
  5750. takes priority and the cycle stops -- which is what the queue_drying_block
  5751. setting has always promised in its off position.
  5752. """
  5753. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5754. return False
  5755. status = printer_manager.get_status(printer_id)
  5756. return supports_drying_while_printing(
  5757. printer_manager.get_model(printer_id),
  5758. status.firmware_version if status else None,
  5759. )
  5760. async def _stop_drying(self, printer_id: int):
  5761. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5762. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5763. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5764. enough to kill a cycle the user had started by hand on a *different*
  5765. unit of the same printer (#2801). That contradicted the contract
  5766. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5767. only knows about cycles Bambuddy began, so the action must not reach
  5768. past them either.
  5769. """
  5770. state = printer_manager.get_status(printer_id)
  5771. if not state:
  5772. self._drying_in_progress.pop(printer_id, None)
  5773. return
  5774. ams_list = state.raw_data.get("ams", [])
  5775. for ams_data in ams_list:
  5776. dry_time = int(ams_data.get("dry_time") or 0)
  5777. if dry_time > 0:
  5778. ams_id = int(ams_data.get("id", 0))
  5779. if (printer_id, ams_id) not in self._auto_dry_units:
  5780. logger.debug(
  5781. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5782. printer_id,
  5783. ams_id,
  5784. )
  5785. continue
  5786. logger.info(
  5787. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5788. printer_id,
  5789. ams_id,
  5790. )
  5791. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5792. self.forget_auto_dry_cycle(printer_id, ams_id)
  5793. self._drying_in_progress.pop(printer_id, None)
  5794. # Scheduled manual drying (#2638) -----------------------------------
  5795. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5796. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5797. async def _check_scheduled_dryings(self, db: AsyncSession):
  5798. """Dispatch due scheduled drying runs and track running ones."""
  5799. now = utcnow_naive()
  5800. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5801. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5802. since_prune = time.monotonic()
  5803. if (
  5804. self._last_scheduled_drying_prune is None
  5805. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5806. ):
  5807. self._last_scheduled_drying_prune = since_prune
  5808. await db.execute(
  5809. delete(ScheduledDrying).where(
  5810. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5811. ScheduledDrying.completed_at.is_not(None),
  5812. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5813. )
  5814. )
  5815. # Same order as the list route: with two rows due on one printer the
  5816. # earliest scheduled wins rather than whatever the DB hands back first.
  5817. result = await db.execute(
  5818. select(ScheduledDrying)
  5819. .where(ScheduledDrying.status.in_(("pending", "running")))
  5820. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5821. )
  5822. rows = list(result.scalars().all())
  5823. # Rebuild from the DB every tick so route-side cancels and completions
  5824. # show up. Auto-drying's stop-all branches check this set before
  5825. # stopping anything (#2638).
  5826. # Kept from the previous pass so a run that ended between passes — a
  5827. # cancel through the route, say — can still be released below.
  5828. previously_running = self._scheduled_drying_printer_ids
  5829. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5830. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5831. # Model and firmware come from the printer row, not the live state.
  5832. printer_ids = {row.printer_id for row in rows}
  5833. printers_by_id: dict[int, Printer] = {}
  5834. if printer_ids:
  5835. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5836. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5837. for row in rows:
  5838. if row.status == "running":
  5839. self._update_running_scheduled_drying(row, now)
  5840. continue
  5841. if row.start_after is not None and row.start_after > now:
  5842. continue
  5843. state = printer_manager.get_status(row.printer_id)
  5844. if not state:
  5845. row.waiting_reason = "printer_offline"
  5846. continue
  5847. # Same preflight the immediate endpoint runs. Without it the publish
  5848. # succeeds, the row goes to running, the printer ignores the command
  5849. # and the run silently cancels itself after the grace window.
  5850. printer = printers_by_id.get(row.printer_id)
  5851. unsupported = drying_preflight.check_drying_supported(
  5852. printer.model if printer else None, state.firmware_version
  5853. )
  5854. if unsupported:
  5855. row.status = "failed"
  5856. row.error_message = unsupported
  5857. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5858. row.completed_at = now
  5859. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5860. continue
  5861. if (
  5862. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5863. ) or row.printer_id in running_printer_ids:
  5864. row.waiting_reason = "already_drying"
  5865. continue
  5866. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5867. row.waiting_reason = "printer_busy"
  5868. continue
  5869. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5870. if target is None:
  5871. row.waiting_reason = "ams_not_found"
  5872. continue
  5873. blocking = drying_preflight.blocking_reason_codes(target)
  5874. if blocking:
  5875. # Keep the power case distinct; it needs the user to act, so the
  5876. # card can say so instead of waiting silently.
  5877. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5878. continue
  5879. filament = drying_preflight.resolve_filament(target, row.filament)
  5880. logger.info(
  5881. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5882. row.id,
  5883. row.printer_id,
  5884. row.ams_id,
  5885. row.temp,
  5886. row.duration_hours,
  5887. )
  5888. success = printer_manager.send_drying_command(
  5889. row.printer_id,
  5890. row.ams_id,
  5891. row.temp,
  5892. row.duration_hours,
  5893. mode=1,
  5894. filament=filament,
  5895. rotate_tray=row.rotate_tray,
  5896. )
  5897. if success:
  5898. row.status = "running"
  5899. row.started_at = now
  5900. row.waiting_reason = None
  5901. row.filament = filament
  5902. self._drying_in_progress[row.printer_id] = time.monotonic()
  5903. self._scheduled_drying_printer_ids.add(row.printer_id)
  5904. running_printer_ids.add(row.printer_id)
  5905. else:
  5906. row.waiting_reason = "printer_offline"
  5907. # Release the printers whose run has ended. `_drying_in_progress` is
  5908. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5909. # but that call sits behind the auto-drying enabled check, and this
  5910. # method is the one writer that runs whether auto-drying is on or not.
  5911. # With it off, nothing would ever drop the entry short of a print being
  5912. # dispatched to the same printer, so the next scheduled run would wait
  5913. # on "already_drying" forever and `queue_drying_block` would hold the
  5914. # printer's prints too. Covers a run that ended during this pass and one
  5915. # cancelled through the route between passes.
  5916. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5917. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5918. self._drying_in_progress.pop(printer_id, None)
  5919. await db.commit()
  5920. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5921. """Detect completion or interruption of a running scheduled drying.
  5922. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5923. drying. Within the grace window after start we ignore dry_time==0
  5924. (the status lags the command). After that, dry_time==0 near the end
  5925. of the configured duration means completed. Much earlier means the
  5926. run was stopped: re-queue it if a print preempted the dryer, but a
  5927. stop while the printer is idle was deliberate, so cancel the row
  5928. rather than restart drying the user just stopped.
  5929. """
  5930. if row.started_at is None:
  5931. row.started_at = now
  5932. return
  5933. elapsed = (now - row.started_at).total_seconds()
  5934. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5935. return
  5936. state = printer_manager.get_status(row.printer_id)
  5937. if not state:
  5938. return # offline mid-dry; resolve when it reconnects
  5939. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5940. # throw on a malformed id would cost the whole pass including print
  5941. # dispatch, every tick.
  5942. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5943. try:
  5944. dry_time = int(target.get("dry_time") or 0) if target else 0
  5945. except (TypeError, ValueError):
  5946. dry_time = 0
  5947. if dry_time > 0 and is_countdown_parked(target):
  5948. # The printer took the command but the countdown is not running
  5949. # (#2896) and will never reach 0, so the run would stay "running"
  5950. # forever. A print in progress is the likely cause (the power budget
  5951. # is spent), so re-queue it like any interruption; the next start
  5952. # waits for the printer to be idle. Parked on an idle printer is a
  5953. # refusal, not something a retry fixes. The timer itself is left on
  5954. # the printer: it may yet start once power frees up.
  5955. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5956. logger.info(
  5957. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5958. row.id,
  5959. row.ams_id,
  5960. )
  5961. row.status = "pending"
  5962. row.started_at = None
  5963. row.waiting_reason = "interrupted"
  5964. else:
  5965. logger.warning(
  5966. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5967. row.id,
  5968. row.ams_id,
  5969. )
  5970. row.status = "failed"
  5971. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5972. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5973. row.completed_at = now
  5974. return
  5975. if dry_time > 0:
  5976. return
  5977. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5978. row.status = "completed"
  5979. row.completed_at = now
  5980. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5981. row.status = "pending"
  5982. row.started_at = None
  5983. row.waiting_reason = "interrupted"
  5984. else:
  5985. row.status = "cancelled"
  5986. row.completed_at = now
  5987. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5988. """Get all smart plugs associated with a printer."""
  5989. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5990. return list(result.scalars().all())
  5991. @staticmethod
  5992. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5993. """Pick the plug to power-cycle a printer back online with (#2629).
  5994. Only a plug flagged ``controls_printer_power`` can actually bring the
  5995. printer back; waiting for a boot on an accessory (filter fan, lights)
  5996. just burns the power-on timeout and fails the dispatch. Falls back to
  5997. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5998. Callers must pass a non-empty list.
  5999. """
  6000. for plug in auto_on_plugs:
  6001. if plug.controls_printer_power:
  6002. return plug
  6003. return auto_on_plugs[0]
  6004. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6005. # chamber-temperature recommendations BambuStudio ships for the matching
  6006. # filament profile; users can override via Settings → Workflow → Preheat
  6007. # card. "default" applies when a loaded tray's normalised type isn't in
  6008. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6009. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6010. "PLA": 0,
  6011. "PETG": 0,
  6012. "PETG-CF": 40,
  6013. "ABS": 45,
  6014. "ASA": 45,
  6015. "PA": 50,
  6016. "PA-CF": 55,
  6017. "PC": 50,
  6018. "PC-FR": 50,
  6019. "TPU": 0,
  6020. "PVA": 0,
  6021. "default": 0,
  6022. }
  6023. @classmethod
  6024. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6025. """The bundled map under the same key casing a parsed one gets.
  6026. The constant is declared with a lowercase ``default`` because that is
  6027. the key the Settings editor writes and displays. Every read of the map
  6028. happens after ``str(key).upper()``, so handing the constant back as
  6029. declared broke the contract the parser documents: an install that had
  6030. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6031. and the resolution loop's fallback silently found nothing. It read the
  6032. right number only because the bundled default happens to be 0 -- change
  6033. that constant and every unconfigured install would keep preheating to
  6034. zero with no way to tell why.
  6035. """
  6036. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6037. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6038. """Parse the user-configured filament→chamber-target map, falling back
  6039. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6040. are uppercased and the 'default' fallback is always present in the
  6041. returned dict so the resolution loop can index it unconditionally."""
  6042. raw = await self._get_setting(db, "preheat_filament_targets")
  6043. if not raw:
  6044. return self._bundled_preheat_targets()
  6045. try:
  6046. parsed = json.loads(raw)
  6047. if not isinstance(parsed, dict):
  6048. raise ValueError("not an object")
  6049. except (json.JSONDecodeError, ValueError) as exc:
  6050. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6051. return self._bundled_preheat_targets()
  6052. # Coerce values to int; drop unparseable rows so a stray string
  6053. # doesn't crash the loop.
  6054. out: dict[str, int] = {}
  6055. for key, value in parsed.items():
  6056. try:
  6057. out[str(key).upper()] = int(value)
  6058. except (TypeError, ValueError):
  6059. continue
  6060. if "DEFAULT" not in out:
  6061. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6062. return out
  6063. @staticmethod
  6064. def _normalize_filament_type(tray_type: str) -> str:
  6065. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6066. existing drying-preset normalisation (split-at-space, upper-case) so
  6067. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6068. "PA-CF" (no space to split on).
  6069. This is the first stage of ``_resolve_filament_key``, which goes on to
  6070. drop the suffix and consult the alias map; on its own it only decides
  6071. what the tray is called, not which row answers for it.
  6072. Indexing the split rather than testing the input: a tray_type of spaces
  6073. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6074. it through to an IndexError.
  6075. """
  6076. words = (tray_type or "").split()
  6077. return words[0].upper() if words else ""
  6078. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6079. """Per-filament chamber target for one tray's reported type, or 0 when
  6080. the tray is empty / RFID-less and reports no type at all.
  6081. A filled or foamed variant wants its base material's chamber when the
  6082. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6083. not the 0 an unknown type falls to. The specific type is still tried
  6084. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6085. (#2902).
  6086. That lookup is now the shared one, which adds the polyamide aliases on
  6087. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6088. too, rather than the catch-all it was landing on (#3067).
  6089. """
  6090. if not self._normalize_filament_type(tray_type or ""):
  6091. return 0
  6092. key = self._resolve_filament_key(tray_type, targets)
  6093. if key is not None:
  6094. return targets[key]
  6095. # A type the map does not list at all, which is not the same as a tray
  6096. # with nothing in it -- that already returned 0 above.
  6097. return targets.get("DEFAULT", 0)
  6098. def _derive_chamber_target(
  6099. self,
  6100. printer: Printer,
  6101. targets: dict[str, int],
  6102. item: PrintQueueItem | None = None,
  6103. ) -> int:
  6104. """Chamber target for the trays this print actually loads: the max of
  6105. their per-filament targets. Returns 0 when there is nothing to read (no
  6106. status, no AMS telemetry — e.g. external-spool prints) or when every
  6107. tray considered maps to 0, and the chamber phase then short-circuits in
  6108. the main loop.
  6109. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6110. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6111. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6112. plus soak burned ahead of each upload, on a printer whose chamber never
  6113. reaches the target anyway (#2886). An item with no usable mapping falls
  6114. back to scanning every loaded tray: that is the only signal left, and
  6115. narrowing to nothing would skip preheat on prints that genuinely need
  6116. it.
  6117. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6118. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6119. less slots have empty `tray_type` and contribute nothing. The external
  6120. spool is consulted only when the mapping names it (>= 254); it stays
  6121. out of the unnarrowed scan, so an item without a mapping derives from
  6122. the AMS alone exactly as before.
  6123. """
  6124. state = printer_manager.get_status(printer.id)
  6125. if state is None:
  6126. return 0
  6127. raw_data = state.raw_data or {}
  6128. used = _used_global_tray_ids(item)
  6129. ams_list = raw_data.get("ams")
  6130. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6131. if isinstance(ams_list, dict):
  6132. ams_list = ams_list.get("ams") or []
  6133. if not isinstance(ams_list, list):
  6134. ams_list = []
  6135. best = 0
  6136. for ams in ams_list:
  6137. if not isinstance(ams, dict):
  6138. continue
  6139. ams_id = _int_or(ams.get("id"), 0)
  6140. for tray in ams.get("tray") or []:
  6141. # A non-dict entry has never been seen from real firmware, but
  6142. # `.get` on one raises, and nothing between here and
  6143. # `_dispatch_one`'s try/finally catches it — the item would be
  6144. # left holding its dispatch claim. Preheat is best-effort by
  6145. # contract, so step over it instead.
  6146. if not isinstance(tray, dict):
  6147. continue
  6148. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6149. continue
  6150. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6151. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6152. for vt in raw_data.get("vt_tray") or []:
  6153. if not isinstance(vt, dict):
  6154. continue
  6155. # `_build_loaded_filaments` addresses external feeds by the id
  6156. # the firmware reports — 255 main, 254 deputy — defaulting to
  6157. # 254 when the field is absent. Same expression here so the two
  6158. # agree on which entry a mapping's 254/255 refers to.
  6159. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6160. continue
  6161. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6162. return best
  6163. def _release_keep_warm(self, pid: int) -> None:
  6164. """Release keep-warm on a printer that left the candidate set.
  6165. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6166. reports the target we set (``entry.held_target``), so a user or
  6167. subsequent print that changed the bed target since is not clobbered.
  6168. Best-effort, never raises.
  6169. The entry is kept, not dropped, when the printer cannot be reached
  6170. right now: a printer that is briefly offline still has a hot bed, and
  6171. holding the entry is what keeps the max-duration timeout applying and
  6172. lets a later tick retry the release. Only a printer that has left the
  6173. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6174. """
  6175. entry = self._keep_warm.get(pid)
  6176. if entry is None:
  6177. return
  6178. state = printer_manager.get_status(pid)
  6179. client = printer_manager.get_client(pid)
  6180. if state is None or client is None:
  6181. logger.debug(
  6182. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6183. pid,
  6184. )
  6185. return
  6186. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6187. if int(cur_bed_target) != entry.held_target:
  6188. # Someone else owns the bed now, so there is nothing of ours to
  6189. # undo and nothing left to track.
  6190. logger.info(
  6191. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6192. pid,
  6193. int(cur_bed_target),
  6194. entry.held_target,
  6195. )
  6196. self._keep_warm.pop(pid, None)
  6197. return
  6198. try:
  6199. client.set_bed_temperature(0)
  6200. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6201. self._keep_warm.pop(pid, None)
  6202. except Exception as exc:
  6203. # Keep the entry so the next tick tries again rather than leaving
  6204. # the bed hot with nothing tracking it.
  6205. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6206. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6207. """Release printers that dropped out of the keep-warm candidate set.
  6208. Called from ``_apply_keep_warm`` on every tick (with the current
  6209. candidate set), and from ``check_queue``'s no-pending-items early
  6210. return (with an empty candidate set) so orphaned holds still get
  6211. released when the queue empties. Also called with an empty candidate
  6212. set when any of the three gate settings toggles off, so a printer
  6213. whose feature was disabled mid-hold gets its bed released.
  6214. Printers being dispatched this tick are excluded from the bed-off
  6215. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6216. transient 0 in between would just churn against preheat. Ownership of
  6217. the hot bed transfers to the preheat rollback pin instead — if the
  6218. dispatch aborts before the print starts (failed upload, cancelled
  6219. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6220. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6221. is the ONLY thing standing between an aborted dispatch and a bed
  6222. left hot with no owner. A successful print start clears the pin and
  6223. the print's own gcode takes over, as usual.
  6224. """
  6225. for _pid in list(self._keep_warm):
  6226. if _pid in active_candidates:
  6227. continue
  6228. if _pid in dispatched:
  6229. handed_over = self._keep_warm.pop(_pid, None)
  6230. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6231. if handed_over is not None:
  6232. self._preheat_pin_bed[_pid] = handed_over.held_target
  6233. continue
  6234. self._release_keep_warm(_pid)
  6235. async def _apply_keep_warm(
  6236. self,
  6237. db: AsyncSession,
  6238. items: list[PrintQueueItem],
  6239. dispatch_ids: list[int] | set[int],
  6240. busy_printers: set[int],
  6241. require_plate_clear: bool,
  6242. ) -> None:
  6243. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6244. When a printer just finished a job (FINISH state) and the next queued
  6245. item needs chamber heating, hold the bed hot so the chamber stays warm
  6246. during the bed-clearing window. The bed is the chamber's heating
  6247. element here, not a print surface — nothing is printing during the
  6248. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6249. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6250. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6251. aftermarket chamber heaters), raised to the item's own parsed
  6252. bed_temperature when that is higher. Items whose archive metadata has
  6253. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6254. get a hold — chamber need is what gates the feature, not metadata.
  6255. Skips entirely for filaments that map to a 0°C chamber target
  6256. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6257. names, so a hot-chamber spool it never touches does not hold the bed of
  6258. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6259. whole unit, as every item was before. Printers being dispatched this
  6260. cycle are excluded:
  6261. ``_preheat_and_soak`` already handles their bed temperature.
  6262. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6263. released to 0 and the entry is latched ``expired=True`` so
  6264. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6265. MQTT: publish is skipped when firmware already has the target.
  6266. The release sweep runs BEFORE the engagement gate so a printer that
  6267. was owned by keep-warm still gets its bed released when any of the
  6268. three gate settings is toggled off mid-hold. The
  6269. ``check_queue`` early-return-when-no-items path also calls
  6270. ``_sweep_keep_warm`` directly to release orphaned holds.
  6271. """
  6272. dispatch_set = set(dispatch_ids)
  6273. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6274. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6275. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6276. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6277. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6278. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6279. # Release sweep first — must run even when gate_open is False so a
  6280. # printer owned by keep-warm when a gate toggles off gets released.
  6281. self._sweep_keep_warm(
  6282. active_candidates=warm_candidates if gate_open else set(),
  6283. dispatched=dispatched_printers,
  6284. )
  6285. if not gate_open:
  6286. return
  6287. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6288. max_hold_seconds = (
  6289. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6290. )
  6291. now_mono = time.monotonic()
  6292. filament_targets: dict[str, int] | None = None
  6293. for pid in warm_candidates:
  6294. entry = self._keep_warm.get(pid)
  6295. # Latched-expired: max-duration timeout already fired for this
  6296. # printer. Skip until the release sweep drops the entry (i.e.
  6297. # until the printer leaves the candidate set).
  6298. if entry is not None and entry.expired:
  6299. continue
  6300. # These two guards sit ahead of the max-duration check below, so an
  6301. # engaged hold only ages out while its printer is still reachable
  6302. # and still in FINISH. That is deliberate rather than a hole: with
  6303. # no status or no client there is no M140 to send anyway, and the
  6304. # elapsed check runs off `entry.started` so it fires on the first
  6305. # tick after the printer comes back. Leaving FINISH means the plate
  6306. # was cleared, which drops the printer out of `warm_candidates` and
  6307. # hands it to `_release_keep_warm` instead. The invariant worth
  6308. # preserving if this is ever reordered: every path out of an
  6309. # engaged hold ends in a bed-off, whether by timeout or release.
  6310. state = printer_manager.get_status(pid)
  6311. if state is None or state.state != "FINISH":
  6312. continue
  6313. client = printer_manager.get_client(pid)
  6314. if client is None:
  6315. continue
  6316. next_item = next((it for it in items if it.printer_id == pid), None)
  6317. if next_item is None:
  6318. continue
  6319. # Hold temperature: the configured keep-warm temp, raised to the
  6320. # item's own bed temp when the metadata reports a higher one. A
  6321. # missing bed_temperature (Orca gcode.3mf exports parse without
  6322. # one) does NOT skip the hold — chamber need gates the feature.
  6323. archive = next_item.archive
  6324. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6325. bed_target = max(item_bed, hold_temp)
  6326. if bed_target <= 0:
  6327. continue
  6328. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6329. if explicit is not None:
  6330. chamber_needed = int(explicit) > 0
  6331. else:
  6332. if filament_targets is None:
  6333. filament_targets = await self._get_preheat_filament_targets(db)
  6334. printer_obj = await self._get_printer(db, pid)
  6335. chamber_needed = (
  6336. printer_obj is not None
  6337. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6338. )
  6339. if not chamber_needed:
  6340. continue
  6341. # Seed the timer on first engagement; keep it on subsequent ticks
  6342. # (never re-seed — that would defeat the max-duration cap).
  6343. if entry is None:
  6344. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6345. self._keep_warm[pid] = entry
  6346. elapsed = now_mono - entry.started
  6347. if elapsed > max_hold_seconds:
  6348. # Timeout: publish bed → 0 once (if firmware still holds our
  6349. # target) and latch expired. The entry stays until the release
  6350. # sweep drops it, preventing the next tick from re-seeding.
  6351. logger.warning(
  6352. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6353. pid,
  6354. elapsed,
  6355. )
  6356. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6357. if int(cur_bed_target) == entry.held_target:
  6358. try:
  6359. client.set_bed_temperature(0)
  6360. except Exception as exc:
  6361. logger.warning(
  6362. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6363. pid,
  6364. exc,
  6365. )
  6366. else:
  6367. logger.info(
  6368. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6369. pid,
  6370. int(cur_bed_target),
  6371. entry.held_target,
  6372. )
  6373. entry.expired = True
  6374. continue
  6375. # Idempotence: skip publish when firmware already has our target.
  6376. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6377. if int(cur_bed_target) == bed_target:
  6378. entry.held_target = bed_target
  6379. continue
  6380. try:
  6381. client.set_bed_temperature(bed_target)
  6382. entry.held_target = bed_target
  6383. logger.info(
  6384. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6385. bed_target,
  6386. pid,
  6387. )
  6388. except Exception as exc:
  6389. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6390. def _sample_chamber_temps(self) -> None:
  6391. """Record a chamber temperature sample for every connected printer.
  6392. Called once per scheduler tick (every 3–30 s). Entries older than
  6393. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6394. Also evicts per-printer state whose printer_id is no longer registered
  6395. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6396. """
  6397. now = time.monotonic()
  6398. cutoff = now - self._chamber_history_ttl
  6399. statuses = printer_manager.get_all_statuses()
  6400. known_pids = set(statuses.keys())
  6401. for pid, status in statuses.items():
  6402. if status is None or not status.connected:
  6403. continue
  6404. temps = status.temperatures or {}
  6405. chamber = temps.get("chamber")
  6406. if chamber is None:
  6407. continue
  6408. hist = self._chamber_history.setdefault(pid, deque())
  6409. hist.append((now, float(chamber)))
  6410. while hist and hist[0][0] < cutoff:
  6411. hist.popleft()
  6412. # Evict state for printers that are no longer registered with the manager.
  6413. # This is the one place a keep-warm entry is dropped without releasing
  6414. # the bed: the printer is gone from the manager, so there is no client
  6415. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6416. # for printers that are merely unreachable, which is what makes this
  6417. # the terminal case rather than a silent leak.
  6418. for pid in list(self._chamber_history):
  6419. if pid not in known_pids:
  6420. self._chamber_history.pop(pid, None)
  6421. for pid in list(self._keep_warm):
  6422. if pid not in known_pids:
  6423. logger.info(
  6424. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6425. pid,
  6426. )
  6427. self._keep_warm.pop(pid, None)
  6428. for pid in list(self._preheat_pin):
  6429. if pid not in known_pids:
  6430. self._preheat_pin.pop(pid, None)
  6431. self._preheat_pin_bed.pop(pid, None)
  6432. def _chamber_soak_remaining(
  6433. self,
  6434. printer_id: int,
  6435. chamber_target: float,
  6436. soak_seconds: int,
  6437. tolerance: float = 2.0,
  6438. ) -> int:
  6439. """Return how many seconds of soak time are still needed.
  6440. Credits the time the chamber has already spent at temperature against
  6441. the configured soak. The credit may not start earlier than any of:
  6442. * **The newest sample.** Nothing recent means the printer stopped
  6443. reporting mid-observation and the chamber may have cooled unseen, so
  6444. the full soak is required. (A 2 h history whose last reading is half
  6445. an hour old is not evidence of anything — the measured cooling rate
  6446. is fast enough to cross the threshold in that time.)
  6447. * **The most recent contiguous run of samples.** A gap wider than
  6448. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6449. far side is not evidence of temperature.
  6450. * **The end of the most recent real dip below the threshold.**
  6451. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6452. — see that constant for the thermal reasoning. A stray low reading is
  6453. an artifact, and treating it as cooling would discard a soak that
  6454. actually happened.
  6455. Returns ``soak_seconds`` when nothing can be credited (no history,
  6456. stale history, or the chamber is below the threshold right now) and 0
  6457. once the credited time covers the whole soak.
  6458. """
  6459. hist = self._chamber_history.get(printer_id)
  6460. if not hist:
  6461. return soak_seconds
  6462. now = time.monotonic()
  6463. newest_ts, newest_temp = hist[-1]
  6464. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6465. return soak_seconds # stale — no fresh evidence to credit
  6466. threshold = chamber_target - tolerance
  6467. if newest_temp < threshold:
  6468. return soak_seconds # below target right now; nothing is soaked
  6469. samples = list(hist)
  6470. # Earliest point we have unbroken observations for.
  6471. credit_from = samples[-1][0]
  6472. for i in range(len(samples) - 1, 0, -1):
  6473. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6474. break
  6475. credit_from = samples[i - 1][0]
  6476. # Pull the credit forward to the end of the last significant dip. Each
  6477. # excursion is measured between the in-range readings that bracket it,
  6478. # so a lone stray sample is charged one sampling interval rather than
  6479. # zero, and the comparison errs towards calling a dip real.
  6480. i = 0
  6481. while i < len(samples):
  6482. if samples[i][1] >= threshold:
  6483. i += 1
  6484. continue
  6485. j = i
  6486. while j < len(samples) and samples[j][1] < threshold:
  6487. j += 1
  6488. # `newest_temp >= threshold` was checked above, so j is in range.
  6489. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6490. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6491. # Credit resumes at the last below-threshold sample rather than
  6492. # the first good one after it, so a recovered dip over-credits
  6493. # by up to one sampling interval — the opposite lean to the
  6494. # bracketing above. Both are bounded by the sample cadence and
  6495. # dwarfed by the grace period, so neither is worth the extra
  6496. # arithmetic to remove.
  6497. credit_from = max(credit_from, samples[j - 1][0])
  6498. i = j
  6499. return max(0, soak_seconds - int(now - credit_from))
  6500. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6501. """Tell an in-flight dispatch that its item no longer wants to print.
  6502. Called by the queue's cancel and delete routes. Those only write to the
  6503. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6504. observe — so preheat would keep heating for the rest of max_wait + soak
  6505. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6506. blocking every other queued item behind a print that is not happening.
  6507. Signalling in memory rather than re-reading the row keeps this off the
  6508. database entirely: no second session, no transaction held across a long
  6509. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6510. Bambuddy serves from a single uvicorn process with one scheduler task,
  6511. so the route and the dispatch always share this object. The flag is
  6512. advisory — dropping it (e.g. after a restart) only costs a wasted
  6513. preheat, never a wrongly-abandoned print.
  6514. Only ids with a dispatch actually in flight are recorded, so the set
  6515. stays bounded by the upload pool rather than growing once per cancelled
  6516. item for the life of the process. Skipping the rest loses nothing: an
  6517. item that is not in flight cannot start heating later either, because
  6518. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6519. the caller has already committed a terminal status (or deleted the row)
  6520. before calling this.
  6521. """
  6522. if item_id in self._inflight:
  6523. self._cancelled_dispatches.add(item_id)
  6524. # A print sent for it earlier that never started is not one any more.
  6525. self._forget_unstarted_print(item_id, unless_printing=False)
  6526. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6527. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6528. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6529. while it is parked, so the wait is chopped into
  6530. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6531. """
  6532. remaining = float(seconds)
  6533. while remaining > 0:
  6534. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6535. await asyncio.sleep(slice_secs)
  6536. remaining -= slice_secs
  6537. if item_id in self._cancelled_dispatches:
  6538. return False
  6539. return True
  6540. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6541. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6542. The full preheat stage does this as part of its own dispatch: an H2D
  6543. left in heating mode by the ABS job before it would otherwise cook the
  6544. PLA that follows. The skip path never reaches that code, so it calls
  6545. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6546. add to the rollback pin, because a flap set to cooling for a print that
  6547. needs no heat is where it should have been either way.
  6548. Best-effort like everything else in the stage: a refused command logs
  6549. and the dispatch carries on.
  6550. """
  6551. model = printer.model or ""
  6552. if not supports_airduct(model):
  6553. return
  6554. state = printer_manager.get_status(printer.id)
  6555. current = getattr(state, "airduct_mode", None) if state else None
  6556. if current == _AIRDUCT_MODE_COOLING:
  6557. return
  6558. client = printer_manager.get_client(printer.id)
  6559. if client is None:
  6560. return
  6561. try:
  6562. client.set_airduct_mode("cooling")
  6563. except Exception as exc:
  6564. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6565. async def _preheat_and_soak(
  6566. self,
  6567. db: AsyncSession,
  6568. item: PrintQueueItem,
  6569. printer: Printer,
  6570. archive: PrintArchive | None,
  6571. ) -> bool:
  6572. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6573. Returns True when the dispatch should carry on to the upload — including
  6574. every case where preheat is skipped, since a skipped preheat is not a
  6575. reason to abandon the print. Returns False only when the item stopped
  6576. wanting to be printed while the stage was waiting (cancelled or
  6577. deleted); the caller must then abandon the dispatch, and
  6578. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6579. Resolution order:
  6580. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6581. to the global `preheat_enabled` setting; 'on' forces the stage on
  6582. even if the global is off.
  6583. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6584. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6585. across the trays `item.ams_mapping` names (every loaded slot when
  6586. it names none).
  6587. 3. A target of 0 off the filament map skips the whole stage: the
  6588. materials this print loads want no chamber, so there is nothing to
  6589. soak for and the bed phase would only delay the upload (#3041).
  6590. An explicit 0 typed into the per-item override, or a per-item
  6591. 'on', still runs the bed phase and the soak — both are the user
  6592. asking for a warm bed in so many words.
  6593. 4. Three hardware tiers branch the wait loop:
  6594. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6595. send M141 to the resolved target, then wait for the chamber sensor
  6596. to reach it (or the max-wait timeout to elapse).
  6597. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6598. no M141; the bed is the only heat source, so we wait for the chamber
  6599. sensor to rise via bed radiation OR fall through on timeout.
  6600. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6601. temperature; the function just heats the bed and holds for the
  6602. configured soak duration.
  6603. The bed target comes from the archive's parsed metadata
  6604. (`bed_temperature`); if missing the preheat stage logs and returns
  6605. without dispatching anything, rather than guessing at a default that
  6606. might wreck filament setup.
  6607. Failures are logged but never re-raised — preheat is best-effort. A
  6608. printer that goes offline mid-soak, a refused gcode command, or a
  6609. missing temperature reading must not turn into a failed queue item; the
  6610. normal upload + start path runs immediately after this method returns.
  6611. """
  6612. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6613. if override == "off":
  6614. return True
  6615. if override == "inherit":
  6616. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6617. if not enabled:
  6618. return True
  6619. # override == "on" forces the stage on regardless of the global setting.
  6620. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6621. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6622. # Chamber target resolution:
  6623. # 1. Explicit per-item override beats everything (user knows best).
  6624. # 2. Otherwise derive from the filament types this print loads, via
  6625. # the per-filament target map. A PLA-only print derives 0 and the
  6626. # block below skips the stage without the user touching anything,
  6627. # even when an ASA spool is sitting in another slot of the same
  6628. # AMS (#2886).
  6629. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6630. if explicit_target is not None and explicit_target > 0:
  6631. chamber_target = int(explicit_target)
  6632. chamber_source = "item-override"
  6633. elif explicit_target == 0:
  6634. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6635. chamber_source = "item-override-zero"
  6636. else:
  6637. targets = await self._get_preheat_filament_targets(db)
  6638. chamber_target = self._derive_chamber_target(printer, targets, item)
  6639. chamber_source = "filament-map"
  6640. # Nothing to preheat *for*. A zero that came out of the filament map is
  6641. # the map saying this print's materials want no chamber conditioning --
  6642. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6643. # anyway heated the bed and then held it for the full soak, which
  6644. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6645. # own G-code sets the bed the moment it starts, so preheating it here
  6646. # only moves that heating ahead of the upload instead of overlapping
  6647. # with it, and the soak has no chamber to condition (#3041).
  6648. #
  6649. # An explicit statement from the user still runs the stage. Forcing the
  6650. # per-item override to 'on', or typing a chamber target of exactly 0,
  6651. # both mean "preheat the bed for this print" -- the second is
  6652. # documented as doing precisely that. Only the automatic path, the
  6653. # global toggle plus the filament map, short-circuits here.
  6654. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6655. logger.info(
  6656. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6657. "target, so there is nothing to soak for (override=%s model=%s)",
  6658. item.id,
  6659. override,
  6660. printer.model or "",
  6661. )
  6662. self._preheat_flap_to_cooling(item.id, printer)
  6663. return True
  6664. bed_target = await _queued_plate_bed_temperature(item, archive)
  6665. if bed_target <= 0:
  6666. # No bed temperature in the slicer metadata. When the print needs a
  6667. # hot chamber the bed is simply how we heat it, so fall back to the
  6668. # configured chamber-heating bed temperature rather than skipping
  6669. # the whole stage — otherwise the print starts with a cold chamber,
  6670. # which is exactly what preheat exists to prevent. Without a chamber
  6671. # requirement there is nothing to preheat *for*, so skip as before
  6672. # rather than guess a bed temperature for the print itself.
  6673. if chamber_target <= 0:
  6674. logger.info(
  6675. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6676. item.id,
  6677. )
  6678. return True
  6679. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6680. logger.info(
  6681. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6682. "%d°C to drive the chamber to %d°C",
  6683. item.id,
  6684. bed_target,
  6685. chamber_target,
  6686. )
  6687. client = printer_manager.get_client(printer.id)
  6688. if client is None:
  6689. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6690. return True
  6691. model = printer.model or ""
  6692. has_heater = supports_chamber_heater(model)
  6693. has_sensor = supports_chamber_temp(model)
  6694. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6695. # Fast path: if the chamber has been continuously above target for at
  6696. # least soak_seconds and the bed is already at temperature, skip the
  6697. # entire preheat stage. Typical case: keep-warm held the bed between
  6698. # consecutive same-material prints and the chamber never dropped.
  6699. if do_chamber and has_sensor and soak_seconds > 0:
  6700. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6701. if remaining == 0:
  6702. cur = printer_manager.get_status(printer.id)
  6703. if cur:
  6704. cur_temps = cur.temperatures or {}
  6705. if (
  6706. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6707. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6708. ):
  6709. logger.info(
  6710. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6711. "and bed is already at temperature (chamber history fast-path)",
  6712. item.id,
  6713. chamber_target,
  6714. soak_seconds,
  6715. )
  6716. # Still set targets to prevent cooling during the 3MF upload window.
  6717. # Register each successful set in the preheat pin so `_dispatch_one`
  6718. # unwinds them on any non-success exit.
  6719. pin = self._preheat_pin.setdefault(printer.id, set())
  6720. try:
  6721. client.set_bed_temperature(bed_target)
  6722. pin.add("bed")
  6723. self._preheat_pin_bed[printer.id] = bed_target
  6724. except Exception as exc:
  6725. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6726. if supports_airduct(model):
  6727. cur_airduct = getattr(cur, "airduct_mode", None)
  6728. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6729. try:
  6730. client.set_airduct_mode("heating")
  6731. # Only undo what we can see we replaced. `None`
  6732. # means no mode has been observed yet, and
  6733. # rolling that back to cooling would assert a
  6734. # state the printer never reported.
  6735. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6736. pin.add("airduct")
  6737. except Exception as exc:
  6738. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6739. if has_heater:
  6740. try:
  6741. client.set_chamber_temperature(chamber_target)
  6742. pin.add("chamber")
  6743. except Exception as exc:
  6744. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6745. return True
  6746. logger.info(
  6747. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6748. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6749. item.id,
  6750. bed_target,
  6751. chamber_target if do_chamber else 0,
  6752. chamber_source,
  6753. override,
  6754. model,
  6755. has_heater,
  6756. has_sensor,
  6757. max_wait,
  6758. soak_seconds,
  6759. )
  6760. # Preheat rollback registry: everything we set below is recorded here so
  6761. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6762. # (bed off, chamber off, airduct back to cooling) on any non-success
  6763. # exit. Populated as each command succeeds; consumed and cleared by
  6764. # `_dispatch_one`.
  6765. pin = self._preheat_pin.setdefault(printer.id, set())
  6766. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6767. # cache the target locally so the polling reads below see consistent
  6768. # state (firmware MQTT echoes lag by ~1s).
  6769. try:
  6770. client.set_bed_temperature(bed_target)
  6771. pin.add("bed")
  6772. self._preheat_pin_bed[printer.id] = bed_target
  6773. except Exception as exc:
  6774. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6775. return True
  6776. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6777. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6778. # left it on, regardless of M141. Default cooling actively vents the
  6779. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6780. # cooling never converges — the heater fights the open exhaust. We
  6781. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6782. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6783. # on an H2D that was previously running ABS would otherwise stay in
  6784. # heating mode and overheat PLA). The current-state read keeps the
  6785. # command idempotent — no MQTT chatter when the flap is already where
  6786. # we want it.
  6787. if supports_airduct(model):
  6788. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6789. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6790. current_state = printer_manager.get_status(printer.id)
  6791. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6792. if current_airduct != desired_id:
  6793. try:
  6794. client.set_airduct_mode(desired_airduct)
  6795. # As in the fast path: only pin a rollback for a flap we
  6796. # saw in cooling. `current_airduct` of None means no mode
  6797. # has been observed, so there is nothing to restore to.
  6798. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6799. pin.add("airduct")
  6800. except Exception as exc:
  6801. logger.warning(
  6802. "Queue item %s: preheat airduct %s mode failed: %s",
  6803. item.id,
  6804. desired_airduct,
  6805. exc,
  6806. )
  6807. if do_chamber and has_heater:
  6808. try:
  6809. client.set_chamber_temperature(chamber_target)
  6810. pin.add("chamber")
  6811. except Exception as exc:
  6812. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6813. # Release the pooled DB connection before the (potentially many-minute)
  6814. # heat-soak wait below (#2572). Every setting this method needs is read
  6815. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6816. # it never touches the DB. Without this the caller's transaction sat
  6817. # "idle in transaction" for the whole soak, pinning one pooled connection
  6818. # per preheating printer. expire_on_commit=False keeps item/printer
  6819. # readable afterwards; there are no pending writes to lose here.
  6820. await db.commit()
  6821. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6822. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6823. # Poll every 3s — frequent enough for responsive logging without
  6824. # spamming the MQTT state stream. The "converged" predicate is:
  6825. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6826. # AND
  6827. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6828. BED_TOLERANCE = 2.0
  6829. CHAMBER_TOLERANCE = 2.0
  6830. POLL_INTERVAL = 3.0
  6831. deadline = asyncio.get_event_loop().time() + max_wait
  6832. while True:
  6833. state = printer_manager.get_status(printer.id)
  6834. if state is None:
  6835. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6836. break
  6837. temps = state.temperatures or {}
  6838. bed_now = float(temps.get("bed", 0) or 0)
  6839. chamber_now = float(temps.get("chamber", 0) or 0)
  6840. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6841. if not do_chamber:
  6842. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6843. elif not has_sensor:
  6844. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6845. else:
  6846. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6847. if bed_ok and chamber_ok:
  6848. logger.info(
  6849. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6850. item.id,
  6851. bed_now,
  6852. chamber_now,
  6853. )
  6854. break
  6855. if asyncio.get_event_loop().time() >= deadline:
  6856. logger.info(
  6857. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6858. item.id,
  6859. bed_now,
  6860. bed_target,
  6861. chamber_now,
  6862. chamber_target if do_chamber else 0,
  6863. )
  6864. break
  6865. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6866. logger.info(
  6867. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6868. item.id,
  6869. )
  6870. return False
  6871. if soak_seconds > 0:
  6872. if do_chamber and has_sensor:
  6873. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6874. else:
  6875. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6876. if remaining > 0:
  6877. logger.info(
  6878. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6879. "has been above target for ~%ds already)",
  6880. item.id,
  6881. remaining,
  6882. soak_seconds,
  6883. soak_seconds - remaining,
  6884. )
  6885. if not await self._preheat_sleep(item.id, remaining):
  6886. logger.info(
  6887. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6888. item.id,
  6889. )
  6890. return False
  6891. else:
  6892. logger.info(
  6893. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6894. item.id,
  6895. chamber_target,
  6896. soak_seconds,
  6897. )
  6898. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6899. return True
  6900. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6901. """Turn on smart plug and wait for printer to connect.
  6902. Returns True if printer connected successfully within timeout.
  6903. """
  6904. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6905. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6906. # Check current plug state
  6907. status = await service.get_status(plug)
  6908. if not status.get("reachable"):
  6909. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6910. return False
  6911. # Turn on if not already on
  6912. if status.get("state") != "ON":
  6913. success = await service.turn_on(plug)
  6914. if not success:
  6915. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6916. return False
  6917. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  6918. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6919. # Get printer from database for connection
  6920. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6921. printer = result.scalar_one_or_none()
  6922. if not printer:
  6923. logger.error("Printer %s not found in database", printer_id)
  6924. return False
  6925. # End the pass's transaction before waiting up to minutes for the boot:
  6926. # held open, it pins a pooled connection idle in transaction
  6927. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  6928. # through it.
  6929. await db.commit()
  6930. # Wait for printer to boot (give it some time before trying to connect)
  6931. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6932. await asyncio.sleep(30)
  6933. # Try to connect to the printer periodically
  6934. elapsed = 30 # Already waited 30s
  6935. while elapsed < self._power_on_wait_time:
  6936. # Try to connect
  6937. logger.info("Attempting to connect to printer %s...", printer_id)
  6938. try:
  6939. connected = await printer_manager.connect_printer(printer)
  6940. if connected:
  6941. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6942. # Give it a moment to stabilize and get status
  6943. await asyncio.sleep(5)
  6944. return True
  6945. except Exception as e:
  6946. logger.debug("Connection attempt failed: %s", e)
  6947. await asyncio.sleep(self._power_on_check_interval)
  6948. elapsed += self._power_on_check_interval
  6949. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6950. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6951. return False
  6952. async def _check_previous_success(
  6953. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  6954. ) -> bool:
  6955. """Check if the previous print on this printer succeeded.
  6956. ``printer_id`` names the printer to look at when the item has none yet
  6957. (a job for any printer of a model, checked against the one offered).
  6958. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6959. deliberate action, not a failure, so subsequent items should still
  6960. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6961. a skip isn't an actual print attempt, so it must not gate downstream
  6962. items — counting it as a failed predecessor was the cascade bug that
  6963. let a single cancellation block 18 items over 3 days for the reporter.
  6964. Only `failed` and `aborted` — real print-attempt failures — block.
  6965. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6966. action — #1818) are also excluded from the lookback so the user can
  6967. clear the gate after fixing the physical issue without having to
  6968. re-queue every downstream job.
  6969. """
  6970. result = await db.execute(
  6971. select(PrintQueueItem)
  6972. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  6973. .where(PrintQueueItem.id != item.id)
  6974. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6975. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6976. # A row ended without a completion time must not count as the
  6977. # latest: PostgreSQL sorts NULL first in a descending order.
  6978. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  6979. .limit(1)
  6980. )
  6981. prev_item = result.scalar_one_or_none()
  6982. # If no previous item, assume success (first in queue)
  6983. if not prev_item:
  6984. return True
  6985. return prev_item.status in ("completed", "cancelled")
  6986. async def _repoint_siblings_at_archive(
  6987. self,
  6988. db: AsyncSession,
  6989. *,
  6990. consumed_library_file_id: int,
  6991. archive_id: int,
  6992. dispatched_item_id: int,
  6993. ) -> int:
  6994. """Move the other queue items off a library row that is about to be deleted (#2819).
  6995. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6996. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6997. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6998. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6999. clones, so the first dispatch could pull the file out from under rows that
  7000. had not run yet. What those rows did next depended on the database, and
  7001. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7002. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7003. they were left pointing at a row that no longer existed, failing with
  7004. "Library file not found" whenever someone started them -- or sitting
  7005. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7006. constraint, so there the rows were deleted outright and the queued copies
  7007. simply vanished, with no error and no history.
  7008. The archive holds its own copy of the 3MF, so the remaining copies can print
  7009. from it instead. Two things happen here, and both must happen *before* the
  7010. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7011. * every row still naming the file has ``library_file_id`` cleared, which is
  7012. what takes it out of the cascade's reach. That covers rows this cannot
  7013. re-point as well -- a copy already printing from its own archive, and the
  7014. finished ones, which are not spare parts but the record a batch order
  7015. counts its progress from.
  7016. * the rows that still need something to print are pointed at the archive.
  7017. Returns how many items were re-pointed.
  7018. """
  7019. variant_item_ids = (
  7020. (
  7021. await db.execute(
  7022. select(PrintQueueVariant.queue_item_id).where(
  7023. PrintQueueVariant.library_file_id == consumed_library_file_id
  7024. )
  7025. )
  7026. )
  7027. .scalars()
  7028. .all()
  7029. )
  7030. # Candidate rows naming the consumed file have to go rather than be
  7031. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7032. # one out of the cascade. This is what PostgreSQL already does, and
  7033. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7034. # outcome changes -- the two backends simply stop disagreeing about
  7035. # whether the row is still there.
  7036. #
  7037. # It also has to happen before the re-point below: a cross-model item
  7038. # (#671) picks a variant every pass and folds it onto the row, and
  7039. # _resolve_variant clears archive_id as it does so, which would undo the
  7040. # re-point on the very next lap.
  7041. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7042. # An item left with other candidates still has somewhere to go, and those
  7043. # carry their own target model -- pointing it at this archive would print a
  7044. # file the matcher never chose. It is excluded from the re-point and simply
  7045. # re-resolves against what is left.
  7046. surviving_variant_item_ids = set(
  7047. (
  7048. await db.execute(
  7049. select(PrintQueueVariant.queue_item_id).where(
  7050. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7051. )
  7052. )
  7053. )
  7054. .scalars()
  7055. .all()
  7056. )
  7057. repoint_ids = set(
  7058. (
  7059. await db.execute(
  7060. select(PrintQueueItem.id)
  7061. .where(PrintQueueItem.id != dispatched_item_id)
  7062. .where(PrintQueueItem.archive_id.is_(None))
  7063. # "skipped" belongs here with the two live states: it is not
  7064. # terminal. Clearing a printer's previous-success gate puts
  7065. # every item skipped by it back to "pending"
  7066. # (resume_after_failure), and one restored onto a deleted
  7067. # file is the same orphan by a slower route. "failed",
  7068. # "cancelled", "aborted" and "completed" never return.
  7069. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7070. .where(
  7071. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7072. )
  7073. .where(
  7074. or_(
  7075. PrintQueueItem.library_file_id == consumed_library_file_id,
  7076. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7077. )
  7078. )
  7079. )
  7080. )
  7081. .scalars()
  7082. .all()
  7083. )
  7084. if repoint_ids:
  7085. await db.execute(
  7086. update(PrintQueueItem)
  7087. .where(PrintQueueItem.id.in_(repoint_ids))
  7088. .values(
  7089. archive_id=archive_id,
  7090. library_file_id=None,
  7091. # The file this flag named is already consumed. Leaving it set
  7092. # would arm every re-pointed copy to delete whatever library
  7093. # row it is next given.
  7094. cleanup_library_after_dispatch=False,
  7095. )
  7096. )
  7097. logger.info(
  7098. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7099. sorted(repoint_ids),
  7100. archive_id,
  7101. consumed_library_file_id,
  7102. dispatched_item_id,
  7103. )
  7104. # Everything else that still names the file: taken out of the cascade's
  7105. # reach without touching what it prints. The file is gone either way; what
  7106. # this preserves is the row.
  7107. await db.execute(
  7108. update(PrintQueueItem)
  7109. .where(PrintQueueItem.id != dispatched_item_id)
  7110. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7111. .values(library_file_id=None)
  7112. )
  7113. return len(repoint_ids)
  7114. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7115. """Schedule power-off if the queue item enabled auto_off_after.
  7116. Delegates to the smart-plug manager so the off honours each plug's
  7117. configured strategy (time delay or temperature threshold), is cancelled
  7118. if the printer starts printing again, and never cuts power on a loaded
  7119. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7120. powered off on the timeout regardless of print state.
  7121. """
  7122. if not item.auto_off_after:
  7123. return
  7124. try:
  7125. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7126. except Exception as e:
  7127. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7128. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7129. """Get a human-readable name for a queue item."""
  7130. if item.archive_id:
  7131. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7132. archive = result.scalar_one_or_none()
  7133. if archive:
  7134. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7135. if item.library_file_id:
  7136. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7137. library_file = result.scalar_one_or_none()
  7138. if library_file:
  7139. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7140. # A cross-model item (#671) holds no file of its own until a printer is
  7141. # picked, so name it after its first candidate — otherwise every waiting
  7142. # notification for one reads "Job #12". Queried rather than read off
  7143. # item.variants because callers outside the selection loop have not
  7144. # eager-loaded them, and a lazy load raises in async.
  7145. first_variant_name = (
  7146. await db.execute(
  7147. select(LibraryFile.filename)
  7148. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7149. .where(PrintQueueVariant.queue_item_id == item.id)
  7150. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7151. .limit(1)
  7152. )
  7153. ).scalar_one_or_none()
  7154. if first_variant_name:
  7155. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7156. return f"Job #{item.id}"
  7157. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7158. """Get printer by ID."""
  7159. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7160. return result.scalar_one_or_none()
  7161. async def _notify_dispatch_gave_up(
  7162. self,
  7163. queue_item_id: int,
  7164. printer_id: int,
  7165. created_by_id: int | None,
  7166. reason: str = "Printer accepted the file but never started printing",
  7167. ) -> None:
  7168. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7169. Called from the watchdog, which is a background task with no session of
  7170. its own — hence the fresh one here. Best-effort throughout: the row is
  7171. already marked failed and that is the load-bearing part; a notification
  7172. provider being down must not resurrect the retry loop we just stopped.
  7173. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7174. path passes its own, because "accepted the file but never started" is the
  7175. opposite of what happened there — the printer refused it outright (#2732).
  7176. """
  7177. try:
  7178. async with async_session() as db:
  7179. item = await db.get(PrintQueueItem, queue_item_id)
  7180. if not item:
  7181. return
  7182. job_name = await self._get_job_name(db, item)
  7183. printer = await self._get_printer(db, printer_id)
  7184. await notification_service.on_queue_job_failed(
  7185. job_name=job_name,
  7186. printer_id=printer_id,
  7187. printer_name=printer.name if printer else "Unknown",
  7188. reason=reason,
  7189. db=db,
  7190. )
  7191. except Exception as e:
  7192. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7193. try:
  7194. await ws_manager.send_queue_item_failed(
  7195. user_id=created_by_id,
  7196. queue_item_id=queue_item_id,
  7197. printer_id=printer_id,
  7198. reason="never_started",
  7199. )
  7200. except Exception:
  7201. pass # toast is best-effort
  7202. async def _filament_short_on(
  7203. self,
  7204. db: AsyncSession,
  7205. item: PrintQueueItem,
  7206. printer_id: int,
  7207. *,
  7208. require_known: bool = False,
  7209. ) -> bool:
  7210. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7211. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7212. assigned there, with the mapping the item would get there, but changes
  7213. nothing. The model-based matcher uses it to prefer a printer whose
  7214. spools can finish the job.
  7215. False whenever the gate would let the item through: "Print Anyway",
  7216. no mapping, or a check that fails. With ``require_known`` all three of
  7217. those, and any printed slot whose remaining amount is unknown, count
  7218. as short instead: releasing a held job starts it with nobody asked, so
  7219. it needs the amount on record, not merely nothing against it.
  7220. """
  7221. if item.skip_filament_check:
  7222. return False
  7223. try:
  7224. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7225. if not mapping:
  7226. return require_known
  7227. deficit = await compute_deficit_for_queue_item(
  7228. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7229. )
  7230. except Exception as e:
  7231. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7232. return require_known
  7233. return bool(deficit)
  7234. async def _release_short_model_hold(
  7235. self,
  7236. db: AsyncSession,
  7237. item: PrintQueueItem,
  7238. unavailable: set[int],
  7239. require_plate_clear: bool,
  7240. printer_scope: PrinterScope,
  7241. ) -> bool:
  7242. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7243. The deficit gate holds a model-based job on the printer the matcher
  7244. gave it, because "Print Anyway" needs a printer to print on. When
  7245. another idle printer of the job's model has the filament, the job is
  7246. moved to that printer and its hold lifted, and the fixed-printer
  7247. branch dispatches it in this same pass, through the same checks a
  7248. held job meets when the user presses Start. It is moved rather than
  7249. put back in the pool because the model-based branch would pick again
  7250. without requiring the amounts on record (below), and could pick a
  7251. different printer. Only the deficit gate sets ``filament_short``, so a
  7252. job held for any other reason stays held.
  7253. The printer it is held on is left out: a spool loaded there is started
  7254. with Start, as before, rather than while someone may still be loading
  7255. the next one. Each job is checked at most every
  7256. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7257. on each idle printer again.
  7258. Cross-model jobs (#671) stay held: checking a variant writes its file
  7259. onto the item, which would leave a job that is not moved holding
  7260. another variant's file for the printer it waits on.
  7261. A printer qualifies only on a positive finding: every slot the plate
  7262. prints mapped to a spool whose remaining amount is on record and
  7263. enough. A printer whose spools Bambuddy does not track is not one.
  7264. Returns True when the job was moved. A check that fails keeps the hold
  7265. rather than stopping the queue pass.
  7266. """
  7267. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7268. return False
  7269. if not item.target_model or item.variants:
  7270. return False
  7271. now = time.monotonic()
  7272. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7273. return False
  7274. self._short_hold_checked_at[item.id] = now
  7275. try:
  7276. candidates = _candidates_for(item)
  7277. if not candidates:
  7278. return False
  7279. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7280. async def is_short(pid: int) -> bool:
  7281. return await self._filament_short_on(db, item, pid, require_known=True)
  7282. match_id, _ = await self._find_idle_printer_for_model(
  7283. db,
  7284. item.target_model,
  7285. unavailable | {item.printer_id},
  7286. effective_types,
  7287. item.target_location,
  7288. filament_overrides=filament_overrides,
  7289. require_plate_clear=require_plate_clear,
  7290. printer_scope=printer_scope,
  7291. is_short=is_short,
  7292. )
  7293. # Every idle printer short comes back as the first of them.
  7294. if match_id is None or await is_short(match_id):
  7295. return False
  7296. except Exception as e:
  7297. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7298. return False
  7299. logger.info(
  7300. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7301. item.id,
  7302. match_id,
  7303. item.printer_id,
  7304. )
  7305. self._short_hold_checked_at.pop(item.id, None)
  7306. item.printer_id = match_id
  7307. # Resolved against the printer it leaves (#3239): the tray mapping and
  7308. # the nozzle positions.
  7309. drop_printer_resolved(item)
  7310. item.manual_start = False
  7311. item.filament_short = False
  7312. item.waiting_reason = None
  7313. await db.commit()
  7314. try:
  7315. printer = await self._get_printer(db, match_id)
  7316. await notification_service.on_queue_job_assigned(
  7317. job_name=await self._get_job_name(db, item),
  7318. printer_id=match_id,
  7319. printer_name=printer.name if printer else "Unknown",
  7320. target_model=item.target_model,
  7321. db=db,
  7322. )
  7323. except Exception as e:
  7324. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7325. return True
  7326. async def _block_on_filament_deficit(
  7327. self,
  7328. db: AsyncSession,
  7329. item: PrintQueueItem,
  7330. ) -> bool:
  7331. """Promote the item to manual_start when the assigned spool is short (#1496).
  7332. Returns True when this dispatch attempt was blocked, False when the
  7333. item is clear to start. A previously-flagged item whose spool has
  7334. since been swapped to one with enough material clears the flag here
  7335. so the next scheduler tick dispatches it.
  7336. """
  7337. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7338. # don't re-flag, don't even compute. Without this short-circuit the
  7339. # scheduler bounces between "user said anyway" (route clears
  7340. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7341. # on identical spool state) (#1698-followup).
  7342. if item.skip_filament_check:
  7343. # #1762 diagnostic: surface the short-circuit at INFO so a
  7344. # future "Print Anyway didn't work" report (e.g. issue #1762
  7345. # comment 3) has actionable evidence in the support bundle
  7346. # without needing DEBUG enabled.
  7347. logger.info(
  7348. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7349. item.id,
  7350. )
  7351. return False
  7352. try:
  7353. deficit = await compute_deficit_for_queue_item(db, item)
  7354. except Exception as e:
  7355. # Never let a flaky deficit check wedge the queue — log and let
  7356. # dispatch proceed. The PrintModal-side check still runs on the
  7357. # manual paths.
  7358. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7359. return False
  7360. if deficit:
  7361. item.filament_short = True
  7362. item.manual_start = True
  7363. await db.commit()
  7364. job_name = await self._get_job_name(db, item)
  7365. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7366. logger.info(
  7367. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7368. item.id,
  7369. len(deficit),
  7370. )
  7371. try:
  7372. await notification_service.on_queue_job_waiting(
  7373. job_name=job_name,
  7374. target_model=(printer.model if printer else "") or "",
  7375. waiting_reason="filament_short",
  7376. db=db,
  7377. printer_id=item.printer_id,
  7378. )
  7379. except Exception as e:
  7380. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7381. return True
  7382. # No deficit — clear any stale flag from a previous tick.
  7383. if item.filament_short:
  7384. item.filament_short = False
  7385. await db.commit()
  7386. return False
  7387. async def _block_on_unmatched_filament(
  7388. self,
  7389. db: AsyncSession,
  7390. item: PrintQueueItem,
  7391. release_assignment: bool = False,
  7392. ) -> bool:
  7393. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7394. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7395. goes ahead, letting the printer choose — which is how a job prints in the
  7396. wrong material without anyone being asked. Holding is the same answer the
  7397. deficit gate already gives for "the spool is too light", so it reuses the
  7398. same promote-and-notify machinery.
  7399. Keyed off unresolved slots in the *computed* mapping intersected with the
  7400. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7401. read: on its own it also pads slots this plate does not print, so the
  7402. array alone would hold perfectly good jobs. Reading the mapping rather
  7403. than the printer's loaded filament types also inherits the matcher's
  7404. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7405. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7406. type-only scan would wave that through.
  7407. A mapping that resolved *nothing* is the same finding arriving as an
  7408. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7409. could not replace, and dispatch then goes out as ``use_ams`` with no
  7410. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7411. That is held too, but only once live status positively reports loaded
  7412. trays: #2589's mapping is bogus precisely because the AMS was not known
  7413. yet, and its empty loaded list is that ignorance rather than a miss.
  7414. ``release_assignment`` is for the model-based path, which commits its
  7415. printer choice before the gates run. Holding an "any P2S" job would
  7416. otherwise pin it to the one P2S that could not run it.
  7417. Returns True when this dispatch attempt was blocked.
  7418. """
  7419. if item.skip_filament_check or not item.printer_id:
  7420. return False
  7421. if item.ams_mapping:
  7422. try:
  7423. mapping = json.loads(item.ams_mapping)
  7424. except (json.JSONDecodeError, TypeError):
  7425. return False
  7426. if not isinstance(mapping, list):
  7427. return False
  7428. else:
  7429. # Nothing resolved, or nothing survived revalidation. Only a printer
  7430. # that reported loaded trays makes that a finding — see the
  7431. # docstring on why an empty list is not one.
  7432. status = printer_manager.get_status(item.printer_id)
  7433. if status is None or not self._build_loaded_filaments(status):
  7434. return False
  7435. # Every required slot reads unresolved against an empty mapping.
  7436. mapping = []
  7437. required = await self._get_filament_requirements(db, item)
  7438. if not required:
  7439. return False
  7440. self._apply_filament_overrides(item, required)
  7441. unmatched = _unresolved_required(required, mapping)
  7442. if not unmatched:
  7443. # No cleanup needed here: once start is pressed the item is no
  7444. # longer staged, and whichever exit runs next overwrites the reason
  7445. # (`hold_item` on the fixed-printer branch, the assignment on the
  7446. # model-based one), as does dispatch.
  7447. return False
  7448. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7449. held_by = item.printer_id
  7450. item.manual_start = True
  7451. # Human-readable: this renders on the queue row.
  7452. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7453. if release_assignment:
  7454. # "Any P2S" means any, so the job returns to the pool rather than
  7455. # waiting on the printer that could not take it. The mapping goes
  7456. # with the assignment: its tray IDs were resolved against the
  7457. # printer being released and mean nothing on the next one (#2799),
  7458. # and keeping them would hold the job again even on a printer that
  7459. # has the filament, since an unresolved slot is deliberately not a
  7460. # conflict worth recomputing over.
  7461. item.printer_id = None
  7462. drop_printer_resolved(item)
  7463. await db.commit()
  7464. job_name = await self._get_job_name(db, item)
  7465. printer = await self._get_printer(db, held_by)
  7466. logger.info(
  7467. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7468. item.id,
  7469. held_by,
  7470. wanted,
  7471. )
  7472. try:
  7473. await notification_service.on_queue_job_waiting(
  7474. job_name=job_name,
  7475. target_model=(printer.model if printer else "") or "",
  7476. waiting_reason=f"needs {wanted}",
  7477. db=db,
  7478. # Released to the pool: no printer holds it any more.
  7479. printer_id=None if release_assignment else held_by,
  7480. )
  7481. except Exception as e:
  7482. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7483. return True
  7484. @staticmethod
  7485. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7486. """The queue item's owner as the row has it now.
  7487. item.created_by_id was read before preheat and upload, which can take
  7488. minutes; deleting the user clears the row, not this session's copy.
  7489. """
  7490. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7491. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7492. """Hand the queue item's owner to printer_manager so the
  7493. print-complete callback can credit the user in PrintLogEntry (#1670).
  7494. No-ops when the item has no `created_by_id` or the referenced user
  7495. row is missing (e.g. user deleted between queue-add and dispatch —
  7496. in that case the print log row falls back to the existing un-credited
  7497. behaviour rather than crashing the dispatch).
  7498. """
  7499. from backend.app.models.user import User
  7500. # Read from the row, not item.created_by_id or db.get: both can still
  7501. # hold a user deleted during the upload, after delete_user forgot them
  7502. # (on SQLite the id may be someone new's by the time the print ends).
  7503. # Joined with the printer too: one deleted during the upload was
  7504. # forgotten as well, and this would write the owner back under its id.
  7505. owner = (
  7506. await db.execute(
  7507. select(User.id, User.username)
  7508. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7509. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7510. .where(PrintQueueItem.id == item.id)
  7511. )
  7512. ).first()
  7513. if owner:
  7514. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7515. if item.printer_id is not None:
  7516. self._unconfirmed_print_user[item.id] = item.printer_id
  7517. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7518. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7519. A cancel lands in another session while the upload runs (the edit route
  7520. even tells users to cancel a job that is being sent). An unconditional
  7521. write here would turn that cancellation into a failure, with a failure
  7522. notification, and block the next job that needs the previous print to
  7523. have succeeded. Returns whether the item was marked failed.
  7524. """
  7525. result = cast(
  7526. CursorResult,
  7527. await db.execute(
  7528. update(PrintQueueItem)
  7529. .where(PrintQueueItem.id == item.id)
  7530. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7531. .values(status="failed", error_message=message, completed_at=datetime.now(timezone.utc))
  7532. .execution_options(synchronize_session=False)
  7533. ),
  7534. )
  7535. await db.commit()
  7536. if result.rowcount == 0:
  7537. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7538. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7539. return False
  7540. await db.refresh(item)
  7541. from backend.app.services.print_batch import refresh_batches_after
  7542. await refresh_batches_after([item.id])
  7543. return True
  7544. @staticmethod
  7545. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7546. """Put a job whose printer turned busy before the start back in the queue.
  7547. Only if it is still printing: a stop that landed meanwhile stands.
  7548. """
  7549. await db.execute(
  7550. update(PrintQueueItem)
  7551. .where(PrintQueueItem.id == item.id)
  7552. .where(PrintQueueItem.status == "printing")
  7553. .values(status="pending", started_at=None)
  7554. .execution_options(synchronize_session=False)
  7555. )
  7556. await db.commit()
  7557. @staticmethod
  7558. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7559. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7560. try:
  7561. await ws_manager.send_queue_item_failed(
  7562. user_id=toast_uid,
  7563. queue_item_id=item.id,
  7564. printer_id=item.printer_id,
  7565. reason="cancelled_mid_dispatch",
  7566. )
  7567. except Exception:
  7568. pass # toast is best-effort
  7569. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7570. """Upload file and start print for a queue item.
  7571. Supports two sources:
  7572. - archive_id: Print from an existing archive
  7573. - library_file_id: Print from a library file (file manager)
  7574. """
  7575. logger.info("Starting queue item %s", item.id)
  7576. # Also covers a reservation left active by a process interruption
  7577. # during an earlier attempt. `_dispatch_one` releases this marker on
  7578. # every exit unless start_print() confirms that the command was sent.
  7579. self._unconfirmed_budget_reservations.add(item.id)
  7580. try:
  7581. from backend.app.models.user import User
  7582. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7583. # Recompute at the final authorization boundary as well as enqueue
  7584. # time. This covers rows created before the server-side estimate
  7585. # migration and prevents any alternate write path from weakening
  7586. # the budget reservation.
  7587. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7588. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7589. item.estimated_cost = await estimate_queue_source_cost(
  7590. db,
  7591. archive=archive,
  7592. library_file=library_file,
  7593. plate_id=item.plate_id,
  7594. ams_mapping=item.ams_mapping,
  7595. printer_id=item.printer_id,
  7596. )
  7597. await validate_print_budget(
  7598. db,
  7599. cost_center_id=item.cost_center_id,
  7600. estimated_cost=item.estimated_cost,
  7601. current_user=queue_user,
  7602. exclude_queue_item_id=item.id,
  7603. exclude_reservation_source_type="print_queue",
  7604. exclude_reservation_source_id=item.id,
  7605. )
  7606. budget_reservation = await create_budget_reservation(
  7607. db,
  7608. cost_center_id=item.cost_center_id,
  7609. estimated_cost=item.estimated_cost,
  7610. current_user=queue_user,
  7611. source_type="print_queue",
  7612. source_id=item.id,
  7613. print_archive_id=item.archive_id,
  7614. exclude_queue_item_id=item.id,
  7615. )
  7616. await db.commit()
  7617. except HTTPException as exc:
  7618. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7619. return
  7620. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7621. await self._power_off_if_needed(db, item)
  7622. return
  7623. # Get printer first (needed for both paths)
  7624. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7625. printer = result.scalar_one_or_none()
  7626. if not printer:
  7627. if not await self._fail_dispatch(db, item, "Printer not found"):
  7628. return
  7629. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7630. await self._power_off_if_needed(db, item)
  7631. return
  7632. # Check printer is connected
  7633. if not printer_manager.is_connected(item.printer_id):
  7634. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7635. return
  7636. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7637. await self._power_off_if_needed(db, item)
  7638. return
  7639. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7640. # `items` was taken at the top of check_queue, but the user can /cancel
  7641. # any pending row in the gap before we reach this point. Re-read the
  7642. # row and bail out cleanly instead of starting an FTP upload for a row
  7643. # that's already cancelled. The atomic CAS at the pending→printing
  7644. # transition (below, before start_print) is the load-bearing guard;
  7645. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7646. await db.refresh(item)
  7647. if item.status != "pending":
  7648. logger.info(
  7649. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7650. item.id,
  7651. item.status,
  7652. )
  7653. return
  7654. # Busy-printer guard (#2598). check_queue gates dispatch on
  7655. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7656. # keep reporting FINISH for tens of seconds *after* it accepted a
  7657. # project_file (see the watchdog's phase-B note). A watchdog revert
  7658. # (#2555) also releases the dispatch hold, so a re-selected item can
  7659. # reach here while its printer has actually started printing. Uploading
  7660. # and dispatching then collides with the live job — the firmware answers
  7661. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7662. # live state right before the expensive FTP upload: if the printer is
  7663. # busy, leave the item pending and let a later tick dispatch it once the
  7664. # printer is genuinely idle. No wasted upload, no collision.
  7665. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7666. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7667. logger.info(
  7668. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7669. "leaving item pending for a later tick (#2598)",
  7670. item.id,
  7671. item.printer_id,
  7672. pre_dispatch_state,
  7673. )
  7674. return
  7675. # Determine source: archive or library file
  7676. archive = None
  7677. library_file = None
  7678. file_path = None
  7679. filename = None
  7680. cleanup_disk_paths: list[Path] = []
  7681. # Set when a dispatch consumes its library file, so the photos can be
  7682. # carried over after the commit that removes the row (#3077).
  7683. consumed_library_file_id: int | None = None
  7684. consumed_photos: list[str] = []
  7685. if item.archive_id:
  7686. # Print from archive
  7687. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7688. archive = result.scalar_one_or_none()
  7689. if not archive:
  7690. if not await self._fail_dispatch(db, item, "Archive not found"):
  7691. return
  7692. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7693. await self._power_off_if_needed(db, item)
  7694. return
  7695. # Persist the queue item's selected plate onto the archive so Print
  7696. # History can show the actual plate after cancel/fail/complete (#2603).
  7697. # Only when the archive doesn't already carry one, so a reprint of a
  7698. # plate-specific archive isn't relabelled by a differently-plated
  7699. # queue row.
  7700. if archive.plate_id is None and item.plate_id is not None:
  7701. archive.plate_id = item.plate_id
  7702. # Ask-for-outcome opt-in rides from the queue item to the archive
  7703. # the same way (#1898); never cleared here so a reprint of an
  7704. # archive that already asked keeps asking.
  7705. if item.confirm_outcome:
  7706. archive.confirm_requested = True
  7707. file_path = settings.base_dir / archive.file_path
  7708. filename = archive.filename
  7709. elif item.library_file_id:
  7710. # Print from library file (file manager)
  7711. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7712. library_file = result.scalar_one_or_none()
  7713. if not library_file:
  7714. # "Not found" covers two different situations and only one of
  7715. # them is recoverable, so say which. A trashed file is still
  7716. # there and restoring it makes a re-queued job work; a file that
  7717. # is really gone needs a different one. Neither is knowable from
  7718. # the queue, which is the whole complaint about this message.
  7719. trashed = (
  7720. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7721. ).scalar_one_or_none()
  7722. if not await self._fail_dispatch(
  7723. db,
  7724. item,
  7725. (
  7726. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7727. if trashed
  7728. else "Library file not found — it was deleted after this job was queued"
  7729. ),
  7730. ):
  7731. return
  7732. logger.error(
  7733. "Queue item %s: library file %s is %s",
  7734. item.id,
  7735. item.library_file_id,
  7736. "in the trash" if trashed else "gone",
  7737. )
  7738. await self._power_off_if_needed(db, item)
  7739. return
  7740. # Library files store absolute paths
  7741. lib_path = Path(library_file.file_path)
  7742. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7743. filename = library_file.filename
  7744. # Create archive from library file so usage tracking has access to the 3MF
  7745. queue_item_id = item.id
  7746. # Held separately: a cleanup dispatch clears item.library_file_id
  7747. # below, and the log line at the end of this block reported that
  7748. # cleared field -- so every consumed print logged "from library
  7749. # file None", which is the one case worth being able to trace.
  7750. source_library_file_id = item.library_file_id
  7751. try:
  7752. from backend.app.services.archive import ArchiveService
  7753. archive_service = ArchiveService(db)
  7754. archive = await archive_service.archive_print(
  7755. printer_id=item.printer_id,
  7756. source_file=file_path,
  7757. original_filename=filename,
  7758. created_by_id=item.created_by_id,
  7759. project_id=item.project_id,
  7760. cost_center_id=item.cost_center_id,
  7761. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7762. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7763. )
  7764. if archive:
  7765. item.archive_id = archive.id
  7766. if item.confirm_outcome:
  7767. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7768. if budget_reservation is not None:
  7769. budget_reservation.print_archive_id = archive.id
  7770. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7771. consumed_library_file_id = library_file.id
  7772. item.library_file_id = None
  7773. cleanup_disk_paths.append(file_path)
  7774. if library_file.thumbnail_path:
  7775. thumb_path = Path(library_file.thumbnail_path)
  7776. if not thumb_path.is_absolute():
  7777. thumb_path = settings.base_dir / library_file.thumbnail_path
  7778. cleanup_disk_paths.append(thumb_path)
  7779. # Before the delete, not after: on PostgreSQL the FK
  7780. # cascade would already have taken these rows (#2819).
  7781. await self._repoint_siblings_at_archive(
  7782. db,
  7783. consumed_library_file_id=consumed_library_file_id,
  7784. archive_id=archive.id,
  7785. dispatched_item_id=item.id,
  7786. )
  7787. # Read while the row is still here; the photos move
  7788. # below, once the delete has actually committed.
  7789. consumed_photos = list(library_file.photos or [])
  7790. # The delete clears the link on the earlier archives of
  7791. # this file (ON DELETE SET NULL; core/sqlite_fk on
  7792. # SQLite). This one is loaded, so set it here too, or it
  7793. # keeps the stale id in the session.
  7794. archive.library_file_id = None
  7795. await db.delete(library_file)
  7796. file_path = settings.base_dir / archive.file_path
  7797. filename = archive.filename
  7798. # Commit, not flush — flush opens the SQLite write
  7799. # transaction (item.archive_id update + library_file
  7800. # delete) and would hold the WAL writer lock through the
  7801. # FTP upload below, causing "database is locked" cascades
  7802. # for sensor history + concurrent cancels (#1853).
  7803. await db.commit()
  7804. logger.info(
  7805. "Queue item %s: Created archive %s from library file %s",
  7806. item.id,
  7807. archive.id,
  7808. source_library_file_id,
  7809. )
  7810. except Exception as e:
  7811. logger.warning(
  7812. "Queue item %s: Failed to create archive from library file: %s",
  7813. queue_item_id,
  7814. e,
  7815. exc_info=True,
  7816. )
  7817. await db.rollback()
  7818. item = await db.get(PrintQueueItem, queue_item_id)
  7819. if item:
  7820. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7821. return
  7822. await self._power_off_if_needed(db, item)
  7823. return
  7824. if not archive:
  7825. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7826. return
  7827. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7828. await self._power_off_if_needed(db, item)
  7829. return
  7830. # The photos follow the file into the archive that replaces it, for
  7831. # the same reason the siblings do (#3077). After the commit above,
  7832. # never before it: that commit can fail ("database is locked",
  7833. # #1853) and roll the library row back, and photos already moved
  7834. # would leave it naming a directory that no longer exists. The
  7835. # file and thumbnail unlinks are deferred for the same reason.
  7836. if consumed_library_file_id is not None and consumed_photos:
  7837. # Held as a plain int, read here while the session is still
  7838. # healthy, because the handler below may not touch an ORM
  7839. # instance at all. The commit it exists for fails inside the
  7840. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7841. # first DML statement, so a busy writer surfaces as "database
  7842. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7843. # internally through safe_reraise before re-raising, which
  7844. # expires every loaded instance and leaves the session in
  7845. # pending-rollback state -- so `archive.id` inside the except
  7846. # would itself raise PendingRollbackError and the rollback
  7847. # below would never be reached.
  7848. archive_id = archive.id
  7849. try:
  7850. carried_photos = move_library_photos(
  7851. consumed_library_file_id,
  7852. consumed_photos,
  7853. archive_photos_dir(archive),
  7854. )
  7855. if carried_photos:
  7856. archive.photos = list(archive.photos or []) + carried_photos
  7857. await db.commit()
  7858. except Exception as e:
  7859. # The archive and the delete are already committed; the
  7860. # print goes ahead either way. Worst case the pictures sit
  7861. # unnamed in the archive's own directory.
  7862. #
  7863. # Ints only until the rollback has run, per the note above,
  7864. # which is why this logs queue_item_id and not item.id --
  7865. # the sibling handler forty lines up does the same.
  7866. logger.warning(
  7867. "Queue item %s: failed to carry library photos into archive %s: %s",
  7868. queue_item_id,
  7869. archive_id,
  7870. e,
  7871. )
  7872. await db.rollback()
  7873. # rollback() expires every loaded instance, and in async
  7874. # SQLAlchemy the next plain attribute read is lazy IO
  7875. # outside the greenlet -- MissingGreenlet, which would turn
  7876. # this cosmetic failure into a dispatch crash in exactly the
  7877. # "database is locked" case the block exists for (#1853).
  7878. # The nozzle guard, the upload and the start all keep
  7879. # reading item, archive and printer, so all three go back
  7880. # into the session before falling through.
  7881. item = await db.get(PrintQueueItem, queue_item_id)
  7882. archive = await db.get(PrintArchive, archive_id)
  7883. printer = await db.get(Printer, item.printer_id) if item else None
  7884. if not item or not archive or not printer:
  7885. logger.error(
  7886. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7887. queue_item_id,
  7888. archive_id,
  7889. )
  7890. return
  7891. else:
  7892. # Neither archive nor library file specified
  7893. if not await self._fail_dispatch(db, item, "No source file specified"):
  7894. return
  7895. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7896. await self._power_off_if_needed(db, item)
  7897. return
  7898. # Check file exists on disk
  7899. if not file_path.exists():
  7900. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  7901. return
  7902. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7903. await self._power_off_if_needed(db, item)
  7904. return
  7905. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7906. # size dispatched to a printer with a different nozzle installed is
  7907. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7908. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7909. # gives the user no idea what went wrong. Catch it here, before we spend
  7910. # time preheating and uploading, and fail with an actionable message.
  7911. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7912. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7913. # the printer hasn't reported its nozzles yet, we fall through and let the
  7914. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7915. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7916. # as one of the two hotends is a 0.6.
  7917. #
  7918. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7919. # (#2885): the printer fetches one as part of starting the print, so the
  7920. # set to test against is "reachable", not "currently mounted". This runs
  7921. # well before the rack picker at the bottom of this method, so without
  7922. # the rack in scope here that picker never got the chance to run.
  7923. sliced_nozzle = archive.nozzle_diameter if archive else None
  7924. if sliced_nozzle:
  7925. nozzle_status = printer_manager.get_status(item.printer_id)
  7926. installed = _installed_nozzle_diameters(nozzle_status)
  7927. rack = _rack_nozzle_diameters(nozzle_status)
  7928. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7929. if mismatch_msg:
  7930. if not await self._fail_dispatch(db, item, mismatch_msg):
  7931. return
  7932. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7933. await notification_service.on_queue_job_failed(
  7934. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7935. printer_id=printer.id,
  7936. printer_name=printer.name,
  7937. reason=mismatch_msg,
  7938. db=db,
  7939. )
  7940. try:
  7941. await ws_manager.send_queue_item_failed(
  7942. user_id=item.created_by_id,
  7943. queue_item_id=item.id,
  7944. printer_id=item.printer_id,
  7945. reason="nozzle_mismatch",
  7946. )
  7947. except Exception:
  7948. pass
  7949. await self._power_off_if_needed(db, item)
  7950. return
  7951. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7952. # bed (and chamber, if applicable) is at temperature when the firmware
  7953. # starts the actual print routine. Best-effort: any failure logs and
  7954. # falls through to the normal upload+start path rather than turning a
  7955. # configuration issue into a failed queue item.
  7956. # Returns False only when the item was cancelled or deleted while the
  7957. # stage was holding at temperature. Uploading and starting it anyway
  7958. # would print a job the user has already called off, so abandon the
  7959. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7960. if not await self._preheat_and_soak(db, item, printer, archive):
  7961. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7962. return
  7963. # See `_effective_plate_id` for why this is resolved once here rather
  7964. # than each site below repeating `item.plate_id or 1`.
  7965. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7966. # G-code injection for auto-print systems (#422)
  7967. injected_path = None
  7968. # #2547: tracked separately from `injected_path`, which is also set when
  7969. # only a START snippet was injected. Only an END snippet changes what the
  7970. # camera sees at print completion.
  7971. end_gcode_injected = False
  7972. if item.gcode_injection:
  7973. try:
  7974. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7975. if snippets_raw:
  7976. snippets = json.loads(snippets_raw)
  7977. model_snippets = snippets.get(printer.model, {})
  7978. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7979. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7980. if start_gc or end_gc:
  7981. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7982. injected_path = inject_gcode_into_3mf(
  7983. file_path, effective_plate_id, start_gc or None, end_gc or None
  7984. )
  7985. if injected_path:
  7986. file_path = injected_path
  7987. end_gcode_injected = bool(end_gc)
  7988. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7989. else:
  7990. logger.warning(
  7991. "Queue item %s: G-code injection returned no result, using original", item.id
  7992. )
  7993. except Exception as e:
  7994. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7995. # #2547: the finish-photo path can't learn from telemetry that this print
  7996. # ends with user End G-code — which means the plate may be gone by the
  7997. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7998. # the print once the printer confirms it running.
  7999. if end_gcode_injected:
  8000. print_dispatch_context.mark_pending(printer.id)
  8001. # Upload to root directory (not /cache/) - the start_print command references
  8002. # files by name only (ftp://{filename}), so they must be in the root
  8003. remote_filename = derive_remote_filename(filename)
  8004. remote_path = f"/{remote_filename}"
  8005. # Get FTP retry settings
  8006. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8007. logger.info(
  8008. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8009. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8010. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8011. )
  8012. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8013. # Every read this method needs (printer, archive/library, preheat) is
  8014. # done, and the library-file branch already committed its archive
  8015. # creation. Without this the transaction opened by the first SELECT above
  8016. # stays "idle in transaction" for the entire upload — multiple seconds
  8017. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8018. # a farm dispatching many jobs at once then exhausts the pool. This was
  8019. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8020. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8021. # readable; the status writes below (upload-failure path and the
  8022. # pending->printing CAS) transparently open a fresh transaction.
  8023. # The owner is read here, after preheat, so the commit releases this read too.
  8024. toast_uid = await self._queue_owner_id(db, item)
  8025. await db.commit()
  8026. # Delete existing file if present (avoids 553 error on overwrite)
  8027. try:
  8028. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8029. delete_result = await delete_file_async(
  8030. printer.ip_address,
  8031. printer.access_code,
  8032. remote_path,
  8033. socket_timeout=ftp_timeout,
  8034. printer_model=printer.model,
  8035. # This delete and the upload below are one bounded, user-initiated
  8036. # unit -- at most nine connections -- so neither skips on the
  8037. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8038. # trace this delete took the TLS failure and armed the cool-off,
  8039. # and the upload's four attempts were then spent against it
  8040. # without a socket being opened.
  8041. respect_handshake_cooloff=False,
  8042. )
  8043. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8044. except Exception as e:
  8045. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8046. # Dispatch toast — announce the upload start with the total byte
  8047. # count so the frontend can render an honest progress bar.
  8048. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8049. try:
  8050. total_bytes = file_path.stat().st_size
  8051. except OSError:
  8052. total_bytes = 0
  8053. try:
  8054. await ws_manager.send_queue_item_uploading(
  8055. user_id=toast_uid,
  8056. queue_item_id=item.id,
  8057. printer_id=item.printer_id,
  8058. printer_name=printer.name,
  8059. file_name=toast_file_name,
  8060. total_bytes=total_bytes,
  8061. )
  8062. except Exception:
  8063. pass # toast is best-effort
  8064. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8065. # A deadline expiry gets its own message: "check your SD card" is the
  8066. # wrong advice for a link that was simply too slow to finish (#2529).
  8067. upload_error: str | None = None
  8068. # Why the upload failed, straight from the client rather than inferred.
  8069. # Owned here, so a background fetch for another print cannot overwrite
  8070. # it between the failure and the sentence built from it (#2899).
  8071. upload_failure = FtpFailureReport()
  8072. try:
  8073. if ftp_retry_enabled:
  8074. uploaded = await with_ftp_retry(
  8075. upload_file_async,
  8076. printer.ip_address,
  8077. printer.access_code,
  8078. file_path,
  8079. remote_path,
  8080. socket_timeout=ftp_timeout,
  8081. printer_model=printer.model,
  8082. progress_callback=progress_bridge,
  8083. respect_handshake_cooloff=False,
  8084. failure=upload_failure,
  8085. max_retries=ftp_retry_count,
  8086. retry_delay=ftp_retry_delay,
  8087. operation_name=f"Upload print to {printer.name}",
  8088. )
  8089. else:
  8090. uploaded = await upload_file_async(
  8091. printer.ip_address,
  8092. printer.access_code,
  8093. file_path,
  8094. remote_path,
  8095. socket_timeout=ftp_timeout,
  8096. printer_model=printer.model,
  8097. progress_callback=progress_bridge,
  8098. respect_handshake_cooloff=False,
  8099. failure=upload_failure,
  8100. )
  8101. except UploadCancelled as e:
  8102. uploaded = False
  8103. upload_error = (
  8104. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8105. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8106. )
  8107. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8108. except Exception as e:
  8109. uploaded = False
  8110. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8111. # Clean up injected temp file after upload attempt
  8112. if injected_path and injected_path.exists():
  8113. injected_path.unlink(missing_ok=True)
  8114. # Again after the upload, which can take minutes: an owner deleted
  8115. # meanwhile gets no more toasts, and neither does whoever has their id.
  8116. toast_uid = await self._queue_owner_id(db, item)
  8117. # The printer's copy at this path was replaced (or deleted above): the
  8118. # file browser's previews must not show the old one.
  8119. from backend.app.services.printer_file_cache import printer_file_cache
  8120. printer_file_cache.forget(printer.id, remote_path)
  8121. if not uploaded:
  8122. # This used to be one string for every upload failure, telling
  8123. # everyone to check the SD card. The client knows which of seven
  8124. # things went wrong and logs each one differently; it just had no
  8125. # way to say so here, so the card got named even for a TLS
  8126. # handshake that never reached the printer's filesystem (#2899).
  8127. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8128. failure = upload_failure.failure
  8129. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8130. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  8131. return
  8132. if not await self._fail_dispatch(db, item, error_msg):
  8133. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8134. return
  8135. logger.error(
  8136. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8137. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8138. )
  8139. # Send failure notification
  8140. await notification_service.on_queue_job_failed(
  8141. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8142. printer_id=printer.id,
  8143. printer_name=printer.name,
  8144. # The same sentence the queue shows. A push notification saying
  8145. # something different from the UI is its own small bug (#2899).
  8146. reason=error_msg,
  8147. db=db,
  8148. )
  8149. try:
  8150. await ws_manager.send_queue_item_failed(
  8151. user_id=toast_uid,
  8152. queue_item_id=item.id,
  8153. printer_id=item.printer_id,
  8154. reason="upload_failed",
  8155. )
  8156. except Exception:
  8157. pass
  8158. await self._power_off_if_needed(db, item)
  8159. return
  8160. # The printer took a file, so any run of refused uploads is over: the
  8161. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8162. self._upload_refusals.pop(printer.id, None)
  8163. self._upload_refusal_notified.discard(printer.id)
  8164. # Parse AMS mapping if stored
  8165. ams_mapping = None
  8166. if item.ams_mapping:
  8167. try:
  8168. ams_mapping = json.loads(item.ams_mapping)
  8169. except json.JSONDecodeError:
  8170. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8171. # Register as expected print so we don't create a duplicate archive
  8172. # Only applicable for archive-based prints
  8173. if archive:
  8174. from backend.app.main import register_expected_print
  8175. register_expected_print(
  8176. item.printer_id,
  8177. remote_filename,
  8178. archive.id,
  8179. ams_mapping=ams_mapping,
  8180. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8181. # no print-start email, and neither does whoever has their id.
  8182. created_by_id=toast_uid,
  8183. cost_center_id=item.cost_center_id,
  8184. # The plate actually dispatched, not the queue item's raw
  8185. # column: on None, `register_expected_print` stores nothing,
  8186. # and `extract_filament_usage_from_3mf` then books every
  8187. # filament in the file rather than the one plate that printed.
  8188. plate_id=effective_plate_id,
  8189. )
  8190. # Registration happens before the print command by necessity (the
  8191. # printer can report the print before the send returns), so record
  8192. # what to undo if we never get as far as sending. `_dispatch_one`
  8193. # rolls back anything still pending here on every exit — exception,
  8194. # early return, or cancel winning the CAS below.
  8195. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8196. # Propagate the queue item's owner into printer_manager so the
  8197. # print-complete callback can credit the user in the PrintLogEntry
  8198. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8199. # items) or when the user clicks the manual-start button.
  8200. await self._propagate_owner_to_printer_manager(db, item)
  8201. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8202. # This prevents phantom reprints if the backend crashes/restarts after the
  8203. # print command is sent but before the status update is committed.
  8204. # If we crash after this commit but before start_print(), the item will be
  8205. # in "printing" status without actually printing - but that's safer than
  8206. # accidentally reprinting the same file hours later.
  8207. #
  8208. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8209. # initial pending read at the top of check_queue and this point) flips
  8210. # the row to "cancelled" in a separate session. Without the WHERE
  8211. # status='pending' clause, the unconditional update here would silently
  8212. # overwrite that cancellation and we'd ship the MQTT start_print below
  8213. # — printer obeys, user sees "I pressed cancel and the print started".
  8214. # rowcount==0 means the user won the race; bail out, best-effort delete
  8215. # the file we just uploaded, do NOT send start_print.
  8216. now_utc = datetime.now(timezone.utc)
  8217. billing_run_id = str(uuid.uuid4())
  8218. cas = await db.execute(
  8219. update(PrintQueueItem)
  8220. .where(PrintQueueItem.id == item.id)
  8221. .where(PrintQueueItem.status == "pending")
  8222. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  8223. )
  8224. await db.commit()
  8225. if cas.rowcount == 0:
  8226. logger.info(
  8227. "Queue item %s no longer pending at print-command time "
  8228. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8229. item.id,
  8230. )
  8231. try:
  8232. await delete_file_async(
  8233. printer.ip_address,
  8234. printer.access_code,
  8235. remote_path,
  8236. socket_timeout=ftp_timeout,
  8237. printer_model=printer.model,
  8238. )
  8239. except Exception as cleanup_err:
  8240. logger.debug(
  8241. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8242. item.id,
  8243. cleanup_err,
  8244. )
  8245. try:
  8246. await ws_manager.send_queue_item_failed(
  8247. user_id=toast_uid,
  8248. queue_item_id=item.id,
  8249. printer_id=item.printer_id,
  8250. reason="cancelled_mid_dispatch",
  8251. )
  8252. except Exception:
  8253. pass
  8254. return
  8255. # Sync the in-memory item so subsequent code that reads item.status /
  8256. # item.started_at sees the values we just persisted.
  8257. item.status = "printing"
  8258. item.started_at = now_utc
  8259. item.billing_run_id = billing_run_id
  8260. if archive is not None:
  8261. archive.billing_run_id = billing_run_id
  8262. # Legacy transaction deletion used an archive-wide skip flag.
  8263. # A newly dispatched run has its own UUID/tombstone, so it must be
  8264. # billable independently of any older deleted run on this archive.
  8265. archive.wallet_charge_skipped = False
  8266. # Persist before MQTT send so completion and restart recovery can
  8267. # always recover the internal billing identity.
  8268. await db.commit()
  8269. for cleanup_path in cleanup_disk_paths:
  8270. try:
  8271. if cleanup_path.exists():
  8272. cleanup_path.unlink()
  8273. except OSError as cleanup_err:
  8274. logger.warning(
  8275. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8276. json.dumps(
  8277. {
  8278. "queue_item_id": item.id,
  8279. "path": str(cleanup_path),
  8280. "error": str(cleanup_err),
  8281. },
  8282. sort_keys=True,
  8283. ),
  8284. )
  8285. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8286. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8287. # #1898: with the opt-in default-good setting, moving on to the next
  8288. # print resolves the previous print's unanswered outcome prompt as
  8289. # "good" — this path also covers the camera-based plate detection,
  8290. # which releases the gate by allowing dispatch rather than by an
  8291. # explicit acknowledgment. Rides on the dispatch transaction.
  8292. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8293. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8294. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8295. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8296. # Capture state before dispatch so the watchdog can detect whether the
  8297. # printer actually transitioned (#967). Also capture subtask_id so the
  8298. # watchdog can recognise "command landed but state hasn't flipped yet"
  8299. # on slow H2D transitions (#1078).
  8300. pre_status = printer_manager.get_status(item.printer_id)
  8301. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8302. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8303. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8304. # #1721: respect the user's explicit timelapse choice. The #1397
  8305. # force-on at dispatch was removed because it caused per-layer nozzle
  8306. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8307. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8308. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8309. # FINISH-state fallback — no need to force a video.
  8310. effective_timelapse = bool(item.timelapse)
  8311. # Nozzle-rack fallback (#2800). A job that never passed through the
  8312. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8313. # dispatches with no nozzle field at all and chooses for itself — which
  8314. # is how a print levelled on one hotend and then printed on another,
  8315. # millimetres above the plate. Derive the per-slot extruder assignment
  8316. # from the file being dispatched.
  8317. #
  8318. # Done here rather than at queue time because this is the first point
  8319. # that knows both the actual printer and the actual file: an item can
  8320. # be created without a printer (model-based assignment), reassigned
  8321. # afterwards, or have its file swapped for a G-code-injected copy just
  8322. # above. Every queue-creation path — the print dialog, a bulk library
  8323. # add, the webhook, a pipeline run — is covered by the one call.
  8324. # Skipped when the item already carries a Bambu Studio capture: that
  8325. # one wins downstream anyway, so reading the 3MF again would be work
  8326. # thrown away on every dispatch.
  8327. # Rack position resolution (#1784), tried before the #2800 fallback
  8328. # below because it can express what that one cannot: a plate wanting a
  8329. # *different* hotend off the rack per filament group. The position per
  8330. # group is the operator's pick — the 3MF states it nowhere, proven by
  8331. # sending one plate twice with different picks and finding the two
  8332. # files identical bar float noise — so it is resolved here against the
  8333. # rack as it stands right now, after the upload, not at queue time.
  8334. resolved_nozzle_mapping = None
  8335. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8336. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8337. if rack_plan is not None:
  8338. try:
  8339. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8340. except (json.JSONDecodeError, TypeError):
  8341. stored_choice = {}
  8342. logger.warning(
  8343. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8344. item.id,
  8345. item.nozzle_rack_choice,
  8346. )
  8347. # JSON object keys are strings; the groups are ints.
  8348. choice: dict[int, int] = {}
  8349. for key, value in (stored_choice or {}).items():
  8350. try:
  8351. choice[int(key)] = int(value)
  8352. except (TypeError, ValueError):
  8353. continue
  8354. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8355. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8356. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8357. )
  8358. if resolved_nozzle_mapping is None and choice:
  8359. # An explicit pick that no longer holds stops the print. The
  8360. # operator named a hotend; printing from a different one is
  8361. # how a plate gets levelled on one nozzle and drawn with
  8362. # another, millimetres above the bed. Nothing has been sent
  8363. # to the printer yet, so failing here costs only the upload.
  8364. # The file is already on the SD card by this point, and a
  8365. # 3MF left there is a phantom print waiting to be started
  8366. # from the touchscreen. Same cleanup the start_print
  8367. # failure path below does, for the same reason.
  8368. try:
  8369. await delete_file_async(
  8370. printer.ip_address,
  8371. printer.access_code,
  8372. remote_path,
  8373. printer_model=printer.model,
  8374. )
  8375. except Exception:
  8376. pass # Best-effort — don't fail the error handler
  8377. if not await self._fail_dispatch(
  8378. db,
  8379. item,
  8380. (
  8381. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8382. "Edit the item to choose another position."
  8383. ),
  8384. ):
  8385. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8386. return
  8387. logger.warning(
  8388. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8389. item.id,
  8390. printer.name,
  8391. rack_error,
  8392. choice,
  8393. [slot.get("id") for slot in live_rack],
  8394. )
  8395. await notification_service.on_queue_job_failed(
  8396. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8397. printer_id=printer.id,
  8398. printer_name=printer.name,
  8399. reason=item.error_message,
  8400. db=db,
  8401. )
  8402. try:
  8403. await ws_manager.send_queue_item_failed(
  8404. user_id=toast_uid,
  8405. queue_item_id=item.id,
  8406. printer_id=item.printer_id,
  8407. reason="nozzle_rack_pick_stale",
  8408. )
  8409. except Exception:
  8410. pass # Best-effort — don't fail the error handler
  8411. return
  8412. if resolved_nozzle_mapping is None:
  8413. # Nothing was picked and nothing could be assigned. Falls
  8414. # through to the #2800 path, which is what ran before this
  8415. # existed — strictly not worse than today.
  8416. logger.info(
  8417. "Queue item %s: no rack positions assignable (%s); falling back",
  8418. item.id,
  8419. rack_error,
  8420. )
  8421. else:
  8422. logger.info(
  8423. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8424. item.id,
  8425. resolved_nozzle_mapping,
  8426. rack_plan.slot_groups,
  8427. choice or "auto",
  8428. )
  8429. nozzle_slot_extruders = None
  8430. if (
  8431. not item.nozzle_mapping
  8432. and resolved_nozzle_mapping is None
  8433. and file_path is not None
  8434. and is_nozzle_rack_model(printer.model)
  8435. ):
  8436. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8437. if slot_extruders:
  8438. nozzle_slot_extruders = json.dumps(slot_extruders)
  8439. # Every filament this plate prints is on the external spool -> the print
  8440. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8441. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8442. # table", which is what held the reporter's P1S at Heatbed preheating
  8443. # for ten minutes before it gave up (#3087). The MQTT command builder
  8444. # already downgrades a mapping that is *only* external ([254]), but a
  8445. # multi-filament project pads the slots this plate does not print with
  8446. # -1 — BambuStudio's own convention — and down there a -1 is
  8447. # indistinguishable from a slot that never resolved, which must never be
  8448. # sent to the spool holder (#2589). Here the plate's filament list says
  8449. # which is which, so the answer is exact rather than a guess.
  8450. #
  8451. # Deliberately narrow: this fires only when every consumed slot is an
  8452. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8453. # alone and the firmware still rejects the print, exactly as today. And
  8454. # only for single-nozzle printers, mirroring the builder's own reconcile
  8455. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8456. # whether to use the AMS, so it is not ours to rewrite.
  8457. effective_use_ams = item.use_ams
  8458. plate_uses_only_external = False
  8459. if (
  8460. ams_mapping
  8461. and file_path is not None
  8462. # Cheap gate before opening the file: with nothing on the spool
  8463. # holder anywhere in the mapping, no subset of it can be all
  8464. # external, so most dispatches never pay for the parse. The
  8465. # isinstance also keeps a malformed stored mapping (a bare number
  8466. # from a hand-edited row) failing where it always failed, in the
  8467. # command builder, rather than here.
  8468. and isinstance(ams_mapping, list)
  8469. and any(_is_external_tray(t) for t in ams_mapping)
  8470. and not _might_be_dual_nozzle(printer.model, pre_status)
  8471. ):
  8472. from backend.app.services.filament_requirements import extract_filament_requirements
  8473. consumed = _consumed_mapping_entries(
  8474. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8475. )
  8476. if consumed and all(_is_external_tray(t) for t in consumed):
  8477. # Exact for this plate: the command builder must not turn the
  8478. # AMS back on for a real tray another plate of the file uses,
  8479. # whether the job asked for the AMS or already had it off.
  8480. plate_uses_only_external = True
  8481. if plate_uses_only_external and effective_use_ams:
  8482. effective_use_ams = False
  8483. logger.info(
  8484. "Queue item %s: every filament plate %s prints is on the external spool "
  8485. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8486. item.id,
  8487. effective_plate_id,
  8488. ams_mapping,
  8489. )
  8490. # A slot that lost its K-profile selection (a power cycle resets every
  8491. # slot to the default K) would print on the default. The idle check in
  8492. # the status handler normally restores it first, but nothing guarantees
  8493. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8494. # Never allowed to stop the print it is protecting.
  8495. try:
  8496. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8497. except Exception:
  8498. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8499. # Start the print with AMS mapping, plate_id and print options.
  8500. # nozzle_mapping rides through verbatim — JSON string captured from
  8501. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8502. # parses + injects it only for dual-nozzle models so a null on every
  8503. # other model is a transparent pass-through. The rack fallback is
  8504. # resolved down there too, where the live rack position is known.
  8505. started = printer_manager.start_print(
  8506. item.printer_id,
  8507. remote_filename,
  8508. plate_id=effective_plate_id,
  8509. ams_mapping=ams_mapping,
  8510. bed_levelling=item.bed_levelling,
  8511. flow_cali=item.flow_cali,
  8512. vibration_cali=item.vibration_cali,
  8513. layer_inspect=item.layer_inspect,
  8514. timelapse=effective_timelapse,
  8515. use_ams=effective_use_ams,
  8516. plate_uses_only_external=plate_uses_only_external,
  8517. nozzle_offset_cali=item.nozzle_offset_cali,
  8518. nozzle_mapping=item.nozzle_mapping
  8519. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8520. nozzle_slot_extruders=nozzle_slot_extruders,
  8521. )
  8522. if started:
  8523. # The command is away, so the expectation is now legitimate and must
  8524. # survive. Anything still in this dict when _dispatch_one exits gets
  8525. # rolled back.
  8526. self._unconfirmed_expected_print.pop(item.id, None)
  8527. self._unconfirmed_budget_reservations.discard(item.id)
  8528. self._unconfirmed_print_user.pop(item.id, None)
  8529. if item.printer_id is not None:
  8530. self._sent_unstarted_print[item.id] = (
  8531. item.printer_id,
  8532. remote_filename if archive else None,
  8533. archive.id if archive else None,
  8534. )
  8535. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8536. # target, chamber target, airduct heating) — the gcode owns
  8537. # heater/flap control from here. Clearing the pin prevents
  8538. # `_dispatch_one`'s finally from unwinding a live print.
  8539. self._preheat_pin.pop(item.printer_id, None)
  8540. self._preheat_pin_bed.pop(item.printer_id, None)
  8541. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8542. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8543. # status='processing' from upload start until the printer acked
  8544. # (or timed out). The frontend derives "Awaiting printer…" purely
  8545. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8546. # event would push the status chip out of 'PROCESSING' prematurely
  8547. # — which is exactly what the screenshot at #1625-followup
  8548. # complained about.
  8549. # Register the local 3MF in the cover-cache so /cover skips FTP
  8550. # (#1166 follow-up). file_path was resolved earlier from either the
  8551. # archive or the library file row.
  8552. if file_path is not None:
  8553. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8554. # Hold the printer against further dispatches until the watchdog
  8555. # confirms the printer transitioned (or until the hard timeout).
  8556. # Prevents multi-plate batches from triple-dispatching onto the
  8557. # same H2D Pro while it digests the first project_file (#1157).
  8558. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8559. # Watchdog: if the printer never transitions out of pre_state AND
  8560. # never advances subtask_id, the MQTT publish was accepted locally but
  8561. # didn't reach the printer (half-broken session — same shape as
  8562. # #887/#936). Revert the queue item so the next dispatch can pick it
  8563. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8564. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8565. # that would otherwise cause the item to re-dispatch as a reprint
  8566. # of the just-finished job (#1078).
  8567. if pre_state:
  8568. spawn_background_task(
  8569. self._watchdog_print_start(
  8570. item.id,
  8571. item.printer_id,
  8572. pre_state,
  8573. pre_subtask_id,
  8574. pre_gcode_file,
  8575. created_by_id=toast_uid,
  8576. ),
  8577. name=f"watchdog-print-start-{item.id}",
  8578. )
  8579. # Get estimated time for notification.
  8580. #
  8581. # This used to fall back to `library_file.print_time_seconds`, a column
  8582. # LibraryFile does not have — the print time it knows about lives in
  8583. # `file_metadata`. So a library print whose archive carried no parseable
  8584. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8585. # AttributeError right here, *after* the printer had already been sent
  8586. # the job: the started-notification never fired, and the exception
  8587. # unwound the whole queue pass, so every other printer still waiting to
  8588. # be dispatched on that tick silently missed its turn.
  8589. #
  8590. # The queue item caches the print time at creation ("Cached from
  8591. # archive/library"), which is the value this was reaching for.
  8592. estimated_time = None
  8593. if archive and archive.print_time_seconds:
  8594. estimated_time = archive.print_time_seconds
  8595. elif item.print_time_seconds:
  8596. estimated_time = item.print_time_seconds
  8597. # Send job started notification
  8598. await notification_service.on_queue_job_started(
  8599. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8600. printer_id=printer.id,
  8601. printer_name=printer.name,
  8602. db=db,
  8603. estimated_time=estimated_time,
  8604. )
  8605. # MQTT relay - publish queue job started
  8606. try:
  8607. await mqtt_relay.on_queue_job_started(
  8608. job_id=item.id,
  8609. filename=filename,
  8610. printer_id=printer.id,
  8611. printer_name=printer.name,
  8612. printer_serial=printer.serial_number,
  8613. )
  8614. except Exception:
  8615. pass # Don't fail if MQTT fails
  8616. else:
  8617. # Clean up uploaded file from SD card to prevent phantom prints
  8618. try:
  8619. await delete_file_async(
  8620. printer.ip_address,
  8621. printer.access_code,
  8622. remote_path,
  8623. printer_model=printer.model,
  8624. )
  8625. except Exception:
  8626. pass # Best-effort — don't fail the error handler
  8627. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8628. # state can flip from idle to active in the window between the
  8629. # pre-dispatch check above and this publish (the FTP upload takes
  8630. # seconds); start_print() then refuses to send project_file to the
  8631. # now-busy printer and returns False. Failing the item here would be
  8632. # wrong — the printer is fine, it is simply busy — so revert to
  8633. # pending and let a later tick dispatch it once the printer is idle,
  8634. # exactly like the pre-dispatch guard. Only a start_print() False on
  8635. # an idle/unknown printer is a genuine command failure.
  8636. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8637. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8638. logger.info(
  8639. "Queue item %s: printer %s became busy (state=%s) before the start "
  8640. "command was sent — deferring, reverting item to pending (#2598)",
  8641. item.id,
  8642. item.printer_id,
  8643. post_dispatch_state,
  8644. )
  8645. await self._defer_until_printer_idle(db, item)
  8646. return
  8647. # Print command failed - revert status
  8648. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8649. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8650. return
  8651. logger.error(
  8652. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8653. f"printer_manager.start_print() returned False. "
  8654. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8655. f"Check printer status and backend logs for details."
  8656. )
  8657. # Send failure notification
  8658. await notification_service.on_queue_job_failed(
  8659. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8660. printer_id=printer.id,
  8661. printer_name=printer.name,
  8662. reason="Failed to send print command to printer - check printer connection and status",
  8663. db=db,
  8664. )
  8665. try:
  8666. await ws_manager.send_queue_item_failed(
  8667. user_id=toast_uid,
  8668. queue_item_id=item.id,
  8669. printer_id=item.printer_id,
  8670. reason="start_command_failed",
  8671. )
  8672. except Exception:
  8673. pass
  8674. await self._power_off_if_needed(db, item)
  8675. @staticmethod
  8676. async def _watchdog_print_start(
  8677. queue_item_id: int,
  8678. printer_id: int,
  8679. pre_state: str,
  8680. pre_subtask_id: str | None = None,
  8681. pre_gcode_file: str | None = None,
  8682. timeout: float = 90.0,
  8683. phase_b_timeout: float = 180.0,
  8684. poll_interval: float = 3.0,
  8685. created_by_id: int | None = None,
  8686. ) -> None:
  8687. """Revert a queue item if the printer never acknowledges the start command.
  8688. Bambuddy optimistically marks the queue item as "printing" right after the
  8689. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8690. Phase A (up to ``timeout``): wait for either an active-state transition
  8691. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8692. primary signal; subtask_id advance handles the H2D case where state can
  8693. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8694. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8695. was lost on a half-broken session (#887/#936) — revert and force
  8696. reconnect (the #967 recovery path).
  8697. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8698. alone): keep watching for the active-state transition. subtask_id alone
  8699. proves the file landed but not that the printer started — and a printer
  8700. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8701. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8702. used to leave the queue item stuck in 'printing' forever because the
  8703. old watchdog returned success as soon as subtask_id advanced. If Phase
  8704. B times out, revert the queue item so the user can retry without
  8705. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8706. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8707. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8708. transitions that also don't emit an early subtask_id tick.
  8709. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8710. refuses to verify our commands will never start this job or any other,
  8711. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8712. burns an upload slot the rest of the farm is queued behind — that path
  8713. is for a printer that might still come good, which this one cannot
  8714. (#2732). It fails the item on the spot with the actual reason instead.
  8715. """
  8716. last_status = None
  8717. landed_on_subtask = False
  8718. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8719. # every push carrying an `hms` key, so the fault can come and go between
  8720. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8721. command_rejected = False
  8722. # Latched for the same reason as command_rejected: drying can finish, or
  8723. # be stopped by the user, part-way through the dispatch window. Seeing it
  8724. # once is what matters — it is the state the printer was in when it
  8725. # declined to start (#2758).
  8726. drying_ams_ids: list[int] = []
  8727. # The printer answered the start with a refusal: nothing will start,
  8728. # and the command was not lost, so no reconnect either.
  8729. start_refusal: tuple[str, str | None] | None = None
  8730. deadline = time.monotonic() + timeout
  8731. while time.monotonic() < deadline:
  8732. await asyncio.sleep(poll_interval)
  8733. status = printer_manager.get_status(printer_id)
  8734. if not status:
  8735. # Printer disconnected — don't mess with the DB. Drop the
  8736. # in-memory dispatch hold too so a fresh dispatch can retry
  8737. # once the printer comes back; the hard timeout would
  8738. # otherwise hold the printer unnecessarily.
  8739. scheduler._release_dispatch_hold(printer_id)
  8740. return
  8741. last_status = status
  8742. if status.state in _ACTIVE_PRINT_STATES:
  8743. # Printer is actively processing the job — release the
  8744. # post-dispatch hold so the next pending item for this printer
  8745. # can be evaluated normally. We do NOT accept arbitrary state
  8746. # transitions: a printer going FINISH -> IDLE (user dismissed
  8747. # the post-print prompt without accepting our project_file)
  8748. # would otherwise look like "command landed" and leave the
  8749. # queue item stuck in 'printing' forever (#1370).
  8750. scheduler._release_dispatch_hold(printer_id)
  8751. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8752. try:
  8753. await ws_manager.send_queue_item_acked(
  8754. user_id=created_by_id,
  8755. queue_item_id=queue_item_id,
  8756. printer_id=printer_id,
  8757. )
  8758. except Exception:
  8759. pass
  8760. return
  8761. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8762. # Checked only after the active-state exit above: a stale HMS left
  8763. # over from an earlier job must never abort a print that is visibly
  8764. # running. An actually-refused command leaves the printer idle, so
  8765. # this ordering costs the detection nothing.
  8766. if _mqtt_commands_rejected(status):
  8767. command_rejected = True
  8768. break
  8769. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  8770. if isinstance(refusal, tuple):
  8771. start_refusal = refusal
  8772. break
  8773. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8774. # Phase A exit — printer accepted the file (subtask_id flipped
  8775. # to our submission id). Don't return yet: the printer may
  8776. # have accepted the command but never actually start (e.g.
  8777. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8778. # B watches for the active-state transition.
  8779. landed_on_subtask = True
  8780. break
  8781. if landed_on_subtask and not command_rejected:
  8782. phase_b_deadline = time.monotonic() + phase_b_timeout
  8783. while time.monotonic() < phase_b_deadline:
  8784. await asyncio.sleep(poll_interval)
  8785. status = printer_manager.get_status(printer_id)
  8786. if not status:
  8787. scheduler._release_dispatch_hold(printer_id)
  8788. return
  8789. last_status = status
  8790. if status.state in _ACTIVE_PRINT_STATES:
  8791. scheduler._release_dispatch_hold(printer_id)
  8792. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8793. try:
  8794. await ws_manager.send_queue_item_acked(
  8795. user_id=created_by_id,
  8796. queue_item_id=queue_item_id,
  8797. printer_id=printer_id,
  8798. )
  8799. except Exception:
  8800. pass
  8801. return
  8802. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8803. # Same ordering rule as Phase A: a running print wins over a
  8804. # lingering HMS.
  8805. if _mqtt_commands_rejected(status):
  8806. command_rejected = True
  8807. break
  8808. # No active-state transition. Revert the item so the scheduler can retry.
  8809. # Drop the in-memory hold so the retry isn't blocked by it.
  8810. scheduler._release_dispatch_hold(printer_id)
  8811. # Logged on every failed dispatch window, not just the last one, so a
  8812. # support bundle shows the correlation from the first attempt rather than
  8813. # only after the retry budget is spent (#2758).
  8814. if drying_ams_ids:
  8815. logger.info(
  8816. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8817. queue_item_id,
  8818. printer_id,
  8819. ", ".join(str(i) for i in drying_ams_ids),
  8820. )
  8821. # Four outcomes from the revert attempt, each routed differently:
  8822. # "reverted": row flipped from printing -> pending, run recovery
  8823. # "gave_up": same, but the retry budget is spent — row failed
  8824. # rather than pending, so it stops going round again
  8825. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8826. # on_print_complete or user). Skip recovery entirely
  8827. # — the print clearly landed somewhere even if the
  8828. # watchdog didn't see the active-state transition.
  8829. # "revert_failed": SQLite contention exhausted retries. Still run
  8830. # recovery so the MQTT session gets a fresh client_id
  8831. # on the half-broken-session path.
  8832. #
  8833. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8834. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8835. # the watchdog again. For a printer that is genuinely wedged that loop never
  8836. # ends — the reporter had one printer "since this morning still not launch"
  8837. # — and each lap also consumes an upload slot that the other printers in the
  8838. # farm are waiting on. Retrying is right; retrying forever is not.
  8839. async def _do_revert(db):
  8840. item = await db.get(PrintQueueItem, queue_item_id)
  8841. if not item or item.status != "printing":
  8842. return "already_moved_on"
  8843. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8844. item.started_at = None
  8845. # Charge the attempt to the candidate that was actually dispatched, so
  8846. # a cross-model item (#671) reaches for its other file next lap instead
  8847. # of retrying the printer that just failed to start. Matched by file
  8848. # because that is what the resolver copied onto the row.
  8849. if item.library_file_id is not None:
  8850. await db.execute(
  8851. update(PrintQueueVariant)
  8852. .where(PrintQueueVariant.queue_item_id == item.id)
  8853. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8854. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8855. )
  8856. if command_rejected:
  8857. # No retry budget for this one: the printer refused to verify the
  8858. # command, and re-uploading the same 3MF to the same printer will
  8859. # be refused the same way. Fail now with the fix rather than after
  8860. # three laps of a message about SD cards (#2732).
  8861. item.status = "failed"
  8862. item.error_message = (
  8863. "The printer rejected the print command: MQTT command verification failed "
  8864. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8865. "then start the job again."
  8866. )
  8867. item.completed_at = datetime.now(timezone.utc)
  8868. await db.commit()
  8869. return "command_rejected"
  8870. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8871. item.status = "failed"
  8872. if drying_ams_ids:
  8873. # #2758: the generic message below sent the reporter looking
  8874. # at the SD card while the actual obstacle — AMS units in a
  8875. # drying cycle — was on screen the whole time. Name what we
  8876. # observed and let the user judge it; Bambuddy does not stop
  8877. # the cycle itself, because on this hardware drying can run
  8878. # alongside a print and stopping it may not be the fix.
  8879. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8880. item.error_message = (
  8881. f"The printer accepted the file but never started printing, after "
  8882. f"{item.dispatch_attempts} attempts. {units} "
  8883. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8884. f"some printers refuse to begin a print while an AMS is in a drying "
  8885. f"cycle, and an AMS drying without its external power supply can also "
  8886. f"leave too little power for the start-of-print calibration. Stop the "
  8887. f"drying, or connect the AMS power supply, and start the job again."
  8888. )
  8889. else:
  8890. item.error_message = (
  8891. f"The printer accepted the file but never started printing, after "
  8892. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8893. f"prompt or error, confirm its SD card is readable, and start the job again."
  8894. )
  8895. item.completed_at = datetime.now(timezone.utc)
  8896. await release_budget_reservation(
  8897. db,
  8898. source_type="print_queue",
  8899. source_id=item.id,
  8900. status="released",
  8901. )
  8902. await db.commit()
  8903. return "gave_up"
  8904. item.status = "pending"
  8905. await db.commit()
  8906. return "reverted"
  8907. try:
  8908. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8909. except Exception as e:
  8910. logger.warning(
  8911. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8912. "scheduler may keep treating this item as in-flight",
  8913. queue_item_id,
  8914. printer_id,
  8915. e,
  8916. )
  8917. revert_outcome = "revert_failed"
  8918. if revert_outcome in ("command_rejected", "gave_up"):
  8919. # The item is failed: its print user and expected print must not
  8920. # pass the printer's next print off as Bambuddy's.
  8921. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  8922. from backend.app.services.print_batch import refresh_batches_after
  8923. await refresh_batches_after([queue_item_id])
  8924. elif revert_outcome == "reverted":
  8925. # Another try claims the printer again. Until then no print on it
  8926. # is vouched for as this item's, except a late start of its file.
  8927. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  8928. elif revert_outcome == "already_moved_on":
  8929. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8930. if revert_outcome == "already_moved_on":
  8931. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8932. # other path) already moved the item past 'printing', don't run the
  8933. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8934. # session breaks ongoing prints on the same printer.
  8935. return
  8936. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8937. if revert_outcome == "command_rejected":
  8938. logger.error(
  8939. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8940. "failed) — the print command was rejected, not lost. Failing the item "
  8941. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8942. queue_item_id,
  8943. printer_id,
  8944. HMS_MQTT_VERIFY_FAILED,
  8945. )
  8946. await scheduler._notify_dispatch_gave_up(
  8947. queue_item_id,
  8948. printer_id,
  8949. created_by_id,
  8950. reason="Printer rejected the print command (MQTT command verification failed)",
  8951. )
  8952. # Same reasoning as the landed_on_subtask path below: the file is on
  8953. # the printer and a forced reconnect would only add 0500_4003 to a
  8954. # problem that has nothing to do with the MQTT session (#1150).
  8955. return
  8956. if revert_outcome == "gave_up":
  8957. logger.error(
  8958. "Queue item %s: printer %d never started the print after %d dispatch "
  8959. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8960. "re-uploading it again (#2555)",
  8961. queue_item_id,
  8962. printer_id,
  8963. DISPATCH_MAX_ATTEMPTS,
  8964. total_timeout,
  8965. )
  8966. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8967. elif revert_outcome == "reverted":
  8968. if start_refusal is not None:
  8969. logger.warning(
  8970. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  8971. "reverted to 'pending' for retry",
  8972. queue_item_id,
  8973. printer_id,
  8974. start_refusal[0],
  8975. start_refusal[1],
  8976. )
  8977. elif landed_on_subtask:
  8978. logger.warning(
  8979. "Queue item %s: printer %d accepted project_file (subtask_id "
  8980. "advanced) but never transitioned to an active state within "
  8981. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8982. "for retry (#1678)",
  8983. queue_item_id,
  8984. printer_id,
  8985. total_timeout,
  8986. )
  8987. else:
  8988. logger.warning(
  8989. "Queue item %s: printer %d did not respond to print command within "
  8990. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8991. "for retry (#967)",
  8992. queue_item_id,
  8993. printer_id,
  8994. timeout,
  8995. pre_state,
  8996. pre_subtask_id,
  8997. )
  8998. # Phase B was entered iff subtask_id advanced, which means the
  8999. # project_file landed on the printer. A forced reconnect at this point
  9000. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9001. # skip the recovery entirely.
  9002. if landed_on_subtask or start_refusal is not None:
  9003. return
  9004. # Phase A timeout path: if the printer's gcode_file changed since
  9005. # pre-dispatch, the project_file command landed and the printer is
  9006. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9007. # If gcode_file is unchanged, the publish was silently swallowed
  9008. # (#887/#936) and force_reconnect recovery is what we want.
  9009. client = printer_manager.get_client(printer_id)
  9010. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9011. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9012. if publish_landed:
  9013. logger.warning(
  9014. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9015. "received the command and is parsing slowly. Skipping forced "
  9016. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9017. queue_item_id,
  9018. current_gcode_file,
  9019. pre_gcode_file,
  9020. )
  9021. elif client and hasattr(client, "force_reconnect_stale_session"):
  9022. client.force_reconnect_stale_session(
  9023. f"queue print command unacknowledged after {timeout:.0f}s "
  9024. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9025. )
  9026. # Global scheduler instance
  9027. scheduler = PrintScheduler()