print_scheduler.py 482 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532
  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 fastapi import HTTPException
  14. from sqlalchemy import delete, false, func, or_, select, true, update
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy.orm import selectinload
  17. from backend.app.core.config import settings
  18. from backend.app.core.database import async_session, run_with_retry
  19. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  20. from backend.app.core.tasks import spawn_background_task
  21. from backend.app.core.websocket import ws_manager
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.library import LibraryFile
  24. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  25. from backend.app.models.printer import Printer
  26. from backend.app.models.scheduled_drying import ScheduledDrying
  27. from backend.app.models.settings import Settings
  28. from backend.app.models.smart_plug import SmartPlug
  29. from backend.app.models.spool_assignment import SpoolAssignment
  30. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  31. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  32. from backend.app.services.bambu_ftp import (
  33. FtpFailureKind,
  34. FtpFailureReport,
  35. UploadCancelled,
  36. cache_3mf_download,
  37. delete_file_async,
  38. describe_upload_failure,
  39. get_ftp_retry_settings,
  40. upload_file_async,
  41. with_ftp_retry,
  42. )
  43. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  44. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  45. from backend.app.services.finance_budget import (
  46. create_budget_reservation,
  47. release_budget_reservation,
  48. validate_print_budget,
  49. )
  50. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  51. from backend.app.services.notification_service import notification_service
  52. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  53. from backend.app.services.printer_manager import (
  54. printer_manager,
  55. supports_airduct,
  56. supports_chamber_heater,
  57. supports_chamber_temp,
  58. supports_drying,
  59. supports_drying_while_printing,
  60. )
  61. from backend.app.services.smart_plug_manager import smart_plug_manager
  62. from backend.app.services.spool_assignment_notifications import (
  63. _global_tray_from_assignment,
  64. _slot_label_from_global_tray,
  65. )
  66. from backend.app.utils.ams_drying import is_countdown_parked
  67. from backend.app.utils.ams_humidity import ams_humidity_percent
  68. from backend.app.utils.archive_paths import archive_photos_dir
  69. from backend.app.utils.color_utils import perceptual_color_distance
  70. from backend.app.utils.filament_types import canonical_filament_type
  71. from backend.app.utils.filename import derive_remote_filename
  72. from backend.app.utils.library_paths import move_library_photos
  73. from backend.app.utils.local_time import utcnow_naive
  74. from backend.app.utils.printer_models import (
  75. is_dual_nozzle_model,
  76. is_gcode_compatible,
  77. is_nozzle_rack_model,
  78. normalize_printer_model,
  79. )
  80. from backend.app.utils.threemf_tools import (
  81. default_plate_number,
  82. extract_rack_plan_from_3mf,
  83. extract_slot_extruders_from_3mf,
  84. select_plate_gcode_name,
  85. )
  86. logger = logging.getLogger(__name__)
  87. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  88. """Human slot name for an assignment tuple, in the spelling already in use.
  89. Composed from the notification side's own pair rather than spelled out again
  90. here. The hand-rolled version this replaces got three real slot kinds wrong:
  91. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  92. ``chr(191)``; both externals collapsed to one label, because an external
  93. assignment stores ams_id 255 with tray_id picking left or right
  94. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  95. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  96. Naming the same slot two ways is its own defect once an alert and the
  97. Inventory page are meant to be talking about the same tray, so this defers
  98. rather than adding a fifth spelling.
  99. """
  100. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  101. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  102. # interval: the fast path runs every 3 s while an upload is in flight, and a
  103. # low spool does not need answering at that resolution (#2913).
  104. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  105. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  106. # days, so a finer check would only repeat the same answer.
  107. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  108. # The settings row that holds which stock alerts have already been sent (#2955).
  109. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  110. # The Inventory page asks for this many usage records and the forecast panel
  111. # builds its rates from them; the alert reads the same window so the two agree.
  112. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  113. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  114. """Remaining filament as a percentage of the label weight.
  115. The same arithmetic the Inventory page's Low Stock count uses, and it works
  116. unchanged in both inventory modes: internal spools store ``weight_used``
  117. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  118. ``remaining_weight`` so the shape matches. Returns None when there is no
  119. label weight to be a percentage of -- a spool that cannot say how full it
  120. started cannot say how empty it is.
  121. """
  122. if not label_weight or label_weight <= 0:
  123. return None
  124. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  125. return remaining / float(label_weight) * 100.0
  126. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  127. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  128. # byte gate) from before the scheduler unification. Time gate keeps small
  129. # files from going silent (a single 8 KB chunk fires once and that's it);
  130. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  131. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  132. # sub-200 ms files.
  133. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  134. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  135. # How far back chamber temperature samples are retained. 2h comfortably spans
  136. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  137. # before the next print.
  138. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  139. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  140. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  141. # who clear plates promptly will want far less than this; it is deliberately
  142. # the cautious end, since the cost of it being too short is only a re-soak.
  143. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  144. # Max acceptable gap between two consecutive chamber samples before we treat
  145. # the older one as belonging to a separate observation run (printer went
  146. # offline and came back). Above ~30s cadence with a safety margin.
  147. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  148. # How long the chamber must read below target before we accept that it really
  149. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  150. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  151. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  152. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  153. # sub-target readings are therefore a door opening or noise, not lost soak,
  154. # and a plate swap (exactly when keep-warm is running) produces one. Six
  155. # minutes clears the longest such artifact observed (~5 min once bracketed by
  156. # its neighbouring samples) and still sits far below the 23-minute floor for
  157. # real cooling.
  158. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  159. # How often the preheat stage re-checks that the item it is heating for still
  160. # wants to be printed. Cancelling only writes `status` to the database — it
  161. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  162. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  163. # and the printer stays in `busy_printers`, blocking every other queued item
  164. # behind a print that is not happening.
  165. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  166. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  167. _AIRDUCT_MODE_COOLING = 0
  168. _AIRDUCT_MODE_HEATING = 1
  169. # How long a queue row may stay 'printing' while its printer sits in a terminal
  170. # state before the scheduler closes it itself (#2829).
  171. #
  172. # A real completion arrives within seconds of the printer going terminal, so
  173. # five minutes is far outside the normal path — this only ever sees a row whose
  174. # completion was refused or never delivered. It is the whole cost of the
  175. # failure to the user, though: a stranded row blocks every later job for that
  176. # printer, so it should not be raised without reason.
  177. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  178. # gcode_state values that mean the print is over, mapped to the queue status
  179. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  180. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  181. # which the queue calls cancelled) so a recovered row cannot disagree with one
  182. # closed by the normal path.
  183. _TERMINAL_STATE_QUEUE_STATUS = {
  184. "FINISH": "completed",
  185. "FAILED": "failed",
  186. "IDLE": "cancelled",
  187. }
  188. def _terminal_queue_status(state) -> str | None:
  189. """Queue status implied by *state*, or None if the print is not over.
  190. None for a disconnected printer as well as a busy one: a printer we are not
  191. talking to has a stale ``state`` field that proves nothing about what it is
  192. doing now.
  193. """
  194. if state is None or not getattr(state, "connected", False):
  195. return None
  196. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  197. @dataclass
  198. class _KeepWarmEntry:
  199. """Per-printer keep-warm state.
  200. - ``started``: monotonic time when keep-warm first fired for this printer.
  201. Used by the max-duration timeout.
  202. - ``held_target``: last bed target we successfully published. On release
  203. we only send bed-off when firmware still reports this value, so a user
  204. or subsequent print that changed the target isn't clobbered.
  205. - ``expired``: latched True when the max-duration timeout fires. Prevents
  206. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  207. release sweep drops the entry entirely once the printer leaves the
  208. candidate set.
  209. """
  210. started: float
  211. held_target: int
  212. expired: bool = False
  213. # Auto-drying re-arm guards (#2770).
  214. #
  215. # An AMS reports HIGHER relative humidity while it is warm than once it has
  216. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  217. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  218. # threshold set inside that band therefore cannot be satisfied while the box is
  219. # hot, and the firmware is free to end a cycle whenever it decides the filament
  220. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  221. # the threshold and arms another cycle. The reporter's log has five 12-hour
  222. # cycles armed inside four hours, one of them six seconds after the previous
  223. # ended.
  224. #
  225. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  226. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  227. # manual or firmware-run dry is untouched.
  228. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  229. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  230. # Sustained-humidity wait (#2518): an above-threshold streak is only
  231. # "continuous" if some pass observed it within the gap ceiling. A unit that
  232. # goes unobserved longer (print running, printer disconnected, sensor silent)
  233. # restarts its streak rather than inheriting a stale one. The ceiling is
  234. # derived from the scheduler cadence — four missed passes — with this floor so
  235. # a fast-polling configuration does not void streaks on a single hiccup.
  236. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  237. # How long a finished scheduled drying row is kept before it is pruned.
  238. SCHEDULED_DRYING_RETENTION_DAYS = 7
  239. # How often that prune actually runs. The check itself is called on every queue
  240. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  241. # write transaction, which SQLite serialises against every other writer. Rows
  242. # only become prunable a week after they finish, so anything short of hourly is
  243. # paying that cost for nothing.
  244. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  245. class _UploadProgressBridge:
  246. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  247. ``upload_file_async`` runs the FTP transfer in an executor thread and
  248. invokes its ``progress_callback`` from that thread, so the callback
  249. body cannot ``await`` directly. This bridge captures the asyncio loop
  250. at construction (on the scheduler thread) and uses
  251. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  252. matches the legacy background_dispatch.py path 1:1 so the toast feels
  253. identical to the pre-#1625 experience.
  254. Failures inside the emit are swallowed — progress is a UX nicety, the
  255. upload itself must not fail because of a WS hiccup.
  256. """
  257. def __init__(self, user_id: int | None, queue_item_id: int):
  258. self._user_id = user_id
  259. self._queue_item_id = queue_item_id
  260. try:
  261. self._loop = asyncio.get_running_loop()
  262. except RuntimeError:
  263. self._loop = None
  264. self._last_emit_bytes = 0
  265. self._last_emit_monotonic = 0.0
  266. self._has_emitted = False
  267. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  268. if self._loop is None or total_bytes <= 0:
  269. return
  270. now = time.monotonic()
  271. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  272. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  273. # the four matter most: first-call so the user sees something even
  274. # for sub-chunk-size files; uploaded >= total so the bar locks at
  275. # 100% even when the throttle would otherwise eat it.
  276. should_emit = (
  277. not self._has_emitted
  278. or bytes_transferred >= total_bytes
  279. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  280. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  281. )
  282. if not should_emit:
  283. return
  284. self._has_emitted = True
  285. self._last_emit_bytes = bytes_transferred
  286. self._last_emit_monotonic = now
  287. try:
  288. asyncio.run_coroutine_threadsafe(
  289. ws_manager.send_queue_item_upload_progress(
  290. user_id=self._user_id,
  291. queue_item_id=self._queue_item_id,
  292. bytes_transferred=bytes_transferred,
  293. total_bytes=total_bytes,
  294. ),
  295. self._loop,
  296. )
  297. except Exception:
  298. pass # progress is best-effort, never block the upload
  299. # Bambu firmware states that mean the project_file has actually been accepted
  300. # and the printer is now processing / running / paused mid-print. Used by the
  301. # dispatch watchdog (#1370): a transition into one of these states means the
  302. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  303. # a post-print prompt) is NOT a valid "command landed" signal even though the
  304. # state value did change. SLICING is included because some firmwares park
  305. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  306. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  307. # How many times the start-watchdog may revert an item to 'pending' before it
  308. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  309. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  310. # both never recovers and starves the other printers of dispatch slots. Three
  311. # is chosen to clear the transient causes the watchdog already recovers from —
  312. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  313. # force-reconnect on the very next attempt — while still bounding the loop.
  314. DISPATCH_MAX_ATTEMPTS = 3
  315. # Upload failures that mean the file never reached the printer's storage: the
  316. # file service refused or never answered (#3210). These put the item back in
  317. # the queue instead of failing it, because nothing about the job is wrong --
  318. # and failing it left the printer idle, so the next pass handed it the next
  319. # item, which failed the same way. One P2S whose file service was out of
  320. # connection slots ate 43 queued jobs in ten minutes that way.
  321. #
  322. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  323. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  324. # and an upload that overran its deadline -- each of those would fail the same
  325. # way on every retry.
  326. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  327. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  328. )
  329. # How long a printer whose upload was put back stays out of dispatch (#3210).
  330. # The first window matches the FTP client's own handshake cool-off, so the
  331. # retry lands after the client would talk to the printer again anyway. Each
  332. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  333. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  334. # five connection attempts and a page of log. A successful upload resets it.
  335. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  336. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  337. def _upload_backoff_seconds(refusals: int) -> int:
  338. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  339. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  340. @dataclass(slots=True)
  341. class _ModelCandidate:
  342. """One (file, printer model) pair the model-based matcher may try.
  343. Model-based assignment used to have exactly one of these per item, held
  344. directly in the item's own columns. Cross-model queue items (#671) have
  345. several, held in ``print_queue_variants``. Both shapes are normalised into
  346. this so the matching, the cross-model gate and the waiting-reason handling
  347. are written once and an item without variants provably takes the same path
  348. it took before variants existed.
  349. ``variant`` is None for the item's own columns and set for a real variant
  350. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  351. item once that candidate wins.
  352. """
  353. target_model: str | None
  354. sliced_for: str | None
  355. required_filament_types: str | None
  356. filament_overrides: str | None
  357. variant: "PrintQueueVariant | None" = None
  358. def _sliced_for_model(archive, library_file) -> str | None:
  359. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  360. if archive is not None:
  361. return archive.sliced_for_model
  362. if library_file is not None and library_file.file_metadata:
  363. return library_file.file_metadata.get("sliced_for_model")
  364. return None
  365. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  366. """The filament a candidate needs, as ``(types, overrides)``.
  367. Both columns are JSON text written by the slicer step. Malformed content is
  368. treated as no constraint rather than as an error: a job whose overrides
  369. cannot be parsed still prints, it just gets no filament-based narrowing.
  370. Overrides carry their own types, so the returned type list is the union of
  371. the two — an override on one slot must not drop the requirements of the
  372. slots it says nothing about.
  373. Shared by the matcher and by the smart-plug wake step so both ask a printer
  374. for the same filament (#2876). Waking a printer the matcher would then
  375. reject on colour is the bug this exists to prevent.
  376. """
  377. required_types = None
  378. if candidate.required_filament_types:
  379. try:
  380. required_types = json.loads(candidate.required_filament_types)
  381. except json.JSONDecodeError:
  382. pass
  383. filament_overrides = None
  384. if candidate.filament_overrides:
  385. try:
  386. filament_overrides = json.loads(candidate.filament_overrides)
  387. except json.JSONDecodeError:
  388. pass
  389. effective_types = required_types
  390. if filament_overrides:
  391. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  392. if override_types:
  393. effective_types = sorted(set(required_types or []) | set(override_types))
  394. return effective_types, filament_overrides
  395. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  396. """Whether ``item`` was competing for the printer another item just took.
  397. The SJF starvation guard marks a job as jumped when a shorter one lower in
  398. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  399. compete for the same printer, so the guard has to look across both lanes
  400. (#3200); looking only inside the dispatched item's own lane let a stream of
  401. short model-based jobs hold a longer pinned job back indefinitely.
  402. Location filters are not checked: over-marking only lifts an item that was
  403. going to wait anyway, while under-marking is the starvation this prevents.
  404. """
  405. if item.printer_id is not None:
  406. return item.printer_id == printer_id
  407. if not printer_model:
  408. return False
  409. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  410. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  411. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  412. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  413. """Candidate files for ``item``, best first.
  414. An item with no variant rows yields exactly one candidate built from its own
  415. columns — the pre-#671 behaviour, unchanged.
  416. Variants come back least-attempted first, ties broken by the user's
  417. ``position``. On the first pass every count is zero, so this is purely the
  418. user's priority order. After a start-watchdog bounce the printer that failed
  419. drops behind, so the next lap tries the other machine rather than spending the
  420. item's whole retry budget on the one that is wedged. Once every candidate has
  421. been tried equally often they cycle again, which keeps the item-level
  422. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  423. still gives up, it just does not give up without trying them.
  424. """
  425. if not item.variants:
  426. if not item.archive_id and not item.library_file_id:
  427. # Nothing to print at all. Dispatching would fail deep in the upload
  428. # on "No archive_id or library_file_id"; the caller holds the item
  429. # with an explanation instead.
  430. return []
  431. return [
  432. _ModelCandidate(
  433. target_model=item.target_model,
  434. sliced_for=_sliced_for_model(item.archive, item.library_file),
  435. required_filament_types=item.required_filament_types,
  436. filament_overrides=item.filament_overrides,
  437. )
  438. ]
  439. # Drop candidates whose file is gone or in the trash. Both are reachable and
  440. # neither is covered by the schema: library deletes are soft (the row lives
  441. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  442. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  443. # fires there and a hard delete leaves the variant row pointing at nothing.
  444. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  445. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  446. return [
  447. _ModelCandidate(
  448. target_model=v.target_model,
  449. sliced_for=_sliced_for_model(None, v.library_file),
  450. required_filament_types=v.required_filament_types,
  451. filament_overrides=v.filament_overrides,
  452. variant=v,
  453. )
  454. for v in ordered
  455. ]
  456. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  457. """Fold one waiting reason per candidate into a single line for the item.
  458. A cross-model item produces a reason per candidate, and pasting them
  459. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  460. — on which machine?). Each reason is prefixed with its model, except in the
  461. single-candidate case where the item already displays its target model and
  462. the prefix would be noise.
  463. Identical reasons collapse rather than repeat, so three idle-less models
  464. read as one clause.
  465. When *every* candidate is merely busy the parts are joined with the ``" | "``
  466. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  467. unprefixed. That case must keep testing busy-only: a fleet that is simply
  468. printing needs no user action, and labelling the clauses would turn each pass
  469. over a two-model item into a "job waiting" notification.
  470. """
  471. reasons = [(model, reason) for model, reason in per_model if reason]
  472. if not reasons:
  473. return None
  474. if len(reasons) == 1:
  475. return reasons[0][1]
  476. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  477. if len(distinct) == 1:
  478. return distinct[0]
  479. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  480. return " | ".join(distinct)
  481. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  482. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  483. """Human label for the models an item is waiting on ("H2S or H2C").
  484. Notifications take a single target model. For a cross-model item the item's
  485. own ``target_model`` is whichever variant happens to be first, which reads as
  486. a lie once it is the H2C that actually runs — so name all of them.
  487. """
  488. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  489. if not models:
  490. return None
  491. return " or ".join(models)
  492. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  493. """True if ``mapping`` is a non-empty list whose every entry is the
  494. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  495. Such a mapping is a bug artifact: a frontend status-load race can serialize
  496. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  497. recomputed from live status at dispatch rather than trusted, otherwise it
  498. reaches the print command and is silently downgraded to external-spool mode.
  499. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  500. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  501. explicit external selection (``>= 254``) is NOT unresolved either — those
  502. keep their meaning.
  503. """
  504. if not isinstance(mapping, list) or not mapping:
  505. return False
  506. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  507. def _is_tray_id(value: object) -> bool:
  508. """True when ``value`` can be read as a global tray ID.
  509. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  510. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  511. against whatever happens to be loaded there.
  512. """
  513. return isinstance(value, int) and not isinstance(value, bool)
  514. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  515. # stages an item (#2799). The manual_start branch clears every other reason on
  516. # a staged item (#3074); this one is the reason it was staged, so it stays.
  517. _UNMATCHED_HOLD_PREFIX = "Needs "
  518. # How often an "any model" job held for low filament looks for another printer
  519. # of its model that has enough (#3137). Each look matches its filament on every
  520. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  521. _SHORT_HOLD_RECHECK_SECONDS = 120
  522. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  523. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  524. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  525. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  526. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  527. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  528. for a filament this plate does not use. A slot past the end of the mapping
  529. is unresolved too.
  530. """
  531. unresolved = []
  532. for req in required:
  533. slot_id = req.get("slot_id") or 0
  534. if slot_id <= 0:
  535. continue
  536. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  537. if not _is_tray_id(tray) or tray < 0:
  538. unresolved.append(req)
  539. return unresolved
  540. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  541. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  542. # on `_mapping_is_all_unresolved`.
  543. _EXTERNAL_TRAY_ID_MIN = 254
  544. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  545. """The ``mapping`` entries for the slots this plate actually prints.
  546. ``required`` comes from ``extract_filament_requirements``, which drops any
  547. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  548. consumes, and one absent from it is padding. That distinction is why this
  549. decision lives here and not in the MQTT command builder: a ``-1`` in the
  550. mapping means either "this plate does not print filament N" or "we never
  551. worked out which tray", and only the plate's own filament list separates
  552. them. The builder sees both as the same byte, which is how a plate whose one
  553. printed filament sat on the external spool went out as `use_ams=true` with a
  554. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  555. with 07FF_8012 (#3087).
  556. Returns None whenever the two cannot be lined up — no mapping, no parsed
  557. requirements, or a requirement the mapping is too short to cover — so every
  558. caller falls back to existing behaviour rather than acting on a guess.
  559. """
  560. if not isinstance(mapping, list) or not mapping or not required:
  561. return None
  562. entries = []
  563. for filament in required:
  564. slot_id = filament.get("slot_id")
  565. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  566. # The mapping and the requirements disagree about how many filaments
  567. # the file has. They came from different reads, so judge nothing.
  568. return None
  569. entries.append(mapping[slot_id - 1])
  570. return entries or None
  571. def _is_external_tray(tray_id) -> bool:
  572. """True for an explicit external-spool selection (254/255), not for an
  573. unresolved slot and not for an AMS tray."""
  574. if tray_id is None:
  575. return False
  576. try:
  577. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  578. except (TypeError, ValueError):
  579. return False
  580. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  581. """Whether this printer could have two extruders, judged generously.
  582. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  583. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  584. why the MQTT command builder skips its own use_ams reconcile there. Anything
  585. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  586. with, external spools or not.
  587. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  588. behaviour it has always had, while a wrong "no" would rewrite a field that
  589. steers which nozzle prints. The model name is the first answer (it is what
  590. the command builder falls back to as well), then the same live evidence the
  591. dispatcher's extruder annotation uses — a second nozzle reporting a
  592. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  593. since a single-nozzle printer has exactly one.
  594. """
  595. if is_dual_nozzle_model(printer_model):
  596. return True
  597. nozzles = getattr(status, "nozzles", None) or []
  598. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  599. return True
  600. raw = getattr(status, "raw_data", None) or {}
  601. if raw.get("ams_extruder_map"):
  602. return True
  603. vt_trays = raw.get("vt_tray") or []
  604. return isinstance(vt_trays, list) and len(vt_trays) > 1
  605. def _int_or(value, default: int) -> int:
  606. """``int(value)``, or ``default`` when the field is missing or junk.
  607. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  608. the next — and a tray id that fails to parse must not take the whole
  609. derivation down with it.
  610. """
  611. try:
  612. return int(value)
  613. except (TypeError, ValueError):
  614. return default
  615. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  616. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  617. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  618. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  619. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  620. agree or a mapping cannot be read back against live tray telemetry.
  621. """
  622. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  623. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  624. """The global tray ids ``item`` actually prints from, or None if unknown.
  625. ``ams_mapping`` is the array the print command carries: position = filament
  626. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  627. not use. None means "no usable statement" — no mapping, unparseable JSON,
  628. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  629. documents), or one that resolves to no tray at all. Callers must treat None
  630. as "consider every loaded tray" rather than "consider none": narrowing on
  631. an absent mapping would silently drop requirements the print really has.
  632. """
  633. raw = getattr(item, "ams_mapping", None)
  634. if not raw:
  635. return None
  636. if isinstance(raw, str):
  637. try:
  638. mapping = json.loads(raw)
  639. except (json.JSONDecodeError, TypeError):
  640. return None
  641. else:
  642. mapping = raw
  643. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  644. return None
  645. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  646. return used or None
  647. def _mqtt_commands_rejected(status) -> bool:
  648. """True when the printer is currently reporting that it refused a command.
  649. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  650. a control command it could not verify. Queries still answer, so the printer
  651. looks connected and idle while project_file, gcode_line and
  652. ams_change_filament are all dropped — no amount of waiting or re-uploading
  653. changes that (#2732).
  654. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  655. ``print_error`` path builds HMSError differently), so this is safe to call on
  656. every watchdog poll.
  657. """
  658. for err in getattr(status, "hms_errors", None) or []:
  659. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  660. return True
  661. return False
  662. def _drying_ams_ids(status) -> list[int]:
  663. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  664. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  665. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  666. started (#2758) — it is a diagnostic, not a gate.
  667. Deliberately not used to block or stop drying before dispatch. This printer
  668. class supports drying concurrently with an active print
  669. (``supports_drying_while_printing``), so drying is not incompatible with
  670. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  671. while two AMS units were drying, one of them without its external PSU. Until
  672. it is known whether the blocker is drying itself or the power budget
  673. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  674. hardware is perfectly happy to continue.
  675. """
  676. ids: list[int] = []
  677. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  678. if not isinstance(unit, dict):
  679. continue
  680. try:
  681. if int(unit.get("dry_time") or 0) > 0:
  682. ids.append(int(unit.get("id", 0)))
  683. except (TypeError, ValueError):
  684. continue
  685. return ids
  686. def _parse_diameter(raw) -> float | None:
  687. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  688. try:
  689. value = float(raw)
  690. except (TypeError, ValueError):
  691. return None
  692. return value if value > 0 else None
  693. def _nozzle_info_by_id(status) -> dict[int, dict]:
  694. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  695. The field name is historical: on the H2 series ``nozzle_info`` carries an
  696. entry for *every* nozzle the printer knows about — the L/R hotends under
  697. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  698. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  699. :func:`_installed_nozzle_diameters` each take the half they need.
  700. """
  701. by_id: dict[int, dict] = {}
  702. for entry in getattr(status, "nozzle_rack", None) or []:
  703. if not isinstance(entry, dict):
  704. continue
  705. try:
  706. by_id[int(entry.get("id"))] = entry
  707. except (TypeError, ValueError):
  708. continue
  709. return by_id
  710. # What the firmware puts in a nozzle's serial number when the carriage or dock
  711. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  712. # its nozzle back in the rack (#2885).
  713. _EMPTY_NOZZLE_SERIAL = "N/A"
  714. def _nozzle_is_mounted(entry: dict | None) -> bool:
  715. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  716. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  717. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  718. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  719. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  720. the dock. So the diameter is not a presence signal (#2885).
  721. Emptiness has to be stated, not merely unstated. The serial must be the
  722. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  723. absent — an empty serial only means the printer didn't say, and a firmware
  724. that reports neither field normalises to exactly that. Treating "didn't
  725. say" as "empty" would silently switch the #1899 guard off on any such
  726. machine, so everything we cannot positively call empty counts as mounted.
  727. """
  728. if entry is None:
  729. return True
  730. serial = str(entry.get("serial_number") or "").strip().upper()
  731. if serial != _EMPTY_NOZZLE_SERIAL:
  732. return True
  733. try:
  734. max_temp = float(entry.get("max_temp") or 0)
  735. except (TypeError, ValueError):
  736. return True
  737. return max_temp > 0
  738. def _installed_nozzle_diameters(status) -> list[float]:
  739. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  740. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  741. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  742. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  743. told us its nozzle hardware" — callers must treat that as unknown, not as a
  744. mismatch, so we never block a print on missing data.
  745. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  746. though ``nozzles`` still carries a diameter for it: that value is stale, and
  747. counting it would let a slice match a nozzle the machine does not have
  748. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  749. """
  750. info = _nozzle_info_by_id(status)
  751. diameters: list[float] = []
  752. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  753. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  754. try:
  755. value = float(raw)
  756. except (TypeError, ValueError):
  757. continue
  758. if value > 0 and _nozzle_is_mounted(info.get(index)):
  759. diameters.append(value)
  760. return diameters
  761. def _rack_nozzle_diameters(status) -> list[float]:
  762. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  763. Keyed off the nozzle ids themselves rather than the printer model: only a
  764. rack machine ever reports ids 16-21, so there is no model registry to keep
  765. in sync. An empty dock is simply absent from the payload — measured on an
  766. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  767. present — so appearing here already means "a nozzle is in that dock".
  768. ``stat`` is deliberately not interpreted: its values aren't known, and
  769. reading it wrongly could hide a nozzle the printer would happily fetch.
  770. """
  771. diameters: list[float] = []
  772. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  773. if nozzle_id not in _RACK_NOZZLE_IDS:
  774. continue
  775. # PrinterState spells it "diameter"; the REST schema renames it to
  776. # "nozzle_diameter". Accept either so a caller holding the serialised
  777. # shape gets the same answer.
  778. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  779. if value is not None:
  780. diameters.append(value)
  781. return diameters
  782. def _format_diameters(diameters: list[float]) -> str:
  783. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  784. Deduplicated because a loaded rack holds several nozzles of the same size,
  785. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  786. short form doesn't. Matching still runs over the full list.
  787. """
  788. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  789. def _nozzle_mismatch_message(
  790. sliced_nozzle: float | None,
  791. installed: list[float],
  792. rack: list[float] | None = None,
  793. ) -> str | None:
  794. """Return an actionable error message when the sliced nozzle can't be
  795. printed on any nozzle the machine can reach, else None (#1899).
  796. Fail-safe: returns None whenever we lack the data to judge — no sliced
  797. diameter, or the printer reported no nozzles — so a print is only ever
  798. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  799. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  800. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  801. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  802. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  803. as reachable: the printer fetches one as part of starting the print, so a
  804. slice that matches a docked nozzle is not a mismatch. Without this the
  805. guard blocked every job whose nozzle happened not to be on a hotend at
  806. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  807. diameter already mounted could ever print, and the user had to fetch the
  808. nozzle by hand on the printer's own UI first (#2885).
  809. """
  810. reachable = [*installed, *(rack or [])]
  811. if not sliced_nozzle or not reachable:
  812. return None
  813. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  814. return None
  815. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  816. if rack:
  817. where += f" and {_format_diameters(rack)} in the nozzle rack"
  818. return (
  819. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  820. f"{where}. Re-slice for an available nozzle, or fit the matching "
  821. f"nozzle before printing."
  822. )
  823. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  824. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  825. Shared by the required and loaded sides, which name their extruder
  826. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  827. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  828. 1 the left/deputy — and both are absent on single-nozzle printers, where
  829. naming a nozzle would be noise.
  830. """
  831. parts = [(entry.get("type") or "filament").upper()]
  832. if entry.get("color"):
  833. parts.append(str(entry["color"]))
  834. nozzle = entry.get(nozzle_key)
  835. if nozzle == 0:
  836. parts.append("(right nozzle)")
  837. elif nozzle == 1:
  838. parts.append("(left nozzle)")
  839. return " ".join(parts)
  840. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  841. """Explain that nothing loaded matches what the file needs (#2771).
  842. Only ever built for a printer with no AMS, where the loaded list is short
  843. enough to quote in full and there is no "load another spool and hit Resume"
  844. recovery — the external spool holder is all there is, so the user needs to
  845. be told which filament to put on it.
  846. """
  847. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  848. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  849. return (
  850. f"No filament loaded on this printer matches the file. It needs {want}; "
  851. f"the printer has {have} and no AMS. Load the required filament on the "
  852. f"external spool holder, or send this job to a printer that has it."
  853. )
  854. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  855. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  856. every call site below it: G-code injection, usage registration, rack-plan
  857. lookup, slot-extruder lookup, the external-spool check, and the actual
  858. print command.
  859. A positive explicit ``plate_id`` on the queue item always wins. A
  860. non-positive one is treated as "not set" and resolved from the archive,
  861. the way the rest of the queue code already reads it (``if item.plate_id:``
  862. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  863. field, and passing a 0 straight through would build a print command for
  864. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  865. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  866. Falling back to a bare ``1`` instead of reading the archive assumes a
  867. single-plate file's one G-code is numbered 1, which only holds for a
  868. plate exported on its own: one cut out of a larger project keeps its
  869. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  870. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  871. the file, throws an HMS error, and sits wedged in IDLE until
  872. power-cycled (#2947).
  873. The call sites agreed on a fallback only by accident before this:
  874. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  875. the archive's own default plate internally whenever the plate id it's
  876. handed isn't in the file, so it could silently inject into a different
  877. plate than the one the print command itself asked for.
  878. Falls back to 1 when the archive can't be read, holds no G-code member at
  879. all, or its default member doesn't follow the ``plate_N`` naming
  880. convention (a slicer that doesn't use it has no number to dispatch).
  881. An explicit plate the archive doesn't hold is logged and then sent
  882. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  883. to a plate that is in the file would print a model nobody asked for,
  884. which is the worse of the two.
  885. """
  886. try:
  887. with zipfile.ZipFile(file_path, "r") as zf:
  888. names = zf.namelist()
  889. except (OSError, zipfile.BadZipFile) as exc:
  890. logger.warning(
  891. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  892. "is unavailable; dispatching plate %s",
  893. file_path,
  894. exc,
  895. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  896. )
  897. names = None
  898. if explicit_plate_id is not None and explicit_plate_id > 0:
  899. if (
  900. names is not None
  901. and default_plate_number(names) is not None
  902. and select_plate_gcode_name(names, explicit_plate_id) is None
  903. ):
  904. logger.warning(
  905. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  906. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  907. "file, since printing a different plate would print the wrong model (#2947)",
  908. file_path,
  909. explicit_plate_id,
  910. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  911. explicit_plate_id,
  912. )
  913. return explicit_plate_id
  914. resolved = default_plate_number(names) if names is not None else None
  915. return resolved if resolved is not None else 1
  916. class PrintScheduler:
  917. """Background scheduler that processes the print queue."""
  918. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  919. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  920. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  921. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  922. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  923. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  924. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  925. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  926. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  927. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  928. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  929. }
  930. def __init__(self):
  931. self._running = False
  932. self._check_interval = 30 # seconds
  933. # After a pass that actually dispatched something, loop again almost
  934. # immediately instead of sleeping the full interval (#2555). A dispatch
  935. # changes printer state — a batch launch fans out over several passes as
  936. # printers free up, a wedged head-of-line job reverts to pending, an
  937. # upload slot opens — and the next batch of ready work should not have to
  938. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  939. # pending items are behind printers that are genuinely busy printing),
  940. # there is nothing to react to, so we fall back to the normal interval;
  941. # that also means this can never tight-loop, since fast ticks only
  942. # continue while dispatches keep happening and the queue is draining.
  943. self._fast_check_interval = 3 # seconds
  944. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  945. self._power_on_check_interval = 10 # seconds between connection checks
  946. # Printers whose class-target power-on failed, mapped to the monotonic
  947. # time their cool-off expires (#2786).
  948. #
  949. # Without this, one printer with an unreachable plug starves every
  950. # sibling of its model forever: the wake step walks candidates in id
  951. # order, spends the pass's single attempt on the same broken printer
  952. # every time, and the healthy one two slots down is never reached. It
  953. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  954. # which delays the whole queue, not just this job.
  955. #
  956. # Entries expire on read rather than being cleared on success: a printer
  957. # inside its cool-off is skipped before the power-on is reached, so a
  958. # live entry can never be overwritten by a success anyway. A printer
  959. # that comes back by any other route stops being a wake candidate the
  960. # moment it connects.
  961. self._wake_failures: dict[int, float] = {}
  962. self._wake_failure_cooloff = 600 # seconds
  963. # Printers whose last upload never reached them, mapped to the monotonic
  964. # time they may be dispatched to again (#3210). Same expire-on-read shape
  965. # as `_wake_failures`. Without it, a printer that cannot take files is
  966. # idle on every pass, so it is picked on every pass.
  967. self._upload_backoff: dict[int, float] = {}
  968. # Refused uploads in a row per printer, which sets the next backoff
  969. # window. Cleared by a successful upload to that printer.
  970. self._upload_refusals: dict[int, int] = {}
  971. # Printers whose current run of refusals has already sent its one
  972. # "job waiting" notification. Each retry clears the item's waiting
  973. # reason and the next refusal sets it again, which `hold_item` reads as
  974. # a new reason; without this, every retry would notify. Cleared with
  975. # `_upload_refusals`.
  976. self._upload_refusal_notified: set[int] = set()
  977. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  978. self._drying_in_progress: dict[int, float] = {}
  979. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  980. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  981. # cycle and the humidity finally coming down, so the normal steady
  982. # state is an empty dict. Fields:
  983. # running — a cycle we armed is (or should be) on the firmware
  984. # ended_at — monotonic when we observed that cycle end
  985. # unproductive — consecutive armed cycles that ended with the reading
  986. # still above the threshold
  987. # suspended — we have stopped arming this unit and said so
  988. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  989. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  990. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  991. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  992. # print-takes-priority stop, the manual-cycle adoption guard, and the
  993. # arming setdefault all act on that meaning -- a unit that is merely
  994. # waiting out its streak must not become stoppable or judgeable.
  995. # since -- monotonic stamp when the current continuous above-threshold
  996. # streak began
  997. # last -- monotonic stamp of the last pass that observed the streak
  998. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  999. # Slots already notified as low on filament:
  1000. # {(printer_id, ams_id, tray_id, spool_id)}.
  1001. # Cleared when the slot goes back above its threshold rather than on a
  1002. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1003. # boundary must not produce an alert on every pass, and a slot that has
  1004. # been refilled has to be able to alert again. See #2913.
  1005. #
  1006. # The spool id is part of the key because the slot alone cannot clear
  1007. # itself. Pull a low spool and put a different part-used one in the same
  1008. # slot: the key survives the pass where the slot resolves to nothing --
  1009. # deliberately, so a brief Spoolman outage does not re-alert everything
  1010. # when it returns -- and the replacement never goes above the threshold,
  1011. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1012. # different key and the stale one is inert.
  1013. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1014. # Earliest monotonic time the next low-filament check may run (#2913).
  1015. self._filament_low_next_check: float = 0.0
  1016. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1017. # condition is "reorder" or "break", the events are those that had a
  1018. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1019. # condition clears, so it can alert again, and when nobody wants either
  1020. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1021. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1022. # re-send one message per SKU that is still low.
  1023. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1024. # The JSON last read from or written to that row; None until it has been read.
  1025. self._stock_alerts_persisted: str | None = None
  1026. # Earliest monotonic time the next stock forecast check may run (#2955).
  1027. self._stock_forecast_next_check: float = 0.0
  1028. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1029. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1030. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1031. # both features share _drying_in_progress.
  1032. self._scheduled_drying_printer_ids: set[int] = set()
  1033. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1034. # the first pass after a restart reaps anything left behind.
  1035. self._last_scheduled_drying_prune: float | None = None
  1036. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1037. # a project_file command must not get a second dispatch until either it
  1038. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1039. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1040. # during that window the DB busy_printers seed is empirically unreliable
  1041. # (multi-plate batches double-/triple-dispatched onto the same printer
  1042. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1043. # or revert.
  1044. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1045. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1046. # Minimum cooldown between dispatches to the same printer (covers the
  1047. # H2D's project_file digestion window).
  1048. self._dispatch_min_cooldown = 60.0
  1049. # Hard timeout — drop the hold even if we never observed a transition,
  1050. # so a lost MQTT session can't lock a printer out of the queue forever.
  1051. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1052. # watchdog runs first on the unhappy path.
  1053. self._dispatch_max_hold = 180.0
  1054. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1055. # an earlier pass and is still running. `_start_print` flips the row
  1056. # pending -> printing only *after* the upload completes, so until then
  1057. # the row stays `pending`: each tick, check_queue excludes these
  1058. # item_ids from re-selection and their printers from new dispatch /
  1059. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1060. # freed slots refill on the next fast tick. check_queue is the sole,
  1061. # sequential caller and the prune done-callbacks run in the same
  1062. # event-loop thread, so this dict needs no lock.
  1063. # item_id -> (task, printer_id)
  1064. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1065. # Expected prints registered by `_start_print` that have not yet had a
  1066. # print command sent. Populated at registration, dropped once
  1067. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1068. # other exit. Same threading argument as `_inflight` above: one
  1069. # sequential caller, callbacks on the same loop, so no lock.
  1070. # item_id -> (printer_id, remote_filename, archive_id)
  1071. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1072. # Budget reservations created for a dispatch whose print command has
  1073. # not been confirmed yet. `_dispatch_one` releases these on every
  1074. # unsuccessful exit; a successful start removes the item id and leaves
  1075. # the reservation for finance_billing to consume with the archive.
  1076. self._unconfirmed_budget_reservations: set[int] = set()
  1077. # Chamber temperature history for smart soak-time reduction.
  1078. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1079. # Entries older than _chamber_history_ttl are pruned on write.
  1080. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1081. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1082. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1083. # Populated on engagement in `_apply_keep_warm`, cleared by
  1084. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1085. # when a gate setting toggles off mid-hold — the release publishes
  1086. # bed → 0 first).
  1087. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1088. # Preheat rollback registry: printer_id -> subset of
  1089. # {"bed", "chamber", "airduct"} listing which preheat commands
  1090. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1091. # every entry still present at exit unless the print successfully
  1092. # started, so a failed upload / cancel / exception never leaves the
  1093. # printer heating for a job that isn't happening.
  1094. self._preheat_pin: dict[int, set[str]] = {}
  1095. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1096. # rollback can tell its own target from one someone else has since
  1097. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1098. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1099. self._preheat_pin_bed: dict[int, int] = {}
  1100. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1101. # its preheat was still holding at temperature. Set by
  1102. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1103. # `_preheat_sleep`, and cleared when the dispatch exits.
  1104. self._cancelled_dispatches: set[int] = set()
  1105. # printer_id -> monotonic time it was first seen terminal while one of
  1106. # its queue rows was still 'printing'. Reset by any non-terminal
  1107. # observation, so it measures an unbroken run rather than a total.
  1108. # In-memory on purpose: a restart re-arms the grace period, which only
  1109. # delays a recovery that is already the exceptional path (#2829).
  1110. self._terminal_since: dict[int, float] = {}
  1111. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1112. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1113. # across idle printers repeats that for every one of them in a single
  1114. # pass. Cleared at the top of each pass so a re-sliced file is never
  1115. # served from a previous tick.
  1116. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1117. # When each "any model" job held for low filament last looked for
  1118. # another printer (#3137), by queue item id.
  1119. self._short_hold_checked_at: dict[int, float] = {}
  1120. async def run(self):
  1121. """Main loop - check queue every interval."""
  1122. self._running = True
  1123. logger.info("Print scheduler started")
  1124. await self._clear_stale_dispatch_claims(at_startup=True)
  1125. while self._running:
  1126. dispatched = False
  1127. try:
  1128. self._sample_chamber_temps()
  1129. # No-op while any upload is in flight; on a quiet tick it releases
  1130. # a claim whose best-effort clear failed (e.g. the database was
  1131. # briefly unreachable), instead of leaving the row wedged until
  1132. # the next restart.
  1133. await self._clear_stale_dispatch_claims()
  1134. await self._close_stranded_printing_items()
  1135. dispatched = await self.check_queue()
  1136. except Exception as e:
  1137. logger.error("Scheduler error: %s", e)
  1138. # Re-check quickly after a productive pass so a draining batch does
  1139. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1140. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1141. async def _close_stranded_printing_items(self) -> None:
  1142. """Close a ``printing`` row the completion event never closed (#2829).
  1143. ``on_print_complete`` refuses to close a row when the completion's
  1144. subtask name disagrees with the file the row was dispatched with, so a
  1145. completion meant for something else (the printer's own
  1146. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1147. The refusal has no way back, though: nothing else ever closes the row,
  1148. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1149. one bad comparison wedges that printer's queue until a human presses
  1150. cancel. That is what #2829's reporters hit, and the guard's own
  1151. docstring already called stranding the worse of the two failures.
  1152. This is the way back. When a row has been ``printing`` while its
  1153. printer sat in a terminal state for the whole grace period, the print
  1154. is over however the event was read, and the row is closed with the
  1155. status the printer's own state implies.
  1156. Deliberately conservative:
  1157. * Only a connected printer counts. A disconnected one has a stale
  1158. ``state`` and proves nothing.
  1159. * The clock is reset by any non-terminal observation, so this cannot
  1160. fire on a printer that is merely between stages.
  1161. * The grace period is far longer than the gap between a printer
  1162. finishing and its completion arriving, so the normal path always
  1163. wins the race and this only ever sees genuine strandings.
  1164. What it does *not* do is replay the completion's side effects --
  1165. notifications, billing, auto-off. It restores the queue, which is the
  1166. harm being undone; the archive was updated by the normal path
  1167. regardless, since only the queue block refuses. A recovery that
  1168. silently re-fired notifications minutes late would be its own bug.
  1169. """
  1170. try:
  1171. async with async_session() as db:
  1172. result = await db.execute(
  1173. select(PrintQueueItem)
  1174. .where(PrintQueueItem.status == "printing")
  1175. .where(PrintQueueItem.printer_id.is_not(None))
  1176. )
  1177. items = list(result.scalars().all())
  1178. if not items:
  1179. self._terminal_since.clear()
  1180. return
  1181. now = time.monotonic()
  1182. seen_printers: set[int] = set()
  1183. closed = False
  1184. for item in items:
  1185. printer_id = item.printer_id
  1186. seen_printers.add(printer_id)
  1187. state = printer_manager.get_status(printer_id)
  1188. status = _terminal_queue_status(state)
  1189. if status is None:
  1190. self._terminal_since.pop(printer_id, None)
  1191. continue
  1192. since = self._terminal_since.setdefault(printer_id, now)
  1193. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1194. continue
  1195. item.status = status
  1196. item.completed_at = datetime.now(timezone.utc)
  1197. closed = True
  1198. logger.warning(
  1199. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1200. "closing it as %s. Its completion event was never matched to it, which blocks "
  1201. "every later job for this printer (#2829).",
  1202. item.id,
  1203. printer_id,
  1204. getattr(state, "state", None),
  1205. now - since,
  1206. status,
  1207. )
  1208. if closed:
  1209. await db.commit()
  1210. for printer_id in list(self._terminal_since):
  1211. if printer_id not in seen_printers:
  1212. del self._terminal_since[printer_id]
  1213. except Exception as e:
  1214. # Best-effort, same as the claim sweep beside it: a recovery path
  1215. # that can itself break the scheduler loop is worse than the strand.
  1216. logger.error("Stranded-item sweep failed: %s", e)
  1217. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1218. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1219. A claim is only ever held by a live dispatch coroutine, so when this
  1220. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1221. is stale. At startup that is trivially true — no coroutine survives a
  1222. restart. It is equally true on any later tick where no upload is running,
  1223. which is what makes this safe to repeat rather than only run once.
  1224. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1225. the database is briefly unreachable at exactly the moment dispatch ends,
  1226. the claim survives and the row is wedged out of the selection query. That
  1227. used to last until the next restart (#2702 follow-up, seen when
  1228. PostgreSQL refused a connection mid-dispatch).
  1229. ``_inflight`` is populated when the task is spawned, before the coroutine
  1230. claims its row, and pruned by a done-callback that cannot run before the
  1231. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1232. race window and needs no age threshold. A size-derived upload deadline
  1233. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1234. """
  1235. if self._inflight:
  1236. return
  1237. try:
  1238. async with async_session() as db:
  1239. res = await db.execute(
  1240. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1241. )
  1242. await db.commit()
  1243. if res.rowcount:
  1244. logger.info(
  1245. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1246. res.rowcount,
  1247. " at startup" if at_startup else "",
  1248. )
  1249. except Exception as exc:
  1250. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1251. def stop(self):
  1252. """Stop the scheduler."""
  1253. self._running = False
  1254. logger.info("Print scheduler stopped")
  1255. async def check_queue(self) -> bool:
  1256. """Check for prints ready to start.
  1257. Returns True if this pass dispatched at least one item, so the caller
  1258. can loop again quickly instead of sleeping the full interval (#2555).
  1259. """
  1260. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1261. self._filament_req_memo.clear()
  1262. async with async_session() as db:
  1263. # Check if shortest-job-first scheduling is enabled
  1264. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1265. # Get all pending items in the one order the queue page shows them
  1266. # in (#3200). The first eligible item takes a printer, so this order
  1267. # decides who wins a printer that a pinned job and an "Any <model>"
  1268. # job both want. It used to start with ``printer_id``, which made the
  1269. # lane outrank the position: SQLite sorts NULL first, so model-based
  1270. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1271. # Neither is what the user dragged into place.
  1272. if sjf_enabled:
  1273. # SJF: items already jumped get top priority (starvation guard),
  1274. # then sort by print_time ascending. Items with no print time go
  1275. # last, and position breaks ties.
  1276. result = await db.execute(
  1277. select(PrintQueueItem)
  1278. .where(PrintQueueItem.status == "pending")
  1279. # Never re-select a row a dispatch worker has already claimed
  1280. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1281. # below, and the guard that lets an orphaned claim be ignored
  1282. # until startup reconciliation clears it.
  1283. .where(PrintQueueItem.dispatching_at.is_(None))
  1284. # archive/library_file are read by the cross-model gate
  1285. # (#2578); eager-load once per pass instead of a lazy-load
  1286. # (which would raise in async) per item.
  1287. .options(
  1288. selectinload(PrintQueueItem.archive),
  1289. selectinload(PrintQueueItem.library_file),
  1290. # Cross-model candidates (#671), plus each candidate's file
  1291. # for the same cross-model gate. Lazy-loading either would
  1292. # raise in async.
  1293. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1294. )
  1295. .order_by(
  1296. PrintQueueItem.been_jumped.desc(),
  1297. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1298. PrintQueueItem.position,
  1299. PrintQueueItem.id,
  1300. )
  1301. )
  1302. else:
  1303. result = await db.execute(
  1304. select(PrintQueueItem)
  1305. .where(PrintQueueItem.status == "pending")
  1306. # Skip rows already claimed by a dispatch worker (#2615).
  1307. .where(PrintQueueItem.dispatching_at.is_(None))
  1308. .options(
  1309. selectinload(PrintQueueItem.archive),
  1310. selectinload(PrintQueueItem.library_file),
  1311. # Cross-model candidates (#671), plus each candidate's file
  1312. # for the same cross-model gate. Lazy-loading either would
  1313. # raise in async.
  1314. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1315. )
  1316. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1317. )
  1318. items = list(result.scalars().all())
  1319. # Drop rows whose upload is still in flight from an earlier pass
  1320. # (#2602). They stay `pending` until the upload finishes, so without
  1321. # this a fast tick would re-select and re-dispatch the same row.
  1322. # Belt-and-suspenders with the printer exclusion below.
  1323. if self._inflight:
  1324. inflight_ids = set(self._inflight)
  1325. items = [it for it in items if it.id not in inflight_ids]
  1326. # Read plate-clear setting once per queue check. Default MUST be
  1327. # False to match the schema (SettingsSchema.require_plate_clear
  1328. # defaults False) and the frontend (toggle + card badge both treat a
  1329. # missing value as off). When no settings row exists, a True default
  1330. # here re-enabled the plate-clear gate the UI showed as disabled,
  1331. # blocking dispatch to FINISH-state printers forever with no UI path
  1332. # to clear it (#1865).
  1333. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1334. # Dispatch and track scheduled drying runs (#2638)
  1335. await self._check_scheduled_dryings(db)
  1336. if not items:
  1337. # No dispatchable pending items — still check auto-drying on idle
  1338. # printers, but keep any printer with an upload still in flight
  1339. # from an earlier pass out of it (#2602): its print is imminent,
  1340. # so it must not be auto-dried in the gap before the row flips to
  1341. # printing. Report the pass as productive while uploads run so the
  1342. # loop stays on the fast interval.
  1343. #
  1344. # Also release any keep-warm holds that got orphaned by the queue
  1345. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1346. # this early return, so call it directly with an empty candidate
  1347. # set. Without this, a printer whose queued item was cancelled or
  1348. # deleted would keep its bed at target until the max-duration
  1349. # timeout expired.
  1350. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1351. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1352. await self._check_auto_drying(db, [], inflight_printers)
  1353. await self._check_filament_low(db)
  1354. await self._check_stock_forecast(db)
  1355. return bool(self._inflight)
  1356. logger.info(
  1357. "Queue check: found %d pending items: %s",
  1358. len(items),
  1359. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1360. )
  1361. # Forget jobs that left the queue since they were last checked.
  1362. pending_ids = {i.id for i in items}
  1363. self._short_hold_checked_at = {
  1364. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1365. }
  1366. # Seed busy_printers with printers that already have an item in 'printing'
  1367. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1368. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1369. # lag several seconds behind the print command, so the next check_queue
  1370. # tick still sees IDLE and would double-dispatch onto the same printer.
  1371. # Without this guard, two pending items targeting the same printer
  1372. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1373. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1374. busy_result = await db.execute(
  1375. select(PrintQueueItem.printer_id)
  1376. .where(PrintQueueItem.status == "printing")
  1377. .where(PrintQueueItem.printer_id.is_not(None))
  1378. )
  1379. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1380. # Why each printer left this pass, recorded where the decision is
  1381. # made rather than re-derived when the summary is logged. #3018's
  1382. # bundle shows what the old summary produced: "printer 1 not
  1383. # available -- connected=True, state=IDLE" immediately followed by a
  1384. # dispatch to printer 1. Two things went wrong at once. The line read
  1385. # live state at log time, which by then no longer matched the state
  1386. # the decision was made on; and `busy_printers` holds both printers
  1387. # that cannot take work and printers this pass has claimed for it,
  1388. # which are opposite facts. It is the first line anyone greps for
  1389. # "why did my item not go out", so it has to say which.
  1390. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1391. # Printers this pass is dispatching to. They are in busy_printers so
  1392. # nothing else in the pass targets them -- that is a reservation, not
  1393. # an obstruction, and the summary says so.
  1394. claimed_printers: set[int] = set()
  1395. def mark_busy(printer_id: int, reason: str) -> None:
  1396. """Take ``printer_id`` out of this pass, recording why.
  1397. First reason wins: a printer already excluded by a stronger fact
  1398. -- a print running on it -- must not be relabelled by a weaker
  1399. check that ran later and would have excluded it anyway.
  1400. """
  1401. busy_printers.add(printer_id)
  1402. busy_reasons.setdefault(printer_id, reason)
  1403. def claim_printer(printer_id: int) -> None:
  1404. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1405. claimed_printers.add(printer_id)
  1406. mark_busy(printer_id, "selected for dispatch in this pass")
  1407. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1408. # worded for a different audience: the log wants "still inside its
  1409. # post-dispatch hold window", the queue row wants to know the printer
  1410. # is taken and nothing is broken. Only the cases that would read wrong
  1411. # as a plain "Busy" are recorded here; the rest fall back to it.
  1412. item_hold_reasons: dict[int, str] = {}
  1413. # Names and models for the printers this pass may have to write a
  1414. # waiting reason about, read once rather than per skip per tick. The
  1415. # model-based branch already has its names from `_printers_for_model`.
  1416. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1417. pinned_printers: dict[int, tuple[str, str]] = {}
  1418. if pinned_printer_ids:
  1419. pinned_rows = await db.execute(
  1420. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1421. )
  1422. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1423. def printer_label(printer_id: int) -> str:
  1424. """What to call this printer in a queue row."""
  1425. entry = pinned_printers.get(printer_id)
  1426. return (entry[0] if entry else "") or f"printer {printer_id}"
  1427. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1428. """Record why *item* is not going out, in the words the queue row shows.
  1429. The fixed-printer branch's single writer for ``waiting_reason``
  1430. (#3074). Before this, the sensor interlock was the only thing that
  1431. wrote the field there, so an item pinned to a printer that was
  1432. merely printing sat at `pending` with nothing to show for it —
  1433. indistinguishable from a queue that had stopped working — while
  1434. the same job queued as "Any <model>" explained itself.
  1435. Every exit from that branch now calls this, which is also what
  1436. replaced the interlock's old habit of clearing the field up front:
  1437. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1438. because whichever exit runs next overwrites it and the dispatch
  1439. path clears it.
  1440. A notification goes out when this item starts asking for
  1441. something, and only then: the new reason needs the user, and what
  1442. it replaced did not. "What it replaced did not" has to include a
  1443. busy-only reason, not just an empty one. The sequence this branch
  1444. actually produces is a print running (``Busy: X1C-01``) and then
  1445. the plate it left behind (``Waiting for plate confirmation``), and
  1446. testing "was the field empty" would call that no transition at all
  1447. and stay quiet through the one case worth saying out loud.
  1448. The cost is that a printer dropping offline, coming back busy and
  1449. dropping again asks twice rather than once. That is the honest
  1450. reading — it went wrong twice — and the alternative was a rule
  1451. that never fired for the case this was built for.
  1452. *notify* is how a caller opts out. The sensor interlock does: it
  1453. has never sent this notification, and a change about what the
  1454. queue *displays* is not the place to start (#1148).
  1455. """
  1456. if item.waiting_reason == reason:
  1457. return
  1458. # Busy-only and empty are the same thing here: neither is the
  1459. # queue asking the user for anything.
  1460. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1461. item.waiting_reason = reason
  1462. await db.commit()
  1463. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1464. return
  1465. try:
  1466. job_name = await self._get_job_name(db, item)
  1467. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1468. await notification_service.on_queue_job_waiting(
  1469. job_name=job_name,
  1470. target_model=(entry[1] if entry else "") or "",
  1471. waiting_reason=reason,
  1472. db=db,
  1473. )
  1474. except Exception as e:
  1475. # A queue that cannot say why it is waiting is the bug being
  1476. # fixed here; a queue that stops dispatching because a
  1477. # notification provider is down would be a worse one.
  1478. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1479. async def hold_for_printer(
  1480. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1481. ) -> None:
  1482. """Take *printer_id* out of this pass and tell the item's owner why."""
  1483. mark_busy(printer_id, log_reason)
  1484. item_hold_reasons.setdefault(printer_id, item_reason)
  1485. await hold_item(item, item_reason)
  1486. # Defense-in-depth (#1157): augment busy_printers with any printer
  1487. # still in its post-dispatch hold window. Empirically, the DB seed
  1488. # above can miss in-flight items in a multi-plate batch — same-file
  1489. # plates were being dispatched 30 s apart while the H2D was still
  1490. # digesting the first project_file. The hold is keyed in-memory and
  1491. # released by the watchdog on the success path, so it adds a layer
  1492. # that doesn't depend on DB row visibility or completion-callback
  1493. # timing.
  1494. for held_printer_id in list(self._dispatch_holds.keys()):
  1495. if self._printer_in_dispatch_hold(held_printer_id):
  1496. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1497. # Exclude printers whose upload is still in flight from an earlier
  1498. # pass (#2602). The row is `pending` until the upload finishes and
  1499. # the printing-state seed / dispatch hold above only arm once the
  1500. # upload completes, so this is what holds the printer (and, via
  1501. # busy_printers, its auto-drying) out of the pass during the upload.
  1502. for _task, inflight_pid in self._inflight.values():
  1503. if inflight_pid is not None:
  1504. mark_busy(inflight_pid, "an upload to it is still in flight")
  1505. # Snapshot taken here, before the item loop adds anything (#2801).
  1506. #
  1507. # The three sources above all mean the same thing: a print on this
  1508. # printer is running or imminent. Everything the loop adds below
  1509. # means only "the queue could not dispatch to it this pass", which
  1510. # is a different statement -- a printer waiting on a plate-clear
  1511. # acknowledgment, an offline printer, one with no matching file.
  1512. #
  1513. # Auto-drying must only see the first kind. Reading the whole set
  1514. # as "is currently printing" is what put a plate-held printer down
  1515. # the mid-print path: it capped the drying temperature, logged the
  1516. # cycle as (mid-print), and skipped the very gate that was supposed
  1517. # to hold it. The interlock block below already documents the same
  1518. # hazard and works around it by staying out of busy_printers; this
  1519. # generalises that workaround instead of repeating it per case.
  1520. dispatching_printers: set[int] = set(busy_printers)
  1521. # Printers whose last upload never reached them (#3210). After the
  1522. # snapshot above on purpose: such a printer is idle, not about to
  1523. # print, and auto-drying must keep treating it as idle.
  1524. now_mono = time.monotonic()
  1525. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1526. # can leave them out: there is no print to keep a bed warm for.
  1527. backoff_printers: set[int] = set()
  1528. # In backoff, and the "job waiting" notification for this run of
  1529. # refusals has gone out already. Their holds are written silently.
  1530. silent_hold_printers: set[int] = set()
  1531. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1532. if now_mono >= retry_at:
  1533. del self._upload_backoff[backoff_pid]
  1534. continue
  1535. backoff_printers.add(backoff_pid)
  1536. if backoff_pid in self._upload_refusal_notified:
  1537. silent_hold_printers.add(backoff_pid)
  1538. else:
  1539. self._upload_refusal_notified.add(backoff_pid)
  1540. mark_busy(
  1541. backoff_pid,
  1542. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1543. )
  1544. item_hold_reasons.setdefault(
  1545. backoff_pid,
  1546. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1547. )
  1548. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1549. # enclosure door left open, say. The fixed-printer branch turns
  1550. # this into a waiting_reason the user can act on; the model-based
  1551. # branch hides these printers from the matcher so an "Any <model>"
  1552. # job runs on a sibling instead of queueing behind the held one.
  1553. #
  1554. # Deliberately NOT merged into busy_printers, even though that set
  1555. # already means "unavailable this pass". _check_auto_drying reads
  1556. # it as "is currently printing" and would put an idle-but-held
  1557. # printer down the mid-print drying path, which caps the drying
  1558. # temperature and skips the queue-only gating. A held printer is
  1559. # idle; it should dry exactly as it did before.
  1560. #
  1561. # Only sensors we actually read and found alerting appear here; see
  1562. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1563. # holds nothing.
  1564. interlocked: dict[int, str] = {}
  1565. try:
  1566. interlocked = await ha_sensor_manager.blocked_printers(db)
  1567. except Exception as e:
  1568. # Never let the interlock stop the queue running. A broken
  1569. # lookup means no holds, not no dispatches.
  1570. logger.warning("Home Assistant interlock check failed: %s", e)
  1571. interlocked = {}
  1572. # Printers a smart plug can bring back, read once for the whole pass
  1573. # (#2786). Used by the model-based branch both to word "Offline" in
  1574. # the waiting reason and to decide what the wake step may switch on.
  1575. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1576. # At most one power-on per queue check. Each one blocks this loop
  1577. # for the boot wait, so a queue of ten class-targeted jobs must not
  1578. # switch on ten printers inside a single pass — the next pass wakes
  1579. # the next one (#2786).
  1580. power_on_attempted = False
  1581. # Log skip reasons once per queue check (not per item)
  1582. skip_reasons: dict[str, int] = {}
  1583. # Items selected for dispatch in this pass, one per printer. The
  1584. # loop below only *decides* — the uploads happen afterwards, in
  1585. # parallel (#2555). See _dispatch_selected().
  1586. dispatch_ids: list[int] = []
  1587. # Library rows queued with `cleanup_library_after_dispatch` (the
  1588. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1589. # that prints them: the row is deleted and the 3MF is unlinked from
  1590. # disk. That was safe only because dispatch was serial. Run two of
  1591. # them against the same row at once and the second DELETE matches no
  1592. # row (StaleDataError), and the winner's unlink can pull the file out
  1593. # from under the loser's in-flight upload.
  1594. #
  1595. # Only the cleanup flag mutates the row. An ordinary library print
  1596. # just reads it, so the common fan-out — one file, many printers,
  1597. # which is exactly the reporter's workload — still goes out fully in
  1598. # parallel. Narrow the guard to the mutating case; do not serialise
  1599. # the case the whole fix exists for.
  1600. dispatch_libs: set[int] = set()
  1601. consumed_libs: set[int] = set()
  1602. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1603. """True if dispatching `candidate` now would race another item's cleanup."""
  1604. lib_id = candidate.library_file_id
  1605. if lib_id is None:
  1606. return False
  1607. if candidate.cleanup_library_after_dispatch:
  1608. # We would delete a row someone else in this pass is reading.
  1609. return lib_id in dispatch_libs
  1610. # Someone else in this pass will delete the row out from under us.
  1611. return lib_id in consumed_libs
  1612. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1613. lib_id = candidate.library_file_id
  1614. if lib_id is None:
  1615. return
  1616. dispatch_libs.add(lib_id)
  1617. if candidate.cleanup_library_after_dispatch:
  1618. consumed_libs.add(lib_id)
  1619. # Printer scope of each job's creator (#1727), so an "any <model>"
  1620. # job only lands on a printer its creator may use. Loaded lazily,
  1621. # once per creator per pass.
  1622. from backend.app.core.auth import is_auth_enabled
  1623. scope_auth_enabled = await is_auth_enabled(db)
  1624. creator_scopes: dict[int, PrinterScope] = {}
  1625. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1626. if not scope_auth_enabled or user_id is None:
  1627. return ALL_PRINTERS
  1628. if user_id not in creator_scopes:
  1629. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1630. return creator_scopes[user_id]
  1631. for item in items:
  1632. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1633. if item.scheduled_time:
  1634. sched = item.scheduled_time
  1635. if sched.tzinfo is None:
  1636. sched = sched.replace(tzinfo=timezone.utc)
  1637. if sched > datetime.now(timezone.utc):
  1638. # Waiting on the clock, not on a printer.
  1639. await hold_item(item, None)
  1640. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1641. continue
  1642. # Skip items that require manual start, except an "any model"
  1643. # job held for low filament that another idle printer can now
  1644. # run: that one is moved there and carries on below (#3137).
  1645. if item.manual_start and not (
  1646. item.filament_short
  1647. and await self._release_short_model_hold(
  1648. db,
  1649. item,
  1650. busy_printers | interlocked.keys(),
  1651. require_plate_clear,
  1652. await _creator_scope(item.created_by_id),
  1653. )
  1654. ):
  1655. # Waiting on the user, not on a printer. Cleared here because
  1656. # this is the last pass that will look at the row: a staged
  1657. # item never reaches the branches below again, so a reason
  1658. # left from before it was staged would stand forever (#3074).
  1659. # The one exception is the unmatched-filament hold, whose
  1660. # reason was written at staging and is why the item waits:
  1661. # it names the filament to load (#2799). Pressing start
  1662. # clears manual_start, and the branches below overwrite it.
  1663. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1664. await hold_item(item, keep)
  1665. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1666. continue
  1667. if item.printer_id and item.printer_id not in pinned_printers:
  1668. # Moved by the release above to a printer no row named when
  1669. # the labels were read.
  1670. moved_to = await self._get_printer(db, item.printer_id)
  1671. if moved_to is not None:
  1672. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1673. if item.printer_id:
  1674. # Its creator may no longer use this printer (#1727): an
  1675. # admin took it away from their group after the job was
  1676. # queued, say to keep it free for a training session. Held,
  1677. # not failed, so it starts if access comes back or the user
  1678. # moves it to a printer they still have.
  1679. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1680. await hold_item(
  1681. item,
  1682. "Its owner no longer has access to this printer — move it to another printer",
  1683. notify=False,
  1684. )
  1685. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1686. continue
  1687. # Held by a sensor interlock (#1148). Checked before the
  1688. # busy_printers test that would otherwise swallow it
  1689. # silently — "waiting for a printer" and "waiting for you
  1690. # to shut the enclosure" need to read differently, and only
  1691. # one of them is something the user can fix.
  1692. #
  1693. # It used to be the only thing that wrote a waiting_reason on
  1694. # this branch, and it cleared the field up front so a lifted
  1695. # hold could not leave a shut door reading "Waiting on
  1696. # Enclosure Door". `hold_item` carries that guarantee now —
  1697. # every exit below writes — so the clear is gone and the
  1698. # interlock is an ordinary hold like the rest (#3074).
  1699. interlock_reason = interlocked.get(item.printer_id)
  1700. if interlock_reason:
  1701. # Silent, exactly as it has always been. #1148 built this
  1702. # as a hold that shows on the row, never as an alert, and
  1703. # routing it through the shared writer must not quietly
  1704. # turn every open door into a notification.
  1705. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1706. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1707. continue
  1708. # Specific printer assignment (existing behavior)
  1709. if item.printer_id in busy_printers:
  1710. # Whatever took the printer out of this pass — a print
  1711. # already running on it, a post-dispatch hold, an upload
  1712. # still in flight, an item ahead of this one in the same
  1713. # pass — reads the same way from the queue: the printer is
  1714. # taken and this item is in line for it. The exceptions
  1715. # that do not (an offline printer, say) recorded their own
  1716. # wording in `item_hold_reasons` when they held it.
  1717. await hold_item(
  1718. item,
  1719. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1720. notify=item.printer_id not in silent_hold_printers,
  1721. )
  1722. continue
  1723. # Check if printer is idle
  1724. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1725. printer_connected = printer_manager.is_connected(item.printer_id)
  1726. # If printer not connected, try to power on via smart plug
  1727. if not printer_connected:
  1728. plugs = await self._get_smart_plugs(db, item.printer_id)
  1729. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1730. if auto_on_plugs:
  1731. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1732. # Power on using the plug that actually feeds the printer, and
  1733. # wait for it to boot on that one only (#2629).
  1734. primary_plug = self._pick_power_plug(auto_on_plugs)
  1735. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1736. if powered_on:
  1737. # Also turn on any remaining auto_on plugs (e.g., filter)
  1738. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1739. try:
  1740. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1741. await service.turn_on(extra_plug)
  1742. logger.info(
  1743. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1744. )
  1745. except Exception as e:
  1746. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1747. printer_connected = True
  1748. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1749. else:
  1750. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1751. await hold_for_printer(
  1752. item,
  1753. item.printer_id,
  1754. "smart-plug power-on failed",
  1755. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1756. )
  1757. continue
  1758. else:
  1759. # No plug or auto_on disabled. Worded exactly as the
  1760. # model-based branch words it (#2786): this is the one
  1761. # entry on that list the user has to act on, because
  1762. # Bambuddy will never switch this printer on itself.
  1763. await hold_for_printer(
  1764. item,
  1765. item.printer_id,
  1766. "offline, with no smart plug to power it on",
  1767. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1768. )
  1769. continue
  1770. # Check if printer is idle (busy with another print)
  1771. if not printer_idle:
  1772. await hold_for_printer(
  1773. item,
  1774. item.printer_id,
  1775. "not idle",
  1776. self._pinned_hold_reason(
  1777. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1778. ),
  1779. )
  1780. continue
  1781. # Drying blocks the queue, if the user asked it to. A hold
  1782. # is a skip like any other, so it belongs here with the
  1783. # rest of the availability checks.
  1784. # A parked timer (#2896) never ends, so it must not hold the
  1785. # queue; it stays tracked so the stop paths still reach it.
  1786. if (
  1787. self._drying_in_progress.get(item.printer_id)
  1788. and not self._drying_is_only_parked(item.printer_id)
  1789. and await self._get_bool_setting(db, "queue_drying_block")
  1790. ):
  1791. # Busy-shaped on purpose: the cycle ends on its own and
  1792. # the job goes out, so there is nothing to alert about.
  1793. await hold_for_printer(
  1794. item,
  1795. item.printer_id,
  1796. "drying, and drying is set to block the queue",
  1797. f"Busy: {printer_label(item.printer_id)} (drying)",
  1798. )
  1799. continue
  1800. # Check condition (previous print success)
  1801. if item.require_previous_success:
  1802. if not await self._check_previous_success(db, item):
  1803. item.status = "skipped"
  1804. item.error_message = "Previous print failed or was aborted"
  1805. item.completed_at = datetime.now(timezone.utc)
  1806. # Not pending any more, so not waiting for anything.
  1807. item.waiting_reason = None
  1808. await db.commit()
  1809. logger.info("Skipped queue item %s - previous print failed", item.id)
  1810. # Send notification
  1811. job_name = await self._get_job_name(db, item)
  1812. printer = await self._get_printer(db, item.printer_id)
  1813. await notification_service.on_queue_job_skipped(
  1814. job_name=job_name,
  1815. printer_id=item.printer_id,
  1816. printer_name=printer.name if printer else "Unknown",
  1817. reason="Previous print failed or was aborted",
  1818. db=db,
  1819. )
  1820. continue
  1821. # Resolve the AMS mapping when it's missing OR unresolved
  1822. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1823. # frontend status-load race can persist [-1] (#2589) — and
  1824. # must be recomputed from live trays rather than trusted.
  1825. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1826. if unmappable:
  1827. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1828. continue
  1829. # Filament-deficit pre-dispatch check (#1496). If the
  1830. # assigned spool can't satisfy any required slot grams,
  1831. # promote the item to manual_start so the user must
  1832. # acknowledge via the ▶ button (which re-checks live).
  1833. if await self._block_on_filament_deficit(db, item):
  1834. # Now staged for the user to start by hand, and the row
  1835. # shows the filament-short badge instead. Cleared because
  1836. # a staged item never reaches this branch again.
  1837. await hold_item(item, None)
  1838. continue
  1839. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1840. # than let the printer pick a substitute for a slot the
  1841. # matcher could not resolve on this printer.
  1842. if await self._block_on_unmatched_filament(db, item):
  1843. continue
  1844. # Hold this item back for the next pass rather than racing
  1845. # another dispatch over the same transient library row. The
  1846. # printer is still marked busy so a later item does not jump
  1847. # its place in this printer's queue.
  1848. if _library_row_conflict(item):
  1849. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1850. await hold_for_printer(
  1851. item,
  1852. item.printer_id,
  1853. "holding its place while another item releases a library row",
  1854. f"Busy: {printer_label(item.printer_id)}",
  1855. )
  1856. continue
  1857. # Print takes priority: stop a cycle Bambuddy armed, now
  1858. # that this item is definitely going out.
  1859. #
  1860. # Placement is the whole point (#2801). This used to sit up
  1861. # with the availability checks, inside the not-idle branch
  1862. # -- so it fired only on the passes where the print was NOT
  1863. # going to start, and never on the ones where it was.
  1864. # Drying is not one of the things `_is_printer_idle` looks
  1865. # at, so a stop could never have unblocked that printer
  1866. # anyway; the cycle was spent for nothing, auto-drying
  1867. # re-armed on the next tick, and a plate left
  1868. # unacknowledged turned that into a loop on the scheduler
  1869. # interval. Every skip between there and here -- a failed
  1870. # previous print, an unmappable item, a filament deficit, a
  1871. # contested library row -- is another way to lose a cycle
  1872. # for a print that never happens, which is why this waits
  1873. # until the decision is actually made.
  1874. if self._drying_in_progress.get(
  1875. item.printer_id
  1876. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1877. await self._stop_drying(item.printer_id)
  1878. # Queue the dispatch instead of running it here — see
  1879. # _dispatch_selected(). busy_printers still gets the printer
  1880. # immediately, so nothing else in this pass can target it.
  1881. #
  1882. # The reason goes first: this item is not waiting for anything
  1883. # any more, and the model-based branch clears its own at the
  1884. # equivalent moment (#3074).
  1885. await hold_item(item, None)
  1886. _claim_library_row(item)
  1887. dispatch_ids.append(item.id)
  1888. claim_printer(item.printer_id)
  1889. # SJF starvation guard: mark items that were jumped
  1890. if sjf_enabled and item.print_time_seconds is not None:
  1891. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1892. for other in items:
  1893. if (
  1894. other.id != item.id
  1895. and other.id not in dispatch_ids
  1896. and other.status == "pending"
  1897. and _could_take_printer(other, item.printer_id, pinned_model)
  1898. and not other.been_jumped
  1899. and other.position < item.position
  1900. and (
  1901. other.print_time_seconds is None
  1902. or other.print_time_seconds > item.print_time_seconds
  1903. )
  1904. ):
  1905. other.been_jumped = True
  1906. await db.commit()
  1907. elif item.target_model or item.variants:
  1908. # Model-based assignment - find any idle printer of matching model.
  1909. # A plain model-based item has exactly one candidate, built from
  1910. # its own columns. A cross-model item (#671) has one per sliced
  1911. # variant and takes the first that matches, walking them in the
  1912. # user's priority order so the pick is reproducible when more
  1913. # than one printer is free in the same pass.
  1914. candidates = _candidates_for(item)
  1915. item_scope = await _creator_scope(item.created_by_id)
  1916. printer_id = None
  1917. chosen: _ModelCandidate | None = None
  1918. per_model_reasons: list[tuple[str | None, str]] = []
  1919. # Candidates that cleared the cross-model gate below. The
  1920. # smart-plug wake step may only consider these — waking a
  1921. # printer for a file that can never legally run on it is
  1922. # worse than not waking at all (#2786).
  1923. wakeable_candidates: list[_ModelCandidate] = []
  1924. if not candidates:
  1925. # Every candidate file has been deleted or trashed out from
  1926. # under this item. Hold it with something the user can act
  1927. # on rather than letting it look dispatchable forever.
  1928. per_model_reasons.append(
  1929. (
  1930. item.target_model,
  1931. "Every file for this job has been deleted — add a file back or remove the item",
  1932. )
  1933. )
  1934. for candidate in candidates:
  1935. effective_types, filament_overrides = _filament_constraints(candidate)
  1936. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1937. # for an incompatible model to a printer, no matter how the
  1938. # row got into the DB (old rows, direct API writes). Held
  1939. # as pending with an actionable waiting_reason — the user
  1940. # fixes it by editing the item's target model.
  1941. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1942. per_model_reasons.append(
  1943. (
  1944. candidate.target_model,
  1945. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  1946. f"{candidate.target_model} — edit the item and fix its target model",
  1947. )
  1948. )
  1949. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  1950. continue
  1951. wakeable_candidates.append(candidate)
  1952. async def is_short(
  1953. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  1954. ) -> bool:
  1955. # The check reads the file and plate off the item,
  1956. # so it must hold this candidate's. Resolving is
  1957. # safe to repeat, and the winner is resolved again
  1958. # below.
  1959. self._resolve_variant(item, candidate)
  1960. return await self._filament_short_on(db, item, pid)
  1961. match_id, match_reason = await self._find_idle_printer_for_model(
  1962. db,
  1963. candidate.target_model,
  1964. # Sensor-held printers are unavailable to the
  1965. # matcher but stay out of busy_printers itself
  1966. # (#1148) — see where `interlocked` is built.
  1967. busy_printers | interlocked.keys(),
  1968. effective_types,
  1969. item.target_location,
  1970. filament_overrides=filament_overrides,
  1971. require_plate_clear=require_plate_clear,
  1972. wakeable_ids=wakeable_printer_ids,
  1973. printer_scope=item_scope,
  1974. is_short=is_short,
  1975. )
  1976. if match_id:
  1977. printer_id = match_id
  1978. chosen = candidate
  1979. break
  1980. per_model_reasons.append((candidate.target_model, match_reason or ""))
  1981. # Nothing is available and nothing has been woken this pass:
  1982. # switch one matching printer on. Assignment is left to the
  1983. # next pass, which sees the booted printer's live state
  1984. # instead of guessing at it seconds after connect (#2786).
  1985. if printer_id is None and not power_on_attempted and wakeable_candidates:
  1986. woken_id, attempted_id = await self._wake_printer_for_model(
  1987. db,
  1988. wakeable_candidates,
  1989. item.target_location,
  1990. busy_printers | interlocked.keys(),
  1991. wakeable_printer_ids,
  1992. require_plate_clear,
  1993. printer_scope=item_scope,
  1994. )
  1995. # An attempt spends the pass's one wake whether or not
  1996. # it worked: it has already blocked the queue loop for
  1997. # the boot wait. A failed printer is held out of later
  1998. # passes by its own cool-off, deliberately NOT by
  1999. # busy_printers — it is off, not busy, and labelling it
  2000. # busy would both misdescribe it in every later item's
  2001. # waiting reason and suppress the notification, since
  2002. # an all-busy reason is treated as needing no action.
  2003. power_on_attempted = attempted_id is not None
  2004. if woken_id is not None:
  2005. # Hold this item back rather than dispatching onto a
  2006. # printer whose AMS has not reported yet.
  2007. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2008. continue
  2009. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2010. # Fold the winning variant's file and settings onto the item
  2011. # before anything else looks at them — the guards below and
  2012. # every step of the dispatch read the item's own columns.
  2013. if chosen is not None:
  2014. self._resolve_variant(item, chosen)
  2015. # Update waiting_reason if changed and send notification when first waiting
  2016. if item.waiting_reason != waiting_reason:
  2017. was_waiting = item.waiting_reason is not None
  2018. item.waiting_reason = waiting_reason
  2019. await db.commit()
  2020. # Send waiting notification only when transitioning to waiting state
  2021. # and the reason requires user action (not just "all printers busy")
  2022. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  2023. job_name = await self._get_job_name(db, item)
  2024. await notification_service.on_queue_job_waiting(
  2025. job_name=job_name,
  2026. target_model=_candidate_model_label(candidates) or item.target_model,
  2027. waiting_reason=waiting_reason,
  2028. db=db,
  2029. )
  2030. if printer_id:
  2031. # Before claiming the printer: hold back rather than race
  2032. # another dispatch over the same transient library row.
  2033. # Checked here so a held item does not get a printer
  2034. # assigned and then sit on it. See _library_row_conflict().
  2035. #
  2036. # No busy_printers.add() here, unlike the fixed-printer
  2037. # branch above: that one protects its printer's own queue
  2038. # ordering, but this item was never assigned to `printer_id`
  2039. # — the matcher merely offered it. Marking it busy would
  2040. # strand an idle printer for the rest of the pass.
  2041. if _library_row_conflict(item):
  2042. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2043. continue
  2044. # Check condition (previous print success) before assigning
  2045. if item.require_previous_success:
  2046. if not await self._check_previous_success(db, item):
  2047. item.status = "skipped"
  2048. item.error_message = "Previous print failed or was aborted"
  2049. item.completed_at = datetime.now(timezone.utc)
  2050. await db.commit()
  2051. logger.info("Skipped queue item %s - previous print failed", item.id)
  2052. # Send notification
  2053. job_name = await self._get_job_name(db, item)
  2054. printer = await self._get_printer(db, printer_id)
  2055. await notification_service.on_queue_job_skipped(
  2056. job_name=job_name,
  2057. printer_id=printer_id,
  2058. printer_name=printer.name if printer else "Unknown",
  2059. reason="Previous print failed or was aborted",
  2060. db=db,
  2061. )
  2062. continue
  2063. # Assign printer and start - clear waiting reason
  2064. item.printer_id = printer_id
  2065. item.waiting_reason = None
  2066. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2067. # Send assignment notification
  2068. job_name = await self._get_job_name(db, item)
  2069. printer = await self._get_printer(db, printer_id)
  2070. await notification_service.on_queue_job_assigned(
  2071. job_name=job_name,
  2072. printer_id=printer_id,
  2073. printer_name=printer.name if printer else "Unknown",
  2074. target_model=item.target_model,
  2075. db=db,
  2076. )
  2077. # A mapping on this item was not made for the printer just
  2078. # picked: it came with a job moved here from a fixed
  2079. # printer, or from a variant. Its tray IDs can name a
  2080. # tray of the right type in another colour here, which
  2081. # the fit check lets through (#3239). Match afresh, by
  2082. # type and colour.
  2083. if item.ams_mapping:
  2084. logger.info(
  2085. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2086. item.id,
  2087. item.ams_mapping,
  2088. printer_id,
  2089. )
  2090. item.ams_mapping = None
  2091. # Resolve the AMS mapping for the assigned printer. It is
  2092. # always missing here, so this computes it, and it also
  2093. # self-heals a bogus stored [-1] (#2589).
  2094. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2095. if unmappable:
  2096. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2097. continue
  2098. # Filament-deficit pre-dispatch check (#1496).
  2099. if await self._block_on_filament_deficit(db, item):
  2100. continue
  2101. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2102. # selection already filters on filament type, so this is a
  2103. # backstop for an AMS that changed between assignment and
  2104. # dispatch, and for a type loaded on the wrong nozzle.
  2105. # The assignment made above is released with the hold —
  2106. # this item asked for a model, not this printer.
  2107. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2108. continue
  2109. _claim_library_row(item)
  2110. dispatch_ids.append(item.id)
  2111. claim_printer(printer_id)
  2112. # SJF starvation guard: mark items that were jumped
  2113. if sjf_enabled and item.print_time_seconds is not None:
  2114. for other in items:
  2115. if (
  2116. other.id != item.id
  2117. and other.id not in dispatch_ids
  2118. and other.status == "pending"
  2119. and _could_take_printer(other, printer_id, item.target_model)
  2120. and not other.been_jumped
  2121. and other.position < item.position
  2122. and (
  2123. other.print_time_seconds is None
  2124. or other.print_time_seconds > item.print_time_seconds
  2125. )
  2126. ):
  2127. other.been_jumped = True
  2128. await db.commit()
  2129. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2130. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2131. # skip summary that only lands after the transfers have finished is
  2132. # useless for working out why an item did not go out.
  2133. if skip_reasons:
  2134. logger.info("Queue skip summary: %s", skip_reasons)
  2135. for pid in sorted(busy_printers):
  2136. reason = busy_reasons.get(pid, "no reason recorded")
  2137. if pid in claimed_printers:
  2138. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2139. continue
  2140. # The three live fields stay, because they are what someone
  2141. # reading a bundle wants next -- but they are labelled as read
  2142. # now, not as the state the decision was made on, which is what
  2143. # made the old line contradict itself.
  2144. state = printer_manager.get_status(pid)
  2145. logger.info(
  2146. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2147. pid,
  2148. reason,
  2149. printer_manager.is_connected(pid),
  2150. state.state if state else "NO_STATUS",
  2151. printer_manager.is_awaiting_plate_clear(pid),
  2152. )
  2153. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2154. # selection and `_launch_uploads`, so anything raising here would
  2155. # discard this tick's selections — computed AMS mappings and all —
  2156. # and, on a persistent fault, stop the queue dispatching entirely.
  2157. # Same reasoning as the deficit check's guard below: never let an
  2158. # auxiliary check wedge the queue. The bed simply stays wherever it
  2159. # was, and the next tick tries again.
  2160. try:
  2161. await self._apply_keep_warm(
  2162. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2163. )
  2164. except Exception as e:
  2165. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2166. # Read the concurrency limit BEFORE the commit below, not inside
  2167. # _dispatch_selected(). A SELECT on this session after the commit
  2168. # implicitly opens a fresh transaction that nothing then closes, and
  2169. # it would stay open for the whole dispatch — minutes of "idle in
  2170. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2171. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2172. # checkpointed while every dispatch is writing to it.
  2173. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2174. # Selection is done; every decision above is recorded on `db`
  2175. # (model-based printer assignment, computed ams_mapping). Flush it
  2176. # before the dispatch tasks open their own sessions, or they will
  2177. # read a row that still says printer_id=None. This also releases the
  2178. # connection back to the pool for the duration of the dispatch.
  2179. await db.commit()
  2180. if dispatch_ids:
  2181. item_printers = {it.id: it.printer_id for it in items}
  2182. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2183. # Auto-drying: start drying on idle printers that have no pending queue items
  2184. await self._check_auto_drying(db, items, dispatching_printers)
  2185. # Low filament: alert on assigned spools that have crossed their
  2186. # low-stock threshold (#2913). Runs on both paths out of this method
  2187. # for the same reason auto-drying does — an empty queue does not mean
  2188. # the spools in the printers stopped mattering.
  2189. await self._check_filament_low(db)
  2190. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2191. # is about to run out before a replenishment could arrive (#2955).
  2192. await self._check_stock_forecast(db)
  2193. # Keep the loop on the fast interval while any upload is in flight so
  2194. # a slot freed mid-tick refills within seconds rather than after the
  2195. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2196. # deferred because the pool was full) also counts as productive.
  2197. return bool(dispatch_ids) or bool(self._inflight)
  2198. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2199. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2200. Dispatch used to happen inline in the selection loop: ``await
  2201. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2202. performs the FTP upload, that serialized every printer behind every
  2203. other printer's transfer even though the printers are independent
  2204. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2205. gather was awaited before ``check_queue`` returned, so the run loop
  2206. stayed blocked until the *slowest* upload in the batch finished — a
  2207. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2208. 93-printer farm even as other printers came free (#2602).
  2209. Each upload now runs as an independent background task tracked in
  2210. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2211. `pending` until their upload completes) and their printers from the
  2212. next pass's selection, and this method launches at most
  2213. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2214. the next fast tick instead of waiting out the whole batch. The bound
  2215. exists because the printers are independent but the host is not: each
  2216. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2217. file handle.
  2218. The no-overlapping-dispatch invariant the batch-await used to provide
  2219. is now carried by the in-flight exclusion in check_queue. Everything
  2220. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2221. per-printer hold, and each item's independent failure handling — still
  2222. lives in ``_start_print`` and runs per task exactly as before.
  2223. Synchronous on purpose: it registers every launched task into
  2224. ``self._inflight`` before returning, so the next (sequential) tick sees
  2225. an accurate in-flight count with no interleaving await.
  2226. """
  2227. free = limit - len(self._inflight)
  2228. if free <= 0:
  2229. logger.info(
  2230. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2231. len(self._inflight),
  2232. limit,
  2233. len(item_ids),
  2234. item_ids,
  2235. )
  2236. return
  2237. to_launch = item_ids[:free]
  2238. deferred = item_ids[free:]
  2239. logger.info(
  2240. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2241. len(to_launch),
  2242. len(self._inflight),
  2243. limit,
  2244. f" — deferring {deferred} to a later tick" if deferred else "",
  2245. )
  2246. for item_id in to_launch:
  2247. task = spawn_background_task(
  2248. self._dispatch_one(item_id, item_printers.get(item_id)),
  2249. name=f"queue-upload-{item_id}",
  2250. )
  2251. self._inflight[item_id] = (task, item_printers.get(item_id))
  2252. # Prune on completion so the freed slot is refillable next tick.
  2253. # spawn_background_task already logs any uncaught exception; this
  2254. # only reclaims the pool slot (fires on success, failure, or cancel).
  2255. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2256. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2257. """Upload + start one queue item in its own session (pool worker, #2602).
  2258. Its own session: pool workers run concurrently and an AsyncSession is
  2259. not safe to share across tasks; it also keeps a slow upload from pinning
  2260. the scheduler's session (and, on SQLite, its transaction) open for the
  2261. transfer's duration.
  2262. ``selected_printer_id`` is the printer this item was selected for, taken
  2263. from the same snapshot the caller used. It exists so the preheat pin can
  2264. be unwound on the paths that never reach the ``finally`` below — see the
  2265. claim failure a few lines down. Optional so the direct-call tests keep
  2266. working; when it is absent those paths simply behave as they did before.
  2267. """
  2268. async with async_session() as item_db:
  2269. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2270. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2271. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2272. # routes reject reassignment (409), so printer_id can't change out from
  2273. # under the in-flight upload and split the queue row from the
  2274. # archive/expected-print/physical command.
  2275. if not await self._claim_for_dispatch(item_db, item_id):
  2276. logger.info(
  2277. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2278. item_id,
  2279. )
  2280. # This return is outside the try/finally below, so the rollback
  2281. # has to happen here. Selecting this item already handed any
  2282. # keep-warm hold on its printer over to the preheat pin
  2283. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2284. # unwind it. Bailing without doing so leaves the bed hot with
  2285. # nothing tracking it: the keep-warm entry is gone, so the
  2286. # max-duration cap no longer applies, and if this was the
  2287. # printer's last pending item nothing else will ever turn it
  2288. # off. Reachable whenever a cancel or delete lands between
  2289. # selection and the claim.
  2290. if selected_printer_id is not None:
  2291. self._rollback_preheat_pin(item_id, selected_printer_id)
  2292. return
  2293. # Seeded from the caller's snapshot so the `item vanished` return
  2294. # below still unwinds the pin; overwritten with the row's own
  2295. # printer_id as soon as we have it.
  2296. item_printer_id: int | None = selected_printer_id
  2297. try:
  2298. item = await item_db.get(PrintQueueItem, item_id)
  2299. if not item:
  2300. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2301. return
  2302. item_printer_id = item.printer_id
  2303. await self._start_print(item_db, item)
  2304. finally:
  2305. # Undo an expected-print registration whose print command never
  2306. # went out. One choke point covers every way `_start_print` can
  2307. # end without sending: a raised exception (a DB failure mid-
  2308. # dispatch is the reported case), an early return, a cancel
  2309. # winning the #1853 CAS, or `start_print()` returning False.
  2310. # A confirmed send removes the entry itself, so this is a no-op
  2311. # on the happy path.
  2312. self._rollback_unconfirmed_expected_print(item_id)
  2313. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2314. # reservation survives only after start_print() accepted the
  2315. # command. Failure, cancellation, deferral, and exceptions all
  2316. # release it here.
  2317. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2318. # Unwind preheat state (bed/chamber/airduct) if the
  2319. # dispatch aborted before the print's own gcode took over.
  2320. # `_start_print` clears the pin on successful `start_print()`;
  2321. # anything still present here is by definition an aborted
  2322. # dispatch and gets rolled back so the printer isn't left
  2323. # heating for a job that isn't happening.
  2324. if item_printer_id is not None:
  2325. self._rollback_preheat_pin(item_id, item_printer_id)
  2326. # The cancellation flag only has meaning while this dispatch is
  2327. # running; drop it so the set cannot grow without bound and a
  2328. # re-queued item never inherits a stale cancellation.
  2329. self._cancelled_dispatches.discard(item_id)
  2330. # Release the claim on every exit. Once dispatch has finished the
  2331. # row's status carries the lock (printing/failed/cancelled are all
  2332. # != pending), so the token is only needed for the duration of the
  2333. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2334. # dispatchable again on the next tick.
  2335. await self._clear_dispatch_claim(item_db, item_id)
  2336. async def _requeue_after_upload_refused(
  2337. self,
  2338. db: AsyncSession,
  2339. item: PrintQueueItem,
  2340. printer: Printer,
  2341. error_msg: str,
  2342. toast_uid: int | None,
  2343. ) -> None:
  2344. """Put an item back in the queue after its file never reached the printer (#3210).
  2345. The item keeps its printer. Its AMS mapping was computed against that
  2346. printer's trays, and nothing on the row says whether a mapping was
  2347. computed or set by the user, so moving it to a sibling could print from
  2348. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2349. keeps every other item away from it; this one waits there and is the
  2350. only thing that knocks again, once per backoff window. The window
  2351. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2352. `dispatch_attempts` is not charged: that budget bounds a printer that
  2353. takes the file and then never starts, which this is not.
  2354. """
  2355. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2356. self._upload_refusals[printer.id] = refusals
  2357. backoff = _upload_backoff_seconds(refusals)
  2358. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2359. # The row is still `pending` -- it only moves to `printing` after a
  2360. # successful upload -- so there is no status to write back. Writing one
  2361. # anyway would undo a cancel that landed during the upload.
  2362. if item.error_message:
  2363. item.error_message = None
  2364. await db.commit()
  2365. logger.warning(
  2366. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2367. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2368. item.id,
  2369. printer.id,
  2370. printer.name,
  2371. error_msg,
  2372. refusals,
  2373. backoff,
  2374. )
  2375. try:
  2376. # Closes the dispatch toast for this attempt. Without it the toast
  2377. # keeps spinning on an upload that has ended.
  2378. await ws_manager.send_queue_item_failed(
  2379. user_id=toast_uid,
  2380. queue_item_id=item.id,
  2381. printer_id=item.printer_id,
  2382. reason="upload_failed",
  2383. )
  2384. except Exception:
  2385. pass # toast is best-effort
  2386. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2387. """Drop an expectation for a print command that was never sent.
  2388. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2389. where the interesting exception is usually the one already propagating.
  2390. """
  2391. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2392. if pending is None:
  2393. return
  2394. printer_id, remote_filename, archive_id = pending
  2395. try:
  2396. from backend.app.main import unregister_expected_print
  2397. unregister_expected_print(printer_id, remote_filename, archive_id)
  2398. except Exception:
  2399. logger.warning(
  2400. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2401. item_id,
  2402. printer_id,
  2403. remote_filename,
  2404. archive_id,
  2405. exc_info=True,
  2406. )
  2407. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2408. """Release a queue reservation without touching the dispatch session."""
  2409. if item_id not in self._unconfirmed_budget_reservations:
  2410. return
  2411. for attempt in range(1, 4):
  2412. async with async_session() as cleanup_db:
  2413. try:
  2414. await release_budget_reservation(
  2415. cleanup_db,
  2416. source_type="print_queue",
  2417. source_id=item_id,
  2418. status="released",
  2419. )
  2420. await cleanup_db.commit()
  2421. self._unconfirmed_budget_reservations.discard(item_id)
  2422. return
  2423. except Exception as exc:
  2424. try:
  2425. await cleanup_db.rollback()
  2426. except Exception:
  2427. pass
  2428. if attempt == 3:
  2429. logger.error(
  2430. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2431. item_id,
  2432. attempt,
  2433. exc,
  2434. )
  2435. return
  2436. await asyncio.sleep(0.5 * attempt)
  2437. @staticmethod
  2438. def _reported_bed_target(printer_id: int) -> int | None:
  2439. """The bed target firmware currently reports, or None if it can't be read.
  2440. None means "no evidence", not "zero" — callers must not treat it as a
  2441. temperature. Deliberately total: this feeds cleanup paths that run in a
  2442. ``finally``, where a malformed status must not become the exception the
  2443. caller sees.
  2444. """
  2445. try:
  2446. state = printer_manager.get_status(printer_id)
  2447. if state is None:
  2448. return None
  2449. temps = state.temperatures
  2450. if not isinstance(temps, dict):
  2451. return None
  2452. return int(float(temps.get("bed_target", 0) or 0))
  2453. except (TypeError, ValueError, AttributeError):
  2454. return None
  2455. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2456. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2457. Turns the bed heater off, the chamber heater off, and opens the
  2458. airduct flap back to cooling — for whichever of those preheat
  2459. actually applied. `_start_print` clears the pin on successful
  2460. `start_print()`; anything still present when `_dispatch_one` exits
  2461. is by definition an aborted dispatch and gets rolled back here.
  2462. The bed is the one action that can be declined: if firmware has since
  2463. been given a target other than the one we pinned, it belongs to someone
  2464. else and is left alone. See the comment at that branch.
  2465. Also called directly from `_dispatch_one`'s claim-failure return, which
  2466. never reaches the ``finally``.
  2467. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2468. """
  2469. pin = self._preheat_pin.pop(printer_id, set())
  2470. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2471. if not pin:
  2472. return
  2473. client = printer_manager.get_client(printer_id)
  2474. if client is None:
  2475. logger.info(
  2476. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2477. item_id,
  2478. printer_id,
  2479. )
  2480. return
  2481. if "bed" in pin:
  2482. # Only undo our own target. If firmware reports something else, the
  2483. # user or another writer owns the bed now and zeroing it would
  2484. # clobber their choice -- the same guard `_release_keep_warm`
  2485. # applies to a keep-warm hold.
  2486. #
  2487. # Every uncertain case switches the bed off rather than leaving it:
  2488. # no recorded target (a pin written before this bookkeeping, or a
  2489. # setter that raised after pinning) and an unreadable status both
  2490. # fall through. A bed left hot with no owner is the worse failure,
  2491. # and this runs in a `finally` where raising would mask the real
  2492. # exception.
  2493. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2494. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2495. logger.info(
  2496. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2497. item_id,
  2498. printer_id,
  2499. cur_bed_target,
  2500. pinned_bed,
  2501. )
  2502. else:
  2503. try:
  2504. client.set_bed_temperature(0)
  2505. except Exception as exc:
  2506. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2507. if "chamber" in pin:
  2508. try:
  2509. client.set_chamber_temperature(0)
  2510. except Exception as exc:
  2511. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2512. if "airduct" in pin:
  2513. try:
  2514. client.set_airduct_mode("cooling")
  2515. except Exception as exc:
  2516. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2517. logger.info(
  2518. "Dispatch item %s (printer %d): preheat rollback → %s",
  2519. item_id,
  2520. printer_id,
  2521. sorted(pin),
  2522. )
  2523. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  2524. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2525. Returns True if this call won the claim, False if the row was already
  2526. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2527. the load-bearing guard against reassign-during-dispatch (#2615)."""
  2528. res = await db.execute(
  2529. update(PrintQueueItem)
  2530. .where(PrintQueueItem.id == item_id)
  2531. .where(PrintQueueItem.status == "pending")
  2532. .where(PrintQueueItem.dispatching_at.is_(None))
  2533. .values(dispatching_at=datetime.now(timezone.utc))
  2534. )
  2535. await db.commit()
  2536. return res.rowcount > 0
  2537. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2538. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2539. mask the dispatch outcome.
  2540. Retried, because the failure mode in practice is transient and narrow: a
  2541. database that is momentarily unreachable — PostgreSQL out of connection
  2542. slots is the observed case — refuses this write for a second or two while
  2543. the dispatch that just ended is still holding the row out of the selection
  2544. query. One attempt was enough to wedge the item; a couple of spaced
  2545. attempts clear it. Each attempt rolls back first, since a failed write
  2546. leaves the session needing it before it can be reused.
  2547. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2548. on the next quiet tick.
  2549. """
  2550. for attempt in range(1, 4):
  2551. try:
  2552. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2553. await db.commit()
  2554. return
  2555. except Exception as exc:
  2556. try:
  2557. await db.rollback()
  2558. except Exception:
  2559. pass
  2560. if attempt == 3:
  2561. logger.warning(
  2562. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2563. "— a later quiet tick will release it",
  2564. item_id,
  2565. attempt,
  2566. exc,
  2567. )
  2568. return
  2569. await asyncio.sleep(0.5 * attempt)
  2570. async def _printers_for_model(
  2571. self,
  2572. db: AsyncSession,
  2573. model: str,
  2574. target_location: str | None = None,
  2575. printer_scope: PrinterScope = ALL_PRINTERS,
  2576. ) -> list[Printer]:
  2577. """Active printers of *model*, optionally narrowed to one location.
  2578. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2579. answer "which printers can this job run on" from one query — a job can
  2580. only be woken onto a printer the matcher would also have considered.
  2581. ``printer_scope`` is the job creator's (#1727).
  2582. """
  2583. normalized_model = normalize_printer_model(model) or model
  2584. query = (
  2585. select(Printer)
  2586. .where(func.lower(Printer.model) == normalized_model.lower())
  2587. .where(Printer.is_active == True) # noqa: E712
  2588. )
  2589. if target_location:
  2590. query = query.where(Printer.location == target_location)
  2591. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2592. query = query.where(clause)
  2593. result = await db.execute(query)
  2594. return list(result.scalars().all())
  2595. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2596. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2597. Read once per queue check rather than per printer: it decides both
  2598. whether the wake step has anything to do and how an offline printer is
  2599. worded in the waiting reason — "Offline" and "offline with no Auto On
  2600. plug" are different problems, and the second is the one the user has to
  2601. fix themselves (#2786).
  2602. """
  2603. result = await db.execute(
  2604. select(SmartPlug.printer_id)
  2605. .where(SmartPlug.printer_id.is_not(None))
  2606. .where(SmartPlug.enabled == True) # noqa: E712
  2607. .where(SmartPlug.auto_on == True) # noqa: E712
  2608. )
  2609. return {pid for (pid,) in result.all() if pid is not None}
  2610. def _wake_recently_failed(self, printer_id: int) -> bool:
  2611. """True while this printer's failed power-on is still cooling off (#2786)."""
  2612. deadline = self._wake_failures.get(printer_id)
  2613. if deadline is None:
  2614. return False
  2615. if time.monotonic() >= deadline:
  2616. del self._wake_failures[printer_id]
  2617. return False
  2618. return True
  2619. async def _wake_printer_for_model(
  2620. self,
  2621. db: AsyncSession,
  2622. candidates: list[_ModelCandidate],
  2623. target_location: str | None,
  2624. exclude_ids: set[int],
  2625. wakeable_ids: set[int],
  2626. require_plate_clear: bool,
  2627. printer_scope: PrinterScope = ALL_PRINTERS,
  2628. ) -> tuple[int | None, int | None]:
  2629. """Power on one offline printer a model-based item could run on (#2786).
  2630. The fixed-printer branch has powered a printer on since smart plugs
  2631. existed. The model-based branch never could: its matcher drops an
  2632. offline printer into the "Offline:" waiting reason and nothing looks at
  2633. its plugs, so a class-targeted job with every matching printer switched
  2634. off sat pending forever. The reporter's log is the controlled
  2635. experiment — the same item, same plug, same Auto On setting, dispatched
  2636. the moment they edited it onto a specific printer.
  2637. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2638. power-on was actually tried, so the caller can tell "nothing here was
  2639. wakeable" (both None — cheap, other items may still find something)
  2640. from "we tried and it did not come up" (only ``attempted_id`` — the
  2641. boot timeout has already been spent).
  2642. A printer whose last known trays cannot satisfy the job is passed over
  2643. rather than woken (#2876): the colours are readable while it is off, so
  2644. switching a farm on one machine at a time to discover them wakes
  2645. printers that could never have taken the job.
  2646. Deliberately does NOT go on to match the job once a printer is up: AMS
  2647. trays arrive with the first status push after connect, so a filament
  2648. check against a printer that booted seconds ago can reject the printer
  2649. we just woke. The next queue pass matches it with live state.
  2650. At most one printer per pass. Each wake blocks the queue loop for the
  2651. boot wait, and a queue of ten class-targeted jobs must not switch on
  2652. ten printers inside one check.
  2653. """
  2654. for candidate in candidates:
  2655. if not candidate.target_model:
  2656. continue
  2657. required_types, filament_overrides = _filament_constraints(candidate)
  2658. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2659. for printer in sorted(printers, key=lambda p: p.id):
  2660. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2661. continue
  2662. if printer_manager.is_connected(printer.id):
  2663. continue
  2664. if self._wake_recently_failed(printer.id):
  2665. # Its plug did not bring it back a moment ago. Move on to a
  2666. # sibling instead of spending this pass — and every pass —
  2667. # on the same printer.
  2668. continue
  2669. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2670. # Waking this one buys nothing: it would boot into IDLE and
  2671. # then be held by the plate-clear gate, which is exactly
  2672. # what the reporter's log shows happening for 80 minutes
  2673. # after a fixed-printer wake. The flag is Bambuddy-side and
  2674. # persisted, so it is readable while the printer is off.
  2675. logger.info(
  2676. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2677. printer.id,
  2678. candidate.target_model,
  2679. )
  2680. continue
  2681. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2682. if shortfall:
  2683. logger.info(
  2684. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2685. printer.id,
  2686. candidate.target_model,
  2687. ", ".join(shortfall),
  2688. )
  2689. continue
  2690. plugs = await self._get_smart_plugs(db, printer.id)
  2691. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2692. if not auto_on_plugs:
  2693. # wakeable_ids said otherwise — the plug changed under us
  2694. # mid-pass. Nothing to do but move on.
  2695. continue
  2696. logger.info(
  2697. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2698. candidate.target_model,
  2699. printer.id,
  2700. )
  2701. primary_plug = self._pick_power_plug(auto_on_plugs)
  2702. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2703. logger.warning(
  2704. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2705. printer.id,
  2706. self._wake_failure_cooloff,
  2707. )
  2708. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2709. return None, printer.id
  2710. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2711. try:
  2712. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2713. await service.turn_on(extra_plug)
  2714. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2715. except Exception as e:
  2716. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2717. return printer.id, printer.id
  2718. return None, None
  2719. async def _find_idle_printer_for_model(
  2720. self,
  2721. db: AsyncSession,
  2722. model: str,
  2723. exclude_ids: set[int],
  2724. required_filament_types: list[str] | None = None,
  2725. target_location: str | None = None,
  2726. filament_overrides: list[dict] | None = None,
  2727. require_plate_clear: bool = True,
  2728. wakeable_ids: set[int] | None = None,
  2729. printer_scope: PrinterScope = ALL_PRINTERS,
  2730. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2731. ) -> tuple[int | None, str | None]:
  2732. """Find an idle, connected printer matching the model with compatible filaments.
  2733. Args:
  2734. db: Database session
  2735. model: Printer model to match (e.g., "X1C", "P1S")
  2736. exclude_ids: Printer IDs to exclude (already busy)
  2737. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2738. If provided, only printers with all required types loaded will match.
  2739. target_location: Optional location filter. If provided, only printers in this location are considered.
  2740. filament_overrides: Optional list of override dicts. Each entry may include
  2741. ``force_color_match: true`` to require an exact type+color match
  2742. on the printer for that slot. Without the flag the existing
  2743. colour-preference logic applies.
  2744. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2745. offline printer is worded: one Bambuddy will switch on reads
  2746. differently from one the user has to go and switch on themselves.
  2747. is_short: Says whether a printer's spools are too light for the job (#3137).
  2748. A printer it flags is passed over while another eligible one
  2749. is not. When every eligible printer is short, the first is
  2750. returned all the same, so the deficit gate holds the job there
  2751. and "Print Anyway" still has a printer to print on.
  2752. Returns:
  2753. Tuple of (printer_id, waiting_reason):
  2754. - (printer_id, None) if a matching printer was found
  2755. - (None, reason) if no printer is available, with explanation
  2756. """
  2757. normalized_model = normalize_printer_model(model) or model
  2758. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2759. location_suffix = f" in {target_location}" if target_location else ""
  2760. if not printers:
  2761. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2762. # Separate force-matched overrides from preference-only overrides
  2763. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2764. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2765. # Track reasons for skipping printers
  2766. printers_busy = []
  2767. printers_offline = []
  2768. printers_offline_no_plug = []
  2769. printers_missing_filament: list[tuple[str, list[str]]] = []
  2770. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2771. # The first eligible printer that is short on filament, kept in case
  2772. # every eligible printer is (#3137).
  2773. short_fallback: int | None = None
  2774. for printer in printers:
  2775. if printer.id in exclude_ids:
  2776. # Printer is already claimed by another job in this scheduling run.
  2777. # For force-color jobs, still check if the color would match — if not,
  2778. # report it as a color mismatch rather than plain "Busy" so the user
  2779. # knows the job needs a filament change, not just to wait for availability.
  2780. if force_overrides and not pref_overrides:
  2781. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2782. if missing_colors:
  2783. printers_missing_filament.append((printer.name, missing_colors))
  2784. continue
  2785. printers_busy.append(printer.name)
  2786. continue
  2787. is_connected = printer_manager.is_connected(printer.id)
  2788. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2789. if not is_connected:
  2790. # An offline printer whose last known filament cannot run this
  2791. # job is reported as needing filament rather than as offline
  2792. # (#2876). It is also the printer the smart-plug step will now
  2793. # decline to switch on, and "Offline:" on its own would leave
  2794. # that decision looking like nothing happening at all.
  2795. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2796. if shortfall:
  2797. printers_missing_filament.append((printer.name, shortfall))
  2798. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2799. printers_offline_no_plug.append(printer.name)
  2800. else:
  2801. printers_offline.append(printer.name)
  2802. continue
  2803. if not is_idle:
  2804. # Printer is currently printing. For force-color jobs, check whether the
  2805. # loaded color would satisfy the requirement — if not, surface it as a
  2806. # color-mismatch reason rather than plain "Busy" so the user understands
  2807. # that the job is waiting for a filament change, not just printer availability.
  2808. if force_overrides and not pref_overrides:
  2809. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2810. if missing_colors:
  2811. printers_missing_filament.append((printer.name, missing_colors))
  2812. logger.debug(
  2813. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2814. printer.id,
  2815. printer.name,
  2816. missing_colors,
  2817. )
  2818. continue
  2819. printers_busy.append(printer.name)
  2820. continue
  2821. # Validate filament compatibility if required types are specified
  2822. if required_filament_types:
  2823. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2824. if missing:
  2825. # When force_overrides are present, enrich missing entries with color info
  2826. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2827. if force_overrides:
  2828. force_color_map = {
  2829. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2830. for o in force_overrides
  2831. }
  2832. missing_enriched = [
  2833. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2834. for t in missing
  2835. ]
  2836. printers_missing_filament.append((printer.name, missing_enriched))
  2837. else:
  2838. printers_missing_filament.append((printer.name, missing))
  2839. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2840. continue
  2841. # Force color match: ALL flagged slots must have an exact type+color match
  2842. if force_overrides:
  2843. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2844. if missing_colors:
  2845. printers_missing_filament.append((printer.name, missing_colors))
  2846. logger.debug(
  2847. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2848. printer.id,
  2849. printer.name,
  2850. missing_colors,
  2851. )
  2852. continue
  2853. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2854. if pref_overrides:
  2855. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2856. if color_matches > 0:
  2857. candidates.append((printer.id, color_matches))
  2858. else:
  2859. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2860. printers_missing_filament.append((printer.name, override_colors))
  2861. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2862. continue
  2863. else:
  2864. # No preference ordering needed: the first eligible printer
  2865. # wins, unless its spools are too light for the job (#3137).
  2866. if is_short is not None and await is_short(printer.id):
  2867. if short_fallback is None:
  2868. short_fallback = printer.id
  2869. logger.info(
  2870. "Model-based assignment: passing over printer %s (%s), not enough filament",
  2871. printer.id,
  2872. printer.name,
  2873. )
  2874. continue
  2875. return printer.id, None
  2876. # If we have candidates from preference override matching, pick the one with most color matches
  2877. if candidates:
  2878. candidates.sort(key=lambda c: c[1], reverse=True)
  2879. if is_short is not None:
  2880. for candidate_id, _ in candidates:
  2881. if not await is_short(candidate_id):
  2882. return candidate_id, None
  2883. logger.info(
  2884. "Model-based assignment: passing over printer %s, not enough filament",
  2885. candidate_id,
  2886. )
  2887. return candidates[0][0], None
  2888. if short_fallback is not None:
  2889. return short_fallback, None
  2890. # Build waiting reason from what we found
  2891. reasons = []
  2892. if printers_missing_filament:
  2893. # Filament/color mismatch is most actionable - show first
  2894. if force_overrides and not pref_overrides:
  2895. # All mismatches are force-color failures — use descriptive message only;
  2896. # but only if there are no busy printers that DO have the matching color.
  2897. # If a printer has the right color but is busy, surface "Busy" instead so
  2898. # the user knows the job will start automatically once that printer is free.
  2899. # Same for a printer that is merely offline: Bambuddy switches that one on
  2900. # by itself, so the job is not actually waiting on anybody to change a
  2901. # spool (#2876 — offline printers reach this list now that a switched-off
  2902. # printer's own filament is read).
  2903. if not printers_busy and not printers_offline:
  2904. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  2905. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  2906. # else: fall through — the self-resolving entries are appended below
  2907. else:
  2908. names_and_missing = [
  2909. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  2910. ]
  2911. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  2912. if printers_busy:
  2913. reasons.append(f"Busy: {', '.join(printers_busy)}")
  2914. if printers_offline:
  2915. reasons.append(f"Offline: {', '.join(printers_offline)}")
  2916. if printers_offline_no_plug:
  2917. # Named separately because it is the one entry on this list the
  2918. # user has to act on: no enabled Auto On plug means Bambuddy will
  2919. # never power this printer on for the queue (#2786).
  2920. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  2921. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  2922. @staticmethod
  2923. def _is_busy_only(waiting_reason: str) -> bool:
  2924. """Check if the waiting reason only contains 'Busy' entries.
  2925. When all matching printers are simply busy printing, the queued job
  2926. will start automatically once a printer finishes — no user action
  2927. is required, so we skip the notification.
  2928. """
  2929. parts = [p.strip() for p in waiting_reason.split(" | ")]
  2930. return all(p.startswith("Busy:") for p in parts)
  2931. def _get_missing_force_color_slots(
  2932. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  2933. ) -> list[str]:
  2934. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  2935. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  2936. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  2937. with an exact type+color match.
  2938. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  2939. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  2940. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  2941. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  2942. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  2943. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  2944. setups are unaffected.
  2945. Returns:
  2946. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  2947. """
  2948. if raw_data is None:
  2949. status = printer_manager.get_status(printer_id)
  2950. if not status:
  2951. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  2952. raw_data = status.raw_data
  2953. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  2954. loaded: list[tuple[str, str, str]] = []
  2955. for ams_unit in raw_data.get("ams", []):
  2956. for tray in ams_unit.get("tray", []):
  2957. tray_type = tray.get("tray_type")
  2958. if tray_type:
  2959. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2960. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  2961. for vt in raw_data.get("vt_tray") or []:
  2962. vt_type = vt.get("tray_type")
  2963. if vt_type:
  2964. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2965. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  2966. missing = []
  2967. for o in force_overrides:
  2968. o_type = canonical_filament_type(o.get("type") or "")
  2969. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2970. o_idx = o.get("tray_info_idx") or ""
  2971. satisfied = any(
  2972. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  2973. for t_type, t_color, t_idx in loaded
  2974. )
  2975. if not satisfied:
  2976. color_label = o.get("color_name") or o.get("color", "?")
  2977. missing.append(f"{o_type} ({color_label})")
  2978. return missing
  2979. def _get_missing_filament_types(
  2980. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  2981. ) -> list[str]:
  2982. """Get the list of required filament types that are not loaded on the printer.
  2983. Args:
  2984. printer_id: The printer ID
  2985. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  2986. Returns:
  2987. List of missing filament types (empty if all are loaded)
  2988. """
  2989. if raw_data is None:
  2990. status = printer_manager.get_status(printer_id)
  2991. if not status:
  2992. return required_types # Can't determine, assume all missing
  2993. raw_data = status.raw_data
  2994. # Collect all filament types loaded on this printer (AMS units + external spool)
  2995. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  2996. loaded_types: set[str] = set()
  2997. # Check AMS units (stored in raw_data["ams"])
  2998. ams_data = raw_data.get("ams", [])
  2999. if ams_data:
  3000. for ams_unit in ams_data:
  3001. for tray in ams_unit.get("tray", []):
  3002. tray_type = tray.get("tray_type")
  3003. if tray_type:
  3004. loaded_types.add(canonical_filament_type(tray_type))
  3005. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3006. for vt in raw_data.get("vt_tray") or []:
  3007. vt_type = vt.get("tray_type")
  3008. if vt_type:
  3009. loaded_types.add(canonical_filament_type(vt_type))
  3010. # Find which required types are missing (using canonical type for equivalence)
  3011. missing = []
  3012. for req_type in required_types:
  3013. if canonical_filament_type(req_type) not in loaded_types:
  3014. missing.append(req_type)
  3015. return missing
  3016. def _count_override_color_matches(
  3017. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3018. ) -> int:
  3019. """Count how many filament overrides have an exact color match on the printer.
  3020. Used to prefer printers that already have the desired override colors loaded.
  3021. """
  3022. if raw_data is None:
  3023. status = printer_manager.get_status(printer_id)
  3024. if not status:
  3025. return 0
  3026. raw_data = status.raw_data
  3027. # Collect loaded filaments' type+color pairs
  3028. loaded: set[tuple[str, str]] = set()
  3029. for ams_unit in raw_data.get("ams", []):
  3030. for tray in ams_unit.get("tray", []):
  3031. tray_type = tray.get("tray_type")
  3032. # `or ""`, not a dict default: a slot can carry the key with a
  3033. # null value, and this now runs against switched-off printers
  3034. # too, where nobody is watching for the AttributeError.
  3035. tray_color = tray.get("tray_color") or ""
  3036. if tray_type:
  3037. color_norm = tray_color.replace("#", "").lower()[:6]
  3038. loaded.add((tray_type.upper(), color_norm))
  3039. for vt in raw_data.get("vt_tray") or []:
  3040. vt_type = vt.get("tray_type")
  3041. if vt_type:
  3042. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3043. loaded.add((vt_type.upper(), color_norm))
  3044. matches = 0
  3045. for o in overrides:
  3046. o_type = (o.get("type") or "").upper()
  3047. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3048. if (o_type, o_color) in loaded:
  3049. matches += 1
  3050. return matches
  3051. @staticmethod
  3052. def _tray_reading(printer_id: int) -> dict:
  3053. """The best tray reading available for a printer that is not printing.
  3054. Live status first: a printer keeps its last status after the power
  3055. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3056. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3057. for when the client itself has been dropped and taken its status with
  3058. it — which is what every power-on attempt does.
  3059. An empty result means "we have never heard", not "nothing is loaded":
  3060. the two are indistinguishable from here, and only the second would be
  3061. safe to act on.
  3062. """
  3063. status = printer_manager.get_status(printer_id)
  3064. raw = (status.raw_data if status else None) or {}
  3065. for ams_unit in raw.get("ams") or []:
  3066. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3067. return raw
  3068. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3069. return raw
  3070. return printer_manager.last_known_trays(printer_id)
  3071. def _cached_filament_shortfall(
  3072. self,
  3073. printer_id: int,
  3074. required_types: list[str] | None,
  3075. filament_overrides: list[dict] | None,
  3076. ) -> list[str]:
  3077. """What a switched-off printer's last known filament cannot provide (#2876).
  3078. The smart-plug wake step used to consider only the model, so a job for a
  3079. colour loaded on the last printer in ID order switched on every earlier
  3080. one in turn, evaluated it, rejected it on colour and left it running.
  3081. Bambuddy knew those colours the whole time. This asks the same three
  3082. questions the matcher asks a live printer — required types, forced
  3083. colours, preferred colours — of the trays it last reported, and returns
  3084. the answers in the same shape the "Waiting for filament" reason uses.
  3085. Empty means the printer may still be able to take the job.
  3086. Fails open, and deliberately: with no tray reading (never connected
  3087. since Bambuddy started, or the cache dropped by a reconnect) this
  3088. returns nothing to report and the printer is treated as it was before.
  3089. A farm restarted while its printers were off must not conclude that
  3090. none of them can print.
  3091. """
  3092. if not required_types and not filament_overrides:
  3093. return []
  3094. raw_data = self._tray_reading(printer_id)
  3095. if not raw_data:
  3096. return []
  3097. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3098. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3099. if required_types:
  3100. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3101. if missing:
  3102. # Same enrichment the live path applies: a bare "PLA" is not
  3103. # much help when what is missing is a particular PLA.
  3104. force_color_map = {
  3105. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3106. }
  3107. return [
  3108. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3109. for t in missing
  3110. ]
  3111. if force_overrides:
  3112. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3113. if missing_colors:
  3114. return missing_colors
  3115. # Preference overrides read as a preference but the matcher treats zero
  3116. # matches as a skip, so a printer with none of the wanted colours is
  3117. # rejected there too. Waking it would only produce that same rejection.
  3118. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3119. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3120. return []
  3121. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3122. """Fold the winning candidate's file and settings onto the queue row (#671).
  3123. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3124. never escapes the selection loop. By the time the pass commits, the row
  3125. looks exactly like an ordinary single-file model-based item, so the upload,
  3126. archive creation, expected-print registration, print history and reprint
  3127. paths need no knowledge that variants exist.
  3128. No-ops for a non-variant candidate, which is already the item's own columns.
  3129. Safe to run and re-run: the item's file columns are only ever *read* when it
  3130. has no variants, so an item that gets resolved and then skipped (library-row
  3131. conflict, previous-print gate) is simply resolved again on the next pass.
  3132. """
  3133. variant = candidate.variant
  3134. if variant is None:
  3135. return
  3136. item.library_file_id = variant.library_file_id
  3137. item.library_file = variant.library_file
  3138. # The dispatcher checks archive_id first and would print that instead of
  3139. # the file we just picked. Creation refuses to combine the two, so this
  3140. # only ever fires on a hand-written row — clear it rather than silently
  3141. # dispatch something the matcher never considered.
  3142. item.archive_id = None
  3143. item.archive = None
  3144. item.target_model = variant.target_model
  3145. item.plate_id = variant.plate_id
  3146. item.ams_mapping = variant.ams_mapping
  3147. item.nozzle_mapping = variant.nozzle_mapping
  3148. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3149. item.filament_overrides = variant.filament_overrides
  3150. item.required_filament_types = variant.required_filament_types
  3151. if variant.print_time_seconds is not None:
  3152. # The row carried the shortest candidate's estimate so SJF could order
  3153. # it before a printer was known; now that one is chosen, record what is
  3154. # actually going to run so history and the ETA agree with reality.
  3155. item.print_time_seconds = variant.print_time_seconds
  3156. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3157. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3158. Recomputes from live printer status when the stored mapping is missing OR
  3159. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3160. frontend status-load race can serialize [-1] before the printer's AMS
  3161. trays are known (#2589) — and must not be trusted: downstream it would be
  3162. silently downgraded to external-spool mode and print against an empty
  3163. feed. A resolved mapping is re-checked against the target printer's
  3164. live trays before it is trusted (#2799) and recomputed when it does not
  3165. fit. When it does fit, its resolved slots are kept as they are and only
  3166. the slots the plate prints that are still unresolved are matched again;
  3167. all of it is left alone when the user has acknowledged it with "Print
  3168. Anyway".
  3169. When recompute cannot resolve it either (no compatible tray loaded), the
  3170. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3171. external selection. On a printer that reported loaded trays,
  3172. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3173. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3174. and the firmware surfaces a clear AMS-mapping error instead of silently
  3175. printing to the empty external feed.
  3176. Returns an actionable message when that firmware error is the only
  3177. possible outcome — the matcher ran, matched nothing, and the printer has
  3178. no AMS to load a different spool into (#2771). The caller fails the item
  3179. on it instead of spending an upload on a print that cannot start.
  3180. Returns None everywhere else, including every case where we simply lack
  3181. the data to judge, so dispatch is only ever blocked on a positive
  3182. finding.
  3183. """
  3184. stored_mapping: list | None = None
  3185. if item.ams_mapping:
  3186. try:
  3187. stored_mapping = json.loads(item.ams_mapping)
  3188. except (json.JSONDecodeError, TypeError):
  3189. stored_mapping = None
  3190. # Present and resolved. Global tray IDs only mean something relative to
  3191. # the printer they were resolved against, so "resolved" is not the same
  3192. # as "resolved *here*" — check the mapping still fits the printer that
  3193. # is about to run this item before trusting it (#2799). "Print anyway"
  3194. # is the user overriding exactly this judgement, so it short-circuits.
  3195. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3196. if item.skip_filament_check:
  3197. return None
  3198. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3199. if conflict is None:
  3200. # It fits, but a slot the plate prints may still be empty: the
  3201. # spool was missing when it was mapped, and has perhaps been
  3202. # loaded since. Nothing else would ever look at that slot again,
  3203. # so a job held for it would be held again on every Start.
  3204. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3205. if filled is not None:
  3206. item.ams_mapping = json.dumps(filled)
  3207. logger.info(
  3208. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3209. item.id,
  3210. stored_mapping,
  3211. printer_id,
  3212. filled,
  3213. )
  3214. await db.commit()
  3215. return None
  3216. logger.warning(
  3217. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3218. item.id,
  3219. stored_mapping,
  3220. printer_id,
  3221. conflict,
  3222. )
  3223. # Drop it before recomputing so a failed recompute cannot fall back
  3224. # to the mapping we just rejected.
  3225. item.ams_mapping = None
  3226. stored_mapping = None
  3227. await db.commit()
  3228. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3229. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3230. item.ams_mapping = json.dumps(computed_mapping)
  3231. logger.info(
  3232. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3233. item.id,
  3234. printer_id,
  3235. computed_mapping,
  3236. )
  3237. await db.commit()
  3238. return None
  3239. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3240. if external_only is not None:
  3241. item.ams_mapping = json.dumps(external_only)
  3242. logger.info(
  3243. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3244. "mapping every filament to it: %s",
  3245. item.id,
  3246. printer_id,
  3247. external_only,
  3248. )
  3249. await db.commit()
  3250. return None
  3251. if _mapping_is_all_unresolved(stored_mapping):
  3252. logger.warning(
  3253. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3254. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3255. item.id,
  3256. stored_mapping,
  3257. printer_id,
  3258. )
  3259. item.ams_mapping = None
  3260. await db.commit()
  3261. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3262. async def _external_spool_only_mapping(
  3263. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3264. ) -> list[int] | None:
  3265. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3266. A printer without an AMS prints from its external spool, and an external
  3267. spool whose filament was never set reports no type, so the matcher has
  3268. nothing to match. Sent without a mapping, the print goes out with the AMS
  3269. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3270. to carry such a job through; a job placed by model or location no longer
  3271. keeps one, and one queued that way never had one.
  3272. Only on a positive report: the printer has said it has no AMS, it has a
  3273. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3274. is not ours to pick), and no feed has a filament set — with one set, the
  3275. matcher has already given its answer. Not for a job that asked for its
  3276. colours to be matched strictly: a spool without a filament set has no
  3277. colour to check. Returns None otherwise.
  3278. """
  3279. if item.filament_overrides:
  3280. try:
  3281. overrides = json.loads(item.filament_overrides)
  3282. except (json.JSONDecodeError, TypeError):
  3283. return None
  3284. if not isinstance(overrides, list) or any(
  3285. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3286. ):
  3287. return None
  3288. status = printer_manager.get_status(printer_id)
  3289. if status is None or not isinstance(status.raw_data, dict):
  3290. return None
  3291. ams_units = status.raw_data.get("ams")
  3292. if not isinstance(ams_units, list) or ams_units:
  3293. return None
  3294. vt_trays = status.raw_data.get("vt_tray")
  3295. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3296. return None
  3297. if self._build_loaded_filaments(status):
  3298. return None
  3299. printer = await self._get_printer(db, printer_id)
  3300. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3301. return None
  3302. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3303. if external < _EXTERNAL_TRAY_ID_MIN:
  3304. return None
  3305. required = await self._get_filament_requirements(db, item)
  3306. slot_ids = [r.get("slot_id") for r in required or []]
  3307. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3308. if not slot_ids:
  3309. return None
  3310. mapping = [-1] * max(slot_ids)
  3311. for slot_id in slot_ids:
  3312. mapping[slot_id - 1] = external
  3313. return mapping
  3314. async def _fill_unresolved_slots(
  3315. self,
  3316. db: AsyncSession,
  3317. printer_id: int,
  3318. item: PrintQueueItem,
  3319. stored_mapping: list | None,
  3320. ) -> list | None:
  3321. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3322. Every resolved entry is kept, so a tray the user picked by hand stays
  3323. picked. Only the plate's unresolved slots are matched, and only against
  3324. trays the mapping does not already use: the matcher never gives two
  3325. slots one tray, and filling a gap with a tray the user assigned to
  3326. another slot would print that slot's filament twice.
  3327. Returns None when there is nothing to fill or nothing could be filled.
  3328. """
  3329. if not isinstance(stored_mapping, list) or not stored_mapping:
  3330. return None
  3331. required = await self._get_filament_requirements(db, item)
  3332. if not required:
  3333. return None
  3334. self._apply_filament_overrides(item, required)
  3335. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3336. if not gaps:
  3337. return None
  3338. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3339. computed = await self._compute_ams_mapping_for_printer(
  3340. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3341. )
  3342. if not computed:
  3343. return None
  3344. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3345. filled = False
  3346. for slot_id in gaps:
  3347. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3348. if _is_tray_id(tray) and tray >= 0:
  3349. merged[slot_id - 1] = tray
  3350. filled = True
  3351. return merged if filled else None
  3352. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3353. """What a staged item would be held for if it were started now (#2799).
  3354. The Start button asks this before releasing an item, so that a job whose
  3355. filament is still not loaded offers "Print Anyway" instead of being
  3356. released, held again by the scheduler and leaving no way past the hold.
  3357. It reaches the same answer the dispatch path would: a stored mapping
  3358. that fits is kept and only its gaps are matched again, and one that
  3359. does not fit (or is missing) is replaced by a fresh match.
  3360. Returns the missing filaments, described the way the queue row
  3361. describes them, or None when nothing is missing or there is not enough
  3362. evidence to say: no printer yet (a model-based item picks one at
  3363. dispatch), no status, no trays reported, or no readable 3MF.
  3364. """
  3365. if item.skip_filament_check or not item.printer_id:
  3366. return None
  3367. status = printer_manager.get_status(item.printer_id)
  3368. if status is None or not self._build_loaded_filaments(status):
  3369. return None
  3370. # Called from a request, not from a pass: drop whatever the last pass
  3371. # memoised so this reads the file as it is now. A pass running at the
  3372. # same time only loses its cache.
  3373. self._filament_req_memo.clear()
  3374. mapping: list | None = None
  3375. if item.ams_mapping:
  3376. try:
  3377. mapping = json.loads(item.ams_mapping)
  3378. except (json.JSONDecodeError, TypeError):
  3379. mapping = None
  3380. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3381. mapping = None
  3382. if mapping is not None:
  3383. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3384. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3385. else:
  3386. mapping = None
  3387. if mapping is None:
  3388. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3389. required = await self._get_filament_requirements(db, item)
  3390. if not required:
  3391. return None
  3392. self._apply_filament_overrides(item, required)
  3393. missing = _unresolved_required(required, mapping)
  3394. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3395. async def _stored_mapping_conflict(
  3396. self,
  3397. db: AsyncSession,
  3398. printer_id: int,
  3399. item: PrintQueueItem,
  3400. stored_mapping: list | None,
  3401. ) -> str | None:
  3402. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3403. A mapping is a list of global tray IDs, and those are only meaningful
  3404. relative to the printer they were resolved against — the same rule
  3405. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3406. arrives at a printer it was not resolved for:
  3407. * the print dialog stamps one mapping onto every selected printer, so a
  3408. mapping computed against the first printer is dispatched verbatim to
  3409. the rest, whose AMS slot order differs;
  3410. * a spool is moved between queueing and dispatch.
  3411. Both end the same way: the slot index still resolves, so nothing looks
  3412. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3413. the firmware's own type check, so a PETG slot happily prints in ASA.
  3414. Returns a short reason when the mapping names a tray this printer does
  3415. not have loaded, points a slot at a tray holding a different filament
  3416. type, or points it at an external spool this printer reports empty while
  3417. its AMS holds that slot's filament (#3239). Returns None when the
  3418. mapping fits, and — deliberately — whenever we lack the evidence to
  3419. judge, so a recompute only ever follows a positive finding.
  3420. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3421. matcher had nothing, not that the mapping belongs to another printer,
  3422. and destroying a partially hand-resolved mapping over it would lose the
  3423. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3424. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3425. item when that finds nothing.
  3426. """
  3427. if not isinstance(stored_mapping, list) or not stored_mapping:
  3428. return None
  3429. status = printer_manager.get_status(printer_id)
  3430. if status is None:
  3431. return None
  3432. loaded = self._build_loaded_filaments(status)
  3433. if not loaded:
  3434. # Nothing reported yet (reconnect, first push pending). Saying
  3435. # "tray not loaded" here would recompute against an AMS we cannot
  3436. # see, which is how #2589 produced a bogus all-[-1] in the first
  3437. # place.
  3438. return None
  3439. by_tray = {f["global_tray_id"]: f for f in loaded}
  3440. # Cheap pass first, on live status alone: every tray the mapping names
  3441. # has to exist here. This catches a foreign mapping without opening the
  3442. # 3MF, which is worth doing because the parse below is neither cached
  3443. # nor free.
  3444. for index, tray in enumerate(stored_mapping):
  3445. if not _is_tray_id(tray) or tray < 0:
  3446. continue
  3447. if tray in by_tray:
  3448. continue
  3449. if tray >= 254:
  3450. # An external feed we have not heard about is absence of
  3451. # evidence about *that slot* — the rest of the mapping is still
  3452. # worth judging, so skip it rather than abandoning the pass.
  3453. continue
  3454. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3455. # Only now is the 3MF worth opening: the type check needs to know what
  3456. # each slot actually asked for. The external spool is checked the same
  3457. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3458. # two printers with different filament in the external feed is the same
  3459. # failure this method exists to catch.
  3460. required = await self._get_filament_requirements(db, item)
  3461. if not required:
  3462. return None
  3463. self._apply_filament_overrides(item, required)
  3464. # External feeds the printer reports and reports as empty. That is
  3465. # evidence, unlike an external feed it says nothing about (#3239).
  3466. empty_external: set[int] = set()
  3467. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3468. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3469. if isinstance(vt, dict) and not vt.get("tray_type"):
  3470. try:
  3471. empty_external.add(int(vt.get("id", 254)))
  3472. except (TypeError, ValueError):
  3473. continue
  3474. for req in required:
  3475. slot_id = req.get("slot_id") or 0
  3476. if slot_id <= 0:
  3477. continue
  3478. if slot_id > len(stored_mapping):
  3479. return f"slot {slot_id} is not covered by the mapping"
  3480. tray = stored_mapping[slot_id - 1]
  3481. if not _is_tray_id(tray) or tray < 0:
  3482. continue
  3483. loaded_tray = by_tray.get(tray)
  3484. if loaded_tray is None:
  3485. # A mapping made for a printer that feeds this slot from its
  3486. # external spool, sent to one whose external spool is empty and
  3487. # whose AMS holds the filament (#3239). Only then: an external
  3488. # spool can be loaded without its filament set, and on a printer
  3489. # with nothing else to offer that job printed before. The colour
  3490. # has to match too: with only another colour in the AMS, the
  3491. # printer asking for the spool beats printing in that colour.
  3492. want = canonical_filament_type(req.get("type"))
  3493. if tray >= 254 and tray in empty_external and want:
  3494. ams_tray = next(
  3495. (
  3496. f
  3497. for f in loaded
  3498. if not f.get("is_external")
  3499. and canonical_filament_type(f.get("type")) == want
  3500. and self._colors_are_similar(f.get("color"), req.get("color"))
  3501. ),
  3502. None,
  3503. )
  3504. if ams_tray is not None:
  3505. return (
  3506. f"slot {slot_id} points at the external spool, which is empty, "
  3507. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3508. )
  3509. continue
  3510. want = canonical_filament_type(req.get("type"))
  3511. have = canonical_filament_type(loaded_tray.get("type"))
  3512. if want and have and want != have:
  3513. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3514. return None
  3515. async def _unmappable_without_ams_message(
  3516. self,
  3517. db: AsyncSession,
  3518. printer_id: int,
  3519. item: PrintQueueItem,
  3520. computed_mapping: list[int] | None,
  3521. ) -> str | None:
  3522. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3523. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3524. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3525. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3526. uploaded several megabytes and burned its dispatch retries. This method
  3527. speaks only for the AMS-less case: there is nothing to resume into — the
  3528. external spool holder is the whole inventory — so the useful answer is to
  3529. say which filament is missing and stop. With an AMS attached it returns
  3530. None: where live status reported loaded trays,
  3531. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3532. reported none the print goes out and the firmware error is the answer —
  3533. the user can load the right spool and press Resume.
  3534. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3535. every branch that lacks the evidence to be sure returns None.
  3536. """
  3537. # None means the matcher never ran (no requirements parsed from the 3MF,
  3538. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3539. # dispatch as they always have.
  3540. if not _mapping_is_all_unresolved(computed_mapping):
  3541. return None
  3542. status = printer_manager.get_status(printer_id)
  3543. if status is None:
  3544. return None
  3545. # "No AMS" has to be a fact the printer stated, not the absence of a
  3546. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3547. # handled and is preserved across partial pushes thereafter, so a missing
  3548. # key means we have not heard yet — most likely a reconnect, where the
  3549. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3550. # empty list is the positive report of a printer with no AMS.
  3551. ams_units = status.raw_data.get("ams")
  3552. if not isinstance(ams_units, list) or ams_units:
  3553. return None
  3554. required = await self._get_filament_requirements(db, item)
  3555. loaded = self._build_loaded_filaments(status)
  3556. if not required or not loaded:
  3557. # Both were non-empty moments ago or the matcher could not have run.
  3558. # If the picture changed under us, say nothing rather than fail an
  3559. # item on stale evidence.
  3560. return None
  3561. self._apply_filament_overrides(item, required)
  3562. return _unmatched_filament_message(required, loaded)
  3563. async def _fail_unmappable_item(
  3564. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3565. ) -> None:
  3566. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3567. This replaces a failure, not a success: without it the item is uploaded,
  3568. rejected by the firmware with 0700_8012, retried twice more and failed
  3569. anyway with "never started the print after N dispatch attempts". So this
  3570. applies on the model-based path too, even though it means an "Any <model>"
  3571. job stops at the first printer offered rather than trying its siblings —
  3572. deferring instead would need the check to move inside
  3573. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3574. re-assigns the same printer on the next tick.
  3575. """
  3576. item.status = "failed"
  3577. item.error_message = message
  3578. item.completed_at = datetime.now(timezone.utc)
  3579. item.waiting_reason = None
  3580. await db.commit()
  3581. logger.warning(
  3582. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3583. item.id,
  3584. printer_id,
  3585. message,
  3586. )
  3587. job_name = await self._get_job_name(db, item)
  3588. printer = await self._get_printer(db, printer_id)
  3589. await notification_service.on_queue_job_failed(
  3590. job_name=job_name,
  3591. printer_id=printer_id,
  3592. printer_name=printer.name if printer else "Unknown",
  3593. reason=message,
  3594. db=db,
  3595. )
  3596. try:
  3597. await ws_manager.send_queue_item_failed(
  3598. user_id=item.created_by_id,
  3599. queue_item_id=item.id,
  3600. printer_id=printer_id,
  3601. reason="filament_unmappable",
  3602. )
  3603. except Exception:
  3604. pass
  3605. async def _compute_ams_mapping_for_printer(
  3606. self,
  3607. db: AsyncSession,
  3608. printer_id: int,
  3609. item: PrintQueueItem,
  3610. *,
  3611. only_slots: set[int] | None = None,
  3612. reserved_trays: set[int] | None = None,
  3613. ) -> list[int] | None:
  3614. """Compute AMS mapping for a printer based on filament requirements.
  3615. Called when a queue item has no ams_mapping set — either for model-based
  3616. items after printer assignment, or printer-specific items (e.g. from VP).
  3617. Args:
  3618. db: Database session
  3619. printer_id: The assigned printer ID
  3620. item: The queue item (contains archive_id or library_file_id)
  3621. only_slots: Match only these filament slots; every other slot comes
  3622. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3623. reserved_trays: Global tray IDs to leave out of the match, because
  3624. the stored mapping already gives them to another slot.
  3625. Returns:
  3626. AMS mapping array or None if no mapping needed/possible
  3627. """
  3628. # Get printer status
  3629. status = printer_manager.get_status(printer_id)
  3630. if not status:
  3631. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3632. return None
  3633. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3634. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3635. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3636. # an AMS on the *other* nozzle, and the matcher falls through to a
  3637. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3638. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3639. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3640. # Get filament requirements from source file
  3641. filament_reqs = await self._get_filament_requirements(db, item)
  3642. if not filament_reqs:
  3643. # When the 3MF can't be read but force-color overrides are present, build a
  3644. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3645. if item.filament_overrides:
  3646. try:
  3647. overrides = json.loads(item.filament_overrides)
  3648. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3649. if force_overrides:
  3650. logger.info(
  3651. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3652. "force-color override(s)",
  3653. item.id,
  3654. len(force_overrides),
  3655. )
  3656. return self._build_override_direct_mapping(force_overrides, status)
  3657. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3658. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3659. logger.debug("No filament requirements found for queue item %s", item.id)
  3660. return None
  3661. self._apply_filament_overrides(item, filament_reqs)
  3662. if only_slots is not None:
  3663. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3664. if not filament_reqs:
  3665. return None
  3666. # Build loaded filaments from printer status
  3667. loaded_filaments = self._build_loaded_filaments(status)
  3668. if reserved_trays:
  3669. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3670. if not loaded_filaments:
  3671. logger.debug("No filaments loaded on printer %s", printer_id)
  3672. return None
  3673. # Check if user prefers lowest remaining filament when multiple spools match
  3674. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3675. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3676. # Without backup, the printer will not switch to a second spool when the
  3677. # picked one runs out — so sorting toward the lowest leaves the print
  3678. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  3679. # today's behaviour intentionally.
  3680. if prefer_lowest and status.ams_filament_backup is False:
  3681. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3682. prefer_lowest = False
  3683. # When the preference is on, surface Bambuddy's inventory-side
  3684. # remaining for each slot that's bound to a tracked spool, so the
  3685. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3686. # entirely when the preference is off — no behaviour change for
  3687. # users who haven't opted in.
  3688. inventory_remain_overrides: dict[int, float] | None = None
  3689. if prefer_lowest:
  3690. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3691. # Compute mapping: match required filaments to available slots
  3692. return self._match_filaments_to_slots(
  3693. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3694. )
  3695. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3696. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3697. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3698. diagnosis (#2771) describes the filament the matcher actually looked
  3699. for, not the one the 3MF was sliced with — naming the pre-override
  3700. filament in a user-facing error would send the user to load the wrong
  3701. spool.
  3702. """
  3703. if not item.filament_overrides:
  3704. return
  3705. try:
  3706. overrides = json.loads(item.filament_overrides)
  3707. override_map = {o["slot_id"]: o for o in overrides}
  3708. for req in filament_reqs:
  3709. if req["slot_id"] in override_map:
  3710. override = override_map[req["slot_id"]]
  3711. req["type"] = override["type"]
  3712. req["color"] = override["color"]
  3713. # A manual/preference override SWAPS the slot's filament, so the
  3714. # 3MF's original tray_info_idx now points at the old spool and must
  3715. # be cleared — matching then falls back to type+colour. A
  3716. # force_color_match override is not a swap: it carries the 3MF's
  3717. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3718. # it here too, letting the matcher pin the correct variant slot on a
  3719. # printer holding two same-colour spools of different variants (#2650).
  3720. # If that variant isn't loaded the matcher falls back to type+colour,
  3721. # so an eligible printer never fails to map.
  3722. req["tray_info_idx"] = (
  3723. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3724. )
  3725. logger.debug(
  3726. "Queue item %s: Override slot %d -> %s %s",
  3727. item.id,
  3728. req["slot_id"],
  3729. override["type"],
  3730. override["color"],
  3731. )
  3732. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3733. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3734. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3735. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3736. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3737. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3738. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3739. treated as the filament requirement for that slot and matched against the
  3740. current AMS state of the printer.
  3741. Returns the same format as ``_match_filaments_to_slots``, or None when
  3742. the AMS has no loaded filaments.
  3743. """
  3744. loaded = self._build_loaded_filaments(status)
  3745. if not loaded:
  3746. return None
  3747. reqs = [
  3748. {
  3749. "slot_id": o["slot_id"],
  3750. "type": o.get("type", ""),
  3751. "color": o.get("color", ""),
  3752. # These are all force_color_match overrides, so the idx (when the
  3753. # 3MF carried one) is the intended variant, not a stale swap —
  3754. # keep it so the matcher pins the right variant slot, falling back
  3755. # to type+colour when it isn't loaded (#2650).
  3756. "tray_info_idx": o.get("tray_info_idx", ""),
  3757. }
  3758. for o in force_overrides
  3759. ]
  3760. return self._match_filaments_to_slots(reqs, loaded)
  3761. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3762. """Resolve the queue item's source 3MF and parse the per-slot
  3763. filament requirements out of it. Thin DB-resolver wrapper around
  3764. ``filament_requirements.extract_filament_requirements`` so the VP
  3765. queue-mode write path (#1188) can reuse the same parser at upload
  3766. time.
  3767. """
  3768. from backend.app.services.filament_requirements import extract_filament_requirements
  3769. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3770. # so every caller gets its own copy — a shared list would leak one
  3771. # item's overrides into the next item that happens to print the same
  3772. # plate.
  3773. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3774. if memo_key in self._filament_req_memo:
  3775. cached = self._filament_req_memo[memo_key]
  3776. return [dict(r) for r in cached] if cached else None
  3777. file_path: Path | None = None
  3778. if item.archive_id:
  3779. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3780. archive = result.scalar_one_or_none()
  3781. if archive:
  3782. file_path = settings.base_dir / archive.file_path
  3783. elif item.library_file_id:
  3784. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3785. library_file = result.scalar_one_or_none()
  3786. if library_file:
  3787. lib_path = Path(library_file.file_path)
  3788. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3789. if not file_path or not file_path.exists():
  3790. self._filament_req_memo[memo_key] = None
  3791. return None
  3792. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3793. self._filament_req_memo[memo_key] = filaments or None
  3794. return [dict(r) for r in filaments] if filaments else None
  3795. def _build_loaded_filaments(self, status) -> list[dict]:
  3796. """Build list of loaded filaments from printer status.
  3797. Args:
  3798. status: PrinterState from printer_manager
  3799. Returns:
  3800. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3801. """
  3802. filaments = []
  3803. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3804. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3805. # Dual-nozzle detection, used below to route external spools to an
  3806. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  3807. # which was corrected for #1257 while this copy kept the old signal.
  3808. #
  3809. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  3810. # printer with zero AMS units reports an empty map — and every external
  3811. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  3812. # `_match_filaments_to_slots` rejects outright because `None` equals
  3813. # neither 0 nor 1. On an X2D feeding from external spools only that left
  3814. # nothing to match, the mapping came back all -1, and the print went out
  3815. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  3816. # "Failed to get AMS mapping table".
  3817. #
  3818. # `nozzles` is always a two-entry list (the state seeds it with two empty
  3819. # NozzleInfo stubs), so its length proves nothing; only a populated
  3820. # diameter on the second entry means real hardware. The other two signals
  3821. # are fallbacks for firmware revisions that surface one but not the
  3822. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  3823. # and so is more than one `vt_tray` entry, since single-nozzle printers
  3824. # expose exactly one external feed.
  3825. nozzles = getattr(status, "nozzles", None) or []
  3826. vt_trays = status.raw_data.get("vt_tray") or []
  3827. is_dual_nozzle = bool(
  3828. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  3829. or ams_extruder_map
  3830. # isinstance, because a dict here would count its ~30 keys as trays.
  3831. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  3832. # so this is unreachable — but the loop below would raise on a dict
  3833. # and that is the pre-existing behaviour to keep, not to paper over.
  3834. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  3835. )
  3836. # Parse AMS units from raw_data
  3837. ams_data = status.raw_data.get("ams", [])
  3838. for ams_unit in ams_data:
  3839. ams_id = int(ams_unit.get("id", 0))
  3840. trays = ams_unit.get("tray", [])
  3841. is_ht = len(trays) == 1 # AMS-HT has single tray
  3842. for tray in trays:
  3843. tray_type = tray.get("tray_type")
  3844. if tray_type:
  3845. tray_id = int(tray.get("id", 0))
  3846. tray_color = tray.get("tray_color", "")
  3847. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  3848. tray_info_idx = tray.get("tray_info_idx", "")
  3849. # Normalize color: remove alpha, add hash
  3850. color = self._normalize_color(tray_color)
  3851. # Calculate global tray ID
  3852. # AMS-HT units have IDs starting at 128 with a single tray
  3853. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  3854. filaments.append(
  3855. {
  3856. "type": tray_type,
  3857. "color": color,
  3858. "tray_info_idx": tray_info_idx,
  3859. "ams_id": ams_id,
  3860. "tray_id": tray_id,
  3861. "is_ht": is_ht,
  3862. "is_external": False,
  3863. "global_tray_id": global_tray_id,
  3864. "extruder_id": ams_extruder_map.get(str(ams_id)),
  3865. "remain": tray.get("remain", -1),
  3866. }
  3867. )
  3868. # Check external spool(s) (vt_tray is a list)
  3869. for idx, vt in enumerate(vt_trays):
  3870. if vt.get("tray_type"):
  3871. color = self._normalize_color(vt.get("tray_color", ""))
  3872. tray_id = int(vt.get("id", 254))
  3873. filaments.append(
  3874. {
  3875. "type": vt["tray_type"],
  3876. "color": color,
  3877. "tray_info_idx": vt.get("tray_info_idx", ""),
  3878. "ams_id": -1,
  3879. "tray_id": idx,
  3880. "is_ht": False,
  3881. "is_external": True,
  3882. "global_tray_id": tray_id,
  3883. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  3884. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  3885. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  3886. "remain": vt.get("remain", -1),
  3887. }
  3888. )
  3889. return filaments
  3890. def _normalize_color(self, color: str | None) -> str:
  3891. """Normalize color to #RRGGBB format."""
  3892. if not color:
  3893. return "#808080"
  3894. hex_color = color.replace("#", "")[:6]
  3895. return f"#{hex_color}"
  3896. def _normalize_color_for_compare(self, color: str | None) -> str:
  3897. """Normalize color for comparison (lowercase, no hash)."""
  3898. if not color:
  3899. return ""
  3900. return color.replace("#", "").lower()[:6]
  3901. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  3902. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  3903. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  3904. stays the per-channel box that shipped — this only decides which of
  3905. several eligible spools is closest, so nothing becomes usable or
  3906. unusable because of it.
  3907. It ranks by how far apart the colours *look*, not how far apart their
  3908. numbers are. RGB distance overweights blue badly enough to invert the
  3909. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  3910. the nearer of two eligible spools by RGB and the further by a factor of
  3911. four once measured perceptually.
  3912. Alpha is ignored, deliberately: the alpha a slicer writes for a
  3913. transparent filament is not a colour the user chose, and counting it
  3914. would stop a transparent filament matching itself.
  3915. """
  3916. return perceptual_color_distance(color1, color2)
  3917. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  3918. """Check if two colors are visually similar within a threshold."""
  3919. hex1 = self._normalize_color_for_compare(color1)
  3920. hex2 = self._normalize_color_for_compare(color2)
  3921. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  3922. return False
  3923. try:
  3924. r1 = int(hex1[0:2], 16)
  3925. g1 = int(hex1[2:4], 16)
  3926. b1 = int(hex1[4:6], 16)
  3927. r2 = int(hex2[0:2], 16)
  3928. g2 = int(hex2[2:4], 16)
  3929. b2 = int(hex2[4:6], 16)
  3930. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  3931. except ValueError:
  3932. return False
  3933. async def _build_inventory_remain_overrides(
  3934. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  3935. ) -> dict[int, float]:
  3936. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  3937. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  3938. The MQTT ``remain`` field on a tray is the printer firmware's
  3939. RFID-decremented value, which has two limitations the "Prefer Lowest
  3940. Remaining Filament" feature has been ignoring (#1508):
  3941. - it's only meaningful for Bambu RFID spools; everything else reports
  3942. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  3943. compare equal and the sort collapses to AMS-slot order — the user
  3944. who's curating inventory weights gets the lower-slot pick instead
  3945. of the lower-remaining pick;
  3946. - even when set, it's the *printer's* counter, not Bambuddy's
  3947. ``label_weight - weight_used`` (internal mode) or Spoolman's
  3948. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  3949. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  3950. When the user has bound a spool to a slot, their own inventory
  3951. tracking is authoritative; this helper surfaces that value so the
  3952. sort can prefer it. Slots without a binding are absent from the
  3953. returned map — the caller then falls back to MQTT ``remain`` for
  3954. those, preserving the pre-#1508 behaviour for un-tracked spools.
  3955. Returns an empty map on any failure (no inventory bindings, DB
  3956. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  3957. is a preference, not a guarantee.
  3958. """
  3959. if not loaded:
  3960. return {}
  3961. # External / virtual-tray slots are tracked separately from AMS — skip
  3962. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  3963. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  3964. # match is fiddly and out of scope for this fix).
  3965. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  3966. if not tracked_slots:
  3967. return {}
  3968. is_spoolman = await self._is_spoolman_mode(db)
  3969. overrides: dict[int, float] = {}
  3970. if is_spoolman:
  3971. result = await db.execute(
  3972. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3973. )
  3974. assignments = list(result.scalars().all())
  3975. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  3976. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  3977. for ams_id, tray_id, gtid in tracked_slots:
  3978. spoolman_id = by_slot.get((ams_id, tray_id))
  3979. if spoolman_id is None:
  3980. continue
  3981. grams = await _spoolman_remaining_grams(spoolman_id)
  3982. if grams is not None:
  3983. overrides[gtid] = grams
  3984. return overrides
  3985. # Internal inventory mode (default). selectinload matches the pattern
  3986. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  3987. # plus an eager-loaded relationship rather than an explicit join, so
  3988. # the row-attribute shape is exactly what those routes already rely on.
  3989. result = await db.execute(
  3990. select(SpoolAssignment)
  3991. .options(selectinload(SpoolAssignment.spool))
  3992. .where(SpoolAssignment.printer_id == printer_id)
  3993. )
  3994. assignments = list(result.scalars().all())
  3995. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  3996. for ams_id, tray_id, gtid in tracked_slots:
  3997. spool = by_slot.get((ams_id, tray_id))
  3998. if spool is None:
  3999. continue
  4000. label = float(spool.label_weight or 0)
  4001. used = float(spool.weight_used or 0)
  4002. overrides[gtid] = max(0.0, label - used)
  4003. return overrides
  4004. @staticmethod
  4005. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4006. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4007. here to avoid making this module import-dependent on that private
  4008. helper's signature."""
  4009. try:
  4010. from backend.app.api.routes.settings import get_setting
  4011. v = await get_setting(db, "spoolman_enabled")
  4012. return bool(v) and v.lower() == "true"
  4013. except Exception:
  4014. return False
  4015. @staticmethod
  4016. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4017. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4018. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4019. so a tied sort produces the same physical-position order the pre-#1508
  4020. stable sort did (preserves the regression-free baseline):
  4021. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4022. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4023. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4024. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4025. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4026. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4027. """
  4028. if ams_id is None or ams_id < 0:
  4029. return 10_000
  4030. if ams_id >= 128:
  4031. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4032. return ams_id * 4 + (tray_id or 0)
  4033. @staticmethod
  4034. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4035. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4036. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4037. non-tracked spools (the user has told us they care about these
  4038. specifically), then ascending by remaining within each tier, then
  4039. ascending by AMS slot position as the deterministic tie-breaker.
  4040. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4041. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4042. because the tier flag dominates — which is what lets us mix grams
  4043. (inventory) and percent (MQTT) without a unit conversion.
  4044. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4045. spools the printer DOES know something about sort ahead of those
  4046. it knows nothing about — preserves pre-#1508 behaviour for the
  4047. no-inventory-binding case.
  4048. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4049. external on ties, matching the legacy emission-order stable sort.
  4050. """
  4051. gtid = f.get("global_tray_id")
  4052. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4053. if overrides and gtid in overrides:
  4054. return (0, overrides[gtid], slot_order)
  4055. remain = f.get("remain", -1)
  4056. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4057. def _match_filaments_to_slots(
  4058. self,
  4059. required: list[dict],
  4060. loaded: list[dict],
  4061. prefer_lowest: bool = False,
  4062. inventory_remain_overrides: dict[int, float] | None = None,
  4063. fts_installed: bool = False,
  4064. ) -> list[int] | None:
  4065. """Match required filaments to loaded filaments and build AMS mapping.
  4066. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4067. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4068. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4069. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4070. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4071. matching among those trays.
  4072. Args:
  4073. required: List of required filaments with slot_id, type, color, tray_info_idx
  4074. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4075. Returns:
  4076. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4077. """
  4078. if not required:
  4079. return None
  4080. # Track used trays to avoid duplicate assignment
  4081. used_tray_ids: set[int] = set()
  4082. comparisons = []
  4083. for req in required:
  4084. req_type = (req.get("type") or "").upper()
  4085. req_color = req.get("color", "")
  4086. req_tray_info_idx = req.get("tray_info_idx", "")
  4087. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4088. idx_match = None
  4089. exact_match = None
  4090. similar_match = None
  4091. similar_distance = float("inf")
  4092. type_only_match = None
  4093. # Get available trays (not already used)
  4094. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4095. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4096. # Hard filter — cross-nozzle assignment causes print failures
  4097. # ("position of left hotend is abnormal"), so never fall back.
  4098. # Skipped when an FTS is installed: it routes any AMS slot to either
  4099. # extruder, so restricting to one nozzle would wrongly exclude the
  4100. # correct spool sitting in the other nozzle's AMS (#2186).
  4101. req_nozzle_id = req.get("nozzle_id")
  4102. if req_nozzle_id is not None and not fts_installed:
  4103. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4104. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4105. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4106. # _prefer_lowest_sort_key for the full rationale.
  4107. if prefer_lowest:
  4108. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4109. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4110. # One line per filament req so a bug report can be diagnosed
  4111. # without enabling debug logging: shows what the matcher saw
  4112. # (req shape + sorted candidate trays with their remain values
  4113. # and any inventory override that was applied). Mirrored by
  4114. # the picked-match log at the bottom of the loop.
  4115. logger.info(
  4116. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4117. req.get("slot_id"),
  4118. req_type,
  4119. req_color,
  4120. req_tray_info_idx,
  4121. req_nozzle_id,
  4122. [
  4123. {
  4124. "gtid": f.get("global_tray_id"),
  4125. "type": f.get("type"),
  4126. "color": f.get("color"),
  4127. "tii": f.get("tray_info_idx"),
  4128. "remain": f.get("remain"),
  4129. "inv_g": (
  4130. inventory_remain_overrides.get(f.get("global_tray_id"))
  4131. if inventory_remain_overrides
  4132. else None
  4133. ),
  4134. }
  4135. for f in available
  4136. ],
  4137. )
  4138. # Check if tray_info_idx is unique among available trays
  4139. if req_tray_info_idx:
  4140. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4141. if len(idx_matches) == 1:
  4142. # Unique tray_info_idx - use it as definitive match
  4143. idx_match = idx_matches[0]
  4144. logger.debug(
  4145. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4146. f"-> tray {idx_match['global_tray_id']}"
  4147. )
  4148. elif len(idx_matches) > 1:
  4149. # Multiple trays with same tray_info_idx - use color matching among them
  4150. logger.debug(
  4151. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4152. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4153. )
  4154. if prefer_lowest:
  4155. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4156. # Use color matching within this subset
  4157. for f in idx_matches:
  4158. f_color = f.get("color", "")
  4159. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4160. if not exact_match:
  4161. exact_match = f
  4162. elif self._colors_are_similar(f_color, req_color):
  4163. distance = self._color_distance(f_color, req_color)
  4164. if distance is not None and distance < similar_distance:
  4165. similar_match = f
  4166. similar_distance = distance
  4167. elif not type_only_match:
  4168. type_only_match = f
  4169. # If no idx_match yet, do standard type/color matching on all available trays
  4170. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4171. for f in available:
  4172. f_type = (f.get("type") or "").upper()
  4173. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4174. continue
  4175. # Type matches - check color
  4176. f_color = f.get("color", "")
  4177. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4178. if not exact_match:
  4179. exact_match = f
  4180. elif self._colors_are_similar(f_color, req_color):
  4181. # Nearest wins, not first-in-tray-order. `available` is
  4182. # already in the caller's order (slot order, or the
  4183. # prefer-lowest sort), and `<` keeps the earliest of
  4184. # equally close spools — so that order survives as the
  4185. # tie-break (#2804).
  4186. distance = self._color_distance(f_color, req_color)
  4187. if distance is not None and distance < similar_distance:
  4188. similar_match = f
  4189. similar_distance = distance
  4190. elif not type_only_match:
  4191. type_only_match = f
  4192. match = idx_match or exact_match or similar_match or type_only_match
  4193. if match:
  4194. used_tray_ids.add(match["global_tray_id"])
  4195. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4196. else:
  4197. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4198. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4199. # "Why did it pick that spool" is the question every wrong-filament
  4200. # report starts with, and a `similar_color` win is now a ranked
  4201. # choice among several eligible spools rather than whichever tray
  4202. # came first, so it is worth being able to see after the fact.
  4203. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4204. # is on (#1766).
  4205. if match:
  4206. bucket = (
  4207. "idx"
  4208. if idx_match is not None
  4209. else "exact_color"
  4210. if exact_match is not None
  4211. else "similar_color"
  4212. if similar_match is not None
  4213. else "type_only"
  4214. )
  4215. logger.info(
  4216. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4217. match["global_tray_id"],
  4218. bucket,
  4219. req.get("slot_id"),
  4220. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4221. )
  4222. else:
  4223. logger.info(
  4224. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4225. req.get("slot_id"),
  4226. req_type,
  4227. req_color,
  4228. req_tray_info_idx,
  4229. )
  4230. # Build mapping array
  4231. if not comparisons:
  4232. return None
  4233. max_slot_id = max(c["slot_id"] for c in comparisons)
  4234. if max_slot_id <= 0:
  4235. return None
  4236. mapping = [-1] * max_slot_id
  4237. for c in comparisons:
  4238. slot_id = c["slot_id"]
  4239. if slot_id and slot_id > 0:
  4240. mapping[slot_id - 1] = c["global_tray_id"]
  4241. return mapping
  4242. def _mark_printer_dispatched(
  4243. self,
  4244. printer_id: int,
  4245. pre_state: str | None,
  4246. pre_subtask_id: str | None,
  4247. ) -> None:
  4248. """Record that a print command was just sent to ``printer_id``.
  4249. Held until either the watchdog observes a state/subtask transition
  4250. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4251. """
  4252. if not pre_state:
  4253. # No pre_state means we can't detect a transition — fall back to a
  4254. # pure time-based hold using empty string as a sentinel that won't
  4255. # match any real printer state.
  4256. pre_state = ""
  4257. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4258. def _release_dispatch_hold(self, printer_id: int) -> None:
  4259. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4260. self._dispatch_holds.pop(printer_id, None)
  4261. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4262. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4263. Returns False (and clears the hold) once any of these are true:
  4264. - hard timeout (``_dispatch_max_hold``) has elapsed
  4265. - the printer has transitioned out of pre_state and we're past the
  4266. minimum cooldown
  4267. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4268. past the minimum cooldown
  4269. Otherwise the printer is held — caller should treat it as busy.
  4270. """
  4271. entry = self._dispatch_holds.get(printer_id)
  4272. if not entry:
  4273. return False
  4274. started_at, pre_state, pre_subtask_id = entry
  4275. elapsed = time.monotonic() - started_at
  4276. if elapsed >= self._dispatch_max_hold:
  4277. self._dispatch_holds.pop(printer_id, None)
  4278. return False
  4279. # Without a pre_state we can't detect a transition — fall back to the
  4280. # min cooldown alone, then drop the hold.
  4281. if not pre_state:
  4282. if elapsed >= self._dispatch_min_cooldown:
  4283. self._dispatch_holds.pop(printer_id, None)
  4284. return False
  4285. return True
  4286. status = printer_manager.get_status(printer_id)
  4287. current_state = getattr(status, "state", None) if status else None
  4288. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4289. transitioned = (current_state is not None and current_state != pre_state) or (
  4290. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4291. )
  4292. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4293. self._dispatch_holds.pop(printer_id, None)
  4294. return False
  4295. return True
  4296. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4297. """Check if a printer is connected and idle."""
  4298. if not printer_manager.is_connected(printer_id):
  4299. logger.debug("Printer %d: not connected", printer_id)
  4300. return False
  4301. state = printer_manager.get_status(printer_id)
  4302. if not state:
  4303. logger.debug("Printer %d: no status available", printer_id)
  4304. return False
  4305. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4306. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4307. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4308. # printer, it boots back into IDLE with no memory of the previous finish; without
  4309. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4310. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4311. logger.debug(
  4312. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4313. printer_id,
  4314. state.state,
  4315. )
  4316. return False
  4317. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4318. if not idle:
  4319. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4320. return idle
  4321. @staticmethod
  4322. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4323. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4324. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4325. and that the fixed-printer branch has already found connected, so the two
  4326. offline cases answer at their own exits and never arrive here.
  4327. The default is the model-based branch's ``Busy:`` wording, which
  4328. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4329. the right answer for the connected-but-no-telemetry second or two after a
  4330. reconnect: the model-based branch has always reported it that way, and it
  4331. is not something to wake anybody up for.
  4332. A plate nobody has confirmed is the one case here that does not resolve
  4333. itself — somebody has to walk over to the printer — so it is worded as
  4334. itself and allowed to notify.
  4335. """
  4336. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4337. return f"Waiting for plate confirmation: {printer_name}"
  4338. return f"Busy: {printer_name}"
  4339. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4340. """Read a setting value from the database."""
  4341. result = await db.execute(select(Settings).where(Settings.key == key))
  4342. setting = result.scalar_one_or_none()
  4343. return setting.value if setting else None
  4344. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4345. """Read a boolean setting from the database."""
  4346. result = await db.execute(select(Settings).where(Settings.key == key))
  4347. setting = result.scalar_one_or_none()
  4348. if setting:
  4349. return setting.value.lower() == "true"
  4350. return default
  4351. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4352. """Read an int setting; falls back to default on missing/unparseable rows."""
  4353. result = await db.execute(select(Settings).where(Settings.key == key))
  4354. setting = result.scalar_one_or_none()
  4355. if setting and setting.value:
  4356. try:
  4357. return int(setting.value)
  4358. except ValueError:
  4359. pass
  4360. return default
  4361. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4362. """Get drying presets (user-configured or built-in defaults)."""
  4363. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4364. setting = result.scalar_one_or_none()
  4365. if setting and setting.value:
  4366. try:
  4367. presets = json.loads(setting.value)
  4368. if isinstance(presets, dict) and presets:
  4369. return presets
  4370. except json.JSONDecodeError:
  4371. pass
  4372. return self.DEFAULT_DRYING_PRESETS
  4373. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4374. """Per-filament humidity thresholds (#1605).
  4375. Returns the user-configured overrides map keyed by normalized filament
  4376. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4377. unknown / unmapped types. Empty / unset → empty dict, in which case
  4378. callers fall back to ``ams_humidity_fair``.
  4379. """
  4380. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4381. setting = result.scalar_one_or_none()
  4382. if not setting or not setting.value:
  4383. return {}
  4384. try:
  4385. data = json.loads(setting.value)
  4386. except json.JSONDecodeError:
  4387. return {}
  4388. if not isinstance(data, dict):
  4389. return {}
  4390. out: dict[str, int] = {}
  4391. for key, value in data.items():
  4392. try:
  4393. out[str(key).upper() if key != "default" else "default"] = int(value)
  4394. except (TypeError, ValueError):
  4395. continue
  4396. return out
  4397. # Materials whose AMS spelling differs from the key the tables above use.
  4398. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4399. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4400. # good PA row (#3067).
  4401. #
  4402. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4403. # The drying popover has resolved these correctly since #2774 and the
  4404. # scheduler never did, which is exactly why #3067's reporter could dry a
  4405. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4406. #
  4407. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4408. # of nylon, so it is the one entry that is a judgement rather than a
  4409. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4410. # way, and PA's row is the hottest the table has. Drying it there is closer
  4411. # to right than not drying it at all, which is what it got before.
  4412. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4413. "NYLON": "PA",
  4414. "PA6": "PA",
  4415. "PA11": "PA",
  4416. "PA12": "PA",
  4417. "PAHT": "PA",
  4418. "PPA": "PA",
  4419. }
  4420. @classmethod
  4421. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4422. """The key in *table* that answers for this tray's material, or None.
  4423. The printer reports the material in ``tray_type``, and it spells filled
  4424. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4425. tables here are keyed by base material, so matching the raw string alone
  4426. found a row for 8 of the 41 types a printer can report and skipped the
  4427. rest -- silently, because every caller reads "no row" as "nothing to do
  4428. for this tray". Auto-drying therefore ignored every composite spool on
  4429. the install (#3067).
  4430. Exact match first, so a table the user has extended with a row of its
  4431. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4432. base material's. Then the suffix is dropped, then the alias map above
  4433. answers for the polyamide spellings.
  4434. Returns None rather than a default: what to do with an unrecognised
  4435. material differs per caller, and only the caller knows whether "no row"
  4436. means skip the tray or fall back to a catch-all. Nothing here invents a
  4437. temperature for a material the table does not list.
  4438. """
  4439. raw = cls._normalize_filament_type(tray_type or "")
  4440. if not raw:
  4441. return None
  4442. for candidate in (raw, raw.split("-")[0]):
  4443. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4444. if key in table:
  4445. return key
  4446. return None
  4447. @staticmethod
  4448. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4449. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4450. For mixed filament types loaded into one AMS, returns the most
  4451. restrictive (lowest) threshold across all loaded tray types — matches
  4452. the conservative-params strategy already used for drying temp/hours.
  4453. Empty / unloaded trays contribute no constraint. Unknown types use the
  4454. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4455. when no per-type map is configured at all.
  4456. """
  4457. default = thresholds.get("default", fallback)
  4458. if not thresholds:
  4459. return fallback
  4460. candidates: list[int] = []
  4461. for tray in trays:
  4462. tray_type = str(tray.get("tray_type") or "").strip()
  4463. if not tray_type:
  4464. continue
  4465. # A composite carries its base material's threshold when it has no
  4466. # row of its own, the same way it takes its drying preset (#3067).
  4467. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4468. candidates.append(thresholds[key] if key is not None else default)
  4469. if not candidates:
  4470. return default
  4471. return min(candidates)
  4472. def _get_conservative_drying_params(
  4473. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4474. ) -> tuple[int, int, str] | None:
  4475. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4476. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4477. """
  4478. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4479. hours_key = f"{temp_key}_hours"
  4480. min_temp = None
  4481. max_hours = None
  4482. filament_type = ""
  4483. for tray in trays:
  4484. tray_type = tray.get("tray_type", "")
  4485. if not tray_type:
  4486. continue
  4487. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4488. # which is what stopped auto-drying on every composite spool (#3067).
  4489. base_type = self._resolve_filament_key(tray_type, presets)
  4490. if base_type is None:
  4491. continue
  4492. # The table is user-editable JSON with no per-row validation, so a
  4493. # row can be present and empty. That has always meant "skip this
  4494. # material", and it has to keep meaning it: the reads below fall
  4495. # back to 55C/12h per missing field, which is a temperature nobody
  4496. # chose and would deform a PLA spool.
  4497. preset = presets[base_type]
  4498. if not preset:
  4499. continue
  4500. temp = preset.get(temp_key, 55)
  4501. hours = preset.get(hours_key, 12)
  4502. # Conservative: lowest temp, longest duration
  4503. if min_temp is None or temp < min_temp:
  4504. min_temp = temp
  4505. if max_hours is None or hours > max_hours:
  4506. max_hours = hours
  4507. if not filament_type:
  4508. filament_type = base_type
  4509. if min_temp is None:
  4510. return None
  4511. return (min_temp, max_hours or 12, filament_type)
  4512. async def _check_filament_low(self, db: AsyncSession) -> None:
  4513. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4514. ``on_filament_low`` has had a column, a schema field, a route, a template
  4515. and a UI toggle since the notification system was built, and no caller --
  4516. so the toggle could be switched on and could never fire. This is the
  4517. producer.
  4518. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4519. ``low_stock_threshold_pct`` override is already exactly this decision:
  4520. already configurable, already surfaced, already driving the Inventory
  4521. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4522. consulted -- it has been measured up to 56 points out against a scale,
  4523. which is not a number to page someone on.
  4524. Only slots with an assigned spool produce an event. A slot Bambuddy
  4525. cannot resolve to a spool has no remaining weight it can stand behind,
  4526. and guessing one is how the remain percentage would have got in.
  4527. """
  4528. from backend.app.models.spool import Spool
  4529. # Time-gated rather than run on every pass. run() sleeps
  4530. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4531. # early-return path counts as productive while an upload is in flight
  4532. # (#2602), so an unthrottled check would re-read the whole spool
  4533. # collection every 3 seconds for the length of a batch drain. In
  4534. # Spoolman mode that is a request storm against a third-party service,
  4535. # which is the thing this producer's design note argues against; and
  4536. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4537. # check_queue holding the scheduler's session, so the outage would
  4538. # throttle the print queue itself. A low spool is not a 3-second
  4539. # concern -- the idle interval is the natural resolution.
  4540. now = time.monotonic()
  4541. if now < self._filament_low_next_check:
  4542. return
  4543. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4544. try:
  4545. # on_filament_low defaults to off on every provider, so on most
  4546. # installs nobody wants this alert. Without this the check would
  4547. # still read every assigned spool each interval -- the whole
  4548. # collection over HTTP in Spoolman mode -- for an event that is
  4549. # switched off. One query against the provider table settles it
  4550. # before any spool work, the same guard the bed-cooled waiter uses.
  4551. # No printer_id: this asks whether any provider wants the event at
  4552. # all; per-printer scoping is applied when the event is sent.
  4553. #
  4554. # While nobody wants it, no pass sees a slot go back above its
  4555. # threshold, so nothing can re-arm; a spool refilled under the same
  4556. # id in that time would stay silenced until a restart. Forgetting
  4557. # what was sent is right anyway: whoever switches the event back on
  4558. # is told about the spools that are low now.
  4559. if not await notification_service._get_providers_for_event(db, "on_filament_low"):
  4560. self._notified_filament_low.clear()
  4561. return
  4562. global_threshold = await self._get_low_stock_threshold(db)
  4563. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4564. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4565. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4566. if spoolman_on:
  4567. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4568. else:
  4569. rows = (
  4570. await db.execute(
  4571. select(SpoolAssignment, Spool)
  4572. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4573. # An archived spool is not stock. The Inventory page's
  4574. # Low Stock count skips them (InventoryPage.tsx:1089)
  4575. # and get_all_spools without allow_archived already
  4576. # excludes them in Spoolman mode, so without this the
  4577. # internal path is the only one that alerts on them.
  4578. .where(Spool.archived_at.is_(None))
  4579. )
  4580. ).all()
  4581. for assignment, spool in rows:
  4582. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4583. if pct is None:
  4584. continue
  4585. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4586. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4587. pct,
  4588. threshold,
  4589. spool.color_name,
  4590. )
  4591. if not slots:
  4592. # Nothing resolvable this pass. Deliberately not clearing the
  4593. # notified set: a Spoolman that is briefly unreachable would
  4594. # otherwise re-alert on every spool as soon as it came back.
  4595. return
  4596. await self._emit_filament_low(db, slots)
  4597. except Exception as e:
  4598. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4599. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4600. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4601. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4602. if raw is None or raw.value is None:
  4603. return 20.0
  4604. try:
  4605. value = float(raw.value)
  4606. except (TypeError, ValueError):
  4607. return 20.0
  4608. return value if 0 < value <= 100 else 20.0
  4609. async def _filament_low_slots_spoolman(
  4610. self, db: AsyncSession, global_threshold: float
  4611. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4612. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4613. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4614. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4615. so the global threshold is the only one that applies here. That matches
  4616. what the Inventory page already does in this mode.
  4617. One ``get_all_spools`` call covers every slot rather than a request per
  4618. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4619. without ``allow_archived`` -- which is the behaviour the internal path
  4620. has to ask for explicitly.
  4621. An unreachable Spoolman returns no slots rather than raising. It is an
  4622. ordinary state for a third-party service, not an error in this pass: the
  4623. caller's "nothing resolvable" branch already leaves the notified set
  4624. alone, which is exactly right here, whereas letting it reach the broad
  4625. ``except`` would write a full traceback every time the check runs.
  4626. """
  4627. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4628. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4629. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4630. if not assignments:
  4631. return {}
  4632. client = await get_spoolman_client()
  4633. if client is None:
  4634. return {}
  4635. try:
  4636. all_spools = await client.get_all_spools()
  4637. except SpoolmanUnavailableError as e:
  4638. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4639. return {}
  4640. by_id: dict[int, dict] = {}
  4641. for raw in all_spools:
  4642. raw_id = raw.get("id")
  4643. if isinstance(raw_id, int):
  4644. by_id[raw_id] = raw
  4645. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4646. for assignment in assignments:
  4647. raw = by_id.get(assignment.spoolman_spool_id)
  4648. if raw is None:
  4649. continue
  4650. try:
  4651. mapped = _map_spoolman_spool(raw)
  4652. except ValueError:
  4653. continue
  4654. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4655. if pct is None:
  4656. continue
  4657. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4658. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4659. return slots
  4660. async def _emit_filament_low(
  4661. self, db: AsyncSession, slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]]
  4662. ) -> None:
  4663. """Send one notification per slot that has newly crossed its threshold."""
  4664. printer_names: dict[int, str] = {}
  4665. for key, (pct, threshold, color) in slots.items():
  4666. printer_id, ams_id, tray_id, _spool_id = key
  4667. if pct >= threshold:
  4668. # Back above the line: re-arm rather than expire on a timer, so a
  4669. # refilled slot can alert again and a spool sitting just under the
  4670. # threshold stays quiet.
  4671. self._notified_filament_low.discard(key)
  4672. continue
  4673. if key in self._notified_filament_low:
  4674. continue
  4675. # Marked before sending, which is a choice rather than the only
  4676. # option, and it is the opposite failure mode from the one the
  4677. # debounce argues against: one transient provider failure loses this
  4678. # alert until the spool goes back above the threshold and crosses it
  4679. # again. Marking after a successful send would trade that for
  4680. # re-alerting on every pass while a provider is down -- which is the
  4681. # repetition the whole debounce exists to prevent, and the louder of
  4682. # the two failures. A spool that is low stays low, so the next real
  4683. # signal is not far away; a provider stuck retrying is a signal that
  4684. # never stops.
  4685. self._notified_filament_low.add(key)
  4686. if printer_id not in printer_names:
  4687. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4688. if printer is None:
  4689. continue
  4690. printer_names[printer_id] = printer.name
  4691. try:
  4692. await notification_service.on_filament_low(
  4693. printer_id,
  4694. printer_names[printer_id],
  4695. _ams_slot_label(ams_id, tray_id),
  4696. int(pct),
  4697. db,
  4698. color=color,
  4699. )
  4700. except Exception as e:
  4701. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4702. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4703. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4704. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4705. a schema field, a template and a UI toggle, and nothing that computes the
  4706. condition -- the Forecast panel does it in the browser, so with no page
  4707. open nothing could ever alert. This runs the same arithmetic
  4708. (``stock_forecast``) from the scheduler loop.
  4709. An alert is sent when a SKU *moves into* a condition, once, and again
  4710. after the condition has cleared. A SKU that worsens from reorder to break
  4711. alerts again as a break, because the panel treats the two as exclusive; one
  4712. that eases from break back to reorder does not alert again.
  4713. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4714. while it is still low tells you.
  4715. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4716. loop runs every 3 s while an upload is in flight, and the whole spool
  4717. collection is read over HTTP in Spoolman mode. Both events default to off
  4718. on every provider, so nothing is read unless a provider wants one.
  4719. """
  4720. now = time.monotonic()
  4721. if now < self._stock_forecast_next_check:
  4722. return
  4723. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4724. try:
  4725. if self._stock_alerts_persisted is None:
  4726. await self._load_stock_alerts(db)
  4727. wanted = {
  4728. "reorder": bool(await notification_service._get_providers_for_event(db, "on_stock_reorder_alert")),
  4729. "break": bool(await notification_service._get_providers_for_event(db, "on_stock_break_alert")),
  4730. }
  4731. if not any(wanted.values()):
  4732. # Nobody wants either event. Forget what was sent, so whoever
  4733. # switches one on is told about the SKUs that are low now.
  4734. self._notified_stock_alerts.clear()
  4735. await self._save_stock_alerts(db)
  4736. return
  4737. forecasts = await self._stock_forecasts(db)
  4738. if forecasts is None:
  4739. # Spoolman unreachable. Deliberately not clearing the notified
  4740. # set: a brief outage would otherwise re-alert every SKU when it
  4741. # came back.
  4742. return
  4743. await self._emit_stock_alerts(db, forecasts, wanted)
  4744. await self._save_stock_alerts(db)
  4745. except Exception as e:
  4746. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4747. def _serialize_stock_alerts(self) -> str:
  4748. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4749. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4750. return json.dumps(rows)
  4751. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4752. """Read the notified set saved by the last run, once per process.
  4753. A missing or unreadable row is an empty set: the worst that does is one
  4754. repeat of what a restart used to cause every time.
  4755. """
  4756. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4757. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4758. if raw and raw.value:
  4759. try:
  4760. for key, kind, events in json.loads(raw.value):
  4761. if len(key) == 4 and kind in ("reorder", "break"):
  4762. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4763. except (ValueError, TypeError):
  4764. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4765. loaded = {}
  4766. self._notified_stock_alerts = loaded
  4767. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4768. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4769. """Write the notified set to its settings row if it changed since it was last read or written."""
  4770. serialized = self._serialize_stock_alerts()
  4771. if serialized == self._stock_alerts_persisted:
  4772. return
  4773. from backend.app.core.db_dialect import upsert_setting
  4774. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4775. await db.commit()
  4776. self._stock_alerts_persisted = serialized
  4777. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4778. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4779. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4780. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4781. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4782. sku_settings = {
  4783. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4784. lead_time_days=row.lead_time_days,
  4785. safety_margin_value=row.safety_margin_value,
  4786. safety_margin_unit=row.safety_margin_unit,
  4787. alerts_snoozed=bool(row.alerts_snoozed),
  4788. )
  4789. for row in sku_rows
  4790. }
  4791. if await self._get_bool_setting(db, "spoolman_enabled"):
  4792. spools = await self._stock_spools_spoolman()
  4793. if spools is None:
  4794. return None
  4795. # Spoolman owns the usage in this mode and Bambuddy's own history
  4796. # table holds nothing for those spools, so the rate is always the
  4797. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4798. # are local spool ids, and a Spoolman id that happens to match one
  4799. # (left over from before Spoolman was switched on) would borrow an
  4800. # unrelated spool's history.
  4801. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4802. else:
  4803. spools = await self._stock_spools_internal(db)
  4804. history = await self._stock_usage_history(db)
  4805. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4806. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4807. from backend.app.models.spool import Spool
  4808. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4809. return [
  4810. stock_forecast.StockSpool(
  4811. id=spool.id,
  4812. material=spool.material,
  4813. subtype=spool.subtype,
  4814. brand=spool.brand,
  4815. color_name=spool.color_name,
  4816. label_weight=float(spool.label_weight or 0),
  4817. weight_used=float(spool.weight_used or 0),
  4818. weight_used_baseline=float(spool.weight_used_baseline or 0),
  4819. created_at=spool.created_at,
  4820. )
  4821. for spool in rows
  4822. ]
  4823. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  4824. from backend.app.models.spool_usage_history import SpoolUsageHistory
  4825. rows = (
  4826. await db.execute(
  4827. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  4828. .order_by(SpoolUsageHistory.created_at.desc())
  4829. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  4830. )
  4831. ).all()
  4832. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4833. for spool_id, created_at, weight_used in rows:
  4834. if created_at is None:
  4835. continue
  4836. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  4837. return history
  4838. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  4839. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  4840. ``get_all_spools`` leaves archived spools out unless asked, which is the
  4841. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  4842. is the same mapping the Inventory page (and so the panel) reads.
  4843. """
  4844. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4845. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4846. client = await get_spoolman_client()
  4847. if client is None:
  4848. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  4849. return None
  4850. try:
  4851. raw_spools = await client.get_all_spools()
  4852. except SpoolmanUnavailableError as e:
  4853. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  4854. return None
  4855. spools: list[stock_forecast.StockSpool] = []
  4856. for raw in raw_spools:
  4857. try:
  4858. mapped = _map_spoolman_spool(raw)
  4859. except ValueError:
  4860. continue
  4861. created_at = None
  4862. if mapped.get("created_at"):
  4863. try:
  4864. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  4865. except ValueError:
  4866. created_at = None
  4867. spools.append(
  4868. stock_forecast.StockSpool(
  4869. id=mapped["id"],
  4870. material=mapped["material"],
  4871. subtype=mapped.get("subtype"),
  4872. brand=mapped.get("brand"),
  4873. color_name=mapped.get("color_name"),
  4874. label_weight=float(mapped.get("label_weight") or 0),
  4875. weight_used=float(mapped.get("weight_used") or 0),
  4876. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  4877. created_at=created_at,
  4878. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  4879. )
  4880. )
  4881. return spools
  4882. async def _emit_stock_alerts(
  4883. self,
  4884. db: AsyncSession,
  4885. forecasts: stock_forecast.ForecastMap,
  4886. wanted: dict[str, bool],
  4887. ) -> None:
  4888. """Send the notifications for each SKU that has moved into a stock alert condition.
  4889. A SKU in break has also reached its reorder point, so both events apply to
  4890. it: the break event goes to providers that have it on, and the reorder event
  4891. to the providers that have only that one on. A provider with both on gets the
  4892. break and no second message.
  4893. What is remembered per SKU is the condition and which events had a
  4894. subscriber when it was sent. An event with no subscriber is forgotten, so
  4895. switching it on later reports the SKUs already in that condition.
  4896. """
  4897. active_events = {event for event, on in wanted.items() if on}
  4898. for key, (forecast, spool) in forecasts.items():
  4899. kind: str | None = None
  4900. if not forecast.snoozed:
  4901. if forecast.stock_break_alert:
  4902. kind = "break"
  4903. elif forecast.reorder_alert:
  4904. kind = "reorder"
  4905. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  4906. events = applicable & active_events
  4907. if not events:
  4908. self._notified_stock_alerts.pop(key, None)
  4909. continue
  4910. previous = self._notified_stock_alerts.get(key)
  4911. told = (previous[1] & active_events) if previous else frozenset()
  4912. # Trimmed to the events this condition can send. That is what makes easing from
  4913. # break back to reorder silent (the reorder event was told with the break) and
  4914. # worsening again news again (the break event is no longer remembered).
  4915. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  4916. # Recorded before sending, for the reason _emit_filament_low gives: a
  4917. # provider that is down should lose this alert, not repeat it every hour.
  4918. to_send = events - told
  4919. # Both flags imply a positive rate and so a day count.
  4920. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  4921. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  4922. color = None if spool.color_name_is_synthesized else spool.color_name
  4923. try:
  4924. if "break" in to_send:
  4925. await notification_service.on_stock_break_alert(
  4926. spool.material,
  4927. spool.brand,
  4928. forecast.remaining_g,
  4929. rate,
  4930. days_left,
  4931. forecast.effective_lead_time_days,
  4932. db,
  4933. subtype=spool.subtype,
  4934. color=color,
  4935. )
  4936. if "reorder" in to_send:
  4937. await notification_service.on_stock_reorder_alert(
  4938. spool.material,
  4939. spool.brand,
  4940. forecast.remaining_g,
  4941. rate,
  4942. days_left,
  4943. db,
  4944. subtype=spool.subtype,
  4945. color=color,
  4946. skip_break_subscribers=kind == "break",
  4947. )
  4948. except Exception as e:
  4949. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  4950. # A SKU with no spools left is no longer alerting.
  4951. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  4952. del self._notified_stock_alerts[key]
  4953. async def _check_auto_drying(
  4954. self,
  4955. db: AsyncSession,
  4956. queue_items: list[PrintQueueItem],
  4957. dispatching_printers: set[int],
  4958. ):
  4959. """Start drying on idle printers based on humidity.
  4960. Three modes (can all be enabled independently):
  4961. - queue_drying_enabled: Dry between scheduled queue prints
  4962. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  4963. - print_drying_enabled: Also evaluate printers that are currently printing,
  4964. when model+firmware supports "Print While Drying" (gated by
  4965. supports_drying_while_printing). Drying temperature is capped at
  4966. max(40, preset_temp - 5) to protect spools mid-print.
  4967. """
  4968. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  4969. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  4970. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  4971. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  4972. # The wait belongs to ambient drying: the settings UI only shows it while
  4973. # ambient drying is on, so a value left behind when ambient is turned off
  4974. # must not keep delaying the one path that still reaches the wait gate
  4975. # without it (a mid-print start under print_drying).
  4976. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  4977. # Clear every streak as soon as the wait is inactive. An early return (or
  4978. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  4979. # a quick toggle-on inherit an old streak.
  4980. if not sustained_wait_active:
  4981. self._auto_dry_above.clear()
  4982. if not queue_drying_enabled and not ambient_drying_enabled:
  4983. # Stop active drying on all printers if both features disabled
  4984. if self._drying_in_progress:
  4985. for pid in list(self._drying_in_progress):
  4986. if pid in self._scheduled_drying_printer_ids:
  4987. continue
  4988. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  4989. await self._stop_drying(pid)
  4990. return
  4991. # Update drying state from printer status (handles backend restart)
  4992. self._sync_drying_state()
  4993. # Find printers with scheduled items (for queue drying mode)
  4994. printers_with_scheduled: set[int] = set()
  4995. printers_with_items: set[int] = set()
  4996. for item in queue_items:
  4997. if item.printer_id:
  4998. printers_with_items.add(item.printer_id)
  4999. if item.scheduled_time and not item.manual_start:
  5000. printers_with_scheduled.add(item.printer_id)
  5001. # If only queue mode is on and no printers have scheduled items, stop drying
  5002. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5003. # may still be eligible for mid-print drying regardless of queue state).
  5004. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5005. for pid in list(self._drying_in_progress):
  5006. if pid in self._scheduled_drying_printer_ids:
  5007. continue
  5008. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5009. await self._stop_drying(pid)
  5010. return
  5011. # Get humidity threshold (global fallback)
  5012. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5013. setting = result.scalar_one_or_none()
  5014. global_humidity_threshold = int(setting.value) if setting else 60
  5015. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5016. # to the global threshold for every AMS unit.
  5017. per_type_thresholds = await self._get_humidity_thresholds(db)
  5018. # Get drying presets
  5019. presets = await self._get_drying_presets(db)
  5020. # Determine if drying should be skipped for printers with pending items
  5021. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5022. # Get all active printers
  5023. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5024. for printer in all_printers.scalars():
  5025. pid = printer.id
  5026. # Resolve model+firmware up front — needed to decide whether this printer
  5027. # qualifies for mid-print drying (busy printer on capable hardware).
  5028. state = printer_manager.get_status(pid)
  5029. if not state:
  5030. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5031. continue
  5032. model = printer_manager.get_model(pid)
  5033. firmware = state.firmware_version
  5034. # "Mid-print" has to mean the printer is actually printing (#2801).
  5035. # It used to be inferred from the dispatch set, which also holds
  5036. # printers that merely could not be dispatched to -- so a printer
  5037. # sitting in FINISH behind an unacknowledged plate was treated as
  5038. # printing, had its drying temperature capped by the mid-print
  5039. # spool protection, and was logged as (mid-print) while idle.
  5040. is_printing = state.state in _ACTIVE_PRINT_STATES
  5041. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5042. # A printer whose print is running or imminent is left alone unless
  5043. # it can dry through it. `dispatching_printers` is deliberately the
  5044. # narrow set: running, held post-dispatch, or mid-upload.
  5045. if (is_printing or pid in dispatching_printers) and not mid_print:
  5046. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5047. continue
  5048. if not mid_print:
  5049. # In queue-only mode, only dry printers that have scheduled prints
  5050. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5051. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5052. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5053. await self._stop_drying(pid)
  5054. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5055. continue
  5056. # When block mode is on, don't START new drying on printers with pending items.
  5057. # But allow already-drying printers through so humidity auto-stop logic still runs.
  5058. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  5059. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  5060. continue
  5061. if not printer_manager.is_connected(pid):
  5062. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5063. continue
  5064. # Plate-clear is deliberately ignored here (#2801). It answers
  5065. # "is the bed ready for the next job", which says nothing about
  5066. # whether the AMS may heat -- and the gap between a finished print
  5067. # and the acknowledgment is exactly when drying is most useful,
  5068. # because the printer is free and nobody is waiting on it. Leaving
  5069. # the plate unacknowledged is also how people hold the queue by
  5070. # hand, and that hold should not cost them their drying.
  5071. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5072. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5073. continue
  5074. # Check drying capability. For mid-print path, supports_drying_while_printing
  5075. # was already verified when computing mid_print above.
  5076. if not mid_print and not supports_drying(model, firmware):
  5077. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5078. continue
  5079. # Check each AMS unit from raw_data
  5080. ams_list = state.raw_data.get("ams", [])
  5081. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5082. for ams_data in ams_list:
  5083. module_type = str(ams_data.get("module_type") or "")
  5084. ams_id = int(ams_data.get("id", 0))
  5085. # Only n3f/n3s support drying
  5086. if module_type not in ("n3f", "n3s"):
  5087. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5088. continue
  5089. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5090. # Most-restrictive of all loaded tray types; falls back to the
  5091. # global threshold when no overrides are configured.
  5092. trays = ams_data.get("tray", []) or []
  5093. humidity_threshold = self.resolve_humidity_threshold(
  5094. trays, per_type_thresholds, global_humidity_threshold
  5095. )
  5096. dry_time = int(ams_data.get("dry_time") or 0)
  5097. # Read humidity as a percentage. The 1-5 index is never
  5098. # substituted: it is inverted, and being unable to exceed any
  5099. # threshold it would read as "dry" forever (#3140). ``None``
  5100. # already means "skip this unit" everywhere below.
  5101. humidity_pct = ams_humidity_percent(ams_data)
  5102. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5103. unit_key = (pid, ams_id)
  5104. unit_state = self._auto_dry_units.get(unit_key)
  5105. # Already drying — let it run to its configured duration (#1892).
  5106. #
  5107. # We deliberately do NOT stop drying from a humidity re-check here.
  5108. # Relative humidity drops steeply in heated air, so the AMS sensor
  5109. # reads ~15-20% within minutes of the dryer starting even while the
  5110. # filament is still saturated. A humidity-based early-stop therefore
  5111. # always fires at the minimum-time floor, truncating both user-started
  5112. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5113. # The firmware stops when the configured duration elapses; scheduling
  5114. # stops (print takes priority, queue no longer needs drying) are
  5115. # handled separately via _stop_drying().
  5116. if dry_time > 0:
  5117. if pid not in self._drying_in_progress:
  5118. # Drying we didn't start (manual or from before restart) —
  5119. # track it so scheduling stops still apply; never auto-stop it.
  5120. self._drying_in_progress[pid] = time.monotonic()
  5121. if unit_state is not None:
  5122. unit_state["running"] = True
  5123. logger.debug(
  5124. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5125. pid,
  5126. ams_id,
  5127. dry_time,
  5128. humidity,
  5129. )
  5130. continue
  5131. # Nothing is drying. Close out a cycle we armed ourselves and
  5132. # judge whether it achieved anything (#2770).
  5133. #
  5134. # "Achieved anything" is measured against the LOWEST reading any
  5135. # cycle on this unit has ended at, not against the threshold and
  5136. # not against the previous cycle. A spool that is genuinely wet
  5137. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5138. # allowed to keep going for as long as it is still coming down,
  5139. # however far it still is from the threshold. What must not
  5140. # continue is a cycle that ends exactly where the last one did,
  5141. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5142. # Comparing against the running minimum rather than the previous
  5143. # end is what stops a sensor oscillating by one point between two
  5144. # values from reading as progress every other cycle.
  5145. if unit_state is not None and unit_state.pop("running", False):
  5146. unit_state["ended_at"] = time.monotonic()
  5147. # The streak that armed this cycle is spent; the next one
  5148. # starts fresh (and accumulates through the re-arm cooldown
  5149. # below, so the wait overlaps the cooldown, never stacks on
  5150. # top of it).
  5151. self._auto_dry_above.pop(unit_key, None)
  5152. if humidity is not None and humidity > humidity_threshold:
  5153. best = unit_state.get("best_end_humidity")
  5154. if isinstance(best, int) and humidity < best:
  5155. # Still coming down. Keep going, however far the
  5156. # threshold still is.
  5157. unproductive = 0
  5158. else:
  5159. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5160. if not isinstance(best, int) or humidity < best:
  5161. unit_state["best_end_humidity"] = humidity
  5162. unit_state["unproductive"] = unproductive
  5163. logger.info(
  5164. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5165. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5166. pid,
  5167. ams_id,
  5168. humidity,
  5169. humidity_threshold,
  5170. unit_state.get("best_end_humidity"),
  5171. unproductive,
  5172. )
  5173. # A cycle that ended at or below the threshold needs no
  5174. # counter reset here: the branch below drops the whole entry.
  5175. # Humidity below threshold — no need to start drying. This is
  5176. # also the only thing that lifts a suspension: the reading we
  5177. # gave up on has come down, so auto-drying works again and the
  5178. # unit goes back to having no history at all.
  5179. if humidity is None or humidity <= humidity_threshold:
  5180. if unit_state is not None and unit_state.get("suspended"):
  5181. logger.info(
  5182. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5183. "threshold, resuming automatic drying",
  5184. pid,
  5185. ams_id,
  5186. humidity,
  5187. humidity_threshold,
  5188. )
  5189. # Clear the judgement, keep the clock (#2801). Dropping the
  5190. # whole entry also dropped `ended_at`, and with it the
  5191. # 30-minute cooldown -- so a reading that dips to the
  5192. # threshold as the AMS cools and comes back above it once
  5193. # warm wiped its own history and re-armed immediately. That
  5194. # oscillation is the very thing #2770's cooldown exists to
  5195. # ride out, and it is worst at exactly the margin that makes
  5196. # a unit dry repeatedly: a point or two above the threshold.
  5197. if unit_state is not None:
  5198. unit_state.pop("suspended", None)
  5199. unit_state.pop("unproductive", None)
  5200. unit_state.pop("best_end_humidity", None)
  5201. # A real below-threshold reading ends any sustained-wait
  5202. # streak (#2518) -- "continuously above" means exactly that.
  5203. # An absent reading (humidity is None) is no-information and
  5204. # leaves the streak alone; the observation-gap guard handles
  5205. # a prolonged sensor silence.
  5206. if humidity is not None:
  5207. _above = self._auto_dry_above.pop(unit_key, None)
  5208. if _above is not None and sustained_wait_active:
  5209. logger.info(
  5210. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5211. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5212. pid,
  5213. ams_id,
  5214. humidity,
  5215. time.monotonic() - _above["since"],
  5216. sustained_minutes,
  5217. humidity_threshold,
  5218. )
  5219. logger.debug(
  5220. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5221. pid,
  5222. ams_id,
  5223. humidity,
  5224. humidity_threshold,
  5225. )
  5226. continue
  5227. # Sustained-humidity streak (#2518): updated on every pass that
  5228. # observes the reading above the threshold, BEFORE the
  5229. # suspension/cooldown gates below -- a suspended or cooling-down
  5230. # unit still accumulates streak time, so the wait overlaps those
  5231. # gates instead of stacking after them. Inert when the feature
  5232. # is off: no entries are written, and an entry left over from a
  5233. # toggle-off is dropped so it cannot seed a stale streak later.
  5234. if sustained_wait_active:
  5235. _now = time.monotonic()
  5236. # Four missed scheduler passes, floored: a single slow pass
  5237. # must not void a streak, but the ceiling has to scale with
  5238. # the cadence or a slow loop silently restarts every streak.
  5239. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5240. _above = self._auto_dry_above.get(unit_key)
  5241. if _above is None:
  5242. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5243. elif _now - _above["last"] > _gap_ceiling:
  5244. # Restart, and say so at the same level as the dip
  5245. # reset: a silent restart voids the streak invisibly,
  5246. # and a user who set a long wait and never gets a dry
  5247. # has no way to see why.
  5248. logger.info(
  5249. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5250. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5251. pid,
  5252. ams_id,
  5253. _now - _above["last"],
  5254. _gap_ceiling,
  5255. sustained_minutes,
  5256. )
  5257. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5258. else:
  5259. _above["last"] = _now
  5260. else:
  5261. self._auto_dry_above.pop(unit_key, None)
  5262. if unit_state is not None:
  5263. if unit_state.get("suspended"):
  5264. logger.debug(
  5265. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5266. "above the %d%% threshold",
  5267. pid,
  5268. ams_id,
  5269. int(unit_state.get("unproductive", 0)),
  5270. humidity_threshold,
  5271. )
  5272. continue
  5273. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5274. unit_state["suspended"] = True
  5275. logger.warning(
  5276. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5277. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5278. "higher while it is warm, so a threshold in that range can never be reached and "
  5279. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5280. pid,
  5281. ams_id,
  5282. int(unit_state.get("unproductive", 0)),
  5283. humidity,
  5284. humidity_threshold,
  5285. )
  5286. await self._notify_auto_drying_suspended(
  5287. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5288. )
  5289. continue
  5290. ended_at = unit_state.get("ended_at")
  5291. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5292. logger.debug(
  5293. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5294. "cycle before the humidity reading is worth acting on",
  5295. pid,
  5296. ams_id,
  5297. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5298. )
  5299. continue
  5300. # Check cannot-dry reasons (power constraints etc.). Sits
  5301. # ahead of the sustained wait so a unit the firmware refuses
  5302. # to dry never logs a wait it was never going to cash in.
  5303. sf_reasons = ams_data.get("dry_sf_reason", [])
  5304. if sf_reasons:
  5305. logger.debug(
  5306. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5307. pid,
  5308. ams_id,
  5309. sf_reasons,
  5310. )
  5311. continue
  5312. # Sustained-humidity wait (#2518): ambient-triggered starts
  5313. # wait; only a printer with a scheduled queue item pending
  5314. # keeps the instant behavior, because that drying has a real
  5315. # deadline. Mid-print is deliberately NOT exempt while ambient
  5316. # drying is on: a humidity start on a printer that happens to be
  5317. # printing is as vulnerable to a lid-open spike as one on an idle
  5318. # printer (proven live: a 2-point threshold crossing mid-print
  5319. # bought a parked 12h command). Inactive when ambient drying is
  5320. # off: print_drying then still starts mid-print cycles on its own
  5321. # (#1816, "regardless of queue state"), and those stay instant.
  5322. if sustained_wait_active and pid not in printers_with_scheduled:
  5323. _above = self._auto_dry_above.get(unit_key)
  5324. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5325. if _waited < sustained_minutes * 60:
  5326. logger.debug(
  5327. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5328. "threshold for %.0fs of the required %dm",
  5329. pid,
  5330. ams_id,
  5331. humidity,
  5332. humidity_threshold,
  5333. _waited,
  5334. sustained_minutes,
  5335. )
  5336. continue
  5337. # Get conservative drying params for mixed filaments
  5338. params = self._get_conservative_drying_params(trays, module_type, presets)
  5339. if not params:
  5340. logger.debug(
  5341. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5342. )
  5343. continue
  5344. temp, duration_hours, filament_type = params
  5345. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5346. # "drying temperature must not exceed the filament's softening temperature"
  5347. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5348. # ineffective and firmware will reject anyway.
  5349. if mid_print:
  5350. temp = max(40, temp - 5)
  5351. # Start drying
  5352. logger.info(
  5353. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5354. "starting %s drying at %d°C for %dh%s",
  5355. pid,
  5356. ams_id,
  5357. humidity,
  5358. humidity_threshold,
  5359. filament_type,
  5360. temp,
  5361. duration_hours,
  5362. " (mid-print)" if mid_print else "",
  5363. )
  5364. success = printer_manager.send_drying_command(
  5365. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5366. )
  5367. if success:
  5368. self._drying_in_progress[pid] = time.monotonic()
  5369. armed = self._auto_dry_units.setdefault(
  5370. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5371. )
  5372. armed["running"] = True
  5373. async def _notify_auto_drying_suspended(
  5374. self,
  5375. db: AsyncSession,
  5376. printer: Printer,
  5377. ams_id: int,
  5378. humidity: int,
  5379. threshold: int,
  5380. cycles: int,
  5381. ) -> None:
  5382. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5383. Fires once per suspension — the caller sets ``suspended`` before calling
  5384. and every later pass short-circuits on it — because the whole point is
  5385. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5386. building needs that to reach them, and the hourly humidity alarm they
  5387. are already getting says the opposite of what happened here.
  5388. Never raises: a notification provider being down must not stop the
  5389. suspension itself from taking effect.
  5390. """
  5391. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5392. try:
  5393. await notification_service.on_ams_drying_suspended(
  5394. printer.id,
  5395. printer.name,
  5396. ams_label,
  5397. float(humidity),
  5398. float(threshold),
  5399. cycles,
  5400. db,
  5401. )
  5402. except Exception as e:
  5403. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5404. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5405. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5406. The unproductive-cycle counter exists to notice that *drying* is not
  5407. moving the humidity reading. A cycle that ended because somebody sent a
  5408. stop says nothing about that — it was cut short before it had a chance —
  5409. so counting it would suspend auto-drying for a reason that has nothing to
  5410. do with the loop the counter is there to break.
  5411. Two callers, both of them a stop Bambuddy is responsible for: the
  5412. print-takes-priority stop below, and the manual Stop button. Left
  5413. uncalled, an install that dries between queue jobs would suspend its own
  5414. auto-drying after two prints interrupted a dry — exactly the install
  5415. queue-drying exists for.
  5416. The rest of the unit's history is kept: the cooldown before re-arming
  5417. still applies, and an earlier count still stands.
  5418. """
  5419. state = self._auto_dry_units.get((printer_id, ams_id))
  5420. if state is not None:
  5421. state.pop("running", None)
  5422. state["ended_at"] = time.monotonic()
  5423. # A stopped cycle spends the streak that armed it, same as a completed
  5424. # one (#2518).
  5425. self._auto_dry_above.pop((printer_id, ams_id), None)
  5426. def _sync_drying_state(self):
  5427. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5428. One direction only: it prunes, it never adds. A printer drying without an
  5429. entry here — because the user started the cycle from Studio, the printer's
  5430. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5431. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5432. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5433. That is deliberate for now rather than an oversight: populating this from
  5434. telemetry would hand the scheduler authority to stop drying a user started
  5435. by hand. It also means the backend-restart case this used to claim to
  5436. handle is not handled.
  5437. """
  5438. to_remove = []
  5439. for pid in self._drying_in_progress:
  5440. state = printer_manager.get_status(pid)
  5441. if not state:
  5442. to_remove.append(pid)
  5443. continue
  5444. # Check if any AMS unit is still drying
  5445. ams_list = state.raw_data.get("ams", [])
  5446. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5447. if not any_drying:
  5448. to_remove.append(pid)
  5449. for pid in to_remove:
  5450. self._drying_in_progress.pop(pid, None)
  5451. # A printer that has gone away entirely takes its per-AMS auto-drying
  5452. # history with it (#2770), so a printer deleted and re-added does not
  5453. # inherit a suspension it never earned.
  5454. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5455. self._auto_dry_units.pop(key, None)
  5456. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5457. # printer starts a fresh wait, and vanished printers do not leak
  5458. # entries.
  5459. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5460. self._auto_dry_above.pop(key, None)
  5461. @staticmethod
  5462. def _drying_is_only_parked(printer_id: int) -> bool:
  5463. """True when every AMS unit with a drying timer on this printer is parked.
  5464. A parked timer (#2896: the command was taken but the countdown never
  5465. runs) does not end on its own, so nothing may wait on it. False when no
  5466. unit reports a timer yet -- a command just sent that the firmware has not
  5467. reported back is real drying about to begin.
  5468. """
  5469. state = printer_manager.get_status(printer_id)
  5470. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5471. timed = []
  5472. for unit in units:
  5473. try:
  5474. if int(unit.get("dry_time") or 0) > 0:
  5475. timed.append(unit)
  5476. except (TypeError, ValueError):
  5477. continue
  5478. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5479. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5480. """True when a running cycle can be left alone while the next print runs.
  5481. Some hardware dries happily through a print and #2758 settled that we
  5482. should not tear those cycles down: the X2D there was refusing to
  5483. *start* a job, which is a different problem, and stopping drying before
  5484. every dispatch would throw away cycles the printer was content to run.
  5485. Where the model cannot do it, or the user has not enabled it, the print
  5486. takes priority and the cycle stops -- which is what the queue_drying_block
  5487. setting has always promised in its off position.
  5488. """
  5489. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5490. return False
  5491. status = printer_manager.get_status(printer_id)
  5492. return supports_drying_while_printing(
  5493. printer_manager.get_model(printer_id),
  5494. status.firmware_version if status else None,
  5495. )
  5496. async def _stop_drying(self, printer_id: int):
  5497. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5498. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5499. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5500. enough to kill a cycle the user had started by hand on a *different*
  5501. unit of the same printer (#2801). That contradicted the contract
  5502. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5503. only knows about cycles Bambuddy began, so the action must not reach
  5504. past them either.
  5505. """
  5506. state = printer_manager.get_status(printer_id)
  5507. if not state:
  5508. self._drying_in_progress.pop(printer_id, None)
  5509. return
  5510. ams_list = state.raw_data.get("ams", [])
  5511. for ams_data in ams_list:
  5512. dry_time = int(ams_data.get("dry_time") or 0)
  5513. if dry_time > 0:
  5514. ams_id = int(ams_data.get("id", 0))
  5515. if (printer_id, ams_id) not in self._auto_dry_units:
  5516. logger.debug(
  5517. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5518. printer_id,
  5519. ams_id,
  5520. )
  5521. continue
  5522. logger.info(
  5523. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5524. printer_id,
  5525. ams_id,
  5526. )
  5527. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5528. self.forget_auto_dry_cycle(printer_id, ams_id)
  5529. self._drying_in_progress.pop(printer_id, None)
  5530. # Scheduled manual drying (#2638) -----------------------------------
  5531. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5532. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5533. async def _check_scheduled_dryings(self, db: AsyncSession):
  5534. """Dispatch due scheduled drying runs and track running ones."""
  5535. now = utcnow_naive()
  5536. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5537. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5538. since_prune = time.monotonic()
  5539. if (
  5540. self._last_scheduled_drying_prune is None
  5541. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5542. ):
  5543. self._last_scheduled_drying_prune = since_prune
  5544. await db.execute(
  5545. delete(ScheduledDrying).where(
  5546. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5547. ScheduledDrying.completed_at.is_not(None),
  5548. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5549. )
  5550. )
  5551. # Same order as the list route: with two rows due on one printer the
  5552. # earliest scheduled wins rather than whatever the DB hands back first.
  5553. result = await db.execute(
  5554. select(ScheduledDrying)
  5555. .where(ScheduledDrying.status.in_(("pending", "running")))
  5556. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5557. )
  5558. rows = list(result.scalars().all())
  5559. # Rebuild from the DB every tick so route-side cancels and completions
  5560. # show up. Auto-drying's stop-all branches check this set before
  5561. # stopping anything (#2638).
  5562. # Kept from the previous pass so a run that ended between passes — a
  5563. # cancel through the route, say — can still be released below.
  5564. previously_running = self._scheduled_drying_printer_ids
  5565. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5566. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5567. # Model and firmware come from the printer row, not the live state.
  5568. printer_ids = {row.printer_id for row in rows}
  5569. printers_by_id: dict[int, Printer] = {}
  5570. if printer_ids:
  5571. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5572. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5573. for row in rows:
  5574. if row.status == "running":
  5575. self._update_running_scheduled_drying(row, now)
  5576. continue
  5577. if row.start_after is not None and row.start_after > now:
  5578. continue
  5579. state = printer_manager.get_status(row.printer_id)
  5580. if not state:
  5581. row.waiting_reason = "printer_offline"
  5582. continue
  5583. # Same preflight the immediate endpoint runs. Without it the publish
  5584. # succeeds, the row goes to running, the printer ignores the command
  5585. # and the run silently cancels itself after the grace window.
  5586. printer = printers_by_id.get(row.printer_id)
  5587. unsupported = drying_preflight.check_drying_supported(
  5588. printer.model if printer else None, state.firmware_version
  5589. )
  5590. if unsupported:
  5591. row.status = "failed"
  5592. row.error_message = unsupported
  5593. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5594. row.completed_at = now
  5595. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5596. continue
  5597. if (
  5598. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5599. ) or row.printer_id in running_printer_ids:
  5600. row.waiting_reason = "already_drying"
  5601. continue
  5602. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5603. row.waiting_reason = "printer_busy"
  5604. continue
  5605. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5606. if target is None:
  5607. row.waiting_reason = "ams_not_found"
  5608. continue
  5609. blocking = drying_preflight.blocking_reason_codes(target)
  5610. if blocking:
  5611. # Keep the power case distinct; it needs the user to act, so the
  5612. # card can say so instead of waiting silently.
  5613. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5614. continue
  5615. filament = drying_preflight.resolve_filament(target, row.filament)
  5616. logger.info(
  5617. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5618. row.id,
  5619. row.printer_id,
  5620. row.ams_id,
  5621. row.temp,
  5622. row.duration_hours,
  5623. )
  5624. success = printer_manager.send_drying_command(
  5625. row.printer_id,
  5626. row.ams_id,
  5627. row.temp,
  5628. row.duration_hours,
  5629. mode=1,
  5630. filament=filament,
  5631. rotate_tray=row.rotate_tray,
  5632. )
  5633. if success:
  5634. row.status = "running"
  5635. row.started_at = now
  5636. row.waiting_reason = None
  5637. row.filament = filament
  5638. self._drying_in_progress[row.printer_id] = time.monotonic()
  5639. self._scheduled_drying_printer_ids.add(row.printer_id)
  5640. running_printer_ids.add(row.printer_id)
  5641. else:
  5642. row.waiting_reason = "printer_offline"
  5643. # Release the printers whose run has ended. `_drying_in_progress` is
  5644. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5645. # but that call sits behind the auto-drying enabled check, and this
  5646. # method is the one writer that runs whether auto-drying is on or not.
  5647. # With it off, nothing would ever drop the entry short of a print being
  5648. # dispatched to the same printer, so the next scheduled run would wait
  5649. # on "already_drying" forever and `queue_drying_block` would hold the
  5650. # printer's prints too. Covers a run that ended during this pass and one
  5651. # cancelled through the route between passes.
  5652. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5653. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5654. self._drying_in_progress.pop(printer_id, None)
  5655. await db.commit()
  5656. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5657. """Detect completion or interruption of a running scheduled drying.
  5658. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5659. drying. Within the grace window after start we ignore dry_time==0
  5660. (the status lags the command). After that, dry_time==0 near the end
  5661. of the configured duration means completed. Much earlier means the
  5662. run was stopped: re-queue it if a print preempted the dryer, but a
  5663. stop while the printer is idle was deliberate, so cancel the row
  5664. rather than restart drying the user just stopped.
  5665. """
  5666. if row.started_at is None:
  5667. row.started_at = now
  5668. return
  5669. elapsed = (now - row.started_at).total_seconds()
  5670. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5671. return
  5672. state = printer_manager.get_status(row.printer_id)
  5673. if not state:
  5674. return # offline mid-dry; resolve when it reconnects
  5675. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5676. # throw on a malformed id would cost the whole pass including print
  5677. # dispatch, every tick.
  5678. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5679. try:
  5680. dry_time = int(target.get("dry_time") or 0) if target else 0
  5681. except (TypeError, ValueError):
  5682. dry_time = 0
  5683. if dry_time > 0 and is_countdown_parked(target):
  5684. # The printer took the command but the countdown is not running
  5685. # (#2896) and will never reach 0, so the run would stay "running"
  5686. # forever. A print in progress is the likely cause (the power budget
  5687. # is spent), so re-queue it like any interruption; the next start
  5688. # waits for the printer to be idle. Parked on an idle printer is a
  5689. # refusal, not something a retry fixes. The timer itself is left on
  5690. # the printer: it may yet start once power frees up.
  5691. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5692. logger.info(
  5693. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5694. row.id,
  5695. row.ams_id,
  5696. )
  5697. row.status = "pending"
  5698. row.started_at = None
  5699. row.waiting_reason = "interrupted"
  5700. else:
  5701. logger.warning(
  5702. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5703. row.id,
  5704. row.ams_id,
  5705. )
  5706. row.status = "failed"
  5707. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5708. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5709. row.completed_at = now
  5710. return
  5711. if dry_time > 0:
  5712. return
  5713. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5714. row.status = "completed"
  5715. row.completed_at = now
  5716. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5717. row.status = "pending"
  5718. row.started_at = None
  5719. row.waiting_reason = "interrupted"
  5720. else:
  5721. row.status = "cancelled"
  5722. row.completed_at = now
  5723. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5724. """Get all smart plugs associated with a printer."""
  5725. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5726. return list(result.scalars().all())
  5727. @staticmethod
  5728. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5729. """Pick the plug to power-cycle a printer back online with (#2629).
  5730. Only a plug flagged ``controls_printer_power`` can actually bring the
  5731. printer back; waiting for a boot on an accessory (filter fan, lights)
  5732. just burns the power-on timeout and fails the dispatch. Falls back to
  5733. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5734. Callers must pass a non-empty list.
  5735. """
  5736. for plug in auto_on_plugs:
  5737. if plug.controls_printer_power:
  5738. return plug
  5739. return auto_on_plugs[0]
  5740. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5741. # chamber-temperature recommendations BambuStudio ships for the matching
  5742. # filament profile; users can override via Settings → Workflow → Preheat
  5743. # card. "default" applies when a loaded tray's normalised type isn't in
  5744. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5745. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5746. "PLA": 0,
  5747. "PETG": 0,
  5748. "PETG-CF": 40,
  5749. "ABS": 45,
  5750. "ASA": 45,
  5751. "PA": 50,
  5752. "PA-CF": 55,
  5753. "PC": 50,
  5754. "PC-FR": 50,
  5755. "TPU": 0,
  5756. "PVA": 0,
  5757. "default": 0,
  5758. }
  5759. @classmethod
  5760. def _bundled_preheat_targets(cls) -> dict[str, int]:
  5761. """The bundled map under the same key casing a parsed one gets.
  5762. The constant is declared with a lowercase ``default`` because that is
  5763. the key the Settings editor writes and displays. Every read of the map
  5764. happens after ``str(key).upper()``, so handing the constant back as
  5765. declared broke the contract the parser documents: an install that had
  5766. never touched the setting returned a dict with no ``DEFAULT`` in it,
  5767. and the resolution loop's fallback silently found nothing. It read the
  5768. right number only because the bundled default happens to be 0 -- change
  5769. that constant and every unconfigured install would keep preheating to
  5770. zero with no way to tell why.
  5771. """
  5772. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  5773. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  5774. """Parse the user-configured filament→chamber-target map, falling back
  5775. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  5776. are uppercased and the 'default' fallback is always present in the
  5777. returned dict so the resolution loop can index it unconditionally."""
  5778. raw = await self._get_setting(db, "preheat_filament_targets")
  5779. if not raw:
  5780. return self._bundled_preheat_targets()
  5781. try:
  5782. parsed = json.loads(raw)
  5783. if not isinstance(parsed, dict):
  5784. raise ValueError("not an object")
  5785. except (json.JSONDecodeError, ValueError) as exc:
  5786. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  5787. return self._bundled_preheat_targets()
  5788. # Coerce values to int; drop unparseable rows so a stray string
  5789. # doesn't crash the loop.
  5790. out: dict[str, int] = {}
  5791. for key, value in parsed.items():
  5792. try:
  5793. out[str(key).upper()] = int(value)
  5794. except (TypeError, ValueError):
  5795. continue
  5796. if "DEFAULT" not in out:
  5797. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  5798. return out
  5799. @staticmethod
  5800. def _normalize_filament_type(tray_type: str) -> str:
  5801. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  5802. existing drying-preset normalisation (split-at-space, upper-case) so
  5803. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  5804. "PA-CF" (no space to split on).
  5805. This is the first stage of ``_resolve_filament_key``, which goes on to
  5806. drop the suffix and consult the alias map; on its own it only decides
  5807. what the tray is called, not which row answers for it.
  5808. Indexing the split rather than testing the input: a tray_type of spaces
  5809. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  5810. it through to an IndexError.
  5811. """
  5812. words = (tray_type or "").split()
  5813. return words[0].upper() if words else ""
  5814. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  5815. """Per-filament chamber target for one tray's reported type, or 0 when
  5816. the tray is empty / RFID-less and reports no type at all.
  5817. A filled or foamed variant wants its base material's chamber when the
  5818. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  5819. not the 0 an unknown type falls to. The specific type is still tried
  5820. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  5821. (#2902).
  5822. That lookup is now the shared one, which adds the polyamide aliases on
  5823. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  5824. too, rather than the catch-all it was landing on (#3067).
  5825. """
  5826. if not self._normalize_filament_type(tray_type or ""):
  5827. return 0
  5828. key = self._resolve_filament_key(tray_type, targets)
  5829. if key is not None:
  5830. return targets[key]
  5831. # A type the map does not list at all, which is not the same as a tray
  5832. # with nothing in it -- that already returned 0 above.
  5833. return targets.get("DEFAULT", 0)
  5834. def _derive_chamber_target(
  5835. self,
  5836. printer: Printer,
  5837. targets: dict[str, int],
  5838. item: PrintQueueItem | None = None,
  5839. ) -> int:
  5840. """Chamber target for the trays this print actually loads: the max of
  5841. their per-filament targets. Returns 0 when there is nothing to read (no
  5842. status, no AMS telemetry — e.g. external-spool prints) or when every
  5843. tray considered maps to 0, and the chamber phase then short-circuits in
  5844. the main loop.
  5845. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  5846. Scanning the whole unit instead meant one ASA spool parked in the AMS
  5847. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  5848. plus soak burned ahead of each upload, on a printer whose chamber never
  5849. reaches the target anyway (#2886). An item with no usable mapping falls
  5850. back to scanning every loaded tray: that is the only signal left, and
  5851. narrowing to nothing would skip preheat on prints that genuinely need
  5852. it.
  5853. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  5854. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  5855. less slots have empty `tray_type` and contribute nothing. The external
  5856. spool is consulted only when the mapping names it (>= 254); it stays
  5857. out of the unnarrowed scan, so an item without a mapping derives from
  5858. the AMS alone exactly as before.
  5859. """
  5860. state = printer_manager.get_status(printer.id)
  5861. if state is None:
  5862. return 0
  5863. raw_data = state.raw_data or {}
  5864. used = _used_global_tray_ids(item)
  5865. ams_list = raw_data.get("ams")
  5866. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  5867. if isinstance(ams_list, dict):
  5868. ams_list = ams_list.get("ams") or []
  5869. if not isinstance(ams_list, list):
  5870. ams_list = []
  5871. best = 0
  5872. for ams in ams_list:
  5873. if not isinstance(ams, dict):
  5874. continue
  5875. ams_id = _int_or(ams.get("id"), 0)
  5876. for tray in ams.get("tray") or []:
  5877. # A non-dict entry has never been seen from real firmware, but
  5878. # `.get` on one raises, and nothing between here and
  5879. # `_dispatch_one`'s try/finally catches it — the item would be
  5880. # left holding its dispatch claim. Preheat is best-effort by
  5881. # contract, so step over it instead.
  5882. if not isinstance(tray, dict):
  5883. continue
  5884. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  5885. continue
  5886. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  5887. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  5888. for vt in raw_data.get("vt_tray") or []:
  5889. if not isinstance(vt, dict):
  5890. continue
  5891. # `_build_loaded_filaments` addresses external feeds by the id
  5892. # the firmware reports — 255 main, 254 deputy — defaulting to
  5893. # 254 when the field is absent. Same expression here so the two
  5894. # agree on which entry a mapping's 254/255 refers to.
  5895. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  5896. continue
  5897. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  5898. return best
  5899. def _release_keep_warm(self, pid: int) -> None:
  5900. """Release keep-warm on a printer that left the candidate set.
  5901. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  5902. reports the target we set (``entry.held_target``), so a user or
  5903. subsequent print that changed the bed target since is not clobbered.
  5904. Best-effort, never raises.
  5905. The entry is kept, not dropped, when the printer cannot be reached
  5906. right now: a printer that is briefly offline still has a hot bed, and
  5907. holding the entry is what keeps the max-duration timeout applying and
  5908. lets a later tick retry the release. Only a printer that has left the
  5909. manager entirely gives up on that, in ``_sample_chamber_temps``.
  5910. """
  5911. entry = self._keep_warm.get(pid)
  5912. if entry is None:
  5913. return
  5914. state = printer_manager.get_status(pid)
  5915. client = printer_manager.get_client(pid)
  5916. if state is None or client is None:
  5917. logger.debug(
  5918. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  5919. pid,
  5920. )
  5921. return
  5922. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  5923. if int(cur_bed_target) != entry.held_target:
  5924. # Someone else owns the bed now, so there is nothing of ours to
  5925. # undo and nothing left to track.
  5926. logger.info(
  5927. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  5928. pid,
  5929. int(cur_bed_target),
  5930. entry.held_target,
  5931. )
  5932. self._keep_warm.pop(pid, None)
  5933. return
  5934. try:
  5935. client.set_bed_temperature(0)
  5936. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  5937. self._keep_warm.pop(pid, None)
  5938. except Exception as exc:
  5939. # Keep the entry so the next tick tries again rather than leaving
  5940. # the bed hot with nothing tracking it.
  5941. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  5942. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  5943. """Release printers that dropped out of the keep-warm candidate set.
  5944. Called from ``_apply_keep_warm`` on every tick (with the current
  5945. candidate set), and from ``check_queue``'s no-pending-items early
  5946. return (with an empty candidate set) so orphaned holds still get
  5947. released when the queue empties. Also called with an empty candidate
  5948. set when any of the three gate settings toggles off, so a printer
  5949. whose feature was disabled mid-hold gets its bed released.
  5950. Printers being dispatched this tick are excluded from the bed-off
  5951. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  5952. transient 0 in between would just churn against preheat. Ownership of
  5953. the hot bed transfers to the preheat rollback pin instead — if the
  5954. dispatch aborts before the print starts (failed upload, cancelled
  5955. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  5956. skips (e.g. the item has no bed_temperature metadata) the pin entry
  5957. is the ONLY thing standing between an aborted dispatch and a bed
  5958. left hot with no owner. A successful print start clears the pin and
  5959. the print's own gcode takes over, as usual.
  5960. """
  5961. for _pid in list(self._keep_warm):
  5962. if _pid in active_candidates:
  5963. continue
  5964. if _pid in dispatched:
  5965. handed_over = self._keep_warm.pop(_pid, None)
  5966. self._preheat_pin.setdefault(_pid, set()).add("bed")
  5967. if handed_over is not None:
  5968. self._preheat_pin_bed[_pid] = handed_over.held_target
  5969. continue
  5970. self._release_keep_warm(_pid)
  5971. async def _apply_keep_warm(
  5972. self,
  5973. db: AsyncSession,
  5974. items: list[PrintQueueItem],
  5975. dispatch_ids: list[int] | set[int],
  5976. busy_printers: set[int],
  5977. require_plate_clear: bool,
  5978. ) -> None:
  5979. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  5980. When a printer just finished a job (FINISH state) and the next queued
  5981. item needs chamber heating, hold the bed hot so the chamber stays warm
  5982. during the bed-clearing window. The bed is the chamber's heating
  5983. element here, not a print surface — nothing is printing during the
  5984. hold and the dispatched print's own preheat/gcode re-targets the bed —
  5985. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  5986. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  5987. aftermarket chamber heaters), raised to the item's own parsed
  5988. bed_temperature when that is higher. Items whose archive metadata has
  5989. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  5990. get a hold — chamber need is what gates the feature, not metadata.
  5991. Skips entirely for filaments that map to a 0°C chamber target
  5992. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  5993. names, so a hot-chamber spool it never touches does not hold the bed of
  5994. a PLA job (#2886). An item still awaiting its mapping is judged on the
  5995. whole unit, as every item was before. Printers being dispatched this
  5996. cycle are excluded:
  5997. ``_preheat_and_soak`` already handles their bed temperature.
  5998. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  5999. released to 0 and the entry is latched ``expired=True`` so
  6000. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6001. MQTT: publish is skipped when firmware already has the target.
  6002. The release sweep runs BEFORE the engagement gate so a printer that
  6003. was owned by keep-warm still gets its bed released when any of the
  6004. three gate settings is toggled off mid-hold. The
  6005. ``check_queue`` early-return-when-no-items path also calls
  6006. ``_sweep_keep_warm`` directly to release orphaned holds.
  6007. """
  6008. dispatch_set = set(dispatch_ids)
  6009. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6010. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6011. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6012. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6013. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6014. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6015. # Release sweep first — must run even when gate_open is False so a
  6016. # printer owned by keep-warm when a gate toggles off gets released.
  6017. self._sweep_keep_warm(
  6018. active_candidates=warm_candidates if gate_open else set(),
  6019. dispatched=dispatched_printers,
  6020. )
  6021. if not gate_open:
  6022. return
  6023. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6024. max_hold_seconds = (
  6025. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6026. )
  6027. now_mono = time.monotonic()
  6028. filament_targets: dict[str, int] | None = None
  6029. for pid in warm_candidates:
  6030. entry = self._keep_warm.get(pid)
  6031. # Latched-expired: max-duration timeout already fired for this
  6032. # printer. Skip until the release sweep drops the entry (i.e.
  6033. # until the printer leaves the candidate set).
  6034. if entry is not None and entry.expired:
  6035. continue
  6036. # These two guards sit ahead of the max-duration check below, so an
  6037. # engaged hold only ages out while its printer is still reachable
  6038. # and still in FINISH. That is deliberate rather than a hole: with
  6039. # no status or no client there is no M140 to send anyway, and the
  6040. # elapsed check runs off `entry.started` so it fires on the first
  6041. # tick after the printer comes back. Leaving FINISH means the plate
  6042. # was cleared, which drops the printer out of `warm_candidates` and
  6043. # hands it to `_release_keep_warm` instead. The invariant worth
  6044. # preserving if this is ever reordered: every path out of an
  6045. # engaged hold ends in a bed-off, whether by timeout or release.
  6046. state = printer_manager.get_status(pid)
  6047. if state is None or state.state != "FINISH":
  6048. continue
  6049. client = printer_manager.get_client(pid)
  6050. if client is None:
  6051. continue
  6052. next_item = next((it for it in items if it.printer_id == pid), None)
  6053. if next_item is None:
  6054. continue
  6055. # Hold temperature: the configured keep-warm temp, raised to the
  6056. # item's own bed temp when the metadata reports a higher one. A
  6057. # missing bed_temperature (Orca gcode.3mf exports parse without
  6058. # one) does NOT skip the hold — chamber need gates the feature.
  6059. archive = next_item.archive
  6060. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6061. bed_target = max(item_bed, hold_temp)
  6062. if bed_target <= 0:
  6063. continue
  6064. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6065. if explicit is not None:
  6066. chamber_needed = int(explicit) > 0
  6067. else:
  6068. if filament_targets is None:
  6069. filament_targets = await self._get_preheat_filament_targets(db)
  6070. printer_obj = await self._get_printer(db, pid)
  6071. chamber_needed = (
  6072. printer_obj is not None
  6073. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6074. )
  6075. if not chamber_needed:
  6076. continue
  6077. # Seed the timer on first engagement; keep it on subsequent ticks
  6078. # (never re-seed — that would defeat the max-duration cap).
  6079. if entry is None:
  6080. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6081. self._keep_warm[pid] = entry
  6082. elapsed = now_mono - entry.started
  6083. if elapsed > max_hold_seconds:
  6084. # Timeout: publish bed → 0 once (if firmware still holds our
  6085. # target) and latch expired. The entry stays until the release
  6086. # sweep drops it, preventing the next tick from re-seeding.
  6087. logger.warning(
  6088. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6089. pid,
  6090. elapsed,
  6091. )
  6092. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6093. if int(cur_bed_target) == entry.held_target:
  6094. try:
  6095. client.set_bed_temperature(0)
  6096. except Exception as exc:
  6097. logger.warning(
  6098. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6099. pid,
  6100. exc,
  6101. )
  6102. else:
  6103. logger.info(
  6104. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6105. pid,
  6106. int(cur_bed_target),
  6107. entry.held_target,
  6108. )
  6109. entry.expired = True
  6110. continue
  6111. # Idempotence: skip publish when firmware already has our target.
  6112. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6113. if int(cur_bed_target) == bed_target:
  6114. entry.held_target = bed_target
  6115. continue
  6116. try:
  6117. client.set_bed_temperature(bed_target)
  6118. entry.held_target = bed_target
  6119. logger.info(
  6120. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6121. bed_target,
  6122. pid,
  6123. )
  6124. except Exception as exc:
  6125. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6126. def _sample_chamber_temps(self) -> None:
  6127. """Record a chamber temperature sample for every connected printer.
  6128. Called once per scheduler tick (every 3–30 s). Entries older than
  6129. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6130. Also evicts per-printer state whose printer_id is no longer registered
  6131. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6132. """
  6133. now = time.monotonic()
  6134. cutoff = now - self._chamber_history_ttl
  6135. statuses = printer_manager.get_all_statuses()
  6136. known_pids = set(statuses.keys())
  6137. for pid, status in statuses.items():
  6138. if status is None or not status.connected:
  6139. continue
  6140. temps = status.temperatures or {}
  6141. chamber = temps.get("chamber")
  6142. if chamber is None:
  6143. continue
  6144. hist = self._chamber_history.setdefault(pid, deque())
  6145. hist.append((now, float(chamber)))
  6146. while hist and hist[0][0] < cutoff:
  6147. hist.popleft()
  6148. # Evict state for printers that are no longer registered with the manager.
  6149. # This is the one place a keep-warm entry is dropped without releasing
  6150. # the bed: the printer is gone from the manager, so there is no client
  6151. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6152. # for printers that are merely unreachable, which is what makes this
  6153. # the terminal case rather than a silent leak.
  6154. for pid in list(self._chamber_history):
  6155. if pid not in known_pids:
  6156. self._chamber_history.pop(pid, None)
  6157. for pid in list(self._keep_warm):
  6158. if pid not in known_pids:
  6159. logger.info(
  6160. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6161. pid,
  6162. )
  6163. self._keep_warm.pop(pid, None)
  6164. for pid in list(self._preheat_pin):
  6165. if pid not in known_pids:
  6166. self._preheat_pin.pop(pid, None)
  6167. self._preheat_pin_bed.pop(pid, None)
  6168. def _chamber_soak_remaining(
  6169. self,
  6170. printer_id: int,
  6171. chamber_target: float,
  6172. soak_seconds: int,
  6173. tolerance: float = 2.0,
  6174. ) -> int:
  6175. """Return how many seconds of soak time are still needed.
  6176. Credits the time the chamber has already spent at temperature against
  6177. the configured soak. The credit may not start earlier than any of:
  6178. * **The newest sample.** Nothing recent means the printer stopped
  6179. reporting mid-observation and the chamber may have cooled unseen, so
  6180. the full soak is required. (A 2 h history whose last reading is half
  6181. an hour old is not evidence of anything — the measured cooling rate
  6182. is fast enough to cross the threshold in that time.)
  6183. * **The most recent contiguous run of samples.** A gap wider than
  6184. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6185. far side is not evidence of temperature.
  6186. * **The end of the most recent real dip below the threshold.**
  6187. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6188. — see that constant for the thermal reasoning. A stray low reading is
  6189. an artifact, and treating it as cooling would discard a soak that
  6190. actually happened.
  6191. Returns ``soak_seconds`` when nothing can be credited (no history,
  6192. stale history, or the chamber is below the threshold right now) and 0
  6193. once the credited time covers the whole soak.
  6194. """
  6195. hist = self._chamber_history.get(printer_id)
  6196. if not hist:
  6197. return soak_seconds
  6198. now = time.monotonic()
  6199. newest_ts, newest_temp = hist[-1]
  6200. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6201. return soak_seconds # stale — no fresh evidence to credit
  6202. threshold = chamber_target - tolerance
  6203. if newest_temp < threshold:
  6204. return soak_seconds # below target right now; nothing is soaked
  6205. samples = list(hist)
  6206. # Earliest point we have unbroken observations for.
  6207. credit_from = samples[-1][0]
  6208. for i in range(len(samples) - 1, 0, -1):
  6209. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6210. break
  6211. credit_from = samples[i - 1][0]
  6212. # Pull the credit forward to the end of the last significant dip. Each
  6213. # excursion is measured between the in-range readings that bracket it,
  6214. # so a lone stray sample is charged one sampling interval rather than
  6215. # zero, and the comparison errs towards calling a dip real.
  6216. i = 0
  6217. while i < len(samples):
  6218. if samples[i][1] >= threshold:
  6219. i += 1
  6220. continue
  6221. j = i
  6222. while j < len(samples) and samples[j][1] < threshold:
  6223. j += 1
  6224. # `newest_temp >= threshold` was checked above, so j is in range.
  6225. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6226. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6227. # Credit resumes at the last below-threshold sample rather than
  6228. # the first good one after it, so a recovered dip over-credits
  6229. # by up to one sampling interval — the opposite lean to the
  6230. # bracketing above. Both are bounded by the sample cadence and
  6231. # dwarfed by the grace period, so neither is worth the extra
  6232. # arithmetic to remove.
  6233. credit_from = max(credit_from, samples[j - 1][0])
  6234. i = j
  6235. return max(0, soak_seconds - int(now - credit_from))
  6236. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6237. """Tell an in-flight dispatch that its item no longer wants to print.
  6238. Called by the queue's cancel and delete routes. Those only write to the
  6239. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6240. observe — so preheat would keep heating for the rest of max_wait + soak
  6241. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6242. blocking every other queued item behind a print that is not happening.
  6243. Signalling in memory rather than re-reading the row keeps this off the
  6244. database entirely: no second session, no transaction held across a long
  6245. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6246. Bambuddy serves from a single uvicorn process with one scheduler task,
  6247. so the route and the dispatch always share this object. The flag is
  6248. advisory — dropping it (e.g. after a restart) only costs a wasted
  6249. preheat, never a wrongly-abandoned print.
  6250. Only ids with a dispatch actually in flight are recorded, so the set
  6251. stays bounded by the upload pool rather than growing once per cancelled
  6252. item for the life of the process. Skipping the rest loses nothing: an
  6253. item that is not in flight cannot start heating later either, because
  6254. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6255. the caller has already committed a terminal status (or deleted the row)
  6256. before calling this.
  6257. """
  6258. if item_id in self._inflight:
  6259. self._cancelled_dispatches.add(item_id)
  6260. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6261. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6262. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6263. while it is parked, so the wait is chopped into
  6264. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6265. """
  6266. remaining = float(seconds)
  6267. while remaining > 0:
  6268. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6269. await asyncio.sleep(slice_secs)
  6270. remaining -= slice_secs
  6271. if item_id in self._cancelled_dispatches:
  6272. return False
  6273. return True
  6274. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6275. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6276. The full preheat stage does this as part of its own dispatch: an H2D
  6277. left in heating mode by the ABS job before it would otherwise cook the
  6278. PLA that follows. The skip path never reaches that code, so it calls
  6279. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6280. add to the rollback pin, because a flap set to cooling for a print that
  6281. needs no heat is where it should have been either way.
  6282. Best-effort like everything else in the stage: a refused command logs
  6283. and the dispatch carries on.
  6284. """
  6285. model = printer.model or ""
  6286. if not supports_airduct(model):
  6287. return
  6288. state = printer_manager.get_status(printer.id)
  6289. current = getattr(state, "airduct_mode", None) if state else None
  6290. if current == _AIRDUCT_MODE_COOLING:
  6291. return
  6292. client = printer_manager.get_client(printer.id)
  6293. if client is None:
  6294. return
  6295. try:
  6296. client.set_airduct_mode("cooling")
  6297. except Exception as exc:
  6298. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6299. async def _preheat_and_soak(
  6300. self,
  6301. db: AsyncSession,
  6302. item: PrintQueueItem,
  6303. printer: Printer,
  6304. archive: PrintArchive | None,
  6305. ) -> bool:
  6306. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6307. Returns True when the dispatch should carry on to the upload — including
  6308. every case where preheat is skipped, since a skipped preheat is not a
  6309. reason to abandon the print. Returns False only when the item stopped
  6310. wanting to be printed while the stage was waiting (cancelled or
  6311. deleted); the caller must then abandon the dispatch, and
  6312. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6313. Resolution order:
  6314. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6315. to the global `preheat_enabled` setting; 'on' forces the stage on
  6316. even if the global is off.
  6317. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6318. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6319. across the trays `item.ams_mapping` names (every loaded slot when
  6320. it names none).
  6321. 3. A target of 0 off the filament map skips the whole stage: the
  6322. materials this print loads want no chamber, so there is nothing to
  6323. soak for and the bed phase would only delay the upload (#3041).
  6324. An explicit 0 typed into the per-item override, or a per-item
  6325. 'on', still runs the bed phase and the soak — both are the user
  6326. asking for a warm bed in so many words.
  6327. 4. Three hardware tiers branch the wait loop:
  6328. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6329. send M141 to the resolved target, then wait for the chamber sensor
  6330. to reach it (or the max-wait timeout to elapse).
  6331. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6332. no M141; the bed is the only heat source, so we wait for the chamber
  6333. sensor to rise via bed radiation OR fall through on timeout.
  6334. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6335. temperature; the function just heats the bed and holds for the
  6336. configured soak duration.
  6337. The bed target comes from the archive's parsed metadata
  6338. (`bed_temperature`); if missing the preheat stage logs and returns
  6339. without dispatching anything, rather than guessing at a default that
  6340. might wreck filament setup.
  6341. Failures are logged but never re-raised — preheat is best-effort. A
  6342. printer that goes offline mid-soak, a refused gcode command, or a
  6343. missing temperature reading must not turn into a failed queue item; the
  6344. normal upload + start path runs immediately after this method returns.
  6345. """
  6346. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6347. if override == "off":
  6348. return True
  6349. if override == "inherit":
  6350. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6351. if not enabled:
  6352. return True
  6353. # override == "on" forces the stage on regardless of the global setting.
  6354. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6355. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6356. # Chamber target resolution:
  6357. # 1. Explicit per-item override beats everything (user knows best).
  6358. # 2. Otherwise derive from the filament types this print loads, via
  6359. # the per-filament target map. A PLA-only print derives 0 and the
  6360. # block below skips the stage without the user touching anything,
  6361. # even when an ASA spool is sitting in another slot of the same
  6362. # AMS (#2886).
  6363. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6364. if explicit_target is not None and explicit_target > 0:
  6365. chamber_target = int(explicit_target)
  6366. chamber_source = "item-override"
  6367. elif explicit_target == 0:
  6368. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6369. chamber_source = "item-override-zero"
  6370. else:
  6371. targets = await self._get_preheat_filament_targets(db)
  6372. chamber_target = self._derive_chamber_target(printer, targets, item)
  6373. chamber_source = "filament-map"
  6374. # Nothing to preheat *for*. A zero that came out of the filament map is
  6375. # the map saying this print's materials want no chamber conditioning --
  6376. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6377. # anyway heated the bed and then held it for the full soak, which
  6378. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6379. # own G-code sets the bed the moment it starts, so preheating it here
  6380. # only moves that heating ahead of the upload instead of overlapping
  6381. # with it, and the soak has no chamber to condition (#3041).
  6382. #
  6383. # An explicit statement from the user still runs the stage. Forcing the
  6384. # per-item override to 'on', or typing a chamber target of exactly 0,
  6385. # both mean "preheat the bed for this print" -- the second is
  6386. # documented as doing precisely that. Only the automatic path, the
  6387. # global toggle plus the filament map, short-circuits here.
  6388. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6389. logger.info(
  6390. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6391. "target, so there is nothing to soak for (override=%s model=%s)",
  6392. item.id,
  6393. override,
  6394. printer.model or "",
  6395. )
  6396. self._preheat_flap_to_cooling(item.id, printer)
  6397. return True
  6398. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6399. if bed_target <= 0:
  6400. # No bed temperature in the slicer metadata. When the print needs a
  6401. # hot chamber the bed is simply how we heat it, so fall back to the
  6402. # configured chamber-heating bed temperature rather than skipping
  6403. # the whole stage — otherwise the print starts with a cold chamber,
  6404. # which is exactly what preheat exists to prevent. Without a chamber
  6405. # requirement there is nothing to preheat *for*, so skip as before
  6406. # rather than guess a bed temperature for the print itself.
  6407. if chamber_target <= 0:
  6408. logger.info(
  6409. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6410. item.id,
  6411. )
  6412. return True
  6413. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6414. logger.info(
  6415. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6416. "%d°C to drive the chamber to %d°C",
  6417. item.id,
  6418. bed_target,
  6419. chamber_target,
  6420. )
  6421. client = printer_manager.get_client(printer.id)
  6422. if client is None:
  6423. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6424. return True
  6425. model = printer.model or ""
  6426. has_heater = supports_chamber_heater(model)
  6427. has_sensor = supports_chamber_temp(model)
  6428. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6429. # Fast path: if the chamber has been continuously above target for at
  6430. # least soak_seconds and the bed is already at temperature, skip the
  6431. # entire preheat stage. Typical case: keep-warm held the bed between
  6432. # consecutive same-material prints and the chamber never dropped.
  6433. if do_chamber and has_sensor and soak_seconds > 0:
  6434. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6435. if remaining == 0:
  6436. cur = printer_manager.get_status(printer.id)
  6437. if cur:
  6438. cur_temps = cur.temperatures or {}
  6439. if (
  6440. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6441. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6442. ):
  6443. logger.info(
  6444. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6445. "and bed is already at temperature (chamber history fast-path)",
  6446. item.id,
  6447. chamber_target,
  6448. soak_seconds,
  6449. )
  6450. # Still set targets to prevent cooling during the 3MF upload window.
  6451. # Register each successful set in the preheat pin so `_dispatch_one`
  6452. # unwinds them on any non-success exit.
  6453. pin = self._preheat_pin.setdefault(printer.id, set())
  6454. try:
  6455. client.set_bed_temperature(bed_target)
  6456. pin.add("bed")
  6457. self._preheat_pin_bed[printer.id] = bed_target
  6458. except Exception as exc:
  6459. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6460. if supports_airduct(model):
  6461. cur_airduct = getattr(cur, "airduct_mode", None)
  6462. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6463. try:
  6464. client.set_airduct_mode("heating")
  6465. # Only undo what we can see we replaced. `None`
  6466. # means no mode has been observed yet, and
  6467. # rolling that back to cooling would assert a
  6468. # state the printer never reported.
  6469. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6470. pin.add("airduct")
  6471. except Exception as exc:
  6472. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6473. if has_heater:
  6474. try:
  6475. client.set_chamber_temperature(chamber_target)
  6476. pin.add("chamber")
  6477. except Exception as exc:
  6478. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6479. return True
  6480. logger.info(
  6481. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6482. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6483. item.id,
  6484. bed_target,
  6485. chamber_target if do_chamber else 0,
  6486. chamber_source,
  6487. override,
  6488. model,
  6489. has_heater,
  6490. has_sensor,
  6491. max_wait,
  6492. soak_seconds,
  6493. )
  6494. # Preheat rollback registry: everything we set below is recorded here so
  6495. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6496. # (bed off, chamber off, airduct back to cooling) on any non-success
  6497. # exit. Populated as each command succeeds; consumed and cleared by
  6498. # `_dispatch_one`.
  6499. pin = self._preheat_pin.setdefault(printer.id, set())
  6500. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6501. # cache the target locally so the polling reads below see consistent
  6502. # state (firmware MQTT echoes lag by ~1s).
  6503. try:
  6504. client.set_bed_temperature(bed_target)
  6505. pin.add("bed")
  6506. self._preheat_pin_bed[printer.id] = bed_target
  6507. except Exception as exc:
  6508. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6509. return True
  6510. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6511. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6512. # left it on, regardless of M141. Default cooling actively vents the
  6513. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6514. # cooling never converges — the heater fights the open exhaust. We
  6515. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6516. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6517. # on an H2D that was previously running ABS would otherwise stay in
  6518. # heating mode and overheat PLA). The current-state read keeps the
  6519. # command idempotent — no MQTT chatter when the flap is already where
  6520. # we want it.
  6521. if supports_airduct(model):
  6522. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6523. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6524. current_state = printer_manager.get_status(printer.id)
  6525. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6526. if current_airduct != desired_id:
  6527. try:
  6528. client.set_airduct_mode(desired_airduct)
  6529. # As in the fast path: only pin a rollback for a flap we
  6530. # saw in cooling. `current_airduct` of None means no mode
  6531. # has been observed, so there is nothing to restore to.
  6532. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6533. pin.add("airduct")
  6534. except Exception as exc:
  6535. logger.warning(
  6536. "Queue item %s: preheat airduct %s mode failed: %s",
  6537. item.id,
  6538. desired_airduct,
  6539. exc,
  6540. )
  6541. if do_chamber and has_heater:
  6542. try:
  6543. client.set_chamber_temperature(chamber_target)
  6544. pin.add("chamber")
  6545. except Exception as exc:
  6546. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6547. # Release the pooled DB connection before the (potentially many-minute)
  6548. # heat-soak wait below (#2572). Every setting this method needs is read
  6549. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6550. # it never touches the DB. Without this the caller's transaction sat
  6551. # "idle in transaction" for the whole soak, pinning one pooled connection
  6552. # per preheating printer. expire_on_commit=False keeps item/printer
  6553. # readable afterwards; there are no pending writes to lose here.
  6554. await db.commit()
  6555. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6556. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6557. # Poll every 3s — frequent enough for responsive logging without
  6558. # spamming the MQTT state stream. The "converged" predicate is:
  6559. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6560. # AND
  6561. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6562. BED_TOLERANCE = 2.0
  6563. CHAMBER_TOLERANCE = 2.0
  6564. POLL_INTERVAL = 3.0
  6565. deadline = asyncio.get_event_loop().time() + max_wait
  6566. while True:
  6567. state = printer_manager.get_status(printer.id)
  6568. if state is None:
  6569. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6570. break
  6571. temps = state.temperatures or {}
  6572. bed_now = float(temps.get("bed", 0) or 0)
  6573. chamber_now = float(temps.get("chamber", 0) or 0)
  6574. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6575. if not do_chamber:
  6576. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6577. elif not has_sensor:
  6578. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6579. else:
  6580. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6581. if bed_ok and chamber_ok:
  6582. logger.info(
  6583. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6584. item.id,
  6585. bed_now,
  6586. chamber_now,
  6587. )
  6588. break
  6589. if asyncio.get_event_loop().time() >= deadline:
  6590. logger.info(
  6591. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6592. item.id,
  6593. bed_now,
  6594. bed_target,
  6595. chamber_now,
  6596. chamber_target if do_chamber else 0,
  6597. )
  6598. break
  6599. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6600. logger.info(
  6601. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6602. item.id,
  6603. )
  6604. return False
  6605. if soak_seconds > 0:
  6606. if do_chamber and has_sensor:
  6607. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6608. else:
  6609. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6610. if remaining > 0:
  6611. logger.info(
  6612. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6613. "has been above target for ~%ds already)",
  6614. item.id,
  6615. remaining,
  6616. soak_seconds,
  6617. soak_seconds - remaining,
  6618. )
  6619. if not await self._preheat_sleep(item.id, remaining):
  6620. logger.info(
  6621. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6622. item.id,
  6623. )
  6624. return False
  6625. else:
  6626. logger.info(
  6627. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6628. item.id,
  6629. chamber_target,
  6630. soak_seconds,
  6631. )
  6632. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6633. return True
  6634. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6635. """Turn on smart plug and wait for printer to connect.
  6636. Returns True if printer connected successfully within timeout.
  6637. """
  6638. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6639. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6640. # Check current plug state
  6641. status = await service.get_status(plug)
  6642. if not status.get("reachable"):
  6643. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6644. return False
  6645. # Turn on if not already on
  6646. if status.get("state") != "ON":
  6647. success = await service.turn_on(plug)
  6648. if not success:
  6649. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6650. return False
  6651. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6652. # Get printer from database for connection
  6653. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6654. printer = result.scalar_one_or_none()
  6655. if not printer:
  6656. logger.error("Printer %s not found in database", printer_id)
  6657. return False
  6658. # Wait for printer to boot (give it some time before trying to connect)
  6659. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6660. await asyncio.sleep(30)
  6661. # Try to connect to the printer periodically
  6662. elapsed = 30 # Already waited 30s
  6663. while elapsed < self._power_on_wait_time:
  6664. # Try to connect
  6665. logger.info("Attempting to connect to printer %s...", printer_id)
  6666. try:
  6667. connected = await printer_manager.connect_printer(printer)
  6668. if connected:
  6669. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6670. # Give it a moment to stabilize and get status
  6671. await asyncio.sleep(5)
  6672. return True
  6673. except Exception as e:
  6674. logger.debug("Connection attempt failed: %s", e)
  6675. await asyncio.sleep(self._power_on_check_interval)
  6676. elapsed += self._power_on_check_interval
  6677. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6678. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6679. return False
  6680. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  6681. """Check if the previous print on this printer succeeded.
  6682. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6683. deliberate action, not a failure, so subsequent items should still
  6684. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6685. a skip isn't an actual print attempt, so it must not gate downstream
  6686. items — counting it as a failed predecessor was the cascade bug that
  6687. let a single cancellation block 18 items over 3 days for the reporter.
  6688. Only `failed` and `aborted` — real print-attempt failures — block.
  6689. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6690. action — #1818) are also excluded from the lookback so the user can
  6691. clear the gate after fixing the physical issue without having to
  6692. re-queue every downstream job.
  6693. """
  6694. result = await db.execute(
  6695. select(PrintQueueItem)
  6696. .where(PrintQueueItem.printer_id == item.printer_id)
  6697. .where(PrintQueueItem.id != item.id)
  6698. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6699. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6700. .order_by(PrintQueueItem.completed_at.desc())
  6701. .limit(1)
  6702. )
  6703. prev_item = result.scalar_one_or_none()
  6704. # If no previous item, assume success (first in queue)
  6705. if not prev_item:
  6706. return True
  6707. return prev_item.status in ("completed", "cancelled")
  6708. async def _repoint_siblings_at_archive(
  6709. self,
  6710. db: AsyncSession,
  6711. *,
  6712. consumed_library_file_id: int,
  6713. archive_id: int,
  6714. dispatched_item_id: int,
  6715. ) -> int:
  6716. """Move the other queue items off a library row that is about to be deleted (#2819).
  6717. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6718. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6719. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6720. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6721. clones, so the first dispatch could pull the file out from under rows that
  6722. had not run yet. What those rows did next depended on the database, and
  6723. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6724. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6725. they were left pointing at a row that no longer existed, failing with
  6726. "Library file not found" whenever someone started them -- or sitting
  6727. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6728. constraint, so there the rows were deleted outright and the queued copies
  6729. simply vanished, with no error and no history.
  6730. The archive holds its own copy of the 3MF, so the remaining copies can print
  6731. from it instead. Two things happen here, and both must happen *before* the
  6732. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6733. * every row still naming the file has ``library_file_id`` cleared, which is
  6734. what takes it out of the cascade's reach. That covers rows this cannot
  6735. re-point as well -- a copy already printing from its own archive, and the
  6736. finished ones, which are not spare parts but the record a batch order
  6737. counts its progress from.
  6738. * the rows that still need something to print are pointed at the archive.
  6739. Returns how many items were re-pointed.
  6740. """
  6741. variant_item_ids = (
  6742. (
  6743. await db.execute(
  6744. select(PrintQueueVariant.queue_item_id).where(
  6745. PrintQueueVariant.library_file_id == consumed_library_file_id
  6746. )
  6747. )
  6748. )
  6749. .scalars()
  6750. .all()
  6751. )
  6752. # Candidate rows naming the consumed file have to go rather than be
  6753. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  6754. # one out of the cascade. This is what PostgreSQL already does, and
  6755. # _candidates_for skips such a variant on SQLite anyway, so no selection
  6756. # outcome changes -- the two backends simply stop disagreeing about
  6757. # whether the row is still there.
  6758. #
  6759. # It also has to happen before the re-point below: a cross-model item
  6760. # (#671) picks a variant every pass and folds it onto the row, and
  6761. # _resolve_variant clears archive_id as it does so, which would undo the
  6762. # re-point on the very next lap.
  6763. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  6764. # An item left with other candidates still has somewhere to go, and those
  6765. # carry their own target model -- pointing it at this archive would print a
  6766. # file the matcher never chose. It is excluded from the re-point and simply
  6767. # re-resolves against what is left.
  6768. surviving_variant_item_ids = set(
  6769. (
  6770. await db.execute(
  6771. select(PrintQueueVariant.queue_item_id).where(
  6772. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  6773. )
  6774. )
  6775. )
  6776. .scalars()
  6777. .all()
  6778. )
  6779. repoint_ids = set(
  6780. (
  6781. await db.execute(
  6782. select(PrintQueueItem.id)
  6783. .where(PrintQueueItem.id != dispatched_item_id)
  6784. .where(PrintQueueItem.archive_id.is_(None))
  6785. # "skipped" belongs here with the two live states: it is not
  6786. # terminal. Clearing a printer's previous-success gate puts
  6787. # every item skipped by it back to "pending"
  6788. # (resume_after_failure), and one restored onto a deleted
  6789. # file is the same orphan by a slower route. "failed",
  6790. # "cancelled", "aborted" and "completed" never return.
  6791. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  6792. .where(
  6793. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  6794. )
  6795. .where(
  6796. or_(
  6797. PrintQueueItem.library_file_id == consumed_library_file_id,
  6798. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  6799. )
  6800. )
  6801. )
  6802. )
  6803. .scalars()
  6804. .all()
  6805. )
  6806. if repoint_ids:
  6807. await db.execute(
  6808. update(PrintQueueItem)
  6809. .where(PrintQueueItem.id.in_(repoint_ids))
  6810. .values(
  6811. archive_id=archive_id,
  6812. library_file_id=None,
  6813. # The file this flag named is already consumed. Leaving it set
  6814. # would arm every re-pointed copy to delete whatever library
  6815. # row it is next given.
  6816. cleanup_library_after_dispatch=False,
  6817. )
  6818. )
  6819. logger.info(
  6820. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  6821. sorted(repoint_ids),
  6822. archive_id,
  6823. consumed_library_file_id,
  6824. dispatched_item_id,
  6825. )
  6826. # Everything else that still names the file: taken out of the cascade's
  6827. # reach without touching what it prints. The file is gone either way; what
  6828. # this preserves is the row.
  6829. await db.execute(
  6830. update(PrintQueueItem)
  6831. .where(PrintQueueItem.id != dispatched_item_id)
  6832. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  6833. .values(library_file_id=None)
  6834. )
  6835. return len(repoint_ids)
  6836. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  6837. """Schedule power-off if the queue item enabled auto_off_after.
  6838. Delegates to the smart-plug manager so the off honours each plug's
  6839. configured strategy (time delay or temperature threshold), is cancelled
  6840. if the printer starts printing again, and never cuts power on a loaded
  6841. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  6842. powered off on the timeout regardless of print state.
  6843. """
  6844. if not item.auto_off_after:
  6845. return
  6846. try:
  6847. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  6848. except Exception as e:
  6849. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  6850. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  6851. """Get a human-readable name for a queue item."""
  6852. if item.archive_id:
  6853. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  6854. archive = result.scalar_one_or_none()
  6855. if archive:
  6856. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6857. if item.library_file_id:
  6858. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  6859. library_file = result.scalar_one_or_none()
  6860. if library_file:
  6861. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6862. # A cross-model item (#671) holds no file of its own until a printer is
  6863. # picked, so name it after its first candidate — otherwise every waiting
  6864. # notification for one reads "Job #12". Queried rather than read off
  6865. # item.variants because callers outside the selection loop have not
  6866. # eager-loaded them, and a lazy load raises in async.
  6867. first_variant_name = (
  6868. await db.execute(
  6869. select(LibraryFile.filename)
  6870. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  6871. .where(PrintQueueVariant.queue_item_id == item.id)
  6872. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  6873. .limit(1)
  6874. )
  6875. ).scalar_one_or_none()
  6876. if first_variant_name:
  6877. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  6878. return f"Job #{item.id}"
  6879. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  6880. """Get printer by ID."""
  6881. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6882. return result.scalar_one_or_none()
  6883. async def _notify_dispatch_gave_up(
  6884. self,
  6885. queue_item_id: int,
  6886. printer_id: int,
  6887. created_by_id: int | None,
  6888. reason: str = "Printer accepted the file but never started printing",
  6889. ) -> None:
  6890. """Tell the user the queue item was failed after exhausting its dispatch retries.
  6891. Called from the watchdog, which is a background task with no session of
  6892. its own — hence the fresh one here. Best-effort throughout: the row is
  6893. already marked failed and that is the load-bearing part; a notification
  6894. provider being down must not resurrect the retry loop we just stopped.
  6895. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  6896. path passes its own, because "accepted the file but never started" is the
  6897. opposite of what happened there — the printer refused it outright (#2732).
  6898. """
  6899. try:
  6900. async with async_session() as db:
  6901. item = await db.get(PrintQueueItem, queue_item_id)
  6902. if not item:
  6903. return
  6904. job_name = await self._get_job_name(db, item)
  6905. printer = await self._get_printer(db, printer_id)
  6906. await notification_service.on_queue_job_failed(
  6907. job_name=job_name,
  6908. printer_id=printer_id,
  6909. printer_name=printer.name if printer else "Unknown",
  6910. reason=reason,
  6911. db=db,
  6912. )
  6913. except Exception as e:
  6914. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  6915. try:
  6916. await ws_manager.send_queue_item_failed(
  6917. user_id=created_by_id,
  6918. queue_item_id=queue_item_id,
  6919. printer_id=printer_id,
  6920. reason="never_started",
  6921. )
  6922. except Exception:
  6923. pass # toast is best-effort
  6924. async def _filament_short_on(
  6925. self,
  6926. db: AsyncSession,
  6927. item: PrintQueueItem,
  6928. printer_id: int,
  6929. *,
  6930. require_known: bool = False,
  6931. ) -> bool:
  6932. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  6933. Asks what ``_block_on_filament_deficit`` would answer once the item is
  6934. assigned there, with the mapping the item would get there, but changes
  6935. nothing. The model-based matcher uses it to prefer a printer whose
  6936. spools can finish the job.
  6937. False whenever the gate would let the item through: "Print Anyway",
  6938. no mapping, or a check that fails. With ``require_known`` all three of
  6939. those, and any printed slot whose remaining amount is unknown, count
  6940. as short instead: releasing a held job starts it with nobody asked, so
  6941. it needs the amount on record, not merely nothing against it.
  6942. """
  6943. if item.skip_filament_check:
  6944. return False
  6945. try:
  6946. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  6947. if not mapping:
  6948. return require_known
  6949. deficit = await compute_deficit_for_queue_item(
  6950. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  6951. )
  6952. except Exception as e:
  6953. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  6954. return require_known
  6955. return bool(deficit)
  6956. async def _release_short_model_hold(
  6957. self,
  6958. db: AsyncSession,
  6959. item: PrintQueueItem,
  6960. unavailable: set[int],
  6961. require_plate_clear: bool,
  6962. printer_scope: PrinterScope,
  6963. ) -> bool:
  6964. """Free an "any model" job held for low filament once a printer can run it (#3137).
  6965. The deficit gate holds a model-based job on the printer the matcher
  6966. gave it, because "Print Anyway" needs a printer to print on. When
  6967. another idle printer of the job's model has the filament, the job is
  6968. moved to that printer and its hold lifted, and the fixed-printer
  6969. branch dispatches it in this same pass, through the same checks a
  6970. held job meets when the user presses Start. It is moved rather than
  6971. put back in the pool because the model-based branch would pick again
  6972. without requiring the amounts on record (below), and could pick a
  6973. different printer. Only the deficit gate sets ``filament_short``, so a
  6974. job held for any other reason stays held.
  6975. The printer it is held on is left out: a spool loaded there is started
  6976. with Start, as before, rather than while someone may still be loading
  6977. the next one. Each job is checked at most every
  6978. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  6979. on each idle printer again.
  6980. Cross-model jobs (#671) stay held: checking a variant writes its file
  6981. onto the item, which would leave a job that is not moved holding
  6982. another variant's file for the printer it waits on.
  6983. A printer qualifies only on a positive finding: every slot the plate
  6984. prints mapped to a spool whose remaining amount is on record and
  6985. enough. A printer whose spools Bambuddy does not track is not one.
  6986. Returns True when the job was moved. A check that fails keeps the hold
  6987. rather than stopping the queue pass.
  6988. """
  6989. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  6990. return False
  6991. if not item.target_model or item.variants:
  6992. return False
  6993. now = time.monotonic()
  6994. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  6995. return False
  6996. self._short_hold_checked_at[item.id] = now
  6997. try:
  6998. candidates = _candidates_for(item)
  6999. if not candidates:
  7000. return False
  7001. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7002. async def is_short(pid: int) -> bool:
  7003. return await self._filament_short_on(db, item, pid, require_known=True)
  7004. match_id, _ = await self._find_idle_printer_for_model(
  7005. db,
  7006. item.target_model,
  7007. unavailable | {item.printer_id},
  7008. effective_types,
  7009. item.target_location,
  7010. filament_overrides=filament_overrides,
  7011. require_plate_clear=require_plate_clear,
  7012. printer_scope=printer_scope,
  7013. is_short=is_short,
  7014. )
  7015. # Every idle printer short comes back as the first of them.
  7016. if match_id is None or await is_short(match_id):
  7017. return False
  7018. except Exception as e:
  7019. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7020. return False
  7021. logger.info(
  7022. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7023. item.id,
  7024. match_id,
  7025. item.printer_id,
  7026. )
  7027. self._short_hold_checked_at.pop(item.id, None)
  7028. item.printer_id = match_id
  7029. # Resolved against the printer it leaves (#3239).
  7030. item.ams_mapping = None
  7031. item.manual_start = False
  7032. item.filament_short = False
  7033. item.waiting_reason = None
  7034. await db.commit()
  7035. try:
  7036. printer = await self._get_printer(db, match_id)
  7037. await notification_service.on_queue_job_assigned(
  7038. job_name=await self._get_job_name(db, item),
  7039. printer_id=match_id,
  7040. printer_name=printer.name if printer else "Unknown",
  7041. target_model=item.target_model,
  7042. db=db,
  7043. )
  7044. except Exception as e:
  7045. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7046. return True
  7047. async def _block_on_filament_deficit(
  7048. self,
  7049. db: AsyncSession,
  7050. item: PrintQueueItem,
  7051. ) -> bool:
  7052. """Promote the item to manual_start when the assigned spool is short (#1496).
  7053. Returns True when this dispatch attempt was blocked, False when the
  7054. item is clear to start. A previously-flagged item whose spool has
  7055. since been swapped to one with enough material clears the flag here
  7056. so the next scheduler tick dispatches it.
  7057. """
  7058. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7059. # don't re-flag, don't even compute. Without this short-circuit the
  7060. # scheduler bounces between "user said anyway" (route clears
  7061. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7062. # on identical spool state) (#1698-followup).
  7063. if item.skip_filament_check:
  7064. # #1762 diagnostic: surface the short-circuit at INFO so a
  7065. # future "Print Anyway didn't work" report (e.g. issue #1762
  7066. # comment 3) has actionable evidence in the support bundle
  7067. # without needing DEBUG enabled.
  7068. logger.info(
  7069. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7070. item.id,
  7071. )
  7072. return False
  7073. try:
  7074. deficit = await compute_deficit_for_queue_item(db, item)
  7075. except Exception as e:
  7076. # Never let a flaky deficit check wedge the queue — log and let
  7077. # dispatch proceed. The PrintModal-side check still runs on the
  7078. # manual paths.
  7079. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7080. return False
  7081. if deficit:
  7082. item.filament_short = True
  7083. item.manual_start = True
  7084. await db.commit()
  7085. job_name = await self._get_job_name(db, item)
  7086. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7087. logger.info(
  7088. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7089. item.id,
  7090. len(deficit),
  7091. )
  7092. try:
  7093. await notification_service.on_queue_job_waiting(
  7094. job_name=job_name,
  7095. target_model=(printer.model if printer else "") or "",
  7096. waiting_reason="filament_short",
  7097. db=db,
  7098. )
  7099. except Exception as e:
  7100. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7101. return True
  7102. # No deficit — clear any stale flag from a previous tick.
  7103. if item.filament_short:
  7104. item.filament_short = False
  7105. await db.commit()
  7106. return False
  7107. async def _block_on_unmatched_filament(
  7108. self,
  7109. db: AsyncSession,
  7110. item: PrintQueueItem,
  7111. release_assignment: bool = False,
  7112. ) -> bool:
  7113. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7114. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7115. goes ahead, letting the printer choose — which is how a job prints in the
  7116. wrong material without anyone being asked. Holding is the same answer the
  7117. deficit gate already gives for "the spool is too light", so it reuses the
  7118. same promote-and-notify machinery.
  7119. Keyed off unresolved slots in the *computed* mapping intersected with the
  7120. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7121. read: on its own it also pads slots this plate does not print, so the
  7122. array alone would hold perfectly good jobs. Reading the mapping rather
  7123. than the printer's loaded filament types also inherits the matcher's
  7124. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7125. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7126. type-only scan would wave that through.
  7127. A mapping that resolved *nothing* is the same finding arriving as an
  7128. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7129. could not replace, and dispatch then goes out as ``use_ams`` with no
  7130. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7131. That is held too, but only once live status positively reports loaded
  7132. trays: #2589's mapping is bogus precisely because the AMS was not known
  7133. yet, and its empty loaded list is that ignorance rather than a miss.
  7134. ``release_assignment`` is for the model-based path, which commits its
  7135. printer choice before the gates run. Holding an "any P2S" job would
  7136. otherwise pin it to the one P2S that could not run it.
  7137. Returns True when this dispatch attempt was blocked.
  7138. """
  7139. if item.skip_filament_check or not item.printer_id:
  7140. return False
  7141. if item.ams_mapping:
  7142. try:
  7143. mapping = json.loads(item.ams_mapping)
  7144. except (json.JSONDecodeError, TypeError):
  7145. return False
  7146. if not isinstance(mapping, list):
  7147. return False
  7148. else:
  7149. # Nothing resolved, or nothing survived revalidation. Only a printer
  7150. # that reported loaded trays makes that a finding — see the
  7151. # docstring on why an empty list is not one.
  7152. status = printer_manager.get_status(item.printer_id)
  7153. if status is None or not self._build_loaded_filaments(status):
  7154. return False
  7155. # Every required slot reads unresolved against an empty mapping.
  7156. mapping = []
  7157. required = await self._get_filament_requirements(db, item)
  7158. if not required:
  7159. return False
  7160. self._apply_filament_overrides(item, required)
  7161. unmatched = _unresolved_required(required, mapping)
  7162. if not unmatched:
  7163. # No cleanup needed here: once start is pressed the item is no
  7164. # longer staged, and whichever exit runs next overwrites the reason
  7165. # (`hold_item` on the fixed-printer branch, the assignment on the
  7166. # model-based one), as does dispatch.
  7167. return False
  7168. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7169. held_by = item.printer_id
  7170. item.manual_start = True
  7171. # Human-readable: this renders on the queue row.
  7172. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7173. if release_assignment:
  7174. # "Any P2S" means any, so the job returns to the pool rather than
  7175. # waiting on the printer that could not take it. The mapping goes
  7176. # with the assignment: its tray IDs were resolved against the
  7177. # printer being released and mean nothing on the next one (#2799),
  7178. # and keeping them would hold the job again even on a printer that
  7179. # has the filament, since an unresolved slot is deliberately not a
  7180. # conflict worth recomputing over.
  7181. item.printer_id = None
  7182. item.ams_mapping = None
  7183. await db.commit()
  7184. job_name = await self._get_job_name(db, item)
  7185. printer = await self._get_printer(db, held_by)
  7186. logger.info(
  7187. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7188. item.id,
  7189. held_by,
  7190. wanted,
  7191. )
  7192. try:
  7193. await notification_service.on_queue_job_waiting(
  7194. job_name=job_name,
  7195. target_model=(printer.model if printer else "") or "",
  7196. waiting_reason=f"needs {wanted}",
  7197. db=db,
  7198. )
  7199. except Exception as e:
  7200. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7201. return True
  7202. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7203. """Hand the queue item's owner to printer_manager so the
  7204. print-complete callback can credit the user in PrintLogEntry (#1670).
  7205. No-ops when the item has no `created_by_id` or the referenced user
  7206. row is missing (e.g. user deleted between queue-add and dispatch —
  7207. in that case the print log row falls back to the existing un-credited
  7208. behaviour rather than crashing the dispatch).
  7209. """
  7210. if not item.created_by_id:
  7211. return
  7212. from backend.app.models.user import User
  7213. owner = await db.get(User, item.created_by_id)
  7214. if owner:
  7215. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  7216. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7217. """Upload file and start print for a queue item.
  7218. Supports two sources:
  7219. - archive_id: Print from an existing archive
  7220. - library_file_id: Print from a library file (file manager)
  7221. """
  7222. logger.info("Starting queue item %s", item.id)
  7223. # Also covers a reservation left active by a process interruption
  7224. # during an earlier attempt. `_dispatch_one` releases this marker on
  7225. # every exit unless start_print() confirms that the command was sent.
  7226. self._unconfirmed_budget_reservations.add(item.id)
  7227. try:
  7228. from backend.app.models.user import User
  7229. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7230. # Recompute at the final authorization boundary as well as enqueue
  7231. # time. This covers rows created before the server-side estimate
  7232. # migration and prevents any alternate write path from weakening
  7233. # the budget reservation.
  7234. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7235. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7236. item.estimated_cost = await estimate_queue_source_cost(
  7237. db,
  7238. archive=archive,
  7239. library_file=library_file,
  7240. plate_id=item.plate_id,
  7241. ams_mapping=item.ams_mapping,
  7242. printer_id=item.printer_id,
  7243. )
  7244. await validate_print_budget(
  7245. db,
  7246. cost_center_id=item.cost_center_id,
  7247. estimated_cost=item.estimated_cost,
  7248. current_user=queue_user,
  7249. exclude_queue_item_id=item.id,
  7250. exclude_reservation_source_type="print_queue",
  7251. exclude_reservation_source_id=item.id,
  7252. )
  7253. budget_reservation = await create_budget_reservation(
  7254. db,
  7255. cost_center_id=item.cost_center_id,
  7256. estimated_cost=item.estimated_cost,
  7257. current_user=queue_user,
  7258. source_type="print_queue",
  7259. source_id=item.id,
  7260. print_archive_id=item.archive_id,
  7261. exclude_queue_item_id=item.id,
  7262. )
  7263. await db.commit()
  7264. except HTTPException as exc:
  7265. item.status = "failed"
  7266. item.error_message = str(exc.detail)
  7267. item.completed_at = datetime.now(timezone.utc)
  7268. await db.commit()
  7269. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7270. await self._power_off_if_needed(db, item)
  7271. return
  7272. # Get printer first (needed for both paths)
  7273. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7274. printer = result.scalar_one_or_none()
  7275. if not printer:
  7276. item.status = "failed"
  7277. item.error_message = "Printer not found"
  7278. item.completed_at = datetime.now(timezone.utc)
  7279. await db.commit()
  7280. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7281. await self._power_off_if_needed(db, item)
  7282. return
  7283. # Check printer is connected
  7284. if not printer_manager.is_connected(item.printer_id):
  7285. item.status = "failed"
  7286. item.error_message = "Printer not connected"
  7287. item.completed_at = datetime.now(timezone.utc)
  7288. await db.commit()
  7289. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7290. await self._power_off_if_needed(db, item)
  7291. return
  7292. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7293. # `items` was taken at the top of check_queue, but the user can /cancel
  7294. # any pending row in the gap before we reach this point. Re-read the
  7295. # row and bail out cleanly instead of starting an FTP upload for a row
  7296. # that's already cancelled. The atomic CAS at the pending→printing
  7297. # transition (below, before start_print) is the load-bearing guard;
  7298. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7299. await db.refresh(item)
  7300. if item.status != "pending":
  7301. logger.info(
  7302. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7303. item.id,
  7304. item.status,
  7305. )
  7306. return
  7307. # Busy-printer guard (#2598). check_queue gates dispatch on
  7308. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7309. # keep reporting FINISH for tens of seconds *after* it accepted a
  7310. # project_file (see the watchdog's phase-B note). A watchdog revert
  7311. # (#2555) also releases the dispatch hold, so a re-selected item can
  7312. # reach here while its printer has actually started printing. Uploading
  7313. # and dispatching then collides with the live job — the firmware answers
  7314. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7315. # live state right before the expensive FTP upload: if the printer is
  7316. # busy, leave the item pending and let a later tick dispatch it once the
  7317. # printer is genuinely idle. No wasted upload, no collision.
  7318. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7319. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7320. logger.info(
  7321. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7322. "leaving item pending for a later tick (#2598)",
  7323. item.id,
  7324. item.printer_id,
  7325. pre_dispatch_state,
  7326. )
  7327. return
  7328. # Determine source: archive or library file
  7329. archive = None
  7330. library_file = None
  7331. file_path = None
  7332. filename = None
  7333. cleanup_disk_paths: list[Path] = []
  7334. # Set when a dispatch consumes its library file, so the photos can be
  7335. # carried over after the commit that removes the row (#3077).
  7336. consumed_library_file_id: int | None = None
  7337. consumed_photos: list[str] = []
  7338. if item.archive_id:
  7339. # Print from archive
  7340. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7341. archive = result.scalar_one_or_none()
  7342. if not archive:
  7343. item.status = "failed"
  7344. item.error_message = "Archive not found"
  7345. item.completed_at = datetime.now(timezone.utc)
  7346. await db.commit()
  7347. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7348. await self._power_off_if_needed(db, item)
  7349. return
  7350. # Persist the queue item's selected plate onto the archive so Print
  7351. # History can show the actual plate after cancel/fail/complete (#2603).
  7352. # Only when the archive doesn't already carry one, so a reprint of a
  7353. # plate-specific archive isn't relabelled by a differently-plated
  7354. # queue row.
  7355. if archive.plate_id is None and item.plate_id is not None:
  7356. archive.plate_id = item.plate_id
  7357. # Ask-for-outcome opt-in rides from the queue item to the archive
  7358. # the same way (#1898); never cleared here so a reprint of an
  7359. # archive that already asked keeps asking.
  7360. if item.confirm_outcome:
  7361. archive.confirm_requested = True
  7362. file_path = settings.base_dir / archive.file_path
  7363. filename = archive.filename
  7364. elif item.library_file_id:
  7365. # Print from library file (file manager)
  7366. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7367. library_file = result.scalar_one_or_none()
  7368. if not library_file:
  7369. # "Not found" covers two different situations and only one of
  7370. # them is recoverable, so say which. A trashed file is still
  7371. # there and restoring it makes a re-queued job work; a file that
  7372. # is really gone needs a different one. Neither is knowable from
  7373. # the queue, which is the whole complaint about this message.
  7374. trashed = (
  7375. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7376. ).scalar_one_or_none()
  7377. item.status = "failed"
  7378. item.error_message = (
  7379. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7380. if trashed
  7381. else "Library file not found — it was deleted after this job was queued"
  7382. )
  7383. item.completed_at = datetime.now(timezone.utc)
  7384. await db.commit()
  7385. logger.error(
  7386. "Queue item %s: library file %s is %s",
  7387. item.id,
  7388. item.library_file_id,
  7389. "in the trash" if trashed else "gone",
  7390. )
  7391. await self._power_off_if_needed(db, item)
  7392. return
  7393. # Library files store absolute paths
  7394. lib_path = Path(library_file.file_path)
  7395. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7396. filename = library_file.filename
  7397. # Create archive from library file so usage tracking has access to the 3MF
  7398. queue_item_id = item.id
  7399. # Held separately: a cleanup dispatch clears item.library_file_id
  7400. # below, and the log line at the end of this block reported that
  7401. # cleared field -- so every consumed print logged "from library
  7402. # file None", which is the one case worth being able to trace.
  7403. source_library_file_id = item.library_file_id
  7404. try:
  7405. from backend.app.services.archive import ArchiveService
  7406. archive_service = ArchiveService(db)
  7407. archive = await archive_service.archive_print(
  7408. printer_id=item.printer_id,
  7409. source_file=file_path,
  7410. original_filename=filename,
  7411. created_by_id=item.created_by_id,
  7412. project_id=item.project_id,
  7413. cost_center_id=item.cost_center_id,
  7414. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7415. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7416. )
  7417. if archive:
  7418. item.archive_id = archive.id
  7419. if item.confirm_outcome:
  7420. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7421. if budget_reservation is not None:
  7422. budget_reservation.print_archive_id = archive.id
  7423. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7424. consumed_library_file_id = library_file.id
  7425. item.library_file_id = None
  7426. cleanup_disk_paths.append(file_path)
  7427. if library_file.thumbnail_path:
  7428. thumb_path = Path(library_file.thumbnail_path)
  7429. if not thumb_path.is_absolute():
  7430. thumb_path = settings.base_dir / library_file.thumbnail_path
  7431. cleanup_disk_paths.append(thumb_path)
  7432. # Before the delete, not after: on PostgreSQL the FK
  7433. # cascade would already have taken these rows (#2819).
  7434. await self._repoint_siblings_at_archive(
  7435. db,
  7436. consumed_library_file_id=consumed_library_file_id,
  7437. archive_id=archive.id,
  7438. dispatched_item_id=item.id,
  7439. )
  7440. # Read while the row is still here; the photos move
  7441. # below, once the delete has actually committed.
  7442. consumed_photos = list(library_file.photos or [])
  7443. await db.delete(library_file)
  7444. file_path = settings.base_dir / archive.file_path
  7445. filename = archive.filename
  7446. # Commit, not flush — flush opens the SQLite write
  7447. # transaction (item.archive_id update + library_file
  7448. # delete) and would hold the WAL writer lock through the
  7449. # FTP upload below, causing "database is locked" cascades
  7450. # for sensor history + concurrent cancels (#1853).
  7451. await db.commit()
  7452. logger.info(
  7453. "Queue item %s: Created archive %s from library file %s",
  7454. item.id,
  7455. archive.id,
  7456. source_library_file_id,
  7457. )
  7458. except Exception as e:
  7459. logger.warning(
  7460. "Queue item %s: Failed to create archive from library file: %s",
  7461. queue_item_id,
  7462. e,
  7463. exc_info=True,
  7464. )
  7465. await db.rollback()
  7466. item = await db.get(PrintQueueItem, queue_item_id)
  7467. if item:
  7468. item.status = "failed"
  7469. item.error_message = "Failed to create archive from library file"
  7470. item.completed_at = datetime.now(timezone.utc)
  7471. await db.commit()
  7472. await self._power_off_if_needed(db, item)
  7473. return
  7474. if not archive:
  7475. item.status = "failed"
  7476. item.error_message = "Failed to create archive from library file"
  7477. item.completed_at = datetime.now(timezone.utc)
  7478. await db.commit()
  7479. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7480. await self._power_off_if_needed(db, item)
  7481. return
  7482. # The photos follow the file into the archive that replaces it, for
  7483. # the same reason the siblings do (#3077). After the commit above,
  7484. # never before it: that commit can fail ("database is locked",
  7485. # #1853) and roll the library row back, and photos already moved
  7486. # would leave it naming a directory that no longer exists. The
  7487. # file and thumbnail unlinks are deferred for the same reason.
  7488. if consumed_library_file_id is not None and consumed_photos:
  7489. # Held as a plain int, read here while the session is still
  7490. # healthy, because the handler below may not touch an ORM
  7491. # instance at all. The commit it exists for fails inside the
  7492. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7493. # first DML statement, so a busy writer surfaces as "database
  7494. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7495. # internally through safe_reraise before re-raising, which
  7496. # expires every loaded instance and leaves the session in
  7497. # pending-rollback state -- so `archive.id` inside the except
  7498. # would itself raise PendingRollbackError and the rollback
  7499. # below would never be reached.
  7500. archive_id = archive.id
  7501. try:
  7502. carried_photos = move_library_photos(
  7503. consumed_library_file_id,
  7504. consumed_photos,
  7505. archive_photos_dir(archive),
  7506. )
  7507. if carried_photos:
  7508. archive.photos = list(archive.photos or []) + carried_photos
  7509. await db.commit()
  7510. except Exception as e:
  7511. # The archive and the delete are already committed; the
  7512. # print goes ahead either way. Worst case the pictures sit
  7513. # unnamed in the archive's own directory.
  7514. #
  7515. # Ints only until the rollback has run, per the note above,
  7516. # which is why this logs queue_item_id and not item.id --
  7517. # the sibling handler forty lines up does the same.
  7518. logger.warning(
  7519. "Queue item %s: failed to carry library photos into archive %s: %s",
  7520. queue_item_id,
  7521. archive_id,
  7522. e,
  7523. )
  7524. await db.rollback()
  7525. # rollback() expires every loaded instance, and in async
  7526. # SQLAlchemy the next plain attribute read is lazy IO
  7527. # outside the greenlet -- MissingGreenlet, which would turn
  7528. # this cosmetic failure into a dispatch crash in exactly the
  7529. # "database is locked" case the block exists for (#1853).
  7530. # The nozzle guard, the upload and the start all keep
  7531. # reading item, archive and printer, so all three go back
  7532. # into the session before falling through.
  7533. item = await db.get(PrintQueueItem, queue_item_id)
  7534. archive = await db.get(PrintArchive, archive_id)
  7535. printer = await db.get(Printer, item.printer_id) if item else None
  7536. if not item or not archive or not printer:
  7537. logger.error(
  7538. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7539. queue_item_id,
  7540. archive_id,
  7541. )
  7542. return
  7543. else:
  7544. # Neither archive nor library file specified
  7545. item.status = "failed"
  7546. item.error_message = "No source file specified"
  7547. item.completed_at = datetime.now(timezone.utc)
  7548. await db.commit()
  7549. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7550. await self._power_off_if_needed(db, item)
  7551. return
  7552. # Check file exists on disk
  7553. if not file_path.exists():
  7554. item.status = "failed"
  7555. item.error_message = "Source file not found on disk"
  7556. item.completed_at = datetime.now(timezone.utc)
  7557. await db.commit()
  7558. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7559. await self._power_off_if_needed(db, item)
  7560. return
  7561. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7562. # size dispatched to a printer with a different nozzle installed is
  7563. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7564. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7565. # gives the user no idea what went wrong. Catch it here, before we spend
  7566. # time preheating and uploading, and fail with an actionable message.
  7567. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7568. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7569. # the printer hasn't reported its nozzles yet, we fall through and let the
  7570. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7571. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7572. # as one of the two hotends is a 0.6.
  7573. #
  7574. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7575. # (#2885): the printer fetches one as part of starting the print, so the
  7576. # set to test against is "reachable", not "currently mounted". This runs
  7577. # well before the rack picker at the bottom of this method, so without
  7578. # the rack in scope here that picker never got the chance to run.
  7579. sliced_nozzle = archive.nozzle_diameter if archive else None
  7580. if sliced_nozzle:
  7581. nozzle_status = printer_manager.get_status(item.printer_id)
  7582. installed = _installed_nozzle_diameters(nozzle_status)
  7583. rack = _rack_nozzle_diameters(nozzle_status)
  7584. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7585. if mismatch_msg:
  7586. item.status = "failed"
  7587. item.error_message = mismatch_msg
  7588. item.completed_at = datetime.now(timezone.utc)
  7589. await db.commit()
  7590. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7591. await notification_service.on_queue_job_failed(
  7592. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7593. printer_id=printer.id,
  7594. printer_name=printer.name,
  7595. reason=mismatch_msg,
  7596. db=db,
  7597. )
  7598. try:
  7599. await ws_manager.send_queue_item_failed(
  7600. user_id=item.created_by_id,
  7601. queue_item_id=item.id,
  7602. printer_id=item.printer_id,
  7603. reason="nozzle_mismatch",
  7604. )
  7605. except Exception:
  7606. pass
  7607. await self._power_off_if_needed(db, item)
  7608. return
  7609. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7610. # bed (and chamber, if applicable) is at temperature when the firmware
  7611. # starts the actual print routine. Best-effort: any failure logs and
  7612. # falls through to the normal upload+start path rather than turning a
  7613. # configuration issue into a failed queue item.
  7614. # Returns False only when the item was cancelled or deleted while the
  7615. # stage was holding at temperature. Uploading and starting it anyway
  7616. # would print a job the user has already called off, so abandon the
  7617. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7618. if not await self._preheat_and_soak(db, item, printer, archive):
  7619. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7620. return
  7621. # See `_effective_plate_id` for why this is resolved once here rather
  7622. # than each site below repeating `item.plate_id or 1`.
  7623. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7624. # G-code injection for auto-print systems (#422)
  7625. injected_path = None
  7626. # #2547: tracked separately from `injected_path`, which is also set when
  7627. # only a START snippet was injected. Only an END snippet changes what the
  7628. # camera sees at print completion.
  7629. end_gcode_injected = False
  7630. if item.gcode_injection:
  7631. try:
  7632. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7633. if snippets_raw:
  7634. snippets = json.loads(snippets_raw)
  7635. model_snippets = snippets.get(printer.model, {})
  7636. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7637. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7638. if start_gc or end_gc:
  7639. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7640. injected_path = inject_gcode_into_3mf(
  7641. file_path, effective_plate_id, start_gc or None, end_gc or None
  7642. )
  7643. if injected_path:
  7644. file_path = injected_path
  7645. end_gcode_injected = bool(end_gc)
  7646. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7647. else:
  7648. logger.warning(
  7649. "Queue item %s: G-code injection returned no result, using original", item.id
  7650. )
  7651. except Exception as e:
  7652. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7653. # #2547: the finish-photo path can't learn from telemetry that this print
  7654. # ends with user End G-code — which means the plate may be gone by the
  7655. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7656. # the print once the printer confirms it running.
  7657. if end_gcode_injected:
  7658. print_dispatch_context.mark_pending(printer.id)
  7659. # Upload to root directory (not /cache/) - the start_print command references
  7660. # files by name only (ftp://{filename}), so they must be in the root
  7661. remote_filename = derive_remote_filename(filename)
  7662. remote_path = f"/{remote_filename}"
  7663. # Get FTP retry settings
  7664. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7665. logger.info(
  7666. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7667. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7668. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7669. )
  7670. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7671. # Every read this method needs (printer, archive/library, preheat) is
  7672. # done, and the library-file branch already committed its archive
  7673. # creation. Without this the transaction opened by the first SELECT above
  7674. # stays "idle in transaction" for the entire upload — multiple seconds
  7675. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7676. # a farm dispatching many jobs at once then exhausts the pool. This was
  7677. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7678. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7679. # readable; the status writes below (upload-failure path and the
  7680. # pending->printing CAS) transparently open a fresh transaction.
  7681. await db.commit()
  7682. # Delete existing file if present (avoids 553 error on overwrite)
  7683. try:
  7684. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  7685. delete_result = await delete_file_async(
  7686. printer.ip_address,
  7687. printer.access_code,
  7688. remote_path,
  7689. socket_timeout=ftp_timeout,
  7690. printer_model=printer.model,
  7691. # This delete and the upload below are one bounded, user-initiated
  7692. # unit -- at most nine connections -- so neither skips on the
  7693. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  7694. # trace this delete took the TLS failure and armed the cool-off,
  7695. # and the upload's four attempts were then spent against it
  7696. # without a socket being opened.
  7697. respect_handshake_cooloff=False,
  7698. )
  7699. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  7700. except Exception as e:
  7701. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  7702. # Dispatch toast — announce the upload start with the total byte
  7703. # count so the frontend can render an honest progress bar.
  7704. toast_uid = item.created_by_id
  7705. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7706. try:
  7707. total_bytes = file_path.stat().st_size
  7708. except OSError:
  7709. total_bytes = 0
  7710. try:
  7711. await ws_manager.send_queue_item_uploading(
  7712. user_id=toast_uid,
  7713. queue_item_id=item.id,
  7714. printer_id=item.printer_id,
  7715. printer_name=printer.name,
  7716. file_name=toast_file_name,
  7717. total_bytes=total_bytes,
  7718. )
  7719. except Exception:
  7720. pass # toast is best-effort
  7721. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  7722. # A deadline expiry gets its own message: "check your SD card" is the
  7723. # wrong advice for a link that was simply too slow to finish (#2529).
  7724. upload_error: str | None = None
  7725. # Why the upload failed, straight from the client rather than inferred.
  7726. # Owned here, so a background fetch for another print cannot overwrite
  7727. # it between the failure and the sentence built from it (#2899).
  7728. upload_failure = FtpFailureReport()
  7729. try:
  7730. if ftp_retry_enabled:
  7731. uploaded = await with_ftp_retry(
  7732. upload_file_async,
  7733. printer.ip_address,
  7734. printer.access_code,
  7735. file_path,
  7736. remote_path,
  7737. socket_timeout=ftp_timeout,
  7738. printer_model=printer.model,
  7739. progress_callback=progress_bridge,
  7740. respect_handshake_cooloff=False,
  7741. failure=upload_failure,
  7742. max_retries=ftp_retry_count,
  7743. retry_delay=ftp_retry_delay,
  7744. operation_name=f"Upload print to {printer.name}",
  7745. )
  7746. else:
  7747. uploaded = await upload_file_async(
  7748. printer.ip_address,
  7749. printer.access_code,
  7750. file_path,
  7751. remote_path,
  7752. socket_timeout=ftp_timeout,
  7753. printer_model=printer.model,
  7754. progress_callback=progress_bridge,
  7755. respect_handshake_cooloff=False,
  7756. failure=upload_failure,
  7757. )
  7758. except UploadCancelled as e:
  7759. uploaded = False
  7760. upload_error = (
  7761. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  7762. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  7763. )
  7764. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  7765. except Exception as e:
  7766. uploaded = False
  7767. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  7768. # Clean up injected temp file after upload attempt
  7769. if injected_path and injected_path.exists():
  7770. injected_path.unlink(missing_ok=True)
  7771. if not uploaded:
  7772. # This used to be one string for every upload failure, telling
  7773. # everyone to check the SD card. The client knows which of seven
  7774. # things went wrong and logs each one differently; it just had no
  7775. # way to say so here, so the card got named even for a TLS
  7776. # handshake that never reached the printer's filesystem (#2899).
  7777. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  7778. failure = upload_failure.failure
  7779. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  7780. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  7781. return
  7782. item.status = "failed"
  7783. item.error_message = error_msg
  7784. item.completed_at = datetime.now(timezone.utc)
  7785. await db.commit()
  7786. logger.error(
  7787. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  7788. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  7789. )
  7790. # Send failure notification
  7791. await notification_service.on_queue_job_failed(
  7792. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7793. printer_id=printer.id,
  7794. printer_name=printer.name,
  7795. # The same sentence the queue shows. A push notification saying
  7796. # something different from the UI is its own small bug (#2899).
  7797. reason=error_msg,
  7798. db=db,
  7799. )
  7800. try:
  7801. await ws_manager.send_queue_item_failed(
  7802. user_id=toast_uid,
  7803. queue_item_id=item.id,
  7804. printer_id=item.printer_id,
  7805. reason="upload_failed",
  7806. )
  7807. except Exception:
  7808. pass
  7809. await self._power_off_if_needed(db, item)
  7810. return
  7811. # The printer took a file, so any run of refused uploads is over: the
  7812. # next refusal starts again at the shortest backoff, and notifies (#3210).
  7813. self._upload_refusals.pop(printer.id, None)
  7814. self._upload_refusal_notified.discard(printer.id)
  7815. # Parse AMS mapping if stored
  7816. ams_mapping = None
  7817. if item.ams_mapping:
  7818. try:
  7819. ams_mapping = json.loads(item.ams_mapping)
  7820. except json.JSONDecodeError:
  7821. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  7822. # Register as expected print so we don't create a duplicate archive
  7823. # Only applicable for archive-based prints
  7824. if archive:
  7825. from backend.app.main import register_expected_print
  7826. register_expected_print(
  7827. item.printer_id,
  7828. remote_filename,
  7829. archive.id,
  7830. ams_mapping=ams_mapping,
  7831. created_by_id=item.created_by_id,
  7832. cost_center_id=item.cost_center_id,
  7833. # The plate actually dispatched, not the queue item's raw
  7834. # column: on None, `register_expected_print` stores nothing,
  7835. # and `extract_filament_usage_from_3mf` then books every
  7836. # filament in the file rather than the one plate that printed.
  7837. plate_id=effective_plate_id,
  7838. )
  7839. # Registration happens before the print command by necessity (the
  7840. # printer can report the print before the send returns), so record
  7841. # what to undo if we never get as far as sending. `_dispatch_one`
  7842. # rolls back anything still pending here on every exit — exception,
  7843. # early return, or cancel winning the CAS below.
  7844. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  7845. # Propagate the queue item's owner into printer_manager so the
  7846. # print-complete callback can credit the user in the PrintLogEntry
  7847. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  7848. # items) or when the user clicks the manual-start button.
  7849. await self._propagate_owner_to_printer_manager(db, item)
  7850. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  7851. # This prevents phantom reprints if the backend crashes/restarts after the
  7852. # print command is sent but before the status update is committed.
  7853. # If we crash after this commit but before start_print(), the item will be
  7854. # in "printing" status without actually printing - but that's safer than
  7855. # accidentally reprinting the same file hours later.
  7856. #
  7857. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  7858. # initial pending read at the top of check_queue and this point) flips
  7859. # the row to "cancelled" in a separate session. Without the WHERE
  7860. # status='pending' clause, the unconditional update here would silently
  7861. # overwrite that cancellation and we'd ship the MQTT start_print below
  7862. # — printer obeys, user sees "I pressed cancel and the print started".
  7863. # rowcount==0 means the user won the race; bail out, best-effort delete
  7864. # the file we just uploaded, do NOT send start_print.
  7865. now_utc = datetime.now(timezone.utc)
  7866. billing_run_id = str(uuid.uuid4())
  7867. cas = await db.execute(
  7868. update(PrintQueueItem)
  7869. .where(PrintQueueItem.id == item.id)
  7870. .where(PrintQueueItem.status == "pending")
  7871. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  7872. )
  7873. await db.commit()
  7874. if cas.rowcount == 0:
  7875. logger.info(
  7876. "Queue item %s no longer pending at print-command time "
  7877. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  7878. item.id,
  7879. )
  7880. try:
  7881. await delete_file_async(
  7882. printer.ip_address,
  7883. printer.access_code,
  7884. remote_path,
  7885. socket_timeout=ftp_timeout,
  7886. printer_model=printer.model,
  7887. )
  7888. except Exception as cleanup_err:
  7889. logger.debug(
  7890. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  7891. item.id,
  7892. cleanup_err,
  7893. )
  7894. try:
  7895. await ws_manager.send_queue_item_failed(
  7896. user_id=toast_uid,
  7897. queue_item_id=item.id,
  7898. printer_id=item.printer_id,
  7899. reason="cancelled_mid_dispatch",
  7900. )
  7901. except Exception:
  7902. pass
  7903. return
  7904. # Sync the in-memory item so subsequent code that reads item.status /
  7905. # item.started_at sees the values we just persisted.
  7906. item.status = "printing"
  7907. item.started_at = now_utc
  7908. item.billing_run_id = billing_run_id
  7909. if archive is not None:
  7910. archive.billing_run_id = billing_run_id
  7911. # Legacy transaction deletion used an archive-wide skip flag.
  7912. # A newly dispatched run has its own UUID/tombstone, so it must be
  7913. # billable independently of any older deleted run on this archive.
  7914. archive.wallet_charge_skipped = False
  7915. # Persist before MQTT send so completion and restart recovery can
  7916. # always recover the internal billing identity.
  7917. await db.commit()
  7918. for cleanup_path in cleanup_disk_paths:
  7919. try:
  7920. if cleanup_path.exists():
  7921. cleanup_path.unlink()
  7922. except OSError as cleanup_err:
  7923. logger.warning(
  7924. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  7925. json.dumps(
  7926. {
  7927. "queue_item_id": item.id,
  7928. "path": str(cleanup_path),
  7929. "error": str(cleanup_err),
  7930. },
  7931. sort_keys=True,
  7932. ),
  7933. )
  7934. # Clear the awaiting-plate-clear flag now that we're starting a new print
  7935. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  7936. # #1898: with the opt-in default-good setting, moving on to the next
  7937. # print resolves the previous print's unanswered outcome prompt as
  7938. # "good" — this path also covers the camera-based plate detection,
  7939. # which releases the gate by allowing dispatch rather than by an
  7940. # explicit acknowledgment. Rides on the dispatch transaction.
  7941. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  7942. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  7943. await resolve_pending_confirmation_as_good(db, item.printer_id)
  7944. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  7945. # Capture state before dispatch so the watchdog can detect whether the
  7946. # printer actually transitioned (#967). Also capture subtask_id so the
  7947. # watchdog can recognise "command landed but state hasn't flipped yet"
  7948. # on slow H2D transitions (#1078).
  7949. pre_status = printer_manager.get_status(item.printer_id)
  7950. pre_state = getattr(pre_status, "state", None) if pre_status else None
  7951. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  7952. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  7953. # #1721: respect the user's explicit timelapse choice. The #1397
  7954. # force-on at dispatch was removed because it caused per-layer nozzle
  7955. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  7956. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  7957. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  7958. # FINISH-state fallback — no need to force a video.
  7959. effective_timelapse = bool(item.timelapse)
  7960. # Nozzle-rack fallback (#2800). A job that never passed through the
  7961. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  7962. # dispatches with no nozzle field at all and chooses for itself — which
  7963. # is how a print levelled on one hotend and then printed on another,
  7964. # millimetres above the plate. Derive the per-slot extruder assignment
  7965. # from the file being dispatched.
  7966. #
  7967. # Done here rather than at queue time because this is the first point
  7968. # that knows both the actual printer and the actual file: an item can
  7969. # be created without a printer (model-based assignment), reassigned
  7970. # afterwards, or have its file swapped for a G-code-injected copy just
  7971. # above. Every queue-creation path — the print dialog, a bulk library
  7972. # add, the webhook, a pipeline run — is covered by the one call.
  7973. # Skipped when the item already carries a Bambu Studio capture: that
  7974. # one wins downstream anyway, so reading the 3MF again would be work
  7975. # thrown away on every dispatch.
  7976. # Rack position resolution (#1784), tried before the #2800 fallback
  7977. # below because it can express what that one cannot: a plate wanting a
  7978. # *different* hotend off the rack per filament group. The position per
  7979. # group is the operator's pick — the 3MF states it nowhere, proven by
  7980. # sending one plate twice with different picks and finding the two
  7981. # files identical bar float noise — so it is resolved here against the
  7982. # rack as it stands right now, after the upload, not at queue time.
  7983. resolved_nozzle_mapping = None
  7984. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  7985. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  7986. if rack_plan is not None:
  7987. try:
  7988. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  7989. except (json.JSONDecodeError, TypeError):
  7990. stored_choice = {}
  7991. logger.warning(
  7992. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  7993. item.id,
  7994. item.nozzle_rack_choice,
  7995. )
  7996. # JSON object keys are strings; the groups are ints.
  7997. choice: dict[int, int] = {}
  7998. for key, value in (stored_choice or {}).items():
  7999. try:
  8000. choice[int(key)] = int(value)
  8001. except (TypeError, ValueError):
  8002. continue
  8003. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8004. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8005. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8006. )
  8007. if resolved_nozzle_mapping is None and choice:
  8008. # An explicit pick that no longer holds stops the print. The
  8009. # operator named a hotend; printing from a different one is
  8010. # how a plate gets levelled on one nozzle and drawn with
  8011. # another, millimetres above the bed. Nothing has been sent
  8012. # to the printer yet, so failing here costs only the upload.
  8013. item.status = "failed"
  8014. item.error_message = (
  8015. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8016. "Edit the item to choose another position."
  8017. )
  8018. item.completed_at = datetime.now(timezone.utc)
  8019. await db.commit()
  8020. logger.warning(
  8021. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8022. item.id,
  8023. printer.name,
  8024. rack_error,
  8025. choice,
  8026. [slot.get("id") for slot in live_rack],
  8027. )
  8028. await notification_service.on_queue_job_failed(
  8029. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8030. printer_id=printer.id,
  8031. printer_name=printer.name,
  8032. reason=item.error_message,
  8033. db=db,
  8034. )
  8035. try:
  8036. await ws_manager.send_queue_item_failed(
  8037. user_id=toast_uid,
  8038. queue_item_id=item.id,
  8039. printer_id=item.printer_id,
  8040. reason="nozzle_rack_pick_stale",
  8041. )
  8042. except Exception:
  8043. pass # Best-effort — don't fail the error handler
  8044. # The file is already on the SD card by this point, and a
  8045. # 3MF left there is a phantom print waiting to be started
  8046. # from the touchscreen. Same cleanup the start_print
  8047. # failure path below does, for the same reason.
  8048. try:
  8049. await delete_file_async(
  8050. printer.ip_address,
  8051. printer.access_code,
  8052. remote_path,
  8053. printer_model=printer.model,
  8054. )
  8055. except Exception:
  8056. pass # Best-effort — don't fail the error handler
  8057. return
  8058. if resolved_nozzle_mapping is None:
  8059. # Nothing was picked and nothing could be assigned. Falls
  8060. # through to the #2800 path, which is what ran before this
  8061. # existed — strictly not worse than today.
  8062. logger.info(
  8063. "Queue item %s: no rack positions assignable (%s); falling back",
  8064. item.id,
  8065. rack_error,
  8066. )
  8067. else:
  8068. logger.info(
  8069. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8070. item.id,
  8071. resolved_nozzle_mapping,
  8072. rack_plan.slot_groups,
  8073. choice or "auto",
  8074. )
  8075. nozzle_slot_extruders = None
  8076. if (
  8077. not item.nozzle_mapping
  8078. and resolved_nozzle_mapping is None
  8079. and file_path is not None
  8080. and is_nozzle_rack_model(printer.model)
  8081. ):
  8082. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8083. if slot_extruders:
  8084. nozzle_slot_extruders = json.dumps(slot_extruders)
  8085. # Every filament this plate prints is on the external spool -> the print
  8086. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8087. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8088. # table", which is what held the reporter's P1S at Heatbed preheating
  8089. # for ten minutes before it gave up (#3087). The MQTT command builder
  8090. # already downgrades a mapping that is *only* external ([254]), but a
  8091. # multi-filament project pads the slots this plate does not print with
  8092. # -1 — BambuStudio's own convention — and down there a -1 is
  8093. # indistinguishable from a slot that never resolved, which must never be
  8094. # sent to the spool holder (#2589). Here the plate's filament list says
  8095. # which is which, so the answer is exact rather than a guess.
  8096. #
  8097. # Deliberately narrow: this fires only when every consumed slot is an
  8098. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8099. # alone and the firmware still rejects the print, exactly as today. And
  8100. # only for single-nozzle printers, mirroring the builder's own reconcile
  8101. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8102. # whether to use the AMS, so it is not ours to rewrite.
  8103. effective_use_ams = item.use_ams
  8104. if (
  8105. effective_use_ams
  8106. and ams_mapping
  8107. and file_path is not None
  8108. # Cheap gate before opening the file: with nothing on the spool
  8109. # holder anywhere in the mapping, no subset of it can be all
  8110. # external, so most dispatches never pay for the parse. The
  8111. # isinstance also keeps a malformed stored mapping (a bare number
  8112. # from a hand-edited row) failing where it always failed, in the
  8113. # command builder, rather than here.
  8114. and isinstance(ams_mapping, list)
  8115. and any(_is_external_tray(t) for t in ams_mapping)
  8116. and not _might_be_dual_nozzle(printer.model, pre_status)
  8117. ):
  8118. from backend.app.services.filament_requirements import extract_filament_requirements
  8119. consumed = _consumed_mapping_entries(
  8120. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8121. )
  8122. if consumed and all(_is_external_tray(t) for t in consumed):
  8123. effective_use_ams = False
  8124. logger.info(
  8125. "Queue item %s: every filament plate %s prints is on the external spool "
  8126. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8127. item.id,
  8128. effective_plate_id,
  8129. ams_mapping,
  8130. )
  8131. # A slot that lost its K-profile selection (a power cycle resets every
  8132. # slot to the default K) would print on the default. The idle check in
  8133. # the status handler normally restores it first, but nothing guarantees
  8134. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8135. # Never allowed to stop the print it is protecting.
  8136. try:
  8137. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8138. except Exception:
  8139. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8140. # Start the print with AMS mapping, plate_id and print options.
  8141. # nozzle_mapping rides through verbatim — JSON string captured from
  8142. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8143. # parses + injects it only for dual-nozzle models so a null on every
  8144. # other model is a transparent pass-through. The rack fallback is
  8145. # resolved down there too, where the live rack position is known.
  8146. started = printer_manager.start_print(
  8147. item.printer_id,
  8148. remote_filename,
  8149. plate_id=effective_plate_id,
  8150. ams_mapping=ams_mapping,
  8151. bed_levelling=item.bed_levelling,
  8152. flow_cali=item.flow_cali,
  8153. vibration_cali=item.vibration_cali,
  8154. layer_inspect=item.layer_inspect,
  8155. timelapse=effective_timelapse,
  8156. use_ams=effective_use_ams,
  8157. nozzle_offset_cali=item.nozzle_offset_cali,
  8158. nozzle_mapping=item.nozzle_mapping
  8159. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8160. nozzle_slot_extruders=nozzle_slot_extruders,
  8161. )
  8162. if started:
  8163. # The command is away, so the expectation is now legitimate and must
  8164. # survive. Anything still in this dict when _dispatch_one exits gets
  8165. # rolled back.
  8166. self._unconfirmed_expected_print.pop(item.id, None)
  8167. self._unconfirmed_budget_reservations.discard(item.id)
  8168. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8169. # target, chamber target, airduct heating) — the gcode owns
  8170. # heater/flap control from here. Clearing the pin prevents
  8171. # `_dispatch_one`'s finally from unwinding a live print.
  8172. self._preheat_pin.pop(item.printer_id, None)
  8173. self._preheat_pin_bed.pop(item.printer_id, None)
  8174. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8175. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8176. # status='processing' from upload start until the printer acked
  8177. # (or timed out). The frontend derives "Awaiting printer…" purely
  8178. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8179. # event would push the status chip out of 'PROCESSING' prematurely
  8180. # — which is exactly what the screenshot at #1625-followup
  8181. # complained about.
  8182. # Register the local 3MF in the cover-cache so /cover skips FTP
  8183. # (#1166 follow-up). file_path was resolved earlier from either the
  8184. # archive or the library file row.
  8185. if file_path is not None:
  8186. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8187. # Hold the printer against further dispatches until the watchdog
  8188. # confirms the printer transitioned (or until the hard timeout).
  8189. # Prevents multi-plate batches from triple-dispatching onto the
  8190. # same H2D Pro while it digests the first project_file (#1157).
  8191. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8192. # Watchdog: if the printer never transitions out of pre_state AND
  8193. # never advances subtask_id, the MQTT publish was accepted locally but
  8194. # didn't reach the printer (half-broken session — same shape as
  8195. # #887/#936). Revert the queue item so the next dispatch can pick it
  8196. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8197. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8198. # that would otherwise cause the item to re-dispatch as a reprint
  8199. # of the just-finished job (#1078).
  8200. if pre_state:
  8201. spawn_background_task(
  8202. self._watchdog_print_start(
  8203. item.id,
  8204. item.printer_id,
  8205. pre_state,
  8206. pre_subtask_id,
  8207. pre_gcode_file,
  8208. created_by_id=toast_uid,
  8209. ),
  8210. name=f"watchdog-print-start-{item.id}",
  8211. )
  8212. # Get estimated time for notification.
  8213. #
  8214. # This used to fall back to `library_file.print_time_seconds`, a column
  8215. # LibraryFile does not have — the print time it knows about lives in
  8216. # `file_metadata`. So a library print whose archive carried no parseable
  8217. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8218. # AttributeError right here, *after* the printer had already been sent
  8219. # the job: the started-notification never fired, and the exception
  8220. # unwound the whole queue pass, so every other printer still waiting to
  8221. # be dispatched on that tick silently missed its turn.
  8222. #
  8223. # The queue item caches the print time at creation ("Cached from
  8224. # archive/library"), which is the value this was reaching for.
  8225. estimated_time = None
  8226. if archive and archive.print_time_seconds:
  8227. estimated_time = archive.print_time_seconds
  8228. elif item.print_time_seconds:
  8229. estimated_time = item.print_time_seconds
  8230. # Send job started notification
  8231. await notification_service.on_queue_job_started(
  8232. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8233. printer_id=printer.id,
  8234. printer_name=printer.name,
  8235. db=db,
  8236. estimated_time=estimated_time,
  8237. )
  8238. # MQTT relay - publish queue job started
  8239. try:
  8240. from backend.app.services.mqtt_relay import mqtt_relay
  8241. await mqtt_relay.on_queue_job_started(
  8242. job_id=item.id,
  8243. filename=filename,
  8244. printer_id=printer.id,
  8245. printer_name=printer.name,
  8246. printer_serial=printer.serial_number,
  8247. )
  8248. except Exception:
  8249. pass # Don't fail if MQTT fails
  8250. else:
  8251. # Clean up uploaded file from SD card to prevent phantom prints
  8252. try:
  8253. await delete_file_async(
  8254. printer.ip_address,
  8255. printer.access_code,
  8256. remote_path,
  8257. printer_model=printer.model,
  8258. )
  8259. except Exception:
  8260. pass # Best-effort — don't fail the error handler
  8261. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8262. # state can flip from idle to active in the window between the
  8263. # pre-dispatch check above and this publish (the FTP upload takes
  8264. # seconds); start_print() then refuses to send project_file to the
  8265. # now-busy printer and returns False. Failing the item here would be
  8266. # wrong — the printer is fine, it is simply busy — so revert to
  8267. # pending and let a later tick dispatch it once the printer is idle,
  8268. # exactly like the pre-dispatch guard. Only a start_print() False on
  8269. # an idle/unknown printer is a genuine command failure.
  8270. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8271. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8272. logger.info(
  8273. "Queue item %s: printer %s became busy (state=%s) before the start "
  8274. "command was sent — deferring, reverting item to pending (#2598)",
  8275. item.id,
  8276. item.printer_id,
  8277. post_dispatch_state,
  8278. )
  8279. item.status = "pending"
  8280. item.started_at = None
  8281. await db.commit()
  8282. return
  8283. # Print command failed - revert status
  8284. item.status = "failed"
  8285. item.error_message = "Failed to send print command to printer"
  8286. item.completed_at = datetime.now(timezone.utc)
  8287. await db.commit()
  8288. logger.error(
  8289. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8290. f"printer_manager.start_print() returned False. "
  8291. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8292. f"Check printer status and backend logs for details."
  8293. )
  8294. # Send failure notification
  8295. await notification_service.on_queue_job_failed(
  8296. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8297. printer_id=printer.id,
  8298. printer_name=printer.name,
  8299. reason="Failed to send print command to printer - check printer connection and status",
  8300. db=db,
  8301. )
  8302. try:
  8303. await ws_manager.send_queue_item_failed(
  8304. user_id=toast_uid,
  8305. queue_item_id=item.id,
  8306. printer_id=item.printer_id,
  8307. reason="start_command_failed",
  8308. )
  8309. except Exception:
  8310. pass
  8311. await self._power_off_if_needed(db, item)
  8312. @staticmethod
  8313. async def _watchdog_print_start(
  8314. queue_item_id: int,
  8315. printer_id: int,
  8316. pre_state: str,
  8317. pre_subtask_id: str | None = None,
  8318. pre_gcode_file: str | None = None,
  8319. timeout: float = 90.0,
  8320. phase_b_timeout: float = 180.0,
  8321. poll_interval: float = 3.0,
  8322. created_by_id: int | None = None,
  8323. ) -> None:
  8324. """Revert a queue item if the printer never acknowledges the start command.
  8325. Bambuddy optimistically marks the queue item as "printing" right after the
  8326. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8327. Phase A (up to ``timeout``): wait for either an active-state transition
  8328. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8329. primary signal; subtask_id advance handles the H2D case where state can
  8330. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8331. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8332. was lost on a half-broken session (#887/#936) — revert and force
  8333. reconnect (the #967 recovery path).
  8334. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8335. alone): keep watching for the active-state transition. subtask_id alone
  8336. proves the file landed but not that the printer started — and a printer
  8337. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8338. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8339. used to leave the queue item stuck in 'printing' forever because the
  8340. old watchdog returned success as soon as subtask_id advanced. If Phase
  8341. B times out, revert the queue item so the user can retry without
  8342. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8343. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8344. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8345. transitions that also don't emit an early subtask_id tick.
  8346. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8347. refuses to verify our commands will never start this job or any other,
  8348. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8349. burns an upload slot the rest of the farm is queued behind — that path
  8350. is for a printer that might still come good, which this one cannot
  8351. (#2732). It fails the item on the spot with the actual reason instead.
  8352. """
  8353. last_status = None
  8354. landed_on_subtask = False
  8355. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8356. # every push carrying an `hms` key, so the fault can come and go between
  8357. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8358. command_rejected = False
  8359. # Latched for the same reason as command_rejected: drying can finish, or
  8360. # be stopped by the user, part-way through the dispatch window. Seeing it
  8361. # once is what matters — it is the state the printer was in when it
  8362. # declined to start (#2758).
  8363. drying_ams_ids: list[int] = []
  8364. deadline = time.monotonic() + timeout
  8365. while time.monotonic() < deadline:
  8366. await asyncio.sleep(poll_interval)
  8367. status = printer_manager.get_status(printer_id)
  8368. if not status:
  8369. # Printer disconnected — don't mess with the DB. Drop the
  8370. # in-memory dispatch hold too so a fresh dispatch can retry
  8371. # once the printer comes back; the hard timeout would
  8372. # otherwise hold the printer unnecessarily.
  8373. scheduler._release_dispatch_hold(printer_id)
  8374. return
  8375. last_status = status
  8376. if status.state in _ACTIVE_PRINT_STATES:
  8377. # Printer is actively processing the job — release the
  8378. # post-dispatch hold so the next pending item for this printer
  8379. # can be evaluated normally. We do NOT accept arbitrary state
  8380. # transitions: a printer going FINISH -> IDLE (user dismissed
  8381. # the post-print prompt without accepting our project_file)
  8382. # would otherwise look like "command landed" and leave the
  8383. # queue item stuck in 'printing' forever (#1370).
  8384. scheduler._release_dispatch_hold(printer_id)
  8385. try:
  8386. await ws_manager.send_queue_item_acked(
  8387. user_id=created_by_id,
  8388. queue_item_id=queue_item_id,
  8389. printer_id=printer_id,
  8390. )
  8391. except Exception:
  8392. pass
  8393. return
  8394. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8395. # Checked only after the active-state exit above: a stale HMS left
  8396. # over from an earlier job must never abort a print that is visibly
  8397. # running. An actually-refused command leaves the printer idle, so
  8398. # this ordering costs the detection nothing.
  8399. if _mqtt_commands_rejected(status):
  8400. command_rejected = True
  8401. break
  8402. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8403. # Phase A exit — printer accepted the file (subtask_id flipped
  8404. # to our submission id). Don't return yet: the printer may
  8405. # have accepted the command but never actually start (e.g.
  8406. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8407. # B watches for the active-state transition.
  8408. landed_on_subtask = True
  8409. break
  8410. if landed_on_subtask and not command_rejected:
  8411. phase_b_deadline = time.monotonic() + phase_b_timeout
  8412. while time.monotonic() < phase_b_deadline:
  8413. await asyncio.sleep(poll_interval)
  8414. status = printer_manager.get_status(printer_id)
  8415. if not status:
  8416. scheduler._release_dispatch_hold(printer_id)
  8417. return
  8418. last_status = status
  8419. if status.state in _ACTIVE_PRINT_STATES:
  8420. scheduler._release_dispatch_hold(printer_id)
  8421. try:
  8422. await ws_manager.send_queue_item_acked(
  8423. user_id=created_by_id,
  8424. queue_item_id=queue_item_id,
  8425. printer_id=printer_id,
  8426. )
  8427. except Exception:
  8428. pass
  8429. return
  8430. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8431. # Same ordering rule as Phase A: a running print wins over a
  8432. # lingering HMS.
  8433. if _mqtt_commands_rejected(status):
  8434. command_rejected = True
  8435. break
  8436. # No active-state transition. Revert the item so the scheduler can retry.
  8437. # Drop the in-memory hold so the retry isn't blocked by it.
  8438. scheduler._release_dispatch_hold(printer_id)
  8439. # Logged on every failed dispatch window, not just the last one, so a
  8440. # support bundle shows the correlation from the first attempt rather than
  8441. # only after the retry budget is spent (#2758).
  8442. if drying_ams_ids:
  8443. logger.info(
  8444. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8445. queue_item_id,
  8446. printer_id,
  8447. ", ".join(str(i) for i in drying_ams_ids),
  8448. )
  8449. # Four outcomes from the revert attempt, each routed differently:
  8450. # "reverted": row flipped from printing -> pending, run recovery
  8451. # "gave_up": same, but the retry budget is spent — row failed
  8452. # rather than pending, so it stops going round again
  8453. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8454. # on_print_complete or user). Skip recovery entirely
  8455. # — the print clearly landed somewhere even if the
  8456. # watchdog didn't see the active-state transition.
  8457. # "revert_failed": SQLite contention exhausted retries. Still run
  8458. # recovery so the MQTT session gets a fresh client_id
  8459. # on the half-broken-session path.
  8460. #
  8461. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8462. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8463. # the watchdog again. For a printer that is genuinely wedged that loop never
  8464. # ends — the reporter had one printer "since this morning still not launch"
  8465. # — and each lap also consumes an upload slot that the other printers in the
  8466. # farm are waiting on. Retrying is right; retrying forever is not.
  8467. async def _do_revert(db):
  8468. item = await db.get(PrintQueueItem, queue_item_id)
  8469. if not item or item.status != "printing":
  8470. return "already_moved_on"
  8471. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8472. item.started_at = None
  8473. # Charge the attempt to the candidate that was actually dispatched, so
  8474. # a cross-model item (#671) reaches for its other file next lap instead
  8475. # of retrying the printer that just failed to start. Matched by file
  8476. # because that is what the resolver copied onto the row.
  8477. if item.library_file_id is not None:
  8478. await db.execute(
  8479. update(PrintQueueVariant)
  8480. .where(PrintQueueVariant.queue_item_id == item.id)
  8481. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8482. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8483. )
  8484. if command_rejected:
  8485. # No retry budget for this one: the printer refused to verify the
  8486. # command, and re-uploading the same 3MF to the same printer will
  8487. # be refused the same way. Fail now with the fix rather than after
  8488. # three laps of a message about SD cards (#2732).
  8489. item.status = "failed"
  8490. item.error_message = (
  8491. "The printer rejected the print command: MQTT command verification failed "
  8492. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8493. "then start the job again."
  8494. )
  8495. item.completed_at = datetime.now(timezone.utc)
  8496. await db.commit()
  8497. return "command_rejected"
  8498. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8499. item.status = "failed"
  8500. if drying_ams_ids:
  8501. # #2758: the generic message below sent the reporter looking
  8502. # at the SD card while the actual obstacle — AMS units in a
  8503. # drying cycle — was on screen the whole time. Name what we
  8504. # observed and let the user judge it; Bambuddy does not stop
  8505. # the cycle itself, because on this hardware drying can run
  8506. # alongside a print and stopping it may not be the fix.
  8507. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8508. item.error_message = (
  8509. f"The printer accepted the file but never started printing, after "
  8510. f"{item.dispatch_attempts} attempts. {units} "
  8511. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8512. f"some printers refuse to begin a print while an AMS is in a drying "
  8513. f"cycle, and an AMS drying without its external power supply can also "
  8514. f"leave too little power for the start-of-print calibration. Stop the "
  8515. f"drying, or connect the AMS power supply, and start the job again."
  8516. )
  8517. else:
  8518. item.error_message = (
  8519. f"The printer accepted the file but never started printing, after "
  8520. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8521. f"prompt or error, confirm its SD card is readable, and start the job again."
  8522. )
  8523. item.completed_at = datetime.now(timezone.utc)
  8524. await release_budget_reservation(
  8525. db,
  8526. source_type="print_queue",
  8527. source_id=item.id,
  8528. status="released",
  8529. )
  8530. await db.commit()
  8531. return "gave_up"
  8532. item.status = "pending"
  8533. await db.commit()
  8534. return "reverted"
  8535. try:
  8536. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8537. except Exception as e:
  8538. logger.warning(
  8539. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8540. "scheduler may keep treating this item as in-flight",
  8541. queue_item_id,
  8542. printer_id,
  8543. e,
  8544. )
  8545. revert_outcome = "revert_failed"
  8546. if revert_outcome == "already_moved_on":
  8547. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8548. # other path) already moved the item past 'printing', don't run the
  8549. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8550. # session breaks ongoing prints on the same printer.
  8551. return
  8552. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8553. if revert_outcome == "command_rejected":
  8554. logger.error(
  8555. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8556. "failed) — the print command was rejected, not lost. Failing the item "
  8557. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8558. queue_item_id,
  8559. printer_id,
  8560. HMS_MQTT_VERIFY_FAILED,
  8561. )
  8562. await scheduler._notify_dispatch_gave_up(
  8563. queue_item_id,
  8564. printer_id,
  8565. created_by_id,
  8566. reason="Printer rejected the print command (MQTT command verification failed)",
  8567. )
  8568. # Same reasoning as the landed_on_subtask path below: the file is on
  8569. # the printer and a forced reconnect would only add 0500_4003 to a
  8570. # problem that has nothing to do with the MQTT session (#1150).
  8571. return
  8572. if revert_outcome == "gave_up":
  8573. logger.error(
  8574. "Queue item %s: printer %d never started the print after %d dispatch "
  8575. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8576. "re-uploading it again (#2555)",
  8577. queue_item_id,
  8578. printer_id,
  8579. DISPATCH_MAX_ATTEMPTS,
  8580. total_timeout,
  8581. )
  8582. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8583. elif revert_outcome == "reverted":
  8584. if landed_on_subtask:
  8585. logger.warning(
  8586. "Queue item %s: printer %d accepted project_file (subtask_id "
  8587. "advanced) but never transitioned to an active state within "
  8588. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8589. "for retry (#1678)",
  8590. queue_item_id,
  8591. printer_id,
  8592. total_timeout,
  8593. )
  8594. else:
  8595. logger.warning(
  8596. "Queue item %s: printer %d did not respond to print command within "
  8597. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8598. "for retry (#967)",
  8599. queue_item_id,
  8600. printer_id,
  8601. timeout,
  8602. pre_state,
  8603. pre_subtask_id,
  8604. )
  8605. # Phase B was entered iff subtask_id advanced, which means the
  8606. # project_file landed on the printer. A forced reconnect at this point
  8607. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8608. # skip the recovery entirely.
  8609. if landed_on_subtask:
  8610. return
  8611. # Phase A timeout path: if the printer's gcode_file changed since
  8612. # pre-dispatch, the project_file command landed and the printer is
  8613. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8614. # If gcode_file is unchanged, the publish was silently swallowed
  8615. # (#887/#936) and force_reconnect recovery is what we want.
  8616. client = printer_manager.get_client(printer_id)
  8617. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8618. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8619. if publish_landed:
  8620. logger.warning(
  8621. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8622. "received the command and is parsing slowly. Skipping forced "
  8623. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8624. queue_item_id,
  8625. current_gcode_file,
  8626. pre_gcode_file,
  8627. )
  8628. elif client and hasattr(client, "force_reconnect_stale_session"):
  8629. client.force_reconnect_stale_session(
  8630. f"queue print command unacknowledged after {timeout:.0f}s "
  8631. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8632. )
  8633. # Global scheduler instance
  8634. scheduler = PrintScheduler()