print_scheduler.py 502 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import derive_remote_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. select_plate_gcode_name,
  90. )
  91. logger = logging.getLogger(__name__)
  92. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  93. """Human slot name for an assignment tuple, in the spelling already in use.
  94. Composed from the notification side's own pair rather than spelled out again
  95. here. The hand-rolled version this replaces got three real slot kinds wrong:
  96. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  97. ``chr(191)``; both externals collapsed to one label, because an external
  98. assignment stores ams_id 255 with tray_id picking left or right
  99. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  100. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  101. Naming the same slot two ways is its own defect once an alert and the
  102. Inventory page are meant to be talking about the same tray, so this defers
  103. rather than adding a fifth spelling.
  104. """
  105. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  106. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  107. # interval: the fast path runs every 3 s while an upload is in flight, and a
  108. # low spool does not need answering at that resolution (#2913).
  109. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  110. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  111. # days, so a finer check would only repeat the same answer.
  112. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  113. # The settings row that holds which stock alerts have already been sent (#2955).
  114. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  115. # The Inventory page asks for this many usage records and the forecast panel
  116. # builds its rates from them; the alert reads the same window so the two agree.
  117. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  118. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  119. """Remaining filament as a percentage of the label weight.
  120. The same arithmetic the Inventory page's Low Stock count uses, and it works
  121. unchanged in both inventory modes: internal spools store ``weight_used``
  122. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  123. ``remaining_weight`` so the shape matches. Returns None when there is no
  124. label weight to be a percentage of -- a spool that cannot say how full it
  125. started cannot say how empty it is.
  126. """
  127. if not label_weight or label_weight <= 0:
  128. return None
  129. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  130. return remaining / float(label_weight) * 100.0
  131. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  132. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  133. # byte gate) from before the scheduler unification. Time gate keeps small
  134. # files from going silent (a single 8 KB chunk fires once and that's it);
  135. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  136. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  137. # sub-200 ms files.
  138. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  139. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  140. # How far back chamber temperature samples are retained. 2h comfortably spans
  141. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  142. # before the next print.
  143. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  144. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  145. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  146. # who clear plates promptly will want far less than this; it is deliberately
  147. # the cautious end, since the cost of it being too short is only a re-soak.
  148. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  149. # Max acceptable gap between two consecutive chamber samples before we treat
  150. # the older one as belonging to a separate observation run (printer went
  151. # offline and came back). Above ~30s cadence with a safety margin.
  152. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  153. # How long the chamber must read below target before we accept that it really
  154. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  155. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  156. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  157. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  158. # sub-target readings are therefore a door opening or noise, not lost soak,
  159. # and a plate swap (exactly when keep-warm is running) produces one. Six
  160. # minutes clears the longest such artifact observed (~5 min once bracketed by
  161. # its neighbouring samples) and still sits far below the 23-minute floor for
  162. # real cooling.
  163. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  164. # How often the preheat stage re-checks that the item it is heating for still
  165. # wants to be printed. Cancelling only writes `status` to the database — it
  166. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  167. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  168. # and the printer stays in `busy_printers`, blocking every other queued item
  169. # behind a print that is not happening.
  170. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  171. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  172. _AIRDUCT_MODE_COOLING = 0
  173. _AIRDUCT_MODE_HEATING = 1
  174. # How long a queue row may stay 'printing' while its printer sits in a terminal
  175. # state before the scheduler closes it itself (#2829).
  176. #
  177. # A real completion arrives within seconds of the printer going terminal, so
  178. # five minutes is far outside the normal path — this only ever sees a row whose
  179. # completion was refused or never delivered. It is the whole cost of the
  180. # failure to the user, though: a stranded row blocks every later job for that
  181. # printer, so it should not be raised without reason.
  182. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  183. # gcode_state values that mean the print is over, mapped to the queue status
  184. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  185. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  186. # which the queue calls cancelled) so a recovered row cannot disagree with one
  187. # closed by the normal path.
  188. _TERMINAL_STATE_QUEUE_STATUS = {
  189. "FINISH": "completed",
  190. "FAILED": "failed",
  191. "IDLE": "cancelled",
  192. }
  193. def _terminal_queue_status(state) -> str | None:
  194. """Queue status implied by *state*, or None if the print is not over.
  195. None for a disconnected printer as well as a busy one: a printer we are not
  196. talking to has a stale ``state`` field that proves nothing about what it is
  197. doing now.
  198. """
  199. if state is None or not getattr(state, "connected", False):
  200. return None
  201. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  202. @dataclass
  203. class _KeepWarmEntry:
  204. """Per-printer keep-warm state.
  205. - ``started``: monotonic time when keep-warm first fired for this printer.
  206. Used by the max-duration timeout.
  207. - ``held_target``: last bed target we successfully published. On release
  208. we only send bed-off when firmware still reports this value, so a user
  209. or subsequent print that changed the target isn't clobbered.
  210. - ``expired``: latched True when the max-duration timeout fires. Prevents
  211. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  212. release sweep drops the entry entirely once the printer leaves the
  213. candidate set.
  214. """
  215. started: float
  216. held_target: int
  217. expired: bool = False
  218. # Auto-drying re-arm guards (#2770).
  219. #
  220. # An AMS reports HIGHER relative humidity while it is warm than once it has
  221. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  222. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  223. # threshold set inside that band therefore cannot be satisfied while the box is
  224. # hot, and the firmware is free to end a cycle whenever it decides the filament
  225. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  226. # the threshold and arms another cycle. The reporter's log has five 12-hour
  227. # cycles armed inside four hours, one of them six seconds after the previous
  228. # ended.
  229. #
  230. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  231. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  232. # manual or firmware-run dry is untouched.
  233. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  234. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  235. # Sustained-humidity wait (#2518): an above-threshold streak is only
  236. # "continuous" if some pass observed it within the gap ceiling. A unit that
  237. # goes unobserved longer (print running, printer disconnected, sensor silent)
  238. # restarts its streak rather than inheriting a stale one. The ceiling is
  239. # derived from the scheduler cadence — four missed passes — with this floor so
  240. # a fast-polling configuration does not void streaks on a single hiccup.
  241. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  242. # How long a finished scheduled drying row is kept before it is pruned.
  243. SCHEDULED_DRYING_RETENTION_DAYS = 7
  244. # How often that prune actually runs. The check itself is called on every queue
  245. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  246. # write transaction, which SQLite serialises against every other writer. Rows
  247. # only become prunable a week after they finish, so anything short of hourly is
  248. # paying that cost for nothing.
  249. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  250. class _UploadProgressBridge:
  251. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  252. ``upload_file_async`` runs the FTP transfer in an executor thread and
  253. invokes its ``progress_callback`` from that thread, so the callback
  254. body cannot ``await`` directly. This bridge captures the asyncio loop
  255. at construction (on the scheduler thread) and uses
  256. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  257. matches the legacy background_dispatch.py path 1:1 so the toast feels
  258. identical to the pre-#1625 experience.
  259. Failures inside the emit are swallowed — progress is a UX nicety, the
  260. upload itself must not fail because of a WS hiccup.
  261. """
  262. def __init__(self, user_id: int | None, queue_item_id: int):
  263. self._user_id = user_id
  264. self._queue_item_id = queue_item_id
  265. try:
  266. self._loop = asyncio.get_running_loop()
  267. except RuntimeError:
  268. self._loop = None
  269. self._last_emit_bytes = 0
  270. self._last_emit_monotonic = 0.0
  271. self._has_emitted = False
  272. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  273. if self._loop is None or total_bytes <= 0:
  274. return
  275. now = time.monotonic()
  276. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  277. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  278. # the four matter most: first-call so the user sees something even
  279. # for sub-chunk-size files; uploaded >= total so the bar locks at
  280. # 100% even when the throttle would otherwise eat it.
  281. should_emit = (
  282. not self._has_emitted
  283. or bytes_transferred >= total_bytes
  284. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  285. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  286. )
  287. if not should_emit:
  288. return
  289. self._has_emitted = True
  290. self._last_emit_bytes = bytes_transferred
  291. self._last_emit_monotonic = now
  292. try:
  293. asyncio.run_coroutine_threadsafe(
  294. ws_manager.send_queue_item_upload_progress(
  295. user_id=self._user_id,
  296. queue_item_id=self._queue_item_id,
  297. bytes_transferred=bytes_transferred,
  298. total_bytes=total_bytes,
  299. ),
  300. self._loop,
  301. )
  302. except Exception:
  303. pass # progress is best-effort, never block the upload
  304. # Bambu firmware states that mean the project_file has actually been accepted
  305. # and the printer is now processing / running / paused mid-print. Used by the
  306. # dispatch watchdog (#1370): a transition into one of these states means the
  307. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  308. # a post-print prompt) is NOT a valid "command landed" signal even though the
  309. # state value did change. SLICING is included because some firmwares park
  310. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  311. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  312. # How many times the start-watchdog may revert an item to 'pending' before it
  313. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  314. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  315. # both never recovers and starves the other printers of dispatch slots. Three
  316. # is chosen to clear the transient causes the watchdog already recovers from —
  317. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  318. # force-reconnect on the very next attempt — while still bounding the loop.
  319. DISPATCH_MAX_ATTEMPTS = 3
  320. # Upload failures that mean the file never reached the printer's storage: the
  321. # file service refused or never answered (#3210). These put the item back in
  322. # the queue instead of failing it, because nothing about the job is wrong --
  323. # and failing it left the printer idle, so the next pass handed it the next
  324. # item, which failed the same way. One P2S whose file service was out of
  325. # connection slots ate 43 queued jobs in ten minutes that way.
  326. #
  327. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  328. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  329. # and an upload that overran its deadline -- each of those would fail the same
  330. # way on every retry.
  331. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  332. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  333. )
  334. # How long a printer whose upload was put back stays out of dispatch (#3210).
  335. # The first window matches the FTP client's own handshake cool-off, so the
  336. # retry lands after the client would talk to the printer again anyway. Each
  337. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  338. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  339. # five connection attempts and a page of log. A successful upload resets it.
  340. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  341. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  342. def _upload_backoff_seconds(refusals: int) -> int:
  343. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  344. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  345. @dataclass(slots=True)
  346. class _ModelCandidate:
  347. """One (file, printer model) pair the model-based matcher may try.
  348. Model-based assignment used to have exactly one of these per item, held
  349. directly in the item's own columns. Cross-model queue items (#671) have
  350. several, held in ``print_queue_variants``. Both shapes are normalised into
  351. this so the matching, the cross-model gate and the waiting-reason handling
  352. are written once and an item without variants provably takes the same path
  353. it took before variants existed.
  354. ``variant`` is None for the item's own columns and set for a real variant
  355. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  356. item once that candidate wins.
  357. """
  358. target_model: str | None
  359. sliced_for: str | None
  360. required_filament_types: str | None
  361. filament_overrides: str | None
  362. variant: "PrintQueueVariant | None" = None
  363. def _sliced_for_model(archive, library_file) -> str | None:
  364. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  365. if archive is not None:
  366. return archive.sliced_for_model
  367. if library_file is not None and library_file.file_metadata:
  368. return library_file.file_metadata.get("sliced_for_model")
  369. return None
  370. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  371. """The filament a candidate needs, as ``(types, overrides)``.
  372. Both columns are JSON text written by the slicer step. Malformed content is
  373. treated as no constraint rather than as an error: a job whose overrides
  374. cannot be parsed still prints, it just gets no filament-based narrowing.
  375. Overrides carry their own types, so the returned type list is the union of
  376. the two — an override on one slot must not drop the requirements of the
  377. slots it says nothing about.
  378. Shared by the matcher and by the smart-plug wake step so both ask a printer
  379. for the same filament (#2876). Waking a printer the matcher would then
  380. reject on colour is the bug this exists to prevent.
  381. """
  382. required_types = None
  383. if candidate.required_filament_types:
  384. try:
  385. required_types = json.loads(candidate.required_filament_types)
  386. except json.JSONDecodeError:
  387. pass
  388. filament_overrides = None
  389. if candidate.filament_overrides:
  390. try:
  391. filament_overrides = json.loads(candidate.filament_overrides)
  392. except json.JSONDecodeError:
  393. pass
  394. effective_types = required_types
  395. if filament_overrides:
  396. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  397. if override_types:
  398. effective_types = sorted(set(required_types or []) | set(override_types))
  399. return effective_types, filament_overrides
  400. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  401. """Whether ``item`` was competing for the printer another item just took.
  402. The SJF starvation guard marks a job as jumped when a shorter one lower in
  403. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  404. compete for the same printer, so the guard has to look across both lanes
  405. (#3200); looking only inside the dispatched item's own lane let a stream of
  406. short model-based jobs hold a longer pinned job back indefinitely.
  407. Location filters are not checked: over-marking only lifts an item that was
  408. going to wait anyway, while under-marking is the starvation this prevents.
  409. """
  410. if item.printer_id is not None:
  411. return item.printer_id == printer_id
  412. if not printer_model:
  413. return False
  414. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  415. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  416. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  417. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  418. """Candidate files for ``item``, best first.
  419. An item with no variant rows yields exactly one candidate built from its own
  420. columns — the pre-#671 behaviour, unchanged.
  421. Variants come back least-attempted first, ties broken by the user's
  422. ``position``. On the first pass every count is zero, so this is purely the
  423. user's priority order. After a start-watchdog bounce the printer that failed
  424. drops behind, so the next lap tries the other machine rather than spending the
  425. item's whole retry budget on the one that is wedged. Once every candidate has
  426. been tried equally often they cycle again, which keeps the item-level
  427. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  428. still gives up, it just does not give up without trying them.
  429. """
  430. if not item.variants:
  431. if not item.archive_id and not item.library_file_id:
  432. # Nothing to print at all. Dispatching would fail deep in the upload
  433. # on "No archive_id or library_file_id"; the caller holds the item
  434. # with an explanation instead.
  435. return []
  436. return [
  437. _ModelCandidate(
  438. target_model=item.target_model,
  439. sliced_for=_sliced_for_model(item.archive, item.library_file),
  440. required_filament_types=item.required_filament_types,
  441. filament_overrides=item.filament_overrides,
  442. )
  443. ]
  444. # Drop candidates whose file is gone or in the trash. Both are reachable and
  445. # neither is covered by the schema: library deletes are soft (the row lives
  446. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  447. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  448. # fires there and a hard delete leaves the variant row pointing at nothing.
  449. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  450. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  451. return [
  452. _ModelCandidate(
  453. target_model=v.target_model,
  454. sliced_for=_sliced_for_model(None, v.library_file),
  455. required_filament_types=v.required_filament_types,
  456. filament_overrides=v.filament_overrides,
  457. variant=v,
  458. )
  459. for v in ordered
  460. ]
  461. # Why a job for any printer of a model waits when every free one's last print
  462. # failed. The queue page matches it to offer Resume for the model.
  463. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  464. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  465. """Fold one waiting reason per candidate into a single line for the item.
  466. A cross-model item produces a reason per candidate, and pasting them
  467. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  468. — on which machine?). Each reason is prefixed with its model, except in the
  469. single-candidate case where the item already displays its target model and
  470. the prefix would be noise.
  471. Identical reasons collapse rather than repeat, so three idle-less models
  472. read as one clause.
  473. When *every* candidate is merely busy the parts are joined with the ``" | "``
  474. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  475. unprefixed. That case must keep testing busy-only: a fleet that is simply
  476. printing needs no user action, and labelling the clauses would turn each pass
  477. over a two-model item into a "job waiting" notification.
  478. """
  479. reasons = [(model, reason) for model, reason in per_model if reason]
  480. if not reasons:
  481. return None
  482. if len(reasons) == 1:
  483. return reasons[0][1]
  484. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  485. if len(distinct) == 1:
  486. return distinct[0]
  487. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  488. return " | ".join(distinct)
  489. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  490. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  491. """Human label for the models an item is waiting on ("H2S or H2C").
  492. Notifications take a single target model. For a cross-model item the item's
  493. own ``target_model`` is whichever variant happens to be first, which reads as
  494. a lie once it is the H2C that actually runs — so name all of them.
  495. """
  496. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  497. if not models:
  498. return None
  499. return " or ".join(models)
  500. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  501. """True if ``mapping`` is a non-empty list whose every entry is the
  502. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  503. Such a mapping is a bug artifact: a frontend status-load race can serialize
  504. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  505. recomputed from live status at dispatch rather than trusted, otherwise it
  506. reaches the print command and is silently downgraded to external-spool mode.
  507. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  508. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  509. explicit external selection (``>= 254``) is NOT unresolved either — those
  510. keep their meaning.
  511. """
  512. if not isinstance(mapping, list) or not mapping:
  513. return False
  514. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  515. def _is_tray_id(value: object) -> bool:
  516. """True when ``value`` can be read as a global tray ID.
  517. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  518. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  519. against whatever happens to be loaded there.
  520. """
  521. return isinstance(value, int) and not isinstance(value, bool)
  522. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  523. # stages an item (#2799). The manual_start branch clears every other reason on
  524. # a staged item (#3074); this one is the reason it was staged, so it stays.
  525. _UNMATCHED_HOLD_PREFIX = "Needs "
  526. # How often an "any model" job held for low filament looks for another printer
  527. # of its model that has enough (#3137). Each look matches its filament on every
  528. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  529. _SHORT_HOLD_RECHECK_SECONDS = 120
  530. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  531. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  532. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  533. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  534. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  535. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  536. for a filament this plate does not use. A slot past the end of the mapping
  537. is unresolved too.
  538. """
  539. unresolved = []
  540. for req in required:
  541. slot_id = req.get("slot_id") or 0
  542. if slot_id <= 0:
  543. continue
  544. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  545. if not _is_tray_id(tray) or tray < 0:
  546. unresolved.append(req)
  547. return unresolved
  548. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  549. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  550. # on `_mapping_is_all_unresolved`.
  551. _EXTERNAL_TRAY_ID_MIN = 254
  552. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  553. """The ``mapping`` entries for the slots this plate actually prints.
  554. ``required`` comes from ``extract_filament_requirements``, which drops any
  555. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  556. consumes, and one absent from it is padding. That distinction is why this
  557. decision lives here and not in the MQTT command builder: a ``-1`` in the
  558. mapping means either "this plate does not print filament N" or "we never
  559. worked out which tray", and only the plate's own filament list separates
  560. them. The builder sees both as the same byte, which is how a plate whose one
  561. printed filament sat on the external spool went out as `use_ams=true` with a
  562. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  563. with 07FF_8012 (#3087).
  564. Returns None whenever the two cannot be lined up — no mapping, no parsed
  565. requirements, or a requirement the mapping is too short to cover — so every
  566. caller falls back to existing behaviour rather than acting on a guess.
  567. """
  568. if not isinstance(mapping, list) or not mapping or not required:
  569. return None
  570. entries = []
  571. for filament in required:
  572. slot_id = filament.get("slot_id")
  573. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  574. # The mapping and the requirements disagree about how many filaments
  575. # the file has. They came from different reads, so judge nothing.
  576. return None
  577. entries.append(mapping[slot_id - 1])
  578. return entries or None
  579. def _is_external_tray(tray_id) -> bool:
  580. """True for an explicit external-spool selection (254/255), not for an
  581. unresolved slot and not for an AMS tray."""
  582. if tray_id is None:
  583. return False
  584. try:
  585. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  586. except (TypeError, ValueError):
  587. return False
  588. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  589. """Whether this printer could have two extruders, judged generously.
  590. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  591. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  592. why the MQTT command builder skips its own use_ams reconcile there. Anything
  593. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  594. with, external spools or not.
  595. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  596. behaviour it has always had, while a wrong "no" would rewrite a field that
  597. steers which nozzle prints. The model name is the first answer (it is what
  598. the command builder falls back to as well), then the same live evidence the
  599. dispatcher's extruder annotation uses — a second nozzle reporting a
  600. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  601. since a single-nozzle printer has exactly one.
  602. """
  603. if is_dual_nozzle_model(printer_model):
  604. return True
  605. nozzles = getattr(status, "nozzles", None) or []
  606. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  607. return True
  608. raw = getattr(status, "raw_data", None) or {}
  609. if raw.get("ams_extruder_map"):
  610. return True
  611. vt_trays = raw.get("vt_tray") or []
  612. return isinstance(vt_trays, list) and len(vt_trays) > 1
  613. def _int_or(value, default: int) -> int:
  614. """``int(value)``, or ``default`` when the field is missing or junk.
  615. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  616. the next — and a tray id that fails to parse must not take the whole
  617. derivation down with it.
  618. """
  619. try:
  620. return int(value)
  621. except (TypeError, ValueError):
  622. return default
  623. # What a queue job's dispatch is worked out from, and an edit can change.
  624. _DISPATCH_INPUTS = (
  625. "printer_id",
  626. "status",
  627. "ams_mapping",
  628. "plate_id",
  629. "filament_overrides",
  630. "skip_filament_check",
  631. "target_model",
  632. "target_location",
  633. )
  634. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  635. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  636. The pass works on the jobs as loaded at its start, and it may have waited
  637. since: a plug powering a printer on takes minutes. A job edited meanwhile
  638. (moved to another printer, given a mapping or another plate, cancelled)
  639. is left to the next pass, which reads it fresh: deciding from the stale
  640. copy would overwrite the edit, or send the job where it no longer goes.
  641. The query flushes the pass's own pending changes first, so those don't
  642. count as edits.
  643. """
  644. row = (
  645. await db.execute(
  646. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  647. )
  648. ).one_or_none()
  649. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  650. return False
  651. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  652. return True
  653. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  654. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  655. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  656. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  657. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  658. agree or a mapping cannot be read back against live tray telemetry.
  659. """
  660. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  661. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  662. """The global tray ids ``item`` actually prints from, or None if unknown.
  663. ``ams_mapping`` is the array the print command carries: position = filament
  664. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  665. not use. None means "no usable statement" — no mapping, unparseable JSON,
  666. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  667. documents), or one that resolves to no tray at all. Callers must treat None
  668. as "consider every loaded tray" rather than "consider none": narrowing on
  669. an absent mapping would silently drop requirements the print really has.
  670. """
  671. raw = getattr(item, "ams_mapping", None)
  672. if not raw:
  673. return None
  674. if isinstance(raw, str):
  675. try:
  676. mapping = json.loads(raw)
  677. except (json.JSONDecodeError, TypeError):
  678. return None
  679. else:
  680. mapping = raw
  681. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  682. return None
  683. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  684. return used or None
  685. def _mqtt_commands_rejected(status) -> bool:
  686. """True when the printer is currently reporting that it refused a command.
  687. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  688. a control command it could not verify. Queries still answer, so the printer
  689. looks connected and idle while project_file, gcode_line and
  690. ams_change_filament are all dropped — no amount of waiting or re-uploading
  691. changes that (#2732).
  692. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  693. ``print_error`` path builds HMSError differently), so this is safe to call on
  694. every watchdog poll.
  695. """
  696. for err in getattr(status, "hms_errors", None) or []:
  697. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  698. return True
  699. return False
  700. def _drying_ams_ids(status) -> list[int]:
  701. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  702. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  703. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  704. started (#2758) — it is a diagnostic, not a gate.
  705. Deliberately not used to block or stop drying before dispatch. This printer
  706. class supports drying concurrently with an active print
  707. (``supports_drying_while_printing``), so drying is not incompatible with
  708. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  709. while two AMS units were drying, one of them without its external PSU. Until
  710. it is known whether the blocker is drying itself or the power budget
  711. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  712. hardware is perfectly happy to continue.
  713. """
  714. ids: list[int] = []
  715. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  716. if not isinstance(unit, dict):
  717. continue
  718. try:
  719. if int(unit.get("dry_time") or 0) > 0:
  720. ids.append(int(unit.get("id", 0)))
  721. except (TypeError, ValueError):
  722. continue
  723. return ids
  724. def _parse_diameter(raw) -> float | None:
  725. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  726. try:
  727. value = float(raw)
  728. except (TypeError, ValueError):
  729. return None
  730. return value if value > 0 else None
  731. def _nozzle_info_by_id(status) -> dict[int, dict]:
  732. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  733. The field name is historical: on the H2 series ``nozzle_info`` carries an
  734. entry for *every* nozzle the printer knows about — the L/R hotends under
  735. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  736. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  737. :func:`_installed_nozzle_diameters` each take the half they need.
  738. """
  739. by_id: dict[int, dict] = {}
  740. for entry in getattr(status, "nozzle_rack", None) or []:
  741. if not isinstance(entry, dict):
  742. continue
  743. try:
  744. by_id[int(entry.get("id"))] = entry
  745. except (TypeError, ValueError):
  746. continue
  747. return by_id
  748. # What the firmware puts in a nozzle's serial number when the carriage or dock
  749. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  750. # its nozzle back in the rack (#2885).
  751. _EMPTY_NOZZLE_SERIAL = "N/A"
  752. def _nozzle_is_mounted(entry: dict | None) -> bool:
  753. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  754. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  755. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  756. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  757. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  758. the dock. So the diameter is not a presence signal (#2885).
  759. Emptiness has to be stated, not merely unstated. The serial must be the
  760. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  761. absent — an empty serial only means the printer didn't say, and a firmware
  762. that reports neither field normalises to exactly that. Treating "didn't
  763. say" as "empty" would silently switch the #1899 guard off on any such
  764. machine, so everything we cannot positively call empty counts as mounted.
  765. """
  766. if entry is None:
  767. return True
  768. serial = str(entry.get("serial_number") or "").strip().upper()
  769. if serial != _EMPTY_NOZZLE_SERIAL:
  770. return True
  771. try:
  772. max_temp = float(entry.get("max_temp") or 0)
  773. except (TypeError, ValueError):
  774. return True
  775. return max_temp > 0
  776. def _installed_nozzle_diameters(status) -> list[float]:
  777. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  778. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  779. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  780. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  781. told us its nozzle hardware" — callers must treat that as unknown, not as a
  782. mismatch, so we never block a print on missing data.
  783. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  784. though ``nozzles`` still carries a diameter for it: that value is stale, and
  785. counting it would let a slice match a nozzle the machine does not have
  786. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  787. """
  788. info = _nozzle_info_by_id(status)
  789. diameters: list[float] = []
  790. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  791. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  792. try:
  793. value = float(raw)
  794. except (TypeError, ValueError):
  795. continue
  796. if value > 0 and _nozzle_is_mounted(info.get(index)):
  797. diameters.append(value)
  798. return diameters
  799. def _rack_nozzle_diameters(status) -> list[float]:
  800. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  801. Keyed off the nozzle ids themselves rather than the printer model: only a
  802. rack machine ever reports ids 16-21, so there is no model registry to keep
  803. in sync. An empty dock is simply absent from the payload — measured on an
  804. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  805. present — so appearing here already means "a nozzle is in that dock".
  806. ``stat`` is deliberately not interpreted: its values aren't known, and
  807. reading it wrongly could hide a nozzle the printer would happily fetch.
  808. """
  809. diameters: list[float] = []
  810. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  811. if nozzle_id not in _RACK_NOZZLE_IDS:
  812. continue
  813. # PrinterState spells it "diameter"; the REST schema renames it to
  814. # "nozzle_diameter". Accept either so a caller holding the serialised
  815. # shape gets the same answer.
  816. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  817. if value is not None:
  818. diameters.append(value)
  819. return diameters
  820. def _format_diameters(diameters: list[float]) -> str:
  821. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  822. Deduplicated because a loaded rack holds several nozzles of the same size,
  823. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  824. short form doesn't. Matching still runs over the full list.
  825. """
  826. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  827. def _nozzle_mismatch_message(
  828. sliced_nozzle: float | None,
  829. installed: list[float],
  830. rack: list[float] | None = None,
  831. ) -> str | None:
  832. """Return an actionable error message when the sliced nozzle can't be
  833. printed on any nozzle the machine can reach, else None (#1899).
  834. Fail-safe: returns None whenever we lack the data to judge — no sliced
  835. diameter, or the printer reported no nozzles — so a print is only ever
  836. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  837. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  838. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  839. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  840. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  841. as reachable: the printer fetches one as part of starting the print, so a
  842. slice that matches a docked nozzle is not a mismatch. Without this the
  843. guard blocked every job whose nozzle happened not to be on a hotend at
  844. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  845. diameter already mounted could ever print, and the user had to fetch the
  846. nozzle by hand on the printer's own UI first (#2885).
  847. """
  848. reachable = [*installed, *(rack or [])]
  849. if not sliced_nozzle or not reachable:
  850. return None
  851. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  852. return None
  853. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  854. if rack:
  855. where += f" and {_format_diameters(rack)} in the nozzle rack"
  856. return (
  857. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  858. f"{where}. Re-slice for an available nozzle, or fit the matching "
  859. f"nozzle before printing."
  860. )
  861. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  862. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  863. Shared by the required and loaded sides, which name their extruder
  864. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  865. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  866. 1 the left/deputy — and both are absent on single-nozzle printers, where
  867. naming a nozzle would be noise.
  868. """
  869. parts = [(entry.get("type") or "filament").upper()]
  870. if entry.get("color"):
  871. parts.append(str(entry["color"]))
  872. nozzle = entry.get(nozzle_key)
  873. if nozzle == 0:
  874. parts.append("(right nozzle)")
  875. elif nozzle == 1:
  876. parts.append("(left nozzle)")
  877. return " ".join(parts)
  878. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  879. """Explain that nothing loaded matches what the file needs (#2771).
  880. Only ever built for a printer with no AMS, where the loaded list is short
  881. enough to quote in full and there is no "load another spool and hit Resume"
  882. recovery — the external spool holder is all there is, so the user needs to
  883. be told which filament to put on it.
  884. """
  885. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  886. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  887. return (
  888. f"No filament loaded on this printer matches the file. It needs {want}; "
  889. f"the printer has {have} and no AMS. Load the required filament on the "
  890. f"external spool holder, or send this job to a printer that has it."
  891. )
  892. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  893. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  894. every call site below it: G-code injection, usage registration, rack-plan
  895. lookup, slot-extruder lookup, the external-spool check, and the actual
  896. print command.
  897. A positive explicit ``plate_id`` on the queue item always wins. A
  898. non-positive one is treated as "not set" and resolved from the archive,
  899. the way the rest of the queue code already reads it (``if item.plate_id:``
  900. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  901. field, and passing a 0 straight through would build a print command for
  902. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  903. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  904. Falling back to a bare ``1`` instead of reading the archive assumes a
  905. single-plate file's one G-code is numbered 1, which only holds for a
  906. plate exported on its own: one cut out of a larger project keeps its
  907. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  908. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  909. the file, throws an HMS error, and sits wedged in IDLE until
  910. power-cycled (#2947).
  911. The call sites agreed on a fallback only by accident before this:
  912. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  913. the archive's own default plate internally whenever the plate id it's
  914. handed isn't in the file, so it could silently inject into a different
  915. plate than the one the print command itself asked for.
  916. Falls back to 1 when the archive can't be read, holds no G-code member at
  917. all, or its default member doesn't follow the ``plate_N`` naming
  918. convention (a slicer that doesn't use it has no number to dispatch).
  919. An explicit plate the archive doesn't hold is logged and then sent
  920. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  921. to a plate that is in the file would print a model nobody asked for,
  922. which is the worse of the two.
  923. """
  924. try:
  925. with zipfile.ZipFile(file_path, "r") as zf:
  926. names = zf.namelist()
  927. except (OSError, zipfile.BadZipFile) as exc:
  928. logger.warning(
  929. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  930. "is unavailable; dispatching plate %s",
  931. file_path,
  932. exc,
  933. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  934. )
  935. names = None
  936. if explicit_plate_id is not None and explicit_plate_id > 0:
  937. if (
  938. names is not None
  939. and default_plate_number(names) is not None
  940. and select_plate_gcode_name(names, explicit_plate_id) is None
  941. ):
  942. logger.warning(
  943. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  944. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  945. "file, since printing a different plate would print the wrong model (#2947)",
  946. file_path,
  947. explicit_plate_id,
  948. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  949. explicit_plate_id,
  950. )
  951. return explicit_plate_id
  952. resolved = default_plate_number(names) if names is not None else None
  953. return resolved if resolved is not None else 1
  954. class PrintScheduler:
  955. """Background scheduler that processes the print queue."""
  956. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  957. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  958. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  959. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  960. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  961. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  962. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  963. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  964. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  965. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  966. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  967. }
  968. def __init__(self):
  969. self._running = False
  970. self._check_interval = 30 # seconds
  971. # After a pass that actually dispatched something, loop again almost
  972. # immediately instead of sleeping the full interval (#2555). A dispatch
  973. # changes printer state — a batch launch fans out over several passes as
  974. # printers free up, a wedged head-of-line job reverts to pending, an
  975. # upload slot opens — and the next batch of ready work should not have to
  976. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  977. # pending items are behind printers that are genuinely busy printing),
  978. # there is nothing to react to, so we fall back to the normal interval;
  979. # that also means this can never tight-loop, since fast ticks only
  980. # continue while dispatches keep happening and the queue is draining.
  981. self._fast_check_interval = 3 # seconds
  982. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  983. self._power_on_check_interval = 10 # seconds between connection checks
  984. # Printers whose class-target power-on failed, mapped to the monotonic
  985. # time their cool-off expires (#2786).
  986. #
  987. # Without this, one printer with an unreachable plug starves every
  988. # sibling of its model forever: the wake step walks candidates in id
  989. # order, spends the pass's single attempt on the same broken printer
  990. # every time, and the healthy one two slots down is never reached. It
  991. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  992. # which delays the whole queue, not just this job.
  993. #
  994. # Entries expire on read rather than being cleared on success: a printer
  995. # inside its cool-off is skipped before the power-on is reached, so a
  996. # live entry can never be overwritten by a success anyway. A printer
  997. # that comes back by any other route stops being a wake candidate the
  998. # moment it connects.
  999. self._wake_failures: dict[int, float] = {}
  1000. self._wake_failure_cooloff = 600 # seconds
  1001. # Printers whose last upload never reached them, mapped to the monotonic
  1002. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1003. # as `_wake_failures`. Without it, a printer that cannot take files is
  1004. # idle on every pass, so it is picked on every pass.
  1005. self._upload_backoff: dict[int, float] = {}
  1006. # Refused uploads in a row per printer, which sets the next backoff
  1007. # window. Cleared by a successful upload to that printer.
  1008. self._upload_refusals: dict[int, int] = {}
  1009. # Printers whose current run of refusals has already sent its one
  1010. # "job waiting" notification. Each retry clears the item's waiting
  1011. # reason and the next refusal sets it again, which `hold_item` reads as
  1012. # a new reason; without this, every retry would notify. Cleared with
  1013. # `_upload_refusals`.
  1014. self._upload_refusal_notified: set[int] = set()
  1015. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1016. self._drying_in_progress: dict[int, float] = {}
  1017. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1018. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1019. # cycle and the humidity finally coming down, so the normal steady
  1020. # state is an empty dict. Fields:
  1021. # running — a cycle we armed is (or should be) on the firmware
  1022. # ended_at — monotonic when we observed that cycle end
  1023. # unproductive — consecutive armed cycles that ended with the reading
  1024. # still above the threshold
  1025. # suspended — we have stopped arming this unit and said so
  1026. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1027. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1028. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1029. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1030. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1031. # arming setdefault all act on that meaning -- a unit that is merely
  1032. # waiting out its streak must not become stoppable or judgeable.
  1033. # since -- monotonic stamp when the current continuous above-threshold
  1034. # streak began
  1035. # last -- monotonic stamp of the last pass that observed the streak
  1036. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1037. # Slots already notified as low on filament:
  1038. # {(printer_id, ams_id, tray_id, spool_id)}.
  1039. # Cleared when the slot goes back above its threshold rather than on a
  1040. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1041. # boundary must not produce an alert on every pass, and a slot that has
  1042. # been refilled has to be able to alert again. See #2913.
  1043. #
  1044. # The spool id is part of the key because the slot alone cannot clear
  1045. # itself. Pull a low spool and put a different part-used one in the same
  1046. # slot: the key survives the pass where the slot resolves to nothing --
  1047. # deliberately, so a brief Spoolman outage does not re-alert everything
  1048. # when it returns -- and the replacement never goes above the threshold,
  1049. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1050. # different key and the stale one is inert.
  1051. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1052. # The same, for the MQTT relay's filament/low event: its own record, so
  1053. # one channel having been told never silences the other.
  1054. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1055. # Earliest monotonic time the next low-filament check may run (#2913).
  1056. self._filament_low_next_check: float = 0.0
  1057. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1058. # condition is "reorder" or "break", the events are those that had a
  1059. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1060. # condition clears, so it can alert again, and when nobody wants either
  1061. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1062. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1063. # re-send one message per SKU that is still low.
  1064. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1065. # The JSON last read from or written to that row; None until it has been read.
  1066. self._stock_alerts_persisted: str | None = None
  1067. # Earliest monotonic time the next stock forecast check may run (#2955).
  1068. self._stock_forecast_next_check: float = 0.0
  1069. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1070. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1071. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1072. # both features share _drying_in_progress.
  1073. self._scheduled_drying_printer_ids: set[int] = set()
  1074. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1075. # the first pass after a restart reaps anything left behind.
  1076. self._last_scheduled_drying_prune: float | None = None
  1077. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1078. # a project_file command must not get a second dispatch until either it
  1079. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1080. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1081. # during that window the DB busy_printers seed is empirically unreliable
  1082. # (multi-plate batches double-/triple-dispatched onto the same printer
  1083. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1084. # or revert.
  1085. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1086. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1087. # Minimum cooldown between dispatches to the same printer (covers the
  1088. # H2D's project_file digestion window).
  1089. self._dispatch_min_cooldown = 60.0
  1090. # Hard timeout — drop the hold even if we never observed a transition,
  1091. # so a lost MQTT session can't lock a printer out of the queue forever.
  1092. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1093. # watchdog runs first on the unhappy path.
  1094. self._dispatch_max_hold = 180.0
  1095. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1096. # an earlier pass and is still running. `_start_print` flips the row
  1097. # pending -> printing only *after* the upload completes, so until then
  1098. # the row stays `pending`: each tick, check_queue excludes these
  1099. # item_ids from re-selection and their printers from new dispatch /
  1100. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1101. # freed slots refill on the next fast tick. check_queue is the sole,
  1102. # sequential caller and the prune done-callbacks run in the same
  1103. # event-loop thread, so this dict needs no lock.
  1104. # item_id -> (task, printer_id)
  1105. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1106. # Expected prints registered by `_start_print` that have not yet had a
  1107. # print command sent. Populated at registration, dropped once
  1108. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1109. # other exit. Same threading argument as `_inflight` above: one
  1110. # sequential caller, callbacks on the same loop, so no lock.
  1111. # item_id -> (printer_id, remote_filename, archive_id)
  1112. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1113. # Budget reservations created for a dispatch whose print command has
  1114. # not been confirmed yet. `_dispatch_one` releases these on every
  1115. # unsuccessful exit; a successful start removes the item id and leaves
  1116. # the reservation for finance_billing to consume with the archive.
  1117. self._unconfirmed_budget_reservations: set[int] = set()
  1118. # The print user `_start_print` handed to printer_manager for an item
  1119. # whose print command has not been sent yet (item_id -> printer_id).
  1120. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1121. # expected print above: it marks the printer's next print as Bambuddy's.
  1122. self._unconfirmed_print_user: dict[int, int] = {}
  1123. # Prints whose command went out but which the printer has not been
  1124. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1125. # the file and archive None for a library print. The watchdog drops the
  1126. # entry once the print runs, and withdraws what it stands for when the
  1127. # print never starts (see `_forget_unstarted_print`).
  1128. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1129. # Chamber temperature history for smart soak-time reduction.
  1130. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1131. # Entries older than _chamber_history_ttl are pruned on write.
  1132. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1133. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1134. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1135. # Populated on engagement in `_apply_keep_warm`, cleared by
  1136. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1137. # when a gate setting toggles off mid-hold — the release publishes
  1138. # bed → 0 first).
  1139. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1140. # Preheat rollback registry: printer_id -> subset of
  1141. # {"bed", "chamber", "airduct"} listing which preheat commands
  1142. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1143. # every entry still present at exit unless the print successfully
  1144. # started, so a failed upload / cancel / exception never leaves the
  1145. # printer heating for a job that isn't happening.
  1146. self._preheat_pin: dict[int, set[str]] = {}
  1147. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1148. # rollback can tell its own target from one someone else has since
  1149. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1150. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1151. self._preheat_pin_bed: dict[int, int] = {}
  1152. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1153. # its preheat was still holding at temperature. Set by
  1154. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1155. # `_preheat_sleep`, and cleared when the dispatch exits.
  1156. self._cancelled_dispatches: set[int] = set()
  1157. # printer_id -> monotonic time it was first seen terminal while one of
  1158. # its queue rows was still 'printing'. Reset by any non-terminal
  1159. # observation, so it measures an unbroken run rather than a total.
  1160. # In-memory on purpose: a restart re-arms the grace period, which only
  1161. # delays a recovery that is already the exceptional path (#2829).
  1162. self._terminal_since: dict[int, float] = {}
  1163. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1164. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1165. # across idle printers repeats that for every one of them in a single
  1166. # pass. Cleared at the top of each pass so a re-sliced file is never
  1167. # served from a previous tick.
  1168. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1169. # When each "any model" job held for low filament last looked for
  1170. # another printer (#3137), by queue item id.
  1171. self._short_hold_checked_at: dict[int, float] = {}
  1172. async def run(self):
  1173. """Main loop - check queue every interval."""
  1174. self._running = True
  1175. logger.info("Print scheduler started")
  1176. await self._clear_stale_dispatch_claims(at_startup=True)
  1177. while self._running:
  1178. dispatched = False
  1179. try:
  1180. self._sample_chamber_temps()
  1181. # No-op while any upload is in flight; on a quiet tick it releases
  1182. # a claim whose best-effort clear failed (e.g. the database was
  1183. # briefly unreachable), instead of leaving the row wedged until
  1184. # the next restart.
  1185. await self._clear_stale_dispatch_claims()
  1186. await self._close_stranded_printing_items()
  1187. dispatched = await self.check_queue()
  1188. except Exception as e:
  1189. logger.error("Scheduler error: %s", e)
  1190. # Re-check quickly after a productive pass so a draining batch does
  1191. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1192. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1193. async def _close_stranded_printing_items(self) -> None:
  1194. """Close a ``printing`` row the completion event never closed (#2829).
  1195. ``on_print_complete`` refuses to close a row when the completion's
  1196. subtask name disagrees with the file the row was dispatched with, so a
  1197. completion meant for something else (the printer's own
  1198. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1199. The refusal has no way back, though: nothing else ever closes the row,
  1200. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1201. one bad comparison wedges that printer's queue until a human presses
  1202. cancel. That is what #2829's reporters hit, and the guard's own
  1203. docstring already called stranding the worse of the two failures.
  1204. This is the way back. When a row has been ``printing`` while its
  1205. printer sat in a terminal state for the whole grace period, the print
  1206. is over however the event was read, and the row is closed with the
  1207. status the printer's own state implies.
  1208. Deliberately conservative:
  1209. * Only a connected printer counts. A disconnected one has a stale
  1210. ``state`` and proves nothing.
  1211. * The clock is reset by any non-terminal observation, so this cannot
  1212. fire on a printer that is merely between stages.
  1213. * The grace period is far longer than the gap between a printer
  1214. finishing and its completion arriving, so the normal path always
  1215. wins the race and this only ever sees genuine strandings.
  1216. What it does *not* do is replay the completion's side effects --
  1217. notifications, billing, auto-off. It restores the queue, which is the
  1218. harm being undone; the archive was updated by the normal path
  1219. regardless, since only the queue block refuses. A recovery that
  1220. silently re-fired notifications minutes late would be its own bug.
  1221. """
  1222. try:
  1223. async with async_session() as db:
  1224. result = await db.execute(
  1225. select(PrintQueueItem)
  1226. .where(PrintQueueItem.status == "printing")
  1227. .where(PrintQueueItem.printer_id.is_not(None))
  1228. )
  1229. items = list(result.scalars().all())
  1230. if not items:
  1231. self._terminal_since.clear()
  1232. return
  1233. now = time.monotonic()
  1234. seen_printers: set[int] = set()
  1235. closed = False
  1236. for item in items:
  1237. printer_id = item.printer_id
  1238. seen_printers.add(printer_id)
  1239. state = printer_manager.get_status(printer_id)
  1240. status = _terminal_queue_status(state)
  1241. if status is None:
  1242. self._terminal_since.pop(printer_id, None)
  1243. continue
  1244. since = self._terminal_since.setdefault(printer_id, now)
  1245. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1246. continue
  1247. item.status = status
  1248. item.completed_at = datetime.now(timezone.utc)
  1249. closed = True
  1250. # The printer is idle: nothing it prints next is this item's.
  1251. self._forget_unstarted_print(item.id, unless_printing=True)
  1252. logger.warning(
  1253. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1254. "closing it as %s. Its completion event was never matched to it, which blocks "
  1255. "every later job for this printer (#2829).",
  1256. item.id,
  1257. printer_id,
  1258. getattr(state, "state", None),
  1259. now - since,
  1260. status,
  1261. )
  1262. if closed:
  1263. await db.commit()
  1264. from backend.app.services.print_batch import refresh_batches_after
  1265. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1266. for printer_id in list(self._terminal_since):
  1267. if printer_id not in seen_printers:
  1268. del self._terminal_since[printer_id]
  1269. except Exception as e:
  1270. # Best-effort, same as the claim sweep beside it: a recovery path
  1271. # that can itself break the scheduler loop is worse than the strand.
  1272. logger.error("Stranded-item sweep failed: %s", e)
  1273. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1274. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1275. A claim is only ever held by a live dispatch coroutine, so when this
  1276. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1277. is stale. At startup that is trivially true — no coroutine survives a
  1278. restart. It is equally true on any later tick where no upload is running,
  1279. which is what makes this safe to repeat rather than only run once.
  1280. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1281. the database is briefly unreachable at exactly the moment dispatch ends,
  1282. the claim survives and the row is wedged out of the selection query. That
  1283. used to last until the next restart (#2702 follow-up, seen when
  1284. PostgreSQL refused a connection mid-dispatch).
  1285. ``_inflight`` is populated when the task is spawned, before the coroutine
  1286. claims its row, and pruned by a done-callback that cannot run before the
  1287. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1288. race window and needs no age threshold. A size-derived upload deadline
  1289. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1290. """
  1291. if self._inflight:
  1292. return
  1293. try:
  1294. async with async_session() as db:
  1295. res = await db.execute(
  1296. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1297. )
  1298. await db.commit()
  1299. if res.rowcount:
  1300. logger.info(
  1301. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1302. res.rowcount,
  1303. " at startup" if at_startup else "",
  1304. )
  1305. except Exception as exc:
  1306. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1307. def stop(self):
  1308. """Stop the scheduler."""
  1309. self._running = False
  1310. logger.info("Print scheduler stopped")
  1311. def forget_printer(self, printer_id: int) -> None:
  1312. """Drop what is kept for a deleted printer, so the next printer given its
  1313. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1314. would keep it out of dispatch for up to an hour.
  1315. A dispatch already in flight keeps its own state (_inflight, the preheat
  1316. pins, unconfirmed prints): it unwinds that when it ends.
  1317. """
  1318. for keyed in (
  1319. self._upload_backoff,
  1320. self._upload_refusals,
  1321. self._wake_failures,
  1322. self._drying_in_progress,
  1323. self._dispatch_holds,
  1324. self._chamber_history,
  1325. self._keep_warm,
  1326. self._terminal_since,
  1327. ):
  1328. keyed.pop(printer_id, None)
  1329. self._upload_refusal_notified.discard(printer_id)
  1330. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1331. for key in [key for key in keyed if key[0] == printer_id]:
  1332. del keyed[key]
  1333. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1334. del self._sent_unstarted_print[item_id]
  1335. async def check_queue(self) -> bool:
  1336. """Check for prints ready to start.
  1337. Returns True if this pass dispatched at least one item, so the caller
  1338. can loop again quickly instead of sleeping the full interval (#2555).
  1339. """
  1340. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1341. self._filament_req_memo.clear()
  1342. async with async_session() as db:
  1343. # Check if shortest-job-first scheduling is enabled
  1344. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1345. # Get all pending items in the one order the queue page shows them
  1346. # in (#3200). The first eligible item takes a printer, so this order
  1347. # decides who wins a printer that a pinned job and an "Any <model>"
  1348. # job both want. It used to start with ``printer_id``, which made the
  1349. # lane outrank the position: SQLite sorts NULL first, so model-based
  1350. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1351. # Neither is what the user dragged into place.
  1352. if sjf_enabled:
  1353. # SJF: items already jumped get top priority (starvation guard),
  1354. # then sort by print_time ascending. Items with no print time go
  1355. # last, and position breaks ties.
  1356. result = await db.execute(
  1357. select(PrintQueueItem)
  1358. .where(PrintQueueItem.status == "pending")
  1359. # Never re-select a row a dispatch worker has already claimed
  1360. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1361. # below, and the guard that lets an orphaned claim be ignored
  1362. # until startup reconciliation clears it.
  1363. .where(PrintQueueItem.dispatching_at.is_(None))
  1364. # archive/library_file are read by the cross-model gate
  1365. # (#2578); eager-load once per pass instead of a lazy-load
  1366. # (which would raise in async) per item.
  1367. .options(
  1368. selectinload(PrintQueueItem.archive),
  1369. selectinload(PrintQueueItem.library_file),
  1370. # Cross-model candidates (#671), plus each candidate's file
  1371. # for the same cross-model gate. Lazy-loading either would
  1372. # raise in async.
  1373. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1374. )
  1375. .order_by(
  1376. PrintQueueItem.been_jumped.desc(),
  1377. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1378. PrintQueueItem.position,
  1379. PrintQueueItem.id,
  1380. )
  1381. )
  1382. else:
  1383. result = await db.execute(
  1384. select(PrintQueueItem)
  1385. .where(PrintQueueItem.status == "pending")
  1386. # Skip rows already claimed by a dispatch worker (#2615).
  1387. .where(PrintQueueItem.dispatching_at.is_(None))
  1388. .options(
  1389. selectinload(PrintQueueItem.archive),
  1390. selectinload(PrintQueueItem.library_file),
  1391. # Cross-model candidates (#671), plus each candidate's file
  1392. # for the same cross-model gate. Lazy-loading either would
  1393. # raise in async.
  1394. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1395. )
  1396. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1397. )
  1398. items = list(result.scalars().all())
  1399. # Drop rows whose upload is still in flight from an earlier pass
  1400. # (#2602). They stay `pending` until the upload finishes, so without
  1401. # this a fast tick would re-select and re-dispatch the same row.
  1402. # Belt-and-suspenders with the printer exclusion below.
  1403. if self._inflight:
  1404. inflight_ids = set(self._inflight)
  1405. items = [it for it in items if it.id not in inflight_ids]
  1406. # Read plate-clear setting once per queue check. Default MUST be
  1407. # False to match the schema (SettingsSchema.require_plate_clear
  1408. # defaults False) and the frontend (toggle + card badge both treat a
  1409. # missing value as off). When no settings row exists, a True default
  1410. # here re-enabled the plate-clear gate the UI showed as disabled,
  1411. # blocking dispatch to FINISH-state printers forever with no UI path
  1412. # to clear it (#1865).
  1413. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1414. # Dispatch and track scheduled drying runs (#2638)
  1415. await self._check_scheduled_dryings(db)
  1416. if not items:
  1417. # No dispatchable pending items — still check auto-drying on idle
  1418. # printers, but keep any printer with an upload still in flight
  1419. # from an earlier pass out of it (#2602): its print is imminent,
  1420. # so it must not be auto-dried in the gap before the row flips to
  1421. # printing. Report the pass as productive while uploads run so the
  1422. # loop stays on the fast interval.
  1423. #
  1424. # Also release any keep-warm holds that got orphaned by the queue
  1425. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1426. # this early return, so call it directly with an empty candidate
  1427. # set. Without this, a printer whose queued item was cancelled or
  1428. # deleted would keep its bed at target until the max-duration
  1429. # timeout expired.
  1430. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1431. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1432. await self._check_auto_drying(db, [], inflight_printers)
  1433. await self._check_filament_low(db)
  1434. await self._check_stock_forecast(db)
  1435. return bool(self._inflight)
  1436. logger.info(
  1437. "Queue check: found %d pending items: %s",
  1438. len(items),
  1439. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1440. )
  1441. # Forget jobs that left the queue since they were last checked.
  1442. pending_ids = {i.id for i in items}
  1443. self._short_hold_checked_at = {
  1444. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1445. }
  1446. # Seed busy_printers with printers that already have an item in 'printing'
  1447. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1448. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1449. # lag several seconds behind the print command, so the next check_queue
  1450. # tick still sees IDLE and would double-dispatch onto the same printer.
  1451. # Without this guard, two pending items targeting the same printer
  1452. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1453. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1454. busy_result = await db.execute(
  1455. select(PrintQueueItem.printer_id)
  1456. .where(PrintQueueItem.status == "printing")
  1457. .where(PrintQueueItem.printer_id.is_not(None))
  1458. )
  1459. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1460. # Why each printer left this pass, recorded where the decision is
  1461. # made rather than re-derived when the summary is logged. #3018's
  1462. # bundle shows what the old summary produced: "printer 1 not
  1463. # available -- connected=True, state=IDLE" immediately followed by a
  1464. # dispatch to printer 1. Two things went wrong at once. The line read
  1465. # live state at log time, which by then no longer matched the state
  1466. # the decision was made on; and `busy_printers` holds both printers
  1467. # that cannot take work and printers this pass has claimed for it,
  1468. # which are opposite facts. It is the first line anyone greps for
  1469. # "why did my item not go out", so it has to say which.
  1470. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1471. # Printers this pass is dispatching to. They are in busy_printers so
  1472. # nothing else in the pass targets them -- that is a reservation, not
  1473. # an obstruction, and the summary says so.
  1474. claimed_printers: set[int] = set()
  1475. def mark_busy(printer_id: int, reason: str) -> None:
  1476. """Take ``printer_id`` out of this pass, recording why.
  1477. First reason wins: a printer already excluded by a stronger fact
  1478. -- a print running on it -- must not be relabelled by a weaker
  1479. check that ran later and would have excluded it anyway.
  1480. """
  1481. busy_printers.add(printer_id)
  1482. busy_reasons.setdefault(printer_id, reason)
  1483. def claim_printer(printer_id: int) -> None:
  1484. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1485. claimed_printers.add(printer_id)
  1486. mark_busy(printer_id, "selected for dispatch in this pass")
  1487. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1488. # worded for a different audience: the log wants "still inside its
  1489. # post-dispatch hold window", the queue row wants to know the printer
  1490. # is taken and nothing is broken. Only the cases that would read wrong
  1491. # as a plain "Busy" are recorded here; the rest fall back to it.
  1492. item_hold_reasons: dict[int, str] = {}
  1493. # Names and models for the printers this pass may have to write a
  1494. # waiting reason about, read once rather than per skip per tick. The
  1495. # model-based branch already has its names from `_printers_for_model`.
  1496. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1497. pinned_printers: dict[int, tuple[str, str]] = {}
  1498. if pinned_printer_ids:
  1499. pinned_rows = await db.execute(
  1500. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1501. )
  1502. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1503. def printer_label(printer_id: int) -> str:
  1504. """What to call this printer in a queue row."""
  1505. entry = pinned_printers.get(printer_id)
  1506. return (entry[0] if entry else "") or f"printer {printer_id}"
  1507. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1508. """Record why *item* is not going out, in the words the queue row shows.
  1509. The fixed-printer branch's single writer for ``waiting_reason``
  1510. (#3074). Before this, the sensor interlock was the only thing that
  1511. wrote the field there, so an item pinned to a printer that was
  1512. merely printing sat at `pending` with nothing to show for it —
  1513. indistinguishable from a queue that had stopped working — while
  1514. the same job queued as "Any <model>" explained itself.
  1515. Every exit from that branch now calls this, which is also what
  1516. replaced the interlock's old habit of clearing the field up front:
  1517. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1518. because whichever exit runs next overwrites it and the dispatch
  1519. path clears it.
  1520. A notification goes out when this item starts asking for
  1521. something, and only then: the new reason needs the user, and what
  1522. it replaced did not. "What it replaced did not" has to include a
  1523. busy-only reason, not just an empty one. The sequence this branch
  1524. actually produces is a print running (``Busy: X1C-01``) and then
  1525. the plate it left behind (``Waiting for plate confirmation``), and
  1526. testing "was the field empty" would call that no transition at all
  1527. and stay quiet through the one case worth saying out loud.
  1528. The cost is that a printer dropping offline, coming back busy and
  1529. dropping again asks twice rather than once. That is the honest
  1530. reading — it went wrong twice — and the alternative was a rule
  1531. that never fired for the case this was built for.
  1532. *notify* is how a caller opts out. The sensor interlock does: it
  1533. has never sent this notification, and a change about what the
  1534. queue *displays* is not the place to start (#1148).
  1535. """
  1536. if item.waiting_reason == reason:
  1537. return
  1538. # Busy-only and empty are the same thing here: neither is the
  1539. # queue asking the user for anything.
  1540. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1541. item.waiting_reason = reason
  1542. await db.commit()
  1543. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1544. return
  1545. try:
  1546. job_name = await self._get_job_name(db, item)
  1547. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1548. await notification_service.on_queue_job_waiting(
  1549. job_name=job_name,
  1550. target_model=(entry[1] if entry else "") or "",
  1551. waiting_reason=reason,
  1552. db=db,
  1553. printer_id=item.printer_id,
  1554. )
  1555. except Exception as e:
  1556. # A queue that cannot say why it is waiting is the bug being
  1557. # fixed here; a queue that stops dispatching because a
  1558. # notification provider is down would be a worse one.
  1559. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1560. async def hold_for_printer(
  1561. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1562. ) -> None:
  1563. """Take *printer_id* out of this pass and tell the item's owner why."""
  1564. mark_busy(printer_id, log_reason)
  1565. item_hold_reasons.setdefault(printer_id, item_reason)
  1566. await hold_item(item, item_reason)
  1567. # Defense-in-depth (#1157): augment busy_printers with any printer
  1568. # still in its post-dispatch hold window. Empirically, the DB seed
  1569. # above can miss in-flight items in a multi-plate batch — same-file
  1570. # plates were being dispatched 30 s apart while the H2D was still
  1571. # digesting the first project_file. The hold is keyed in-memory and
  1572. # released by the watchdog on the success path, so it adds a layer
  1573. # that doesn't depend on DB row visibility or completion-callback
  1574. # timing.
  1575. for held_printer_id in list(self._dispatch_holds.keys()):
  1576. if self._printer_in_dispatch_hold(held_printer_id):
  1577. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1578. # Exclude printers whose upload is still in flight from an earlier
  1579. # pass (#2602). The row is `pending` until the upload finishes and
  1580. # the printing-state seed / dispatch hold above only arm once the
  1581. # upload completes, so this is what holds the printer (and, via
  1582. # busy_printers, its auto-drying) out of the pass during the upload.
  1583. for _task, inflight_pid in self._inflight.values():
  1584. if inflight_pid is not None:
  1585. mark_busy(inflight_pid, "an upload to it is still in flight")
  1586. # Snapshot taken here, before the item loop adds anything (#2801).
  1587. #
  1588. # The three sources above all mean the same thing: a print on this
  1589. # printer is running or imminent. Everything the loop adds below
  1590. # means only "the queue could not dispatch to it this pass", which
  1591. # is a different statement -- a printer waiting on a plate-clear
  1592. # acknowledgment, an offline printer, one with no matching file.
  1593. #
  1594. # Auto-drying must only see the first kind. Reading the whole set
  1595. # as "is currently printing" is what put a plate-held printer down
  1596. # the mid-print path: it capped the drying temperature, logged the
  1597. # cycle as (mid-print), and skipped the very gate that was supposed
  1598. # to hold it. The interlock block below already documents the same
  1599. # hazard and works around it by staying out of busy_printers; this
  1600. # generalises that workaround instead of repeating it per case.
  1601. dispatching_printers: set[int] = set(busy_printers)
  1602. # Printers whose last upload never reached them (#3210). After the
  1603. # snapshot above on purpose: such a printer is idle, not about to
  1604. # print, and auto-drying must keep treating it as idle.
  1605. now_mono = time.monotonic()
  1606. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1607. # can leave them out: there is no print to keep a bed warm for.
  1608. backoff_printers: set[int] = set()
  1609. # In backoff, and the "job waiting" notification for this run of
  1610. # refusals has gone out already. Their holds are written silently.
  1611. silent_hold_printers: set[int] = set()
  1612. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1613. if now_mono >= retry_at:
  1614. del self._upload_backoff[backoff_pid]
  1615. continue
  1616. backoff_printers.add(backoff_pid)
  1617. if backoff_pid in self._upload_refusal_notified:
  1618. silent_hold_printers.add(backoff_pid)
  1619. else:
  1620. self._upload_refusal_notified.add(backoff_pid)
  1621. mark_busy(
  1622. backoff_pid,
  1623. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1624. )
  1625. item_hold_reasons.setdefault(
  1626. backoff_pid,
  1627. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1628. )
  1629. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1630. # enclosure door left open, say. The fixed-printer branch turns
  1631. # this into a waiting_reason the user can act on; the model-based
  1632. # branch hides these printers from the matcher so an "Any <model>"
  1633. # job runs on a sibling instead of queueing behind the held one.
  1634. #
  1635. # Deliberately NOT merged into busy_printers, even though that set
  1636. # already means "unavailable this pass". _check_auto_drying reads
  1637. # it as "is currently printing" and would put an idle-but-held
  1638. # printer down the mid-print drying path, which caps the drying
  1639. # temperature and skips the queue-only gating. A held printer is
  1640. # idle; it should dry exactly as it did before.
  1641. #
  1642. # Only sensors we actually read and found alerting appear here; see
  1643. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1644. # holds nothing.
  1645. interlocked: dict[int, str] = {}
  1646. try:
  1647. interlocked = await ha_sensor_manager.blocked_printers(db)
  1648. except Exception as e:
  1649. # Never let the interlock stop the queue running. A broken
  1650. # lookup means no holds, not no dispatches.
  1651. logger.warning("Home Assistant interlock check failed: %s", e)
  1652. interlocked = {}
  1653. # Printers a smart plug can bring back, read once for the whole pass
  1654. # (#2786). Used by the model-based branch both to word "Offline" in
  1655. # the waiting reason and to decide what the wake step may switch on.
  1656. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1657. # At most one power-on per queue check. Each one blocks this loop
  1658. # for the boot wait, so a queue of ten class-targeted jobs must not
  1659. # switch on ten printers inside a single pass — the next pass wakes
  1660. # the next one (#2786).
  1661. power_on_attempted = False
  1662. # Log skip reasons once per queue check (not per item)
  1663. skip_reasons: dict[str, int] = {}
  1664. # Items selected for dispatch in this pass, one per printer. The
  1665. # loop below only *decides* — the uploads happen afterwards, in
  1666. # parallel (#2555). See _dispatch_selected().
  1667. dispatch_ids: list[int] = []
  1668. # Library rows queued with `cleanup_library_after_dispatch` (the
  1669. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1670. # that prints them: the row is deleted and the 3MF is unlinked from
  1671. # disk. That was safe only because dispatch was serial. Run two of
  1672. # them against the same row at once and the second DELETE matches no
  1673. # row (StaleDataError), and the winner's unlink can pull the file out
  1674. # from under the loser's in-flight upload.
  1675. #
  1676. # Only the cleanup flag mutates the row. An ordinary library print
  1677. # just reads it, so the common fan-out — one file, many printers,
  1678. # which is exactly the reporter's workload — still goes out fully in
  1679. # parallel. Narrow the guard to the mutating case; do not serialise
  1680. # the case the whole fix exists for.
  1681. dispatch_libs: set[int] = set()
  1682. consumed_libs: set[int] = set()
  1683. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1684. """True if dispatching `candidate` now would race another item's cleanup."""
  1685. lib_id = candidate.library_file_id
  1686. if lib_id is None:
  1687. return False
  1688. if candidate.cleanup_library_after_dispatch:
  1689. # We would delete a row someone else in this pass is reading.
  1690. return lib_id in dispatch_libs
  1691. # Someone else in this pass will delete the row out from under us.
  1692. return lib_id in consumed_libs
  1693. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1694. lib_id = candidate.library_file_id
  1695. if lib_id is None:
  1696. return
  1697. dispatch_libs.add(lib_id)
  1698. if candidate.cleanup_library_after_dispatch:
  1699. consumed_libs.add(lib_id)
  1700. # Printer scope of each job's creator (#1727), so an "any <model>"
  1701. # job only lands on a printer its creator may use. Loaded lazily,
  1702. # once per creator per pass.
  1703. from backend.app.core.auth import is_auth_enabled
  1704. scope_auth_enabled = await is_auth_enabled(db)
  1705. creator_scopes: dict[int, PrinterScope] = {}
  1706. # Printers a model job passes over while drying blocks the queue,
  1707. # as a pinned job waits for its own. A parked timer never ends,
  1708. # so it does not hold (#2896).
  1709. drying_held: set[int] = (
  1710. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1711. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1712. else set()
  1713. )
  1714. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1715. if not scope_auth_enabled or user_id is None:
  1716. return ALL_PRINTERS
  1717. if user_id not in creator_scopes:
  1718. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1719. return creator_scopes[user_id]
  1720. for item in items:
  1721. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1722. if item.scheduled_time:
  1723. sched = item.scheduled_time
  1724. if sched.tzinfo is None:
  1725. sched = sched.replace(tzinfo=timezone.utc)
  1726. if sched > datetime.now(timezone.utc):
  1727. # Waiting on the clock, not on a printer.
  1728. await hold_item(item, None)
  1729. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1730. continue
  1731. # Skip items that require manual start, except an "any model"
  1732. # job held for low filament that another idle printer can now
  1733. # run: that one is moved there and carries on below (#3137).
  1734. if item.manual_start and not (
  1735. item.filament_short
  1736. and await self._release_short_model_hold(
  1737. db,
  1738. item,
  1739. busy_printers | interlocked.keys() | drying_held,
  1740. require_plate_clear,
  1741. await _creator_scope(item.created_by_id),
  1742. )
  1743. ):
  1744. # Waiting on the user, not on a printer. Cleared here because
  1745. # this is the last pass that will look at the row: a staged
  1746. # item never reaches the branches below again, so a reason
  1747. # left from before it was staged would stand forever (#3074).
  1748. # The one exception is the unmatched-filament hold, whose
  1749. # reason was written at staging and is why the item waits:
  1750. # it names the filament to load (#2799). Pressing start
  1751. # clears manual_start, and the branches below overwrite it.
  1752. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1753. await hold_item(item, keep)
  1754. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1755. continue
  1756. if item.printer_id and item.printer_id not in pinned_printers:
  1757. # Moved by the release above to a printer no row named when
  1758. # the labels were read.
  1759. moved_to = await self._get_printer(db, item.printer_id)
  1760. if moved_to is not None:
  1761. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1762. if item.printer_id:
  1763. # Its creator may no longer use this printer (#1727): an
  1764. # admin took it away from their group after the job was
  1765. # queued, say to keep it free for a training session. Held,
  1766. # not failed, so it starts if access comes back or the user
  1767. # moves it to a printer they still have.
  1768. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1769. await hold_item(
  1770. item,
  1771. "Its owner no longer has access to this printer — move it to another printer",
  1772. notify=False,
  1773. )
  1774. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1775. continue
  1776. # Held by a sensor interlock (#1148). Checked before the
  1777. # busy_printers test that would otherwise swallow it
  1778. # silently — "waiting for a printer" and "waiting for you
  1779. # to shut the enclosure" need to read differently, and only
  1780. # one of them is something the user can fix.
  1781. #
  1782. # It used to be the only thing that wrote a waiting_reason on
  1783. # this branch, and it cleared the field up front so a lifted
  1784. # hold could not leave a shut door reading "Waiting on
  1785. # Enclosure Door". `hold_item` carries that guarantee now —
  1786. # every exit below writes — so the clear is gone and the
  1787. # interlock is an ordinary hold like the rest (#3074).
  1788. interlock_reason = interlocked.get(item.printer_id)
  1789. if interlock_reason:
  1790. # Silent, exactly as it has always been. #1148 built this
  1791. # as a hold that shows on the row, never as an alert, and
  1792. # routing it through the shared writer must not quietly
  1793. # turn every open door into a notification.
  1794. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1795. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1796. continue
  1797. # Specific printer assignment (existing behavior)
  1798. if item.printer_id in busy_printers:
  1799. # Whatever took the printer out of this pass — a print
  1800. # already running on it, a post-dispatch hold, an upload
  1801. # still in flight, an item ahead of this one in the same
  1802. # pass — reads the same way from the queue: the printer is
  1803. # taken and this item is in line for it. The exceptions
  1804. # that do not (an offline printer, say) recorded their own
  1805. # wording in `item_hold_reasons` when they held it.
  1806. await hold_item(
  1807. item,
  1808. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1809. notify=item.printer_id not in silent_hold_printers,
  1810. )
  1811. continue
  1812. # Check if printer is idle
  1813. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1814. printer_connected = printer_manager.is_connected(item.printer_id)
  1815. # If printer not connected, try to power on via smart plug
  1816. if not printer_connected:
  1817. plugs = await self._get_smart_plugs(db, item.printer_id)
  1818. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1819. if auto_on_plugs:
  1820. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1821. # Power on using the plug that actually feeds the printer, and
  1822. # wait for it to boot on that one only (#2629).
  1823. primary_plug = self._pick_power_plug(auto_on_plugs)
  1824. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1825. if powered_on:
  1826. # Also turn on any remaining auto_on plugs (e.g., filter)
  1827. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1828. try:
  1829. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1830. if await service.turn_on(extra_plug):
  1831. await publish_plug_state(
  1832. extra_plug.id,
  1833. extra_plug.name,
  1834. extra_plug.printer_id,
  1835. on=True,
  1836. ha_entity_id=extra_plug.ha_entity_id,
  1837. )
  1838. logger.info(
  1839. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1840. )
  1841. except Exception as e:
  1842. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1843. printer_connected = True
  1844. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1845. else:
  1846. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1847. await hold_for_printer(
  1848. item,
  1849. item.printer_id,
  1850. "smart-plug power-on failed",
  1851. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1852. )
  1853. continue
  1854. else:
  1855. # No plug or auto_on disabled. Worded exactly as the
  1856. # model-based branch words it (#2786): this is the one
  1857. # entry on that list the user has to act on, because
  1858. # Bambuddy will never switch this printer on itself.
  1859. await hold_for_printer(
  1860. item,
  1861. item.printer_id,
  1862. "offline, with no smart plug to power it on",
  1863. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1864. )
  1865. continue
  1866. # Check if printer is idle (busy with another print)
  1867. if not printer_idle:
  1868. await hold_for_printer(
  1869. item,
  1870. item.printer_id,
  1871. "not idle",
  1872. self._pinned_hold_reason(
  1873. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1874. ),
  1875. )
  1876. continue
  1877. # Drying blocks the queue, if the user asked it to. A hold
  1878. # is a skip like any other, so it belongs here with the
  1879. # rest of the availability checks.
  1880. # A parked timer (#2896) never ends, so it must not hold the
  1881. # queue; it stays tracked so the stop paths still reach it.
  1882. if (
  1883. self._drying_in_progress.get(item.printer_id)
  1884. and not self._drying_is_only_parked(item.printer_id)
  1885. and await self._get_bool_setting(db, "queue_drying_block")
  1886. ):
  1887. # Busy-shaped on purpose: the cycle ends on its own and
  1888. # the job goes out, so there is nothing to alert about.
  1889. await hold_for_printer(
  1890. item,
  1891. item.printer_id,
  1892. "drying, and drying is set to block the queue",
  1893. f"Busy: {printer_label(item.printer_id)} (drying)",
  1894. )
  1895. continue
  1896. # Check condition (previous print success)
  1897. if item.require_previous_success:
  1898. if not await self._check_previous_success(db, item):
  1899. item.status = "skipped"
  1900. item.error_message = "Previous print failed or was aborted"
  1901. item.completed_at = datetime.now(timezone.utc)
  1902. # Not pending any more, so not waiting for anything.
  1903. item.waiting_reason = None
  1904. await db.commit()
  1905. logger.info("Skipped queue item %s - previous print failed", item.id)
  1906. # Send notification
  1907. job_name = await self._get_job_name(db, item)
  1908. printer = await self._get_printer(db, item.printer_id)
  1909. await notification_service.on_queue_job_skipped(
  1910. job_name=job_name,
  1911. printer_id=item.printer_id,
  1912. printer_name=printer.name if printer else "Unknown",
  1913. reason="Previous print failed or was aborted",
  1914. db=db,
  1915. )
  1916. continue
  1917. # Resolve the AMS mapping when it's missing OR unresolved
  1918. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1919. # frontend status-load race can persist [-1] (#2589) — and
  1920. # must be recomputed from live trays rather than trusted.
  1921. if await _edited_since_loaded(db, item):
  1922. continue
  1923. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1924. if unmappable:
  1925. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1926. continue
  1927. # Filament-deficit pre-dispatch check (#1496). If the
  1928. # assigned spool can't satisfy any required slot grams,
  1929. # promote the item to manual_start so the user must
  1930. # acknowledge via the ▶ button (which re-checks live).
  1931. if await self._block_on_filament_deficit(db, item):
  1932. # Now staged for the user to start by hand, and the row
  1933. # shows the filament-short badge instead. Cleared because
  1934. # a staged item never reaches this branch again.
  1935. await hold_item(item, None)
  1936. continue
  1937. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1938. # than let the printer pick a substitute for a slot the
  1939. # matcher could not resolve on this printer.
  1940. if await self._block_on_unmatched_filament(db, item):
  1941. continue
  1942. # Hold this item back for the next pass rather than racing
  1943. # another dispatch over the same transient library row. The
  1944. # printer is still marked busy so a later item does not jump
  1945. # its place in this printer's queue.
  1946. if _library_row_conflict(item):
  1947. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1948. await hold_for_printer(
  1949. item,
  1950. item.printer_id,
  1951. "holding its place while another item releases a library row",
  1952. f"Busy: {printer_label(item.printer_id)}",
  1953. )
  1954. continue
  1955. # Print takes priority: stop a cycle Bambuddy armed, now
  1956. # that this item is definitely going out.
  1957. #
  1958. # Placement is the whole point (#2801). This used to sit up
  1959. # with the availability checks, inside the not-idle branch
  1960. # -- so it fired only on the passes where the print was NOT
  1961. # going to start, and never on the ones where it was.
  1962. # Drying is not one of the things `_is_printer_idle` looks
  1963. # at, so a stop could never have unblocked that printer
  1964. # anyway; the cycle was spent for nothing, auto-drying
  1965. # re-armed on the next tick, and a plate left
  1966. # unacknowledged turned that into a loop on the scheduler
  1967. # interval. Every skip between there and here -- a failed
  1968. # previous print, an unmappable item, a filament deficit, a
  1969. # contested library row -- is another way to lose a cycle
  1970. # for a print that never happens, which is why this waits
  1971. # until the decision is actually made.
  1972. if self._drying_in_progress.get(
  1973. item.printer_id
  1974. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1975. await self._stop_drying(item.printer_id)
  1976. # Queue the dispatch instead of running it here — see
  1977. # _dispatch_selected(). busy_printers still gets the printer
  1978. # immediately, so nothing else in this pass can target it.
  1979. #
  1980. # The reason goes first: this item is not waiting for anything
  1981. # any more, and the model-based branch clears its own at the
  1982. # equivalent moment (#3074).
  1983. await hold_item(item, None)
  1984. _claim_library_row(item)
  1985. dispatch_ids.append(item.id)
  1986. claim_printer(item.printer_id)
  1987. # SJF starvation guard: mark items that were jumped
  1988. if sjf_enabled and item.print_time_seconds is not None:
  1989. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1990. for other in items:
  1991. if (
  1992. other.id != item.id
  1993. and other.id not in dispatch_ids
  1994. and other.status == "pending"
  1995. and _could_take_printer(other, item.printer_id, pinned_model)
  1996. and not other.been_jumped
  1997. and other.position < item.position
  1998. and (
  1999. other.print_time_seconds is None
  2000. or other.print_time_seconds > item.print_time_seconds
  2001. )
  2002. ):
  2003. other.been_jumped = True
  2004. await db.commit()
  2005. elif item.target_model or item.variants:
  2006. # Model-based assignment - find any idle printer of matching model.
  2007. # A plain model-based item has exactly one candidate, built from
  2008. # its own columns. A cross-model item (#671) has one per sliced
  2009. # variant and takes the first that matches, walking them in the
  2010. # user's priority order so the pick is reproducible when more
  2011. # than one printer is free in the same pass.
  2012. candidates = _candidates_for(item)
  2013. item_scope = await _creator_scope(item.created_by_id)
  2014. printer_id = None
  2015. chosen: _ModelCandidate | None = None
  2016. per_model_reasons: list[tuple[str | None, str]] = []
  2017. # Candidates that cleared the cross-model gate below. The
  2018. # smart-plug wake step may only consider these — waking a
  2019. # printer for a file that can never legally run on it is
  2020. # worse than not waking at all (#2786).
  2021. wakeable_candidates: list[_ModelCandidate] = []
  2022. # Printers passed over because their last print failed.
  2023. gate_blocked: set[int] = set()
  2024. if not candidates:
  2025. # Every candidate file has been deleted or trashed out from
  2026. # under this item. Hold it with something the user can act
  2027. # on rather than letting it look dispatchable forever.
  2028. per_model_reasons.append(
  2029. (
  2030. item.target_model,
  2031. "Every file for this job has been deleted — add a file back or remove the item",
  2032. )
  2033. )
  2034. for candidate in candidates:
  2035. effective_types, filament_overrides = _filament_constraints(candidate)
  2036. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2037. # for an incompatible model to a printer, no matter how the
  2038. # row got into the DB (old rows, direct API writes). Held
  2039. # as pending with an actionable waiting_reason — the user
  2040. # fixes it by editing the item's target model.
  2041. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2042. per_model_reasons.append(
  2043. (
  2044. candidate.target_model,
  2045. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2046. f"{candidate.target_model} — edit the item and fix its target model",
  2047. )
  2048. )
  2049. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2050. continue
  2051. wakeable_candidates.append(candidate)
  2052. async def is_short(
  2053. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2054. ) -> bool:
  2055. # The check reads the file and plate off the item,
  2056. # so it must hold this candidate's. Resolving is
  2057. # safe to repeat, and the winner is resolved again
  2058. # below.
  2059. self._resolve_variant(item, candidate)
  2060. return await self._filament_short_on(db, item, pid)
  2061. while True:
  2062. match_id, match_reason = await self._find_idle_printer_for_model(
  2063. db,
  2064. candidate.target_model,
  2065. # Sensor-held printers are unavailable to the
  2066. # matcher but stay out of busy_printers itself
  2067. # (#1148) — see where `interlocked` is built.
  2068. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2069. effective_types,
  2070. item.target_location,
  2071. filament_overrides=filament_overrides,
  2072. require_plate_clear=require_plate_clear,
  2073. wakeable_ids=wakeable_printer_ids,
  2074. printer_scope=item_scope,
  2075. is_short=is_short,
  2076. drying_ids=drying_held,
  2077. )
  2078. # "Only if the previous print succeeded" is about the
  2079. # printer the job lands on: one whose last print failed
  2080. # is passed over for another of the model.
  2081. if (
  2082. match_id
  2083. and item.require_previous_success
  2084. and not await self._check_previous_success(db, item, printer_id=match_id)
  2085. ):
  2086. gate_blocked.add(match_id)
  2087. continue
  2088. break
  2089. if match_id:
  2090. printer_id = match_id
  2091. chosen = candidate
  2092. break
  2093. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2094. # Nothing is available and nothing has been woken this pass:
  2095. # switch one matching printer on. Assignment is left to the
  2096. # next pass, which sees the booted printer's live state
  2097. # instead of guessing at it seconds after connect (#2786).
  2098. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2099. woken_id, attempted_id = await self._wake_printer_for_model(
  2100. db,
  2101. wakeable_candidates,
  2102. item.target_location,
  2103. busy_printers | interlocked.keys(),
  2104. wakeable_printer_ids,
  2105. require_plate_clear,
  2106. printer_scope=item_scope,
  2107. )
  2108. # An attempt spends the pass's one wake whether or not
  2109. # it worked: it has already blocked the queue loop for
  2110. # the boot wait. A failed printer is held out of later
  2111. # passes by its own cool-off, deliberately NOT by
  2112. # busy_printers — it is off, not busy, and labelling it
  2113. # busy would both misdescribe it in every later item's
  2114. # waiting reason and suppress the notification, since
  2115. # an all-busy reason is treated as needing no action.
  2116. power_on_attempted = attempted_id is not None
  2117. if woken_id is not None:
  2118. # Hold this item back rather than dispatching onto a
  2119. # printer whose AMS has not reported yet.
  2120. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2121. continue
  2122. if printer_id is None and gate_blocked:
  2123. # The matcher reports the printers passed over as busy;
  2124. # what holds the job is their failed last print.
  2125. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2126. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2127. # Fold the winning variant's file and settings onto the item
  2128. # before anything else looks at them — the guards below and
  2129. # every step of the dispatch read the item's own columns.
  2130. if chosen is not None:
  2131. self._resolve_variant(item, chosen)
  2132. # Update waiting_reason if changed and send notification when first waiting
  2133. if item.waiting_reason != waiting_reason:
  2134. was_waiting = item.waiting_reason is not None
  2135. previous_reason = item.waiting_reason
  2136. item.waiting_reason = waiting_reason
  2137. await db.commit()
  2138. # Send waiting notification only when transitioning to waiting state
  2139. # and the reason requires user action (not just "all printers busy")
  2140. # Also when a job that only waited for a busy printer
  2141. # now waits on something the user has to do.
  2142. if (
  2143. waiting_reason
  2144. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2145. and not self._is_busy_only(waiting_reason)
  2146. ):
  2147. job_name = await self._get_job_name(db, item)
  2148. await notification_service.on_queue_job_waiting(
  2149. job_name=job_name,
  2150. target_model=_candidate_model_label(candidates) or item.target_model,
  2151. waiting_reason=waiting_reason,
  2152. db=db,
  2153. )
  2154. if printer_id:
  2155. # Before claiming the printer: hold back rather than race
  2156. # another dispatch over the same transient library row.
  2157. # Checked here so a held item does not get a printer
  2158. # assigned and then sit on it. See _library_row_conflict().
  2159. #
  2160. # No busy_printers.add() here, unlike the fixed-printer
  2161. # branch above: that one protects its printer's own queue
  2162. # ordering, but this item was never assigned to `printer_id`
  2163. # — the matcher merely offered it. Marking it busy would
  2164. # strand an idle printer for the rest of the pass.
  2165. if _library_row_conflict(item):
  2166. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2167. continue
  2168. if await _edited_since_loaded(db, item):
  2169. continue
  2170. # Assign printer and start - clear waiting reason
  2171. item.printer_id = printer_id
  2172. item.waiting_reason = None
  2173. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2174. # Send assignment notification
  2175. job_name = await self._get_job_name(db, item)
  2176. printer = await self._get_printer(db, printer_id)
  2177. await notification_service.on_queue_job_assigned(
  2178. job_name=job_name,
  2179. printer_id=printer_id,
  2180. printer_name=printer.name if printer else "Unknown",
  2181. target_model=item.target_model,
  2182. db=db,
  2183. )
  2184. # A mapping on this item was not made for the printer just
  2185. # picked: it came with a job moved here from a fixed
  2186. # printer, or from a variant. Its tray IDs can name a
  2187. # tray of the right type in another colour here, which
  2188. # the fit check lets through (#3239). Match afresh, by
  2189. # type and colour.
  2190. if item.ams_mapping:
  2191. logger.info(
  2192. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2193. item.id,
  2194. item.ams_mapping,
  2195. printer_id,
  2196. )
  2197. item.ams_mapping = None
  2198. # On a nozzle-rack printer its own nozzle mapping likewise
  2199. # (set through the API or an order's plate spec): it names
  2200. # rack positions, and the dispatch sends a stored one as-is
  2201. # instead of resolving this printer's rack. Elsewhere it
  2202. # holds extruder indices, the same on every printer of the
  2203. # model (an H2D VP keeps the slicer's for that reason), and
  2204. # one that came with the chosen variant belongs to that
  2205. # variant's file: both stay.
  2206. if (
  2207. (chosen is None or chosen.variant is None)
  2208. and printer is not None
  2209. and is_nozzle_rack_model(printer.model)
  2210. ):
  2211. item.nozzle_mapping = None
  2212. # Resolve the AMS mapping for the assigned printer. It is
  2213. # always missing here, so this computes it, and it also
  2214. # self-heals a bogus stored [-1] (#2589).
  2215. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2216. if unmappable:
  2217. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2218. continue
  2219. # Filament-deficit pre-dispatch check (#1496).
  2220. if await self._block_on_filament_deficit(db, item):
  2221. continue
  2222. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2223. # selection already filters on filament type, so this is a
  2224. # backstop for an AMS that changed between assignment and
  2225. # dispatch, and for a type loaded on the wrong nozzle.
  2226. # The assignment made above is released with the hold —
  2227. # this item asked for a model, not this printer.
  2228. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2229. continue
  2230. # As for a pinned job: drying stops once the print is
  2231. # decided, unless it may run through it.
  2232. if self._drying_in_progress.get(
  2233. printer_id
  2234. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2235. await self._stop_drying(printer_id)
  2236. _claim_library_row(item)
  2237. dispatch_ids.append(item.id)
  2238. claim_printer(printer_id)
  2239. # SJF starvation guard: mark items that were jumped
  2240. if sjf_enabled and item.print_time_seconds is not None:
  2241. for other in items:
  2242. if (
  2243. other.id != item.id
  2244. and other.id not in dispatch_ids
  2245. and other.status == "pending"
  2246. and _could_take_printer(other, printer_id, item.target_model)
  2247. and not other.been_jumped
  2248. and other.position < item.position
  2249. and (
  2250. other.print_time_seconds is None
  2251. or other.print_time_seconds > item.print_time_seconds
  2252. )
  2253. ):
  2254. other.been_jumped = True
  2255. await db.commit()
  2256. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2257. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2258. # skip summary that only lands after the transfers have finished is
  2259. # useless for working out why an item did not go out.
  2260. if skip_reasons:
  2261. logger.info("Queue skip summary: %s", skip_reasons)
  2262. for pid in sorted(busy_printers):
  2263. reason = busy_reasons.get(pid, "no reason recorded")
  2264. if pid in claimed_printers:
  2265. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2266. continue
  2267. # The three live fields stay, because they are what someone
  2268. # reading a bundle wants next -- but they are labelled as read
  2269. # now, not as the state the decision was made on, which is what
  2270. # made the old line contradict itself.
  2271. state = printer_manager.get_status(pid)
  2272. logger.info(
  2273. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2274. pid,
  2275. reason,
  2276. printer_manager.is_connected(pid),
  2277. state.state if state else "NO_STATUS",
  2278. printer_manager.is_awaiting_plate_clear(pid),
  2279. )
  2280. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2281. # selection and `_launch_uploads`, so anything raising here would
  2282. # discard this tick's selections — computed AMS mappings and all —
  2283. # and, on a persistent fault, stop the queue dispatching entirely.
  2284. # Same reasoning as the deficit check's guard below: never let an
  2285. # auxiliary check wedge the queue. The bed simply stays wherever it
  2286. # was, and the next tick tries again.
  2287. try:
  2288. await self._apply_keep_warm(
  2289. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2290. )
  2291. except Exception as e:
  2292. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2293. # Read the concurrency limit BEFORE the commit below, not inside
  2294. # _dispatch_selected(). A SELECT on this session after the commit
  2295. # implicitly opens a fresh transaction that nothing then closes, and
  2296. # it would stay open for the whole dispatch — minutes of "idle in
  2297. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2298. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2299. # checkpointed while every dispatch is writing to it.
  2300. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2301. # Selection is done; every decision above is recorded on `db`
  2302. # (model-based printer assignment, computed ams_mapping). Flush it
  2303. # before the dispatch tasks open their own sessions, or they will
  2304. # read a row that still says printer_id=None. This also releases the
  2305. # connection back to the pool for the duration of the dispatch.
  2306. await db.commit()
  2307. if dispatch_ids:
  2308. item_printers = {it.id: it.printer_id for it in items}
  2309. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2310. # Auto-drying: start drying on idle printers that have no pending queue items
  2311. await self._check_auto_drying(db, items, dispatching_printers)
  2312. # Low filament: alert on assigned spools that have crossed their
  2313. # low-stock threshold (#2913). Runs on both paths out of this method
  2314. # for the same reason auto-drying does — an empty queue does not mean
  2315. # the spools in the printers stopped mattering.
  2316. await self._check_filament_low(db)
  2317. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2318. # is about to run out before a replenishment could arrive (#2955).
  2319. await self._check_stock_forecast(db)
  2320. # Keep the loop on the fast interval while any upload is in flight so
  2321. # a slot freed mid-tick refills within seconds rather than after the
  2322. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2323. # deferred because the pool was full) also counts as productive.
  2324. return bool(dispatch_ids) or bool(self._inflight)
  2325. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2326. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2327. Dispatch used to happen inline in the selection loop: ``await
  2328. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2329. performs the FTP upload, that serialized every printer behind every
  2330. other printer's transfer even though the printers are independent
  2331. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2332. gather was awaited before ``check_queue`` returned, so the run loop
  2333. stayed blocked until the *slowest* upload in the batch finished — a
  2334. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2335. 93-printer farm even as other printers came free (#2602).
  2336. Each upload now runs as an independent background task tracked in
  2337. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2338. `pending` until their upload completes) and their printers from the
  2339. next pass's selection, and this method launches at most
  2340. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2341. the next fast tick instead of waiting out the whole batch. The bound
  2342. exists because the printers are independent but the host is not: each
  2343. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2344. file handle.
  2345. The no-overlapping-dispatch invariant the batch-await used to provide
  2346. is now carried by the in-flight exclusion in check_queue. Everything
  2347. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2348. per-printer hold, and each item's independent failure handling — still
  2349. lives in ``_start_print`` and runs per task exactly as before.
  2350. Synchronous on purpose: it registers every launched task into
  2351. ``self._inflight`` before returning, so the next (sequential) tick sees
  2352. an accurate in-flight count with no interleaving await.
  2353. """
  2354. free = limit - len(self._inflight)
  2355. if free <= 0:
  2356. logger.info(
  2357. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2358. len(self._inflight),
  2359. limit,
  2360. len(item_ids),
  2361. item_ids,
  2362. )
  2363. return
  2364. to_launch = item_ids[:free]
  2365. deferred = item_ids[free:]
  2366. logger.info(
  2367. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2368. len(to_launch),
  2369. len(self._inflight),
  2370. limit,
  2371. f" — deferring {deferred} to a later tick" if deferred else "",
  2372. )
  2373. for item_id in to_launch:
  2374. task = spawn_background_task(
  2375. self._dispatch_one(item_id, item_printers.get(item_id)),
  2376. name=f"queue-upload-{item_id}",
  2377. )
  2378. self._inflight[item_id] = (task, item_printers.get(item_id))
  2379. # Prune on completion so the freed slot is refillable next tick.
  2380. # spawn_background_task already logs any uncaught exception; this
  2381. # only reclaims the pool slot (fires on success, failure, or cancel).
  2382. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2383. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2384. """Upload + start one queue item in its own session (pool worker, #2602).
  2385. Its own session: pool workers run concurrently and an AsyncSession is
  2386. not safe to share across tasks; it also keeps a slow upload from pinning
  2387. the scheduler's session (and, on SQLite, its transaction) open for the
  2388. transfer's duration.
  2389. ``selected_printer_id`` is the printer this item was selected for, taken
  2390. from the same snapshot the caller used. It exists so the preheat pin can
  2391. be unwound on the paths that never reach the ``finally`` below — see the
  2392. claim failure a few lines down. Optional so the direct-call tests keep
  2393. working; when it is absent those paths simply behave as they did before.
  2394. """
  2395. async with async_session() as item_db:
  2396. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2397. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2398. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2399. # routes reject reassignment (409), so printer_id can't change out from
  2400. # under the in-flight upload and split the queue row from the
  2401. # archive/expected-print/physical command.
  2402. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2403. logger.info(
  2404. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2405. item_id,
  2406. )
  2407. # This return is outside the try/finally below, so the rollback
  2408. # has to happen here. Selecting this item already handed any
  2409. # keep-warm hold on its printer over to the preheat pin
  2410. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2411. # unwind it. Bailing without doing so leaves the bed hot with
  2412. # nothing tracking it: the keep-warm entry is gone, so the
  2413. # max-duration cap no longer applies, and if this was the
  2414. # printer's last pending item nothing else will ever turn it
  2415. # off. Reachable whenever a cancel or delete lands between
  2416. # selection and the claim.
  2417. if selected_printer_id is not None:
  2418. self._rollback_preheat_pin(item_id, selected_printer_id)
  2419. return
  2420. # Seeded from the caller's snapshot so the `item vanished` return
  2421. # below still unwinds the pin; overwritten with the row's own
  2422. # printer_id as soon as we have it.
  2423. item_printer_id: int | None = selected_printer_id
  2424. try:
  2425. item = await item_db.get(PrintQueueItem, item_id)
  2426. if not item:
  2427. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2428. return
  2429. item_printer_id = item.printer_id
  2430. await self._start_print(item_db, item)
  2431. finally:
  2432. # Undo an expected-print registration whose print command never
  2433. # went out. One choke point covers every way `_start_print` can
  2434. # end without sending: a raised exception (a DB failure mid-
  2435. # dispatch is the reported case), an early return, a cancel
  2436. # winning the #1853 CAS, or `start_print()` returning False.
  2437. # A confirmed send removes the entry itself, so this is a no-op
  2438. # on the happy path.
  2439. self._rollback_unconfirmed_expected_print(item_id)
  2440. # Likewise the print user it set: the printer's next print is
  2441. # not this item's.
  2442. self._rollback_unconfirmed_print_user(item_id)
  2443. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2444. # reservation survives only after start_print() accepted the
  2445. # command. Failure, cancellation, deferral, and exceptions all
  2446. # release it here.
  2447. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2448. # Unwind preheat state (bed/chamber/airduct) if the
  2449. # dispatch aborted before the print's own gcode took over.
  2450. # `_start_print` clears the pin on successful `start_print()`;
  2451. # anything still present here is by definition an aborted
  2452. # dispatch and gets rolled back so the printer isn't left
  2453. # heating for a job that isn't happening.
  2454. if item_printer_id is not None:
  2455. self._rollback_preheat_pin(item_id, item_printer_id)
  2456. # The cancellation flag only has meaning while this dispatch is
  2457. # running; drop it so the set cannot grow without bound and a
  2458. # re-queued item never inherits a stale cancellation.
  2459. self._cancelled_dispatches.discard(item_id)
  2460. # Release the claim on every exit. Once dispatch has finished the
  2461. # row's status carries the lock (printing/failed/cancelled are all
  2462. # != pending), so the token is only needed for the duration of the
  2463. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2464. # dispatchable again on the next tick.
  2465. await self._clear_dispatch_claim(item_db, item_id)
  2466. async def _requeue_after_upload_refused(
  2467. self,
  2468. db: AsyncSession,
  2469. item: PrintQueueItem,
  2470. printer: Printer,
  2471. error_msg: str,
  2472. toast_uid: int | None,
  2473. ) -> None:
  2474. """Put an item back in the queue after its file never reached the printer (#3210).
  2475. The item keeps its printer. Its AMS mapping was computed against that
  2476. printer's trays, and nothing on the row says whether a mapping was
  2477. computed or set by the user, so moving it to a sibling could print from
  2478. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2479. keeps every other item away from it; this one waits there and is the
  2480. only thing that knocks again, once per backoff window. The window
  2481. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2482. `dispatch_attempts` is not charged: that budget bounds a printer that
  2483. takes the file and then never starts, which this is not.
  2484. """
  2485. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2486. self._upload_refusals[printer.id] = refusals
  2487. backoff = _upload_backoff_seconds(refusals)
  2488. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2489. # The row is still `pending` -- it only moves to `printing` after a
  2490. # successful upload -- so there is no status to write back. Writing one
  2491. # anyway would undo a cancel that landed during the upload.
  2492. if item.error_message:
  2493. item.error_message = None
  2494. await db.commit()
  2495. logger.warning(
  2496. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2497. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2498. item.id,
  2499. printer.id,
  2500. printer.name,
  2501. error_msg,
  2502. refusals,
  2503. backoff,
  2504. )
  2505. try:
  2506. # Closes the dispatch toast for this attempt. Without it the toast
  2507. # keeps spinning on an upload that has ended.
  2508. await ws_manager.send_queue_item_failed(
  2509. user_id=toast_uid,
  2510. queue_item_id=item.id,
  2511. printer_id=item.printer_id,
  2512. reason="upload_failed",
  2513. )
  2514. except Exception:
  2515. pass # toast is best-effort
  2516. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2517. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2518. if printer_id is not None:
  2519. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2520. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2521. """Withdraw the expected print and print user of a sent print that never started.
  2522. Both tell the rest of Bambuddy that the printer's next print is this
  2523. item's: left behind, a print started by hand later is taken for it.
  2524. With ``unless_printing``, a printer that is printing after all keeps
  2525. them, as that print is most likely this one starting late.
  2526. ``keep_expected`` withdraws only the print user, which vouches for any
  2527. print on the printer. The expected print names this item's file, so a
  2528. late start of it is still matched to its archive.
  2529. """
  2530. sent = self._sent_unstarted_print.get(item_id)
  2531. if sent is None:
  2532. return
  2533. printer_id, remote_filename, archive_id = sent
  2534. if unless_printing:
  2535. status = printer_manager.get_status(printer_id)
  2536. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2537. return
  2538. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2539. if keep_expected:
  2540. return
  2541. del self._sent_unstarted_print[item_id]
  2542. if remote_filename is not None and archive_id is not None:
  2543. try:
  2544. from backend.app.main import unregister_expected_print
  2545. unregister_expected_print(printer_id, remote_filename, archive_id)
  2546. except Exception:
  2547. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2548. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2549. """Drop an expectation for a print command that was never sent.
  2550. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2551. where the interesting exception is usually the one already propagating.
  2552. """
  2553. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2554. if pending is None:
  2555. return
  2556. printer_id, remote_filename, archive_id = pending
  2557. try:
  2558. from backend.app.main import unregister_expected_print
  2559. unregister_expected_print(printer_id, remote_filename, archive_id)
  2560. except Exception:
  2561. logger.warning(
  2562. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2563. item_id,
  2564. printer_id,
  2565. remote_filename,
  2566. archive_id,
  2567. exc_info=True,
  2568. )
  2569. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2570. """Release a queue reservation without touching the dispatch session."""
  2571. if item_id not in self._unconfirmed_budget_reservations:
  2572. return
  2573. for attempt in range(1, 4):
  2574. async with async_session() as cleanup_db:
  2575. try:
  2576. await release_budget_reservation(
  2577. cleanup_db,
  2578. source_type="print_queue",
  2579. source_id=item_id,
  2580. status="released",
  2581. )
  2582. await cleanup_db.commit()
  2583. self._unconfirmed_budget_reservations.discard(item_id)
  2584. return
  2585. except Exception as exc:
  2586. try:
  2587. await cleanup_db.rollback()
  2588. except Exception:
  2589. pass
  2590. if attempt == 3:
  2591. logger.error(
  2592. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2593. item_id,
  2594. attempt,
  2595. exc,
  2596. )
  2597. return
  2598. await asyncio.sleep(0.5 * attempt)
  2599. @staticmethod
  2600. def _reported_bed_target(printer_id: int) -> int | None:
  2601. """The bed target firmware currently reports, or None if it can't be read.
  2602. None means "no evidence", not "zero" — callers must not treat it as a
  2603. temperature. Deliberately total: this feeds cleanup paths that run in a
  2604. ``finally``, where a malformed status must not become the exception the
  2605. caller sees.
  2606. """
  2607. try:
  2608. state = printer_manager.get_status(printer_id)
  2609. if state is None:
  2610. return None
  2611. temps = state.temperatures
  2612. if not isinstance(temps, dict):
  2613. return None
  2614. return int(float(temps.get("bed_target", 0) or 0))
  2615. except (TypeError, ValueError, AttributeError):
  2616. return None
  2617. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2618. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2619. Turns the bed heater off, the chamber heater off, and opens the
  2620. airduct flap back to cooling — for whichever of those preheat
  2621. actually applied. `_start_print` clears the pin on successful
  2622. `start_print()`; anything still present when `_dispatch_one` exits
  2623. is by definition an aborted dispatch and gets rolled back here.
  2624. The bed is the one action that can be declined: if firmware has since
  2625. been given a target other than the one we pinned, it belongs to someone
  2626. else and is left alone. See the comment at that branch.
  2627. Also called directly from `_dispatch_one`'s claim-failure return, which
  2628. never reaches the ``finally``.
  2629. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2630. """
  2631. pin = self._preheat_pin.pop(printer_id, set())
  2632. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2633. if not pin:
  2634. return
  2635. client = printer_manager.get_client(printer_id)
  2636. if client is None:
  2637. logger.info(
  2638. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2639. item_id,
  2640. printer_id,
  2641. )
  2642. return
  2643. if "bed" in pin:
  2644. # Only undo our own target. If firmware reports something else, the
  2645. # user or another writer owns the bed now and zeroing it would
  2646. # clobber their choice -- the same guard `_release_keep_warm`
  2647. # applies to a keep-warm hold.
  2648. #
  2649. # Every uncertain case switches the bed off rather than leaving it:
  2650. # no recorded target (a pin written before this bookkeeping, or a
  2651. # setter that raised after pinning) and an unreadable status both
  2652. # fall through. A bed left hot with no owner is the worse failure,
  2653. # and this runs in a `finally` where raising would mask the real
  2654. # exception.
  2655. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2656. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2657. logger.info(
  2658. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2659. item_id,
  2660. printer_id,
  2661. cur_bed_target,
  2662. pinned_bed,
  2663. )
  2664. else:
  2665. try:
  2666. client.set_bed_temperature(0)
  2667. except Exception as exc:
  2668. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2669. if "chamber" in pin:
  2670. try:
  2671. client.set_chamber_temperature(0)
  2672. except Exception as exc:
  2673. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2674. if "airduct" in pin:
  2675. try:
  2676. client.set_airduct_mode("cooling")
  2677. except Exception as exc:
  2678. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2679. logger.info(
  2680. "Dispatch item %s (printer %d): preheat rollback → %s",
  2681. item_id,
  2682. printer_id,
  2683. sorted(pin),
  2684. )
  2685. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2686. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2687. Returns True if this call won the claim, False if the row was already
  2688. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2689. the load-bearing guard against reassign-during-dispatch (#2615).
  2690. ``printer_id`` is the printer the item was selected for: a row moved to
  2691. another printer since is not claimed, and the next pass selects it for
  2692. that one."""
  2693. query = (
  2694. update(PrintQueueItem)
  2695. .where(PrintQueueItem.id == item_id)
  2696. .where(PrintQueueItem.status == "pending")
  2697. .where(PrintQueueItem.dispatching_at.is_(None))
  2698. )
  2699. if printer_id is not None:
  2700. query = query.where(PrintQueueItem.printer_id == printer_id)
  2701. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2702. await db.commit()
  2703. return res.rowcount > 0
  2704. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2705. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2706. mask the dispatch outcome.
  2707. Retried, because the failure mode in practice is transient and narrow: a
  2708. database that is momentarily unreachable — PostgreSQL out of connection
  2709. slots is the observed case — refuses this write for a second or two while
  2710. the dispatch that just ended is still holding the row out of the selection
  2711. query. One attempt was enough to wedge the item; a couple of spaced
  2712. attempts clear it. Each attempt rolls back first, since a failed write
  2713. leaves the session needing it before it can be reused.
  2714. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2715. on the next quiet tick.
  2716. """
  2717. for attempt in range(1, 4):
  2718. try:
  2719. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2720. await db.commit()
  2721. return
  2722. except Exception as exc:
  2723. try:
  2724. await db.rollback()
  2725. except Exception:
  2726. pass
  2727. if attempt == 3:
  2728. logger.warning(
  2729. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2730. "— a later quiet tick will release it",
  2731. item_id,
  2732. attempt,
  2733. exc,
  2734. )
  2735. return
  2736. await asyncio.sleep(0.5 * attempt)
  2737. async def _printers_for_model(
  2738. self,
  2739. db: AsyncSession,
  2740. model: str,
  2741. target_location: str | None = None,
  2742. printer_scope: PrinterScope = ALL_PRINTERS,
  2743. ) -> list[Printer]:
  2744. """Active printers of *model*, optionally narrowed to one location.
  2745. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2746. answer "which printers can this job run on" from one query — a job can
  2747. only be woken onto a printer the matcher would also have considered.
  2748. ``printer_scope`` is the job creator's (#1727).
  2749. """
  2750. normalized_model = normalize_printer_model(model) or model
  2751. query = (
  2752. select(Printer)
  2753. .where(func.lower(Printer.model) == normalized_model.lower())
  2754. .where(Printer.is_active == True) # noqa: E712
  2755. )
  2756. if target_location:
  2757. query = query.where(Printer.location == target_location)
  2758. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2759. query = query.where(clause)
  2760. result = await db.execute(query)
  2761. return list(result.scalars().all())
  2762. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2763. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2764. Read once per queue check rather than per printer: it decides both
  2765. whether the wake step has anything to do and how an offline printer is
  2766. worded in the waiting reason — "Offline" and "offline with no Auto On
  2767. plug" are different problems, and the second is the one the user has to
  2768. fix themselves (#2786).
  2769. """
  2770. result = await db.execute(
  2771. select(SmartPlug.printer_id)
  2772. .where(SmartPlug.printer_id.is_not(None))
  2773. .where(SmartPlug.enabled == True) # noqa: E712
  2774. .where(SmartPlug.auto_on == True) # noqa: E712
  2775. )
  2776. return {pid for (pid,) in result.all() if pid is not None}
  2777. def _wake_recently_failed(self, printer_id: int) -> bool:
  2778. """True while this printer's failed power-on is still cooling off (#2786)."""
  2779. deadline = self._wake_failures.get(printer_id)
  2780. if deadline is None:
  2781. return False
  2782. if time.monotonic() >= deadline:
  2783. del self._wake_failures[printer_id]
  2784. return False
  2785. return True
  2786. async def _wake_printer_for_model(
  2787. self,
  2788. db: AsyncSession,
  2789. candidates: list[_ModelCandidate],
  2790. target_location: str | None,
  2791. exclude_ids: set[int],
  2792. wakeable_ids: set[int],
  2793. require_plate_clear: bool,
  2794. printer_scope: PrinterScope = ALL_PRINTERS,
  2795. ) -> tuple[int | None, int | None]:
  2796. """Power on one offline printer a model-based item could run on (#2786).
  2797. The fixed-printer branch has powered a printer on since smart plugs
  2798. existed. The model-based branch never could: its matcher drops an
  2799. offline printer into the "Offline:" waiting reason and nothing looks at
  2800. its plugs, so a class-targeted job with every matching printer switched
  2801. off sat pending forever. The reporter's log is the controlled
  2802. experiment — the same item, same plug, same Auto On setting, dispatched
  2803. the moment they edited it onto a specific printer.
  2804. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2805. power-on was actually tried, so the caller can tell "nothing here was
  2806. wakeable" (both None — cheap, other items may still find something)
  2807. from "we tried and it did not come up" (only ``attempted_id`` — the
  2808. boot timeout has already been spent).
  2809. A printer whose last known trays cannot satisfy the job is passed over
  2810. rather than woken (#2876): the colours are readable while it is off, so
  2811. switching a farm on one machine at a time to discover them wakes
  2812. printers that could never have taken the job.
  2813. Deliberately does NOT go on to match the job once a printer is up: AMS
  2814. trays arrive with the first status push after connect, so a filament
  2815. check against a printer that booted seconds ago can reject the printer
  2816. we just woke. The next queue pass matches it with live state.
  2817. At most one printer per pass. Each wake blocks the queue loop for the
  2818. boot wait, and a queue of ten class-targeted jobs must not switch on
  2819. ten printers inside one check.
  2820. """
  2821. for candidate in candidates:
  2822. if not candidate.target_model:
  2823. continue
  2824. required_types, filament_overrides = _filament_constraints(candidate)
  2825. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2826. for printer in sorted(printers, key=lambda p: p.id):
  2827. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2828. continue
  2829. if printer_manager.is_connected(printer.id):
  2830. continue
  2831. if self._wake_recently_failed(printer.id):
  2832. # Its plug did not bring it back a moment ago. Move on to a
  2833. # sibling instead of spending this pass — and every pass —
  2834. # on the same printer.
  2835. continue
  2836. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2837. # Waking this one buys nothing: it would boot into IDLE and
  2838. # then be held by the plate-clear gate, which is exactly
  2839. # what the reporter's log shows happening for 80 minutes
  2840. # after a fixed-printer wake. The flag is Bambuddy-side and
  2841. # persisted, so it is readable while the printer is off.
  2842. logger.info(
  2843. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2844. printer.id,
  2845. candidate.target_model,
  2846. )
  2847. continue
  2848. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2849. if shortfall:
  2850. logger.info(
  2851. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2852. printer.id,
  2853. candidate.target_model,
  2854. ", ".join(shortfall),
  2855. )
  2856. continue
  2857. plugs = await self._get_smart_plugs(db, printer.id)
  2858. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2859. if not auto_on_plugs:
  2860. # wakeable_ids said otherwise — the plug changed under us
  2861. # mid-pass. Nothing to do but move on.
  2862. continue
  2863. logger.info(
  2864. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2865. candidate.target_model,
  2866. printer.id,
  2867. )
  2868. primary_plug = self._pick_power_plug(auto_on_plugs)
  2869. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2870. logger.warning(
  2871. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2872. printer.id,
  2873. self._wake_failure_cooloff,
  2874. )
  2875. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2876. return None, printer.id
  2877. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2878. try:
  2879. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2880. if await service.turn_on(extra_plug):
  2881. await publish_plug_state(
  2882. extra_plug.id,
  2883. extra_plug.name,
  2884. extra_plug.printer_id,
  2885. on=True,
  2886. ha_entity_id=extra_plug.ha_entity_id,
  2887. )
  2888. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2889. except Exception as e:
  2890. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2891. return printer.id, printer.id
  2892. return None, None
  2893. async def _find_idle_printer_for_model(
  2894. self,
  2895. db: AsyncSession,
  2896. model: str,
  2897. exclude_ids: set[int],
  2898. required_filament_types: list[str] | None = None,
  2899. target_location: str | None = None,
  2900. filament_overrides: list[dict] | None = None,
  2901. require_plate_clear: bool = True,
  2902. wakeable_ids: set[int] | None = None,
  2903. printer_scope: PrinterScope = ALL_PRINTERS,
  2904. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2905. drying_ids: set[int] | None = None,
  2906. ) -> tuple[int | None, str | None]:
  2907. """Find an idle, connected printer matching the model with compatible filaments.
  2908. Args:
  2909. db: Database session
  2910. model: Printer model to match (e.g., "X1C", "P1S")
  2911. exclude_ids: Printer IDs to exclude (already busy)
  2912. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2913. If provided, only printers with all required types loaded will match.
  2914. target_location: Optional location filter. If provided, only printers in this location are considered.
  2915. filament_overrides: Optional list of override dicts. Each entry may include
  2916. ``force_color_match: true`` to require an exact type+color match
  2917. on the printer for that slot. Without the flag the existing
  2918. colour-preference logic applies.
  2919. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2920. offline printer is worded: one Bambuddy will switch on reads
  2921. differently from one the user has to go and switch on themselves.
  2922. is_short: Says whether a printer's spools are too light for the job (#3137).
  2923. A printer it flags is passed over while another eligible one
  2924. is not. When every eligible printer is short, the first is
  2925. returned all the same, so the deficit gate holds the job there
  2926. and "Print Anyway" still has a printer to print on.
  2927. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  2928. in the reason, as a pinned job's wait is.
  2929. Returns:
  2930. Tuple of (printer_id, waiting_reason):
  2931. - (printer_id, None) if a matching printer was found
  2932. - (None, reason) if no printer is available, with explanation
  2933. """
  2934. normalized_model = normalize_printer_model(model) or model
  2935. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2936. location_suffix = f" in {target_location}" if target_location else ""
  2937. if not printers:
  2938. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2939. # Separate force-matched overrides from preference-only overrides
  2940. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2941. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2942. # Track reasons for skipping printers
  2943. printers_busy = []
  2944. printers_offline = []
  2945. printers_offline_no_plug = []
  2946. printers_missing_filament: list[tuple[str, list[str]]] = []
  2947. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2948. # The first eligible printer that is short on filament, kept in case
  2949. # every eligible printer is (#3137).
  2950. short_fallback: int | None = None
  2951. for printer in printers:
  2952. if printer.id in exclude_ids:
  2953. # Printer is already claimed by another job in this scheduling run.
  2954. # For force-color jobs, still check if the color would match — if not,
  2955. # report it as a color mismatch rather than plain "Busy" so the user
  2956. # knows the job needs a filament change, not just to wait for availability.
  2957. if force_overrides and not pref_overrides:
  2958. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2959. if missing_colors:
  2960. printers_missing_filament.append((printer.name, missing_colors))
  2961. continue
  2962. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  2963. continue
  2964. is_connected = printer_manager.is_connected(printer.id)
  2965. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2966. if not is_connected:
  2967. # An offline printer whose last known filament cannot run this
  2968. # job is reported as needing filament rather than as offline
  2969. # (#2876). It is also the printer the smart-plug step will now
  2970. # decline to switch on, and "Offline:" on its own would leave
  2971. # that decision looking like nothing happening at all.
  2972. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2973. if shortfall:
  2974. printers_missing_filament.append((printer.name, shortfall))
  2975. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2976. printers_offline_no_plug.append(printer.name)
  2977. else:
  2978. printers_offline.append(printer.name)
  2979. continue
  2980. if not is_idle:
  2981. # Printer is currently printing. For force-color jobs, check whether the
  2982. # loaded color would satisfy the requirement — if not, surface it as a
  2983. # color-mismatch reason rather than plain "Busy" so the user understands
  2984. # that the job is waiting for a filament change, not just printer availability.
  2985. if force_overrides and not pref_overrides:
  2986. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2987. if missing_colors:
  2988. printers_missing_filament.append((printer.name, missing_colors))
  2989. logger.debug(
  2990. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2991. printer.id,
  2992. printer.name,
  2993. missing_colors,
  2994. )
  2995. continue
  2996. printers_busy.append(printer.name)
  2997. continue
  2998. # Validate filament compatibility if required types are specified
  2999. if required_filament_types:
  3000. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3001. if missing:
  3002. # When force_overrides are present, enrich missing entries with color info
  3003. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3004. if force_overrides:
  3005. force_color_map = {
  3006. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3007. for o in force_overrides
  3008. }
  3009. missing_enriched = [
  3010. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3011. for t in missing
  3012. ]
  3013. printers_missing_filament.append((printer.name, missing_enriched))
  3014. else:
  3015. printers_missing_filament.append((printer.name, missing))
  3016. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3017. continue
  3018. # Force color match: ALL flagged slots must have an exact type+color match
  3019. if force_overrides:
  3020. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3021. if missing_colors:
  3022. printers_missing_filament.append((printer.name, missing_colors))
  3023. logger.debug(
  3024. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3025. printer.id,
  3026. printer.name,
  3027. missing_colors,
  3028. )
  3029. continue
  3030. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3031. if pref_overrides:
  3032. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3033. if color_matches > 0:
  3034. candidates.append((printer.id, color_matches))
  3035. else:
  3036. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3037. printers_missing_filament.append((printer.name, override_colors))
  3038. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3039. continue
  3040. else:
  3041. # No preference ordering needed: the first eligible printer
  3042. # wins, unless its spools are too light for the job (#3137).
  3043. if is_short is not None and await is_short(printer.id):
  3044. if short_fallback is None:
  3045. short_fallback = printer.id
  3046. logger.info(
  3047. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3048. printer.id,
  3049. printer.name,
  3050. )
  3051. continue
  3052. return printer.id, None
  3053. # If we have candidates from preference override matching, pick the one with most color matches
  3054. if candidates:
  3055. candidates.sort(key=lambda c: c[1], reverse=True)
  3056. if is_short is not None:
  3057. for candidate_id, _ in candidates:
  3058. if not await is_short(candidate_id):
  3059. return candidate_id, None
  3060. logger.info(
  3061. "Model-based assignment: passing over printer %s, not enough filament",
  3062. candidate_id,
  3063. )
  3064. return candidates[0][0], None
  3065. if short_fallback is not None:
  3066. return short_fallback, None
  3067. # Build waiting reason from what we found
  3068. reasons = []
  3069. if printers_missing_filament:
  3070. # Filament/color mismatch is most actionable - show first
  3071. if force_overrides and not pref_overrides:
  3072. # All mismatches are force-color failures — use descriptive message only;
  3073. # but only if there are no busy printers that DO have the matching color.
  3074. # If a printer has the right color but is busy, surface "Busy" instead so
  3075. # the user knows the job will start automatically once that printer is free.
  3076. # Same for a printer that is merely offline: Bambuddy switches that one on
  3077. # by itself, so the job is not actually waiting on anybody to change a
  3078. # spool (#2876 — offline printers reach this list now that a switched-off
  3079. # printer's own filament is read).
  3080. if not printers_busy and not printers_offline:
  3081. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3082. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3083. # else: fall through — the self-resolving entries are appended below
  3084. else:
  3085. names_and_missing = [
  3086. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3087. ]
  3088. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3089. if printers_busy:
  3090. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3091. if printers_offline:
  3092. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3093. if printers_offline_no_plug:
  3094. # Named separately because it is the one entry on this list the
  3095. # user has to act on: no enabled Auto On plug means Bambuddy will
  3096. # never power this printer on for the queue (#2786).
  3097. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3098. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3099. @staticmethod
  3100. def _is_busy_only(waiting_reason: str) -> bool:
  3101. """Check if the waiting reason only contains 'Busy' entries.
  3102. When all matching printers are simply busy printing, the queued job
  3103. will start automatically once a printer finishes — no user action
  3104. is required, so we skip the notification.
  3105. """
  3106. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3107. return all(p.startswith("Busy:") for p in parts)
  3108. def _get_missing_force_color_slots(
  3109. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3110. ) -> list[str]:
  3111. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3112. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3113. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3114. with an exact type+color match.
  3115. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3116. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3117. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3118. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3119. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3120. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3121. setups are unaffected.
  3122. Returns:
  3123. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3124. """
  3125. if raw_data is None:
  3126. status = printer_manager.get_status(printer_id)
  3127. if not status:
  3128. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3129. raw_data = status.raw_data
  3130. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3131. loaded: list[tuple[str, str, str]] = []
  3132. for ams_unit in raw_data.get("ams", []):
  3133. for tray in ams_unit.get("tray", []):
  3134. tray_type = tray.get("tray_type")
  3135. if tray_type:
  3136. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3137. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3138. for vt in raw_data.get("vt_tray") or []:
  3139. vt_type = vt.get("tray_type")
  3140. if vt_type:
  3141. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3142. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3143. missing = []
  3144. for o in force_overrides:
  3145. o_type = canonical_filament_type(o.get("type") or "")
  3146. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3147. o_idx = o.get("tray_info_idx") or ""
  3148. satisfied = any(
  3149. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  3150. for t_type, t_color, t_idx in loaded
  3151. )
  3152. if not satisfied:
  3153. color_label = o.get("color_name") or o.get("color", "?")
  3154. missing.append(f"{o_type} ({color_label})")
  3155. return missing
  3156. def _get_missing_filament_types(
  3157. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3158. ) -> list[str]:
  3159. """Get the list of required filament types that are not loaded on the printer.
  3160. Args:
  3161. printer_id: The printer ID
  3162. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3163. Returns:
  3164. List of missing filament types (empty if all are loaded)
  3165. """
  3166. if raw_data is None:
  3167. status = printer_manager.get_status(printer_id)
  3168. if not status:
  3169. return required_types # Can't determine, assume all missing
  3170. raw_data = status.raw_data
  3171. # Collect all filament types loaded on this printer (AMS units + external spool)
  3172. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3173. loaded_types: set[str] = set()
  3174. # Check AMS units (stored in raw_data["ams"])
  3175. ams_data = raw_data.get("ams", [])
  3176. if ams_data:
  3177. for ams_unit in ams_data:
  3178. for tray in ams_unit.get("tray", []):
  3179. tray_type = tray.get("tray_type")
  3180. if tray_type:
  3181. loaded_types.add(canonical_filament_type(tray_type))
  3182. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3183. for vt in raw_data.get("vt_tray") or []:
  3184. vt_type = vt.get("tray_type")
  3185. if vt_type:
  3186. loaded_types.add(canonical_filament_type(vt_type))
  3187. # Find which required types are missing (using canonical type for equivalence)
  3188. missing = []
  3189. for req_type in required_types:
  3190. if canonical_filament_type(req_type) not in loaded_types:
  3191. missing.append(req_type)
  3192. return missing
  3193. def _count_override_color_matches(
  3194. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3195. ) -> int:
  3196. """Count how many filament overrides have an exact color match on the printer.
  3197. Used to prefer printers that already have the desired override colors loaded.
  3198. """
  3199. if raw_data is None:
  3200. status = printer_manager.get_status(printer_id)
  3201. if not status:
  3202. return 0
  3203. raw_data = status.raw_data
  3204. # Collect loaded filaments' type+color pairs
  3205. loaded: set[tuple[str, str]] = set()
  3206. for ams_unit in raw_data.get("ams", []):
  3207. for tray in ams_unit.get("tray", []):
  3208. tray_type = tray.get("tray_type")
  3209. # `or ""`, not a dict default: a slot can carry the key with a
  3210. # null value, and this now runs against switched-off printers
  3211. # too, where nobody is watching for the AttributeError.
  3212. tray_color = tray.get("tray_color") or ""
  3213. if tray_type:
  3214. color_norm = tray_color.replace("#", "").lower()[:6]
  3215. loaded.add((tray_type.upper(), color_norm))
  3216. for vt in raw_data.get("vt_tray") or []:
  3217. vt_type = vt.get("tray_type")
  3218. if vt_type:
  3219. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3220. loaded.add((vt_type.upper(), color_norm))
  3221. matches = 0
  3222. for o in overrides:
  3223. o_type = (o.get("type") or "").upper()
  3224. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3225. if (o_type, o_color) in loaded:
  3226. matches += 1
  3227. return matches
  3228. @staticmethod
  3229. def _tray_reading(printer_id: int) -> dict:
  3230. """The best tray reading available for a printer that is not printing.
  3231. Live status first: a printer keeps its last status after the power
  3232. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3233. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3234. for when the client itself has been dropped and taken its status with
  3235. it — which is what every power-on attempt does.
  3236. An empty result means "we have never heard", not "nothing is loaded":
  3237. the two are indistinguishable from here, and only the second would be
  3238. safe to act on.
  3239. """
  3240. status = printer_manager.get_status(printer_id)
  3241. raw = (status.raw_data if status else None) or {}
  3242. for ams_unit in raw.get("ams") or []:
  3243. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3244. return raw
  3245. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3246. return raw
  3247. return printer_manager.last_known_trays(printer_id)
  3248. def _cached_filament_shortfall(
  3249. self,
  3250. printer_id: int,
  3251. required_types: list[str] | None,
  3252. filament_overrides: list[dict] | None,
  3253. ) -> list[str]:
  3254. """What a switched-off printer's last known filament cannot provide (#2876).
  3255. The smart-plug wake step used to consider only the model, so a job for a
  3256. colour loaded on the last printer in ID order switched on every earlier
  3257. one in turn, evaluated it, rejected it on colour and left it running.
  3258. Bambuddy knew those colours the whole time. This asks the same three
  3259. questions the matcher asks a live printer — required types, forced
  3260. colours, preferred colours — of the trays it last reported, and returns
  3261. the answers in the same shape the "Waiting for filament" reason uses.
  3262. Empty means the printer may still be able to take the job.
  3263. Fails open, and deliberately: with no tray reading (never connected
  3264. since Bambuddy started, or the cache dropped by a reconnect) this
  3265. returns nothing to report and the printer is treated as it was before.
  3266. A farm restarted while its printers were off must not conclude that
  3267. none of them can print.
  3268. """
  3269. if not required_types and not filament_overrides:
  3270. return []
  3271. raw_data = self._tray_reading(printer_id)
  3272. if not raw_data:
  3273. return []
  3274. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3275. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3276. if required_types:
  3277. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3278. if missing:
  3279. # Same enrichment the live path applies: a bare "PLA" is not
  3280. # much help when what is missing is a particular PLA.
  3281. force_color_map = {
  3282. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3283. }
  3284. return [
  3285. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3286. for t in missing
  3287. ]
  3288. if force_overrides:
  3289. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3290. if missing_colors:
  3291. return missing_colors
  3292. # Preference overrides read as a preference but the matcher treats zero
  3293. # matches as a skip, so a printer with none of the wanted colours is
  3294. # rejected there too. Waking it would only produce that same rejection.
  3295. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3296. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3297. return []
  3298. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3299. """Fold the winning candidate's file and settings onto the queue row (#671).
  3300. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3301. never escapes the selection loop. By the time the pass commits, the row
  3302. looks exactly like an ordinary single-file model-based item, so the upload,
  3303. archive creation, expected-print registration, print history and reprint
  3304. paths need no knowledge that variants exist.
  3305. No-ops for a non-variant candidate, which is already the item's own columns.
  3306. Safe to run and re-run: the item's file columns are only ever *read* when it
  3307. has no variants, so an item that gets resolved and then skipped (library-row
  3308. conflict, previous-print gate) is simply resolved again on the next pass.
  3309. """
  3310. variant = candidate.variant
  3311. if variant is None:
  3312. return
  3313. item.library_file_id = variant.library_file_id
  3314. item.library_file = variant.library_file
  3315. # The dispatcher checks archive_id first and would print that instead of
  3316. # the file we just picked. Creation refuses to combine the two, so this
  3317. # only ever fires on a hand-written row — clear it rather than silently
  3318. # dispatch something the matcher never considered.
  3319. item.archive_id = None
  3320. item.archive = None
  3321. item.target_model = variant.target_model
  3322. item.plate_id = variant.plate_id
  3323. item.ams_mapping = variant.ams_mapping
  3324. item.nozzle_mapping = variant.nozzle_mapping
  3325. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3326. item.filament_overrides = variant.filament_overrides
  3327. item.required_filament_types = variant.required_filament_types
  3328. if variant.print_time_seconds is not None:
  3329. # The row carried the shortest candidate's estimate so SJF could order
  3330. # it before a printer was known; now that one is chosen, record what is
  3331. # actually going to run so history and the ETA agree with reality.
  3332. item.print_time_seconds = variant.print_time_seconds
  3333. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3334. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3335. Recomputes from live printer status when the stored mapping is missing OR
  3336. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3337. frontend status-load race can serialize [-1] before the printer's AMS
  3338. trays are known (#2589) — and must not be trusted: downstream it would be
  3339. silently downgraded to external-spool mode and print against an empty
  3340. feed. A resolved mapping is re-checked against the target printer's
  3341. live trays before it is trusted (#2799) and recomputed when it does not
  3342. fit. When it does fit, its resolved slots are kept as they are and only
  3343. the slots the plate prints that are still unresolved are matched again;
  3344. all of it is left alone when the user has acknowledged it with "Print
  3345. Anyway".
  3346. When recompute cannot resolve it either (no compatible tray loaded), the
  3347. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3348. external selection. On a printer that reported loaded trays,
  3349. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3350. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3351. and the firmware surfaces a clear AMS-mapping error instead of silently
  3352. printing to the empty external feed.
  3353. Returns an actionable message when that firmware error is the only
  3354. possible outcome — the matcher ran, matched nothing, and the printer has
  3355. no AMS to load a different spool into (#2771). The caller fails the item
  3356. on it instead of spending an upload on a print that cannot start.
  3357. Returns None everywhere else, including every case where we simply lack
  3358. the data to judge, so dispatch is only ever blocked on a positive
  3359. finding.
  3360. """
  3361. stored_mapping: list | None = None
  3362. if item.ams_mapping:
  3363. try:
  3364. stored_mapping = json.loads(item.ams_mapping)
  3365. except (json.JSONDecodeError, TypeError):
  3366. stored_mapping = None
  3367. # Present and resolved. Global tray IDs only mean something relative to
  3368. # the printer they were resolved against, so "resolved" is not the same
  3369. # as "resolved *here*" — check the mapping still fits the printer that
  3370. # is about to run this item before trusting it (#2799). "Print anyway"
  3371. # is the user overriding exactly this judgement, so it short-circuits.
  3372. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3373. if item.skip_filament_check:
  3374. return None
  3375. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3376. if conflict is None:
  3377. # It fits, but a slot the plate prints may still be empty: the
  3378. # spool was missing when it was mapped, and has perhaps been
  3379. # loaded since. Nothing else would ever look at that slot again,
  3380. # so a job held for it would be held again on every Start.
  3381. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3382. if filled is not None:
  3383. item.ams_mapping = json.dumps(filled)
  3384. logger.info(
  3385. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3386. item.id,
  3387. stored_mapping,
  3388. printer_id,
  3389. filled,
  3390. )
  3391. await db.commit()
  3392. return None
  3393. logger.warning(
  3394. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3395. item.id,
  3396. stored_mapping,
  3397. printer_id,
  3398. conflict,
  3399. )
  3400. # Drop it before recomputing so a failed recompute cannot fall back
  3401. # to the mapping we just rejected.
  3402. item.ams_mapping = None
  3403. stored_mapping = None
  3404. await db.commit()
  3405. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3406. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3407. item.ams_mapping = json.dumps(computed_mapping)
  3408. logger.info(
  3409. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3410. item.id,
  3411. printer_id,
  3412. computed_mapping,
  3413. )
  3414. await db.commit()
  3415. return None
  3416. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3417. if external_only is not None:
  3418. item.ams_mapping = json.dumps(external_only)
  3419. logger.info(
  3420. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3421. "mapping every filament to it: %s",
  3422. item.id,
  3423. printer_id,
  3424. external_only,
  3425. )
  3426. await db.commit()
  3427. return None
  3428. if _mapping_is_all_unresolved(stored_mapping):
  3429. logger.warning(
  3430. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3431. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3432. item.id,
  3433. stored_mapping,
  3434. printer_id,
  3435. )
  3436. item.ams_mapping = None
  3437. await db.commit()
  3438. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3439. async def _external_spool_only_mapping(
  3440. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3441. ) -> list[int] | None:
  3442. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3443. A printer without an AMS prints from its external spool, and an external
  3444. spool whose filament was never set reports no type, so the matcher has
  3445. nothing to match. Sent without a mapping, the print goes out with the AMS
  3446. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3447. to carry such a job through; a job placed by model or location no longer
  3448. keeps one, and one queued that way never had one.
  3449. Only on a positive report: the printer has said it has no AMS, it has a
  3450. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3451. is not ours to pick), and no feed has a filament set — with one set, the
  3452. matcher has already given its answer. Not for a job that asked for its
  3453. colours to be matched strictly: a spool without a filament set has no
  3454. colour to check. Returns None otherwise.
  3455. """
  3456. if item.filament_overrides:
  3457. try:
  3458. overrides = json.loads(item.filament_overrides)
  3459. except (json.JSONDecodeError, TypeError):
  3460. return None
  3461. if not isinstance(overrides, list) or any(
  3462. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3463. ):
  3464. return None
  3465. status = printer_manager.get_status(printer_id)
  3466. if status is None or not isinstance(status.raw_data, dict):
  3467. return None
  3468. ams_units = status.raw_data.get("ams")
  3469. if not isinstance(ams_units, list) or ams_units:
  3470. return None
  3471. vt_trays = status.raw_data.get("vt_tray")
  3472. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3473. return None
  3474. if self._build_loaded_filaments(status):
  3475. return None
  3476. printer = await self._get_printer(db, printer_id)
  3477. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3478. return None
  3479. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3480. if external < _EXTERNAL_TRAY_ID_MIN:
  3481. return None
  3482. required = await self._get_filament_requirements(db, item)
  3483. slot_ids = [r.get("slot_id") for r in required or []]
  3484. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3485. if not slot_ids:
  3486. return None
  3487. mapping = [-1] * max(slot_ids)
  3488. for slot_id in slot_ids:
  3489. mapping[slot_id - 1] = external
  3490. return mapping
  3491. async def _fill_unresolved_slots(
  3492. self,
  3493. db: AsyncSession,
  3494. printer_id: int,
  3495. item: PrintQueueItem,
  3496. stored_mapping: list | None,
  3497. ) -> list | None:
  3498. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3499. Every resolved entry is kept, so a tray the user picked by hand stays
  3500. picked. Only the plate's unresolved slots are matched, and only against
  3501. trays the mapping does not already use: the matcher never gives two
  3502. slots one tray, and filling a gap with a tray the user assigned to
  3503. another slot would print that slot's filament twice.
  3504. Returns None when there is nothing to fill or nothing could be filled.
  3505. """
  3506. if not isinstance(stored_mapping, list) or not stored_mapping:
  3507. return None
  3508. required = await self._get_filament_requirements(db, item)
  3509. if not required:
  3510. return None
  3511. self._apply_filament_overrides(item, required)
  3512. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3513. if not gaps:
  3514. return None
  3515. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3516. computed = await self._compute_ams_mapping_for_printer(
  3517. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3518. )
  3519. if not computed:
  3520. return None
  3521. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3522. filled = False
  3523. for slot_id in gaps:
  3524. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3525. if _is_tray_id(tray) and tray >= 0:
  3526. merged[slot_id - 1] = tray
  3527. filled = True
  3528. return merged if filled else None
  3529. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3530. """What a staged item would be held for if it were started now (#2799).
  3531. The Start button asks this before releasing an item, so that a job whose
  3532. filament is still not loaded offers "Print Anyway" instead of being
  3533. released, held again by the scheduler and leaving no way past the hold.
  3534. It reaches the same answer the dispatch path would: a stored mapping
  3535. that fits is kept and only its gaps are matched again, and one that
  3536. does not fit (or is missing) is replaced by a fresh match.
  3537. Returns the missing filaments, described the way the queue row
  3538. describes them, or None when nothing is missing or there is not enough
  3539. evidence to say: no printer yet (a model-based item picks one at
  3540. dispatch), no status, no trays reported, or no readable 3MF.
  3541. """
  3542. if item.skip_filament_check or not item.printer_id:
  3543. return None
  3544. status = printer_manager.get_status(item.printer_id)
  3545. if status is None or not self._build_loaded_filaments(status):
  3546. return None
  3547. # Called from a request, not from a pass: drop whatever the last pass
  3548. # memoised so this reads the file as it is now. A pass running at the
  3549. # same time only loses its cache.
  3550. self._filament_req_memo.clear()
  3551. mapping: list | None = None
  3552. if item.ams_mapping:
  3553. try:
  3554. mapping = json.loads(item.ams_mapping)
  3555. except (json.JSONDecodeError, TypeError):
  3556. mapping = None
  3557. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3558. mapping = None
  3559. if mapping is not None:
  3560. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3561. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3562. else:
  3563. mapping = None
  3564. if mapping is None:
  3565. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3566. required = await self._get_filament_requirements(db, item)
  3567. if not required:
  3568. return None
  3569. self._apply_filament_overrides(item, required)
  3570. missing = _unresolved_required(required, mapping)
  3571. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3572. async def _stored_mapping_conflict(
  3573. self,
  3574. db: AsyncSession,
  3575. printer_id: int,
  3576. item: PrintQueueItem,
  3577. stored_mapping: list | None,
  3578. ) -> str | None:
  3579. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3580. A mapping is a list of global tray IDs, and those are only meaningful
  3581. relative to the printer they were resolved against — the same rule
  3582. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3583. arrives at a printer it was not resolved for:
  3584. * the print dialog stamps one mapping onto every selected printer, so a
  3585. mapping computed against the first printer is dispatched verbatim to
  3586. the rest, whose AMS slot order differs;
  3587. * a spool is moved between queueing and dispatch.
  3588. Both end the same way: the slot index still resolves, so nothing looks
  3589. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3590. the firmware's own type check, so a PETG slot happily prints in ASA.
  3591. Returns a short reason when the mapping names a tray this printer does
  3592. not have loaded, points a slot at a tray holding a different filament
  3593. type, or points it at an external spool this printer reports empty while
  3594. its AMS holds that slot's filament (#3239). Returns None when the
  3595. mapping fits, and — deliberately — whenever we lack the evidence to
  3596. judge, so a recompute only ever follows a positive finding.
  3597. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3598. matcher had nothing, not that the mapping belongs to another printer,
  3599. and destroying a partially hand-resolved mapping over it would lose the
  3600. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3601. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3602. item when that finds nothing.
  3603. """
  3604. if not isinstance(stored_mapping, list) or not stored_mapping:
  3605. return None
  3606. status = printer_manager.get_status(printer_id)
  3607. if status is None:
  3608. return None
  3609. loaded = self._build_loaded_filaments(status)
  3610. if not loaded:
  3611. # Nothing reported yet (reconnect, first push pending). Saying
  3612. # "tray not loaded" here would recompute against an AMS we cannot
  3613. # see, which is how #2589 produced a bogus all-[-1] in the first
  3614. # place.
  3615. return None
  3616. by_tray = {f["global_tray_id"]: f for f in loaded}
  3617. # Cheap pass first, on live status alone: every tray the mapping names
  3618. # has to exist here. This catches a foreign mapping without opening the
  3619. # 3MF, which is worth doing because the parse below is neither cached
  3620. # nor free.
  3621. for index, tray in enumerate(stored_mapping):
  3622. if not _is_tray_id(tray) or tray < 0:
  3623. continue
  3624. if tray in by_tray:
  3625. continue
  3626. if tray >= 254:
  3627. # An external feed we have not heard about is absence of
  3628. # evidence about *that slot* — the rest of the mapping is still
  3629. # worth judging, so skip it rather than abandoning the pass.
  3630. continue
  3631. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3632. # Only now is the 3MF worth opening: the type check needs to know what
  3633. # each slot actually asked for. The external spool is checked the same
  3634. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3635. # two printers with different filament in the external feed is the same
  3636. # failure this method exists to catch.
  3637. required = await self._get_filament_requirements(db, item)
  3638. if not required:
  3639. return None
  3640. self._apply_filament_overrides(item, required)
  3641. # External feeds the printer reports and reports as empty. That is
  3642. # evidence, unlike an external feed it says nothing about (#3239).
  3643. empty_external: set[int] = set()
  3644. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3645. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3646. if isinstance(vt, dict) and not vt.get("tray_type"):
  3647. try:
  3648. empty_external.add(int(vt.get("id", 254)))
  3649. except (TypeError, ValueError):
  3650. continue
  3651. for req in required:
  3652. slot_id = req.get("slot_id") or 0
  3653. if slot_id <= 0:
  3654. continue
  3655. if slot_id > len(stored_mapping):
  3656. return f"slot {slot_id} is not covered by the mapping"
  3657. tray = stored_mapping[slot_id - 1]
  3658. if not _is_tray_id(tray) or tray < 0:
  3659. continue
  3660. loaded_tray = by_tray.get(tray)
  3661. if loaded_tray is None:
  3662. # A mapping made for a printer that feeds this slot from its
  3663. # external spool, sent to one whose external spool is empty and
  3664. # whose AMS holds the filament (#3239). Only then: an external
  3665. # spool can be loaded without its filament set, and on a printer
  3666. # with nothing else to offer that job printed before. The colour
  3667. # has to match too: with only another colour in the AMS, the
  3668. # printer asking for the spool beats printing in that colour.
  3669. want = canonical_filament_type(req.get("type"))
  3670. if tray >= 254 and tray in empty_external and want:
  3671. ams_tray = next(
  3672. (
  3673. f
  3674. for f in loaded
  3675. if not f.get("is_external")
  3676. and canonical_filament_type(f.get("type")) == want
  3677. and self._colors_are_similar(f.get("color"), req.get("color"))
  3678. ),
  3679. None,
  3680. )
  3681. if ams_tray is not None:
  3682. return (
  3683. f"slot {slot_id} points at the external spool, which is empty, "
  3684. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3685. )
  3686. continue
  3687. want = canonical_filament_type(req.get("type"))
  3688. have = canonical_filament_type(loaded_tray.get("type"))
  3689. if want and have and want != have:
  3690. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3691. return None
  3692. async def _unmappable_without_ams_message(
  3693. self,
  3694. db: AsyncSession,
  3695. printer_id: int,
  3696. item: PrintQueueItem,
  3697. computed_mapping: list[int] | None,
  3698. ) -> str | None:
  3699. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3700. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3701. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3702. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3703. uploaded several megabytes and burned its dispatch retries. This method
  3704. speaks only for the AMS-less case: there is nothing to resume into — the
  3705. external spool holder is the whole inventory — so the useful answer is to
  3706. say which filament is missing and stop. With an AMS attached it returns
  3707. None: where live status reported loaded trays,
  3708. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3709. reported none the print goes out and the firmware error is the answer —
  3710. the user can load the right spool and press Resume.
  3711. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3712. every branch that lacks the evidence to be sure returns None.
  3713. """
  3714. # None means the matcher never ran (no requirements parsed from the 3MF,
  3715. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3716. # dispatch as they always have.
  3717. if not _mapping_is_all_unresolved(computed_mapping):
  3718. return None
  3719. status = printer_manager.get_status(printer_id)
  3720. if status is None:
  3721. return None
  3722. # "No AMS" has to be a fact the printer stated, not the absence of a
  3723. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3724. # handled and is preserved across partial pushes thereafter, so a missing
  3725. # key means we have not heard yet — most likely a reconnect, where the
  3726. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3727. # empty list is the positive report of a printer with no AMS.
  3728. ams_units = status.raw_data.get("ams")
  3729. if not isinstance(ams_units, list) or ams_units:
  3730. return None
  3731. required = await self._get_filament_requirements(db, item)
  3732. loaded = self._build_loaded_filaments(status)
  3733. if not required or not loaded:
  3734. # Both were non-empty moments ago or the matcher could not have run.
  3735. # If the picture changed under us, say nothing rather than fail an
  3736. # item on stale evidence.
  3737. return None
  3738. self._apply_filament_overrides(item, required)
  3739. return _unmatched_filament_message(required, loaded)
  3740. async def _fail_unmappable_item(
  3741. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3742. ) -> None:
  3743. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3744. This replaces a failure, not a success: without it the item is uploaded,
  3745. rejected by the firmware with 0700_8012, retried twice more and failed
  3746. anyway with "never started the print after N dispatch attempts". So this
  3747. applies on the model-based path too, even though it means an "Any <model>"
  3748. job stops at the first printer offered rather than trying its siblings —
  3749. deferring instead would need the check to move inside
  3750. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3751. re-assigns the same printer on the next tick.
  3752. """
  3753. item.status = "failed"
  3754. item.error_message = message
  3755. item.completed_at = datetime.now(timezone.utc)
  3756. item.waiting_reason = None
  3757. await db.commit()
  3758. from backend.app.services.print_batch import refresh_batches_after
  3759. await refresh_batches_after([item.id])
  3760. logger.warning(
  3761. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3762. item.id,
  3763. printer_id,
  3764. message,
  3765. )
  3766. job_name = await self._get_job_name(db, item)
  3767. printer = await self._get_printer(db, printer_id)
  3768. await notification_service.on_queue_job_failed(
  3769. job_name=job_name,
  3770. printer_id=printer_id,
  3771. printer_name=printer.name if printer else "Unknown",
  3772. reason=message,
  3773. db=db,
  3774. )
  3775. try:
  3776. await ws_manager.send_queue_item_failed(
  3777. user_id=item.created_by_id,
  3778. queue_item_id=item.id,
  3779. printer_id=printer_id,
  3780. reason="filament_unmappable",
  3781. )
  3782. except Exception:
  3783. pass
  3784. async def _compute_ams_mapping_for_printer(
  3785. self,
  3786. db: AsyncSession,
  3787. printer_id: int,
  3788. item: PrintQueueItem,
  3789. *,
  3790. only_slots: set[int] | None = None,
  3791. reserved_trays: set[int] | None = None,
  3792. ) -> list[int] | None:
  3793. """Compute AMS mapping for a printer based on filament requirements.
  3794. Called when a queue item has no ams_mapping set — either for model-based
  3795. items after printer assignment, or printer-specific items (e.g. from VP).
  3796. Args:
  3797. db: Database session
  3798. printer_id: The assigned printer ID
  3799. item: The queue item (contains archive_id or library_file_id)
  3800. only_slots: Match only these filament slots; every other slot comes
  3801. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3802. reserved_trays: Global tray IDs to leave out of the match, because
  3803. the stored mapping already gives them to another slot.
  3804. Returns:
  3805. AMS mapping array or None if no mapping needed/possible
  3806. """
  3807. # Get printer status
  3808. status = printer_manager.get_status(printer_id)
  3809. if not status:
  3810. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3811. return None
  3812. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3813. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3814. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3815. # an AMS on the *other* nozzle, and the matcher falls through to a
  3816. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3817. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3818. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3819. # Get filament requirements from source file
  3820. filament_reqs = await self._get_filament_requirements(db, item)
  3821. if not filament_reqs:
  3822. # When the 3MF can't be read but force-color overrides are present, build a
  3823. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3824. if item.filament_overrides:
  3825. try:
  3826. overrides = json.loads(item.filament_overrides)
  3827. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3828. if force_overrides:
  3829. logger.info(
  3830. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3831. "force-color override(s)",
  3832. item.id,
  3833. len(force_overrides),
  3834. )
  3835. return self._build_override_direct_mapping(force_overrides, status)
  3836. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3837. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3838. logger.debug("No filament requirements found for queue item %s", item.id)
  3839. return None
  3840. self._apply_filament_overrides(item, filament_reqs)
  3841. if only_slots is not None:
  3842. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3843. if not filament_reqs:
  3844. return None
  3845. # Build loaded filaments from printer status
  3846. loaded_filaments = self._build_loaded_filaments(status)
  3847. if reserved_trays:
  3848. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3849. if not loaded_filaments:
  3850. logger.debug("No filaments loaded on printer %s", printer_id)
  3851. return None
  3852. # Check if user prefers lowest remaining filament when multiple spools match
  3853. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3854. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3855. # Without backup, the printer will not switch to a second spool when the
  3856. # picked one runs out — so sorting toward the lowest leaves the print
  3857. # at risk of running dry mid-job. None (unknown: no status report with
  3858. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3859. if prefer_lowest and status.ams_filament_backup is False:
  3860. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3861. prefer_lowest = False
  3862. # When the preference is on, surface Bambuddy's inventory-side
  3863. # remaining for each slot that's bound to a tracked spool, so the
  3864. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3865. # entirely when the preference is off — no behaviour change for
  3866. # users who haven't opted in.
  3867. inventory_remain_overrides: dict[int, float] | None = None
  3868. if prefer_lowest:
  3869. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3870. # Compute mapping: match required filaments to available slots
  3871. return self._match_filaments_to_slots(
  3872. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3873. )
  3874. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3875. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3876. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3877. diagnosis (#2771) describes the filament the matcher actually looked
  3878. for, not the one the 3MF was sliced with — naming the pre-override
  3879. filament in a user-facing error would send the user to load the wrong
  3880. spool.
  3881. """
  3882. if not item.filament_overrides:
  3883. return
  3884. try:
  3885. overrides = json.loads(item.filament_overrides)
  3886. override_map = {o["slot_id"]: o for o in overrides}
  3887. for req in filament_reqs:
  3888. if req["slot_id"] in override_map:
  3889. override = override_map[req["slot_id"]]
  3890. req["type"] = override["type"]
  3891. req["color"] = override["color"]
  3892. # A manual/preference override SWAPS the slot's filament, so the
  3893. # 3MF's original tray_info_idx now points at the old spool and must
  3894. # be cleared — matching then falls back to type+colour. A
  3895. # force_color_match override is not a swap: it carries the 3MF's
  3896. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3897. # it here too, letting the matcher pin the correct variant slot on a
  3898. # printer holding two same-colour spools of different variants (#2650).
  3899. # If that variant isn't loaded the matcher falls back to type+colour,
  3900. # so an eligible printer never fails to map.
  3901. req["tray_info_idx"] = (
  3902. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3903. )
  3904. logger.debug(
  3905. "Queue item %s: Override slot %d -> %s %s",
  3906. item.id,
  3907. req["slot_id"],
  3908. override["type"],
  3909. override["color"],
  3910. )
  3911. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3912. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3913. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3914. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3915. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3916. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3917. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3918. treated as the filament requirement for that slot and matched against the
  3919. current AMS state of the printer.
  3920. Returns the same format as ``_match_filaments_to_slots``, or None when
  3921. the AMS has no loaded filaments.
  3922. """
  3923. loaded = self._build_loaded_filaments(status)
  3924. if not loaded:
  3925. return None
  3926. reqs = [
  3927. {
  3928. "slot_id": o["slot_id"],
  3929. "type": o.get("type", ""),
  3930. "color": o.get("color", ""),
  3931. # These are all force_color_match overrides, so the idx (when the
  3932. # 3MF carried one) is the intended variant, not a stale swap —
  3933. # keep it so the matcher pins the right variant slot, falling back
  3934. # to type+colour when it isn't loaded (#2650).
  3935. "tray_info_idx": o.get("tray_info_idx", ""),
  3936. }
  3937. for o in force_overrides
  3938. ]
  3939. return self._match_filaments_to_slots(reqs, loaded)
  3940. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3941. """Resolve the queue item's source 3MF and parse the per-slot
  3942. filament requirements out of it. Thin DB-resolver wrapper around
  3943. ``filament_requirements.extract_filament_requirements`` so the VP
  3944. queue-mode write path (#1188) can reuse the same parser at upload
  3945. time.
  3946. """
  3947. from backend.app.services.filament_requirements import extract_filament_requirements
  3948. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3949. # so every caller gets its own copy — a shared list would leak one
  3950. # item's overrides into the next item that happens to print the same
  3951. # plate.
  3952. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3953. if memo_key in self._filament_req_memo:
  3954. cached = self._filament_req_memo[memo_key]
  3955. return [dict(r) for r in cached] if cached else None
  3956. file_path: Path | None = None
  3957. if item.archive_id:
  3958. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3959. archive = result.scalar_one_or_none()
  3960. if archive:
  3961. file_path = settings.base_dir / archive.file_path
  3962. elif item.library_file_id:
  3963. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3964. library_file = result.scalar_one_or_none()
  3965. if library_file:
  3966. lib_path = Path(library_file.file_path)
  3967. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3968. if not file_path or not file_path.exists():
  3969. self._filament_req_memo[memo_key] = None
  3970. return None
  3971. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3972. self._filament_req_memo[memo_key] = filaments or None
  3973. return [dict(r) for r in filaments] if filaments else None
  3974. def _build_loaded_filaments(self, status) -> list[dict]:
  3975. """Build list of loaded filaments from printer status.
  3976. Args:
  3977. status: PrinterState from printer_manager
  3978. Returns:
  3979. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3980. """
  3981. filaments = []
  3982. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3983. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3984. # Routes external spools to an extruder (#2771). Mirrors
  3985. # `buildLoadedFilaments` in the frontend.
  3986. vt_trays = status.raw_data.get("vt_tray") or []
  3987. is_dual_nozzle = reports_two_nozzles(status)
  3988. # Parse AMS units from raw_data
  3989. ams_data = status.raw_data.get("ams", [])
  3990. for ams_unit in ams_data:
  3991. ams_id = int(ams_unit.get("id", 0))
  3992. trays = ams_unit.get("tray", [])
  3993. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  3994. for tray in trays:
  3995. tray_type = tray.get("tray_type")
  3996. if tray_type:
  3997. tray_id = int(tray.get("id", 0))
  3998. tray_color = tray.get("tray_color", "")
  3999. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4000. tray_info_idx = tray.get("tray_info_idx", "")
  4001. # Normalize color: remove alpha, add hash
  4002. color = self._normalize_color(tray_color)
  4003. # Calculate global tray ID
  4004. # AMS-HT units have IDs starting at 128 with a single tray
  4005. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4006. filaments.append(
  4007. {
  4008. "type": tray_type,
  4009. "color": color,
  4010. "tray_info_idx": tray_info_idx,
  4011. "ams_id": ams_id,
  4012. "tray_id": tray_id,
  4013. "is_ht": is_ht,
  4014. "is_external": False,
  4015. "global_tray_id": global_tray_id,
  4016. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4017. "remain": tray.get("remain", -1),
  4018. }
  4019. )
  4020. # Check external spool(s) (vt_tray is a list)
  4021. for idx, vt in enumerate(vt_trays):
  4022. if vt.get("tray_type"):
  4023. color = self._normalize_color(vt.get("tray_color", ""))
  4024. tray_id = int(vt.get("id", 254))
  4025. filaments.append(
  4026. {
  4027. "type": vt["tray_type"],
  4028. "color": color,
  4029. "tray_info_idx": vt.get("tray_info_idx", ""),
  4030. "ams_id": -1,
  4031. "tray_id": idx,
  4032. "is_ht": False,
  4033. "is_external": True,
  4034. "global_tray_id": tray_id,
  4035. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4036. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4037. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4038. "remain": vt.get("remain", -1),
  4039. }
  4040. )
  4041. return filaments
  4042. def _normalize_color(self, color: str | None) -> str:
  4043. """Normalize color to #RRGGBB format."""
  4044. if not color:
  4045. return "#808080"
  4046. hex_color = color.replace("#", "")[:6]
  4047. return f"#{hex_color}"
  4048. def _normalize_color_for_compare(self, color: str | None) -> str:
  4049. """Normalize color for comparison (lowercase, no hash)."""
  4050. if not color:
  4051. return ""
  4052. return color.replace("#", "").lower()[:6]
  4053. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4054. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4055. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4056. stays the per-channel box that shipped — this only decides which of
  4057. several eligible spools is closest, so nothing becomes usable or
  4058. unusable because of it.
  4059. It ranks by how far apart the colours *look*, not how far apart their
  4060. numbers are. RGB distance overweights blue badly enough to invert the
  4061. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4062. the nearer of two eligible spools by RGB and the further by a factor of
  4063. four once measured perceptually.
  4064. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4065. transparent filament is not a colour the user chose, and counting it
  4066. would stop a transparent filament matching itself.
  4067. """
  4068. return perceptual_color_distance(color1, color2)
  4069. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4070. """Check if two colors are visually similar within a threshold."""
  4071. hex1 = self._normalize_color_for_compare(color1)
  4072. hex2 = self._normalize_color_for_compare(color2)
  4073. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4074. return False
  4075. try:
  4076. r1 = int(hex1[0:2], 16)
  4077. g1 = int(hex1[2:4], 16)
  4078. b1 = int(hex1[4:6], 16)
  4079. r2 = int(hex2[0:2], 16)
  4080. g2 = int(hex2[2:4], 16)
  4081. b2 = int(hex2[4:6], 16)
  4082. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4083. except ValueError:
  4084. return False
  4085. async def _build_inventory_remain_overrides(
  4086. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4087. ) -> dict[int, float]:
  4088. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4089. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4090. The MQTT ``remain`` field on a tray is the printer firmware's
  4091. RFID-decremented value, which has two limitations the "Prefer Lowest
  4092. Remaining Filament" feature has been ignoring (#1508):
  4093. - it's only meaningful for Bambu RFID spools; everything else reports
  4094. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4095. compare equal and the sort collapses to AMS-slot order — the user
  4096. who's curating inventory weights gets the lower-slot pick instead
  4097. of the lower-remaining pick;
  4098. - even when set, it's the *printer's* counter, not Bambuddy's
  4099. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4100. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4101. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4102. When the user has bound a spool to a slot, their own inventory
  4103. tracking is authoritative; this helper surfaces that value so the
  4104. sort can prefer it. Slots without a binding are absent from the
  4105. returned map — the caller then falls back to MQTT ``remain`` for
  4106. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4107. Returns an empty map on any failure (no inventory bindings, DB
  4108. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4109. is a preference, not a guarantee.
  4110. """
  4111. if not loaded:
  4112. return {}
  4113. # External / virtual-tray slots are tracked separately from AMS — skip
  4114. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4115. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4116. # match is fiddly and out of scope for this fix).
  4117. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4118. if not tracked_slots:
  4119. return {}
  4120. is_spoolman = await self._is_spoolman_mode(db)
  4121. overrides: dict[int, float] = {}
  4122. if is_spoolman:
  4123. result = await db.execute(
  4124. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4125. )
  4126. assignments = list(result.scalars().all())
  4127. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4128. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4129. for ams_id, tray_id, gtid in tracked_slots:
  4130. spoolman_id = by_slot.get((ams_id, tray_id))
  4131. if spoolman_id is None:
  4132. continue
  4133. grams = await _spoolman_remaining_grams(spoolman_id)
  4134. if grams is not None:
  4135. overrides[gtid] = grams
  4136. return overrides
  4137. # Internal inventory mode (default). selectinload matches the pattern
  4138. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4139. # plus an eager-loaded relationship rather than an explicit join, so
  4140. # the row-attribute shape is exactly what those routes already rely on.
  4141. result = await db.execute(
  4142. select(SpoolAssignment)
  4143. .options(selectinload(SpoolAssignment.spool))
  4144. .where(SpoolAssignment.printer_id == printer_id)
  4145. )
  4146. assignments = list(result.scalars().all())
  4147. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4148. for ams_id, tray_id, gtid in tracked_slots:
  4149. spool = by_slot.get((ams_id, tray_id))
  4150. if spool is None:
  4151. continue
  4152. label = float(spool.label_weight or 0)
  4153. used = float(spool.weight_used or 0)
  4154. overrides[gtid] = max(0.0, label - used)
  4155. return overrides
  4156. @staticmethod
  4157. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4158. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4159. here to avoid making this module import-dependent on that private
  4160. helper's signature."""
  4161. try:
  4162. from backend.app.api.routes.settings import get_setting
  4163. v = await get_setting(db, "spoolman_enabled")
  4164. return bool(v) and v.lower() == "true"
  4165. except Exception:
  4166. return False
  4167. @staticmethod
  4168. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4169. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4170. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4171. so a tied sort produces the same physical-position order the pre-#1508
  4172. stable sort did (preserves the regression-free baseline):
  4173. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4174. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4175. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4176. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4177. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4178. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4179. """
  4180. if ams_id is None or ams_id < 0:
  4181. return 10_000
  4182. if ams_id >= 128:
  4183. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4184. return ams_id * 4 + (tray_id or 0)
  4185. @staticmethod
  4186. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4187. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4188. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4189. non-tracked spools (the user has told us they care about these
  4190. specifically), then ascending by remaining within each tier, then
  4191. ascending by AMS slot position as the deterministic tie-breaker.
  4192. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4193. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4194. because the tier flag dominates — which is what lets us mix grams
  4195. (inventory) and percent (MQTT) without a unit conversion.
  4196. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4197. spools the printer DOES know something about sort ahead of those
  4198. it knows nothing about — preserves pre-#1508 behaviour for the
  4199. no-inventory-binding case.
  4200. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4201. external on ties, matching the legacy emission-order stable sort.
  4202. """
  4203. gtid = f.get("global_tray_id")
  4204. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4205. if overrides and gtid in overrides:
  4206. return (0, overrides[gtid], slot_order)
  4207. remain = f.get("remain", -1)
  4208. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4209. def _match_filaments_to_slots(
  4210. self,
  4211. required: list[dict],
  4212. loaded: list[dict],
  4213. prefer_lowest: bool = False,
  4214. inventory_remain_overrides: dict[int, float] | None = None,
  4215. fts_installed: bool = False,
  4216. ) -> list[int] | None:
  4217. """Match required filaments to loaded filaments and build AMS mapping.
  4218. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4219. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4220. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4221. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4222. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4223. matching among those trays.
  4224. Args:
  4225. required: List of required filaments with slot_id, type, color, tray_info_idx
  4226. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4227. Returns:
  4228. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4229. """
  4230. if not required:
  4231. return None
  4232. # Track used trays to avoid duplicate assignment
  4233. used_tray_ids: set[int] = set()
  4234. comparisons = []
  4235. for req in required:
  4236. req_type = (req.get("type") or "").upper()
  4237. req_color = req.get("color", "")
  4238. req_tray_info_idx = req.get("tray_info_idx", "")
  4239. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4240. idx_match = None
  4241. exact_match = None
  4242. similar_match = None
  4243. similar_distance = float("inf")
  4244. type_only_match = None
  4245. # Get available trays (not already used)
  4246. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4247. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4248. # Hard filter — cross-nozzle assignment causes print failures
  4249. # ("position of left hotend is abnormal"), so never fall back.
  4250. # Skipped when an FTS is installed: it routes any AMS slot to either
  4251. # extruder, so restricting to one nozzle would wrongly exclude the
  4252. # correct spool sitting in the other nozzle's AMS (#2186).
  4253. req_nozzle_id = req.get("nozzle_id")
  4254. if req_nozzle_id is not None and not fts_installed:
  4255. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4256. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4257. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4258. # _prefer_lowest_sort_key for the full rationale.
  4259. if prefer_lowest:
  4260. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4261. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4262. # One line per filament req so a bug report can be diagnosed
  4263. # without enabling debug logging: shows what the matcher saw
  4264. # (req shape + sorted candidate trays with their remain values
  4265. # and any inventory override that was applied). Mirrored by
  4266. # the picked-match log at the bottom of the loop.
  4267. logger.info(
  4268. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4269. req.get("slot_id"),
  4270. req_type,
  4271. req_color,
  4272. req_tray_info_idx,
  4273. req_nozzle_id,
  4274. [
  4275. {
  4276. "gtid": f.get("global_tray_id"),
  4277. "type": f.get("type"),
  4278. "color": f.get("color"),
  4279. "tii": f.get("tray_info_idx"),
  4280. "remain": f.get("remain"),
  4281. "inv_g": (
  4282. inventory_remain_overrides.get(f.get("global_tray_id"))
  4283. if inventory_remain_overrides
  4284. else None
  4285. ),
  4286. }
  4287. for f in available
  4288. ],
  4289. )
  4290. # Check if tray_info_idx is unique among available trays
  4291. if req_tray_info_idx:
  4292. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4293. if len(idx_matches) == 1:
  4294. # Unique tray_info_idx - use it as definitive match
  4295. idx_match = idx_matches[0]
  4296. logger.debug(
  4297. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4298. f"-> tray {idx_match['global_tray_id']}"
  4299. )
  4300. elif len(idx_matches) > 1:
  4301. # Multiple trays with same tray_info_idx - use color matching among them
  4302. logger.debug(
  4303. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4304. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4305. )
  4306. if prefer_lowest:
  4307. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4308. # Use color matching within this subset
  4309. for f in idx_matches:
  4310. f_color = f.get("color", "")
  4311. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4312. if not exact_match:
  4313. exact_match = f
  4314. elif self._colors_are_similar(f_color, req_color):
  4315. distance = self._color_distance(f_color, req_color)
  4316. if distance is not None and distance < similar_distance:
  4317. similar_match = f
  4318. similar_distance = distance
  4319. elif not type_only_match:
  4320. type_only_match = f
  4321. # If no idx_match yet, do standard type/color matching on all available trays
  4322. if not idx_match and not exact_match and not similar_match and not type_only_match:
  4323. for f in available:
  4324. f_type = (f.get("type") or "").upper()
  4325. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4326. continue
  4327. # Type matches - check color
  4328. f_color = f.get("color", "")
  4329. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4330. if not exact_match:
  4331. exact_match = f
  4332. elif self._colors_are_similar(f_color, req_color):
  4333. # Nearest wins, not first-in-tray-order. `available` is
  4334. # already in the caller's order (slot order, or the
  4335. # prefer-lowest sort), and `<` keeps the earliest of
  4336. # equally close spools — so that order survives as the
  4337. # tie-break (#2804).
  4338. distance = self._color_distance(f_color, req_color)
  4339. if distance is not None and distance < similar_distance:
  4340. similar_match = f
  4341. similar_distance = distance
  4342. elif not type_only_match:
  4343. type_only_match = f
  4344. match = idx_match or exact_match or similar_match or type_only_match
  4345. if match:
  4346. used_tray_ids.add(match["global_tray_id"])
  4347. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4348. else:
  4349. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4350. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4351. # "Why did it pick that spool" is the question every wrong-filament
  4352. # report starts with, and a `similar_color` win is now a ranked
  4353. # choice among several eligible spools rather than whichever tray
  4354. # came first, so it is worth being able to see after the fact.
  4355. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4356. # is on (#1766).
  4357. if match:
  4358. bucket = (
  4359. "idx"
  4360. if idx_match is not None
  4361. else "exact_color"
  4362. if exact_match is not None
  4363. else "similar_color"
  4364. if similar_match is not None
  4365. else "type_only"
  4366. )
  4367. logger.info(
  4368. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4369. match["global_tray_id"],
  4370. bucket,
  4371. req.get("slot_id"),
  4372. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4373. )
  4374. else:
  4375. logger.info(
  4376. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4377. req.get("slot_id"),
  4378. req_type,
  4379. req_color,
  4380. req_tray_info_idx,
  4381. )
  4382. # Build mapping array
  4383. if not comparisons:
  4384. return None
  4385. max_slot_id = max(c["slot_id"] for c in comparisons)
  4386. if max_slot_id <= 0:
  4387. return None
  4388. mapping = [-1] * max_slot_id
  4389. for c in comparisons:
  4390. slot_id = c["slot_id"]
  4391. if slot_id and slot_id > 0:
  4392. mapping[slot_id - 1] = c["global_tray_id"]
  4393. return mapping
  4394. def _mark_printer_dispatched(
  4395. self,
  4396. printer_id: int,
  4397. pre_state: str | None,
  4398. pre_subtask_id: str | None,
  4399. ) -> None:
  4400. """Record that a print command was just sent to ``printer_id``.
  4401. Held until either the watchdog observes a state/subtask transition
  4402. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4403. """
  4404. if not pre_state:
  4405. # No pre_state means we can't detect a transition — fall back to a
  4406. # pure time-based hold using empty string as a sentinel that won't
  4407. # match any real printer state.
  4408. pre_state = ""
  4409. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4410. def _release_dispatch_hold(self, printer_id: int) -> None:
  4411. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4412. self._dispatch_holds.pop(printer_id, None)
  4413. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4414. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4415. Returns False (and clears the hold) once any of these are true:
  4416. - hard timeout (``_dispatch_max_hold``) has elapsed
  4417. - the printer has transitioned out of pre_state and we're past the
  4418. minimum cooldown
  4419. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4420. past the minimum cooldown
  4421. Otherwise the printer is held — caller should treat it as busy.
  4422. """
  4423. entry = self._dispatch_holds.get(printer_id)
  4424. if not entry:
  4425. return False
  4426. started_at, pre_state, pre_subtask_id = entry
  4427. elapsed = time.monotonic() - started_at
  4428. if elapsed >= self._dispatch_max_hold:
  4429. self._dispatch_holds.pop(printer_id, None)
  4430. return False
  4431. # Without a pre_state we can't detect a transition — fall back to the
  4432. # min cooldown alone, then drop the hold.
  4433. if not pre_state:
  4434. if elapsed >= self._dispatch_min_cooldown:
  4435. self._dispatch_holds.pop(printer_id, None)
  4436. return False
  4437. return True
  4438. status = printer_manager.get_status(printer_id)
  4439. current_state = getattr(status, "state", None) if status else None
  4440. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4441. transitioned = (current_state is not None and current_state != pre_state) or (
  4442. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4443. )
  4444. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4445. self._dispatch_holds.pop(printer_id, None)
  4446. return False
  4447. return True
  4448. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4449. """Check if a printer is connected and idle."""
  4450. if not printer_manager.is_connected(printer_id):
  4451. logger.debug("Printer %d: not connected", printer_id)
  4452. return False
  4453. state = printer_manager.get_status(printer_id)
  4454. if not state:
  4455. logger.debug("Printer %d: no status available", printer_id)
  4456. return False
  4457. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4458. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4459. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4460. # printer, it boots back into IDLE with no memory of the previous finish; without
  4461. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4462. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4463. logger.debug(
  4464. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4465. printer_id,
  4466. state.state,
  4467. )
  4468. return False
  4469. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4470. if not idle:
  4471. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4472. return idle
  4473. @staticmethod
  4474. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4475. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4476. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4477. and that the fixed-printer branch has already found connected, so the two
  4478. offline cases answer at their own exits and never arrive here.
  4479. The default is the model-based branch's ``Busy:`` wording, which
  4480. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4481. the right answer for the connected-but-no-telemetry second or two after a
  4482. reconnect: the model-based branch has always reported it that way, and it
  4483. is not something to wake anybody up for.
  4484. A plate nobody has confirmed is the one case here that does not resolve
  4485. itself — somebody has to walk over to the printer — so it is worded as
  4486. itself and allowed to notify.
  4487. """
  4488. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4489. return f"Waiting for plate confirmation: {printer_name}"
  4490. return f"Busy: {printer_name}"
  4491. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4492. """Read a setting value from the database."""
  4493. result = await db.execute(select(Settings).where(Settings.key == key))
  4494. setting = result.scalar_one_or_none()
  4495. return setting.value if setting else None
  4496. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4497. """Read a boolean setting from the database."""
  4498. result = await db.execute(select(Settings).where(Settings.key == key))
  4499. setting = result.scalar_one_or_none()
  4500. if setting:
  4501. return setting.value.lower() == "true"
  4502. return default
  4503. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4504. """Read an int setting; falls back to default on missing/unparseable rows."""
  4505. result = await db.execute(select(Settings).where(Settings.key == key))
  4506. setting = result.scalar_one_or_none()
  4507. if setting and setting.value:
  4508. try:
  4509. return int(setting.value)
  4510. except ValueError:
  4511. pass
  4512. return default
  4513. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4514. """Get drying presets (user-configured or built-in defaults)."""
  4515. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4516. setting = result.scalar_one_or_none()
  4517. if setting and setting.value:
  4518. try:
  4519. presets = json.loads(setting.value)
  4520. if isinstance(presets, dict) and presets:
  4521. return presets
  4522. except json.JSONDecodeError:
  4523. pass
  4524. return self.DEFAULT_DRYING_PRESETS
  4525. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4526. """Per-filament humidity thresholds (#1605).
  4527. Returns the user-configured overrides map keyed by normalized filament
  4528. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4529. unknown / unmapped types. Empty / unset → empty dict, in which case
  4530. callers fall back to ``ams_humidity_fair``.
  4531. """
  4532. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4533. setting = result.scalar_one_or_none()
  4534. if not setting or not setting.value:
  4535. return {}
  4536. try:
  4537. data = json.loads(setting.value)
  4538. except json.JSONDecodeError:
  4539. return {}
  4540. if not isinstance(data, dict):
  4541. return {}
  4542. out: dict[str, int] = {}
  4543. for key, value in data.items():
  4544. try:
  4545. out[str(key).upper() if key != "default" else "default"] = int(value)
  4546. except (TypeError, ValueError):
  4547. continue
  4548. return out
  4549. # Materials whose AMS spelling differs from the key the tables above use.
  4550. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4551. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4552. # good PA row (#3067).
  4553. #
  4554. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4555. # The drying popover has resolved these correctly since #2774 and the
  4556. # scheduler never did, which is exactly why #3067's reporter could dry a
  4557. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4558. #
  4559. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4560. # of nylon, so it is the one entry that is a judgement rather than a
  4561. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4562. # way, and PA's row is the hottest the table has. Drying it there is closer
  4563. # to right than not drying it at all, which is what it got before.
  4564. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4565. "NYLON": "PA",
  4566. "PA6": "PA",
  4567. "PA11": "PA",
  4568. "PA12": "PA",
  4569. "PAHT": "PA",
  4570. "PPA": "PA",
  4571. }
  4572. @classmethod
  4573. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4574. """The key in *table* that answers for this tray's material, or None.
  4575. The printer reports the material in ``tray_type``, and it spells filled
  4576. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4577. tables here are keyed by base material, so matching the raw string alone
  4578. found a row for 8 of the 41 types a printer can report and skipped the
  4579. rest -- silently, because every caller reads "no row" as "nothing to do
  4580. for this tray". Auto-drying therefore ignored every composite spool on
  4581. the install (#3067).
  4582. Exact match first, so a table the user has extended with a row of its
  4583. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4584. base material's. Then the suffix is dropped, then the alias map above
  4585. answers for the polyamide spellings.
  4586. Returns None rather than a default: what to do with an unrecognised
  4587. material differs per caller, and only the caller knows whether "no row"
  4588. means skip the tray or fall back to a catch-all. Nothing here invents a
  4589. temperature for a material the table does not list.
  4590. """
  4591. raw = cls._normalize_filament_type(tray_type or "")
  4592. if not raw:
  4593. return None
  4594. for candidate in (raw, raw.split("-")[0]):
  4595. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4596. if key in table:
  4597. return key
  4598. return None
  4599. @staticmethod
  4600. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4601. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4602. For mixed filament types loaded into one AMS, returns the most
  4603. restrictive (lowest) threshold across all loaded tray types — matches
  4604. the conservative-params strategy already used for drying temp/hours.
  4605. Empty / unloaded trays contribute no constraint. Unknown types use the
  4606. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4607. when no per-type map is configured at all.
  4608. """
  4609. default = thresholds.get("default", fallback)
  4610. if not thresholds:
  4611. return fallback
  4612. candidates: list[int] = []
  4613. for tray in trays:
  4614. tray_type = str(tray.get("tray_type") or "").strip()
  4615. if not tray_type:
  4616. continue
  4617. # A composite carries its base material's threshold when it has no
  4618. # row of its own, the same way it takes its drying preset (#3067).
  4619. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4620. candidates.append(thresholds[key] if key is not None else default)
  4621. if not candidates:
  4622. return default
  4623. return min(candidates)
  4624. def _get_conservative_drying_params(
  4625. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4626. ) -> tuple[int, int, str] | None:
  4627. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4628. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4629. """
  4630. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4631. hours_key = f"{temp_key}_hours"
  4632. min_temp = None
  4633. max_hours = None
  4634. filament_type = ""
  4635. for tray in trays:
  4636. tray_type = tray.get("tray_type", "")
  4637. if not tray_type:
  4638. continue
  4639. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4640. # which is what stopped auto-drying on every composite spool (#3067).
  4641. base_type = self._resolve_filament_key(tray_type, presets)
  4642. if base_type is None:
  4643. continue
  4644. # The table is user-editable JSON with no per-row validation, so a
  4645. # row can be present and empty. That has always meant "skip this
  4646. # material", and it has to keep meaning it: the reads below fall
  4647. # back to 55C/12h per missing field, which is a temperature nobody
  4648. # chose and would deform a PLA spool.
  4649. preset = presets[base_type]
  4650. if not preset:
  4651. continue
  4652. temp = preset.get(temp_key, 55)
  4653. hours = preset.get(hours_key, 12)
  4654. # Conservative: lowest temp, longest duration
  4655. if min_temp is None or temp < min_temp:
  4656. min_temp = temp
  4657. if max_hours is None or hours > max_hours:
  4658. max_hours = hours
  4659. if not filament_type:
  4660. filament_type = base_type
  4661. if min_temp is None:
  4662. return None
  4663. return (min_temp, max_hours or 12, filament_type)
  4664. async def _check_filament_low(self, db: AsyncSession) -> None:
  4665. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4666. ``on_filament_low`` has had a column, a schema field, a route, a template
  4667. and a UI toggle since the notification system was built, and no caller --
  4668. so the toggle could be switched on and could never fire. This is the
  4669. producer.
  4670. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4671. ``low_stock_threshold_pct`` override is already exactly this decision:
  4672. already configurable, already surfaced, already driving the Inventory
  4673. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4674. consulted -- it has been measured up to 56 points out against a scale,
  4675. which is not a number to page someone on.
  4676. Only slots with an assigned spool produce an event. A slot Bambuddy
  4677. cannot resolve to a spool has no remaining weight it can stand behind,
  4678. and guessing one is how the remain percentage would have got in.
  4679. """
  4680. from backend.app.models.spool import Spool
  4681. # Time-gated rather than run on every pass. run() sleeps
  4682. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4683. # early-return path counts as productive while an upload is in flight
  4684. # (#2602), so an unthrottled check would re-read the whole spool
  4685. # collection every 3 seconds for the length of a batch drain. In
  4686. # Spoolman mode that is a request storm against a third-party service,
  4687. # which is the thing this producer's design note argues against; and
  4688. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4689. # check_queue holding the scheduler's session, so the outage would
  4690. # throttle the print queue itself. A low spool is not a 3-second
  4691. # concern -- the idle interval is the natural resolution.
  4692. now = time.monotonic()
  4693. if now < self._filament_low_next_check:
  4694. return
  4695. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4696. try:
  4697. # on_filament_low defaults to off on every provider, so on most
  4698. # installs nobody wants this alert. Without this the check would
  4699. # still read every assigned spool each interval -- the whole
  4700. # collection over HTTP in Spoolman mode -- for an event that is
  4701. # switched off. One query against the provider table settles it
  4702. # before any spool work, the same guard the bed-cooled waiter uses.
  4703. # No printer_id: this asks whether any provider wants the event at
  4704. # all; per-printer scoping is applied when the event is sent.
  4705. #
  4706. # While nobody wants it, no pass sees a slot go back above its
  4707. # threshold, so nothing can re-arm; a spool refilled under the same
  4708. # id in that time would stay silenced until a restart. Forgetting
  4709. # what was sent is right anyway: whoever switches the event back on
  4710. # is told about the spools that are low now.
  4711. #
  4712. # The MQTT relay publishes the same event, so a connected relay is
  4713. # reason enough to run the check. Its record is forgotten when the
  4714. # relay is switched off, not when the broker drops: a reconnect must
  4715. # not re-send every low slot.
  4716. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4717. relay = mqtt_relay.enabled and mqtt_relay.connected
  4718. if not notify:
  4719. self._notified_filament_low.clear()
  4720. if not mqtt_relay.enabled:
  4721. self._relayed_filament_low.clear()
  4722. if not notify and not relay:
  4723. return
  4724. global_threshold = await self._get_low_stock_threshold(db)
  4725. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4726. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4727. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4728. if spoolman_on:
  4729. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4730. else:
  4731. rows = (
  4732. await db.execute(
  4733. select(SpoolAssignment, Spool)
  4734. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4735. # An archived spool is not stock. The Inventory page's
  4736. # Low Stock count skips them (InventoryPage.tsx:1089)
  4737. # and get_all_spools without allow_archived already
  4738. # excludes them in Spoolman mode, so without this the
  4739. # internal path is the only one that alerts on them.
  4740. .where(Spool.archived_at.is_(None))
  4741. )
  4742. ).all()
  4743. for assignment, spool in rows:
  4744. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4745. if pct is None:
  4746. continue
  4747. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4748. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4749. pct,
  4750. threshold,
  4751. spool.color_name,
  4752. )
  4753. if not slots:
  4754. # Nothing resolvable this pass. Deliberately not clearing the
  4755. # notified set: a Spoolman that is briefly unreachable would
  4756. # otherwise re-alert on every spool as soon as it came back.
  4757. return
  4758. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4759. except Exception as e:
  4760. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4761. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4762. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4763. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4764. if raw is None or raw.value is None:
  4765. return 20.0
  4766. try:
  4767. value = float(raw.value)
  4768. except (TypeError, ValueError):
  4769. return 20.0
  4770. return value if 0 < value <= 100 else 20.0
  4771. async def _filament_low_slots_spoolman(
  4772. self, db: AsyncSession, global_threshold: float
  4773. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4774. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4775. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4776. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4777. so the global threshold is the only one that applies here. That matches
  4778. what the Inventory page already does in this mode.
  4779. One ``get_all_spools`` call covers every slot rather than a request per
  4780. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4781. without ``allow_archived`` -- which is the behaviour the internal path
  4782. has to ask for explicitly.
  4783. An unreachable Spoolman returns no slots rather than raising. It is an
  4784. ordinary state for a third-party service, not an error in this pass: the
  4785. caller's "nothing resolvable" branch already leaves the notified set
  4786. alone, which is exactly right here, whereas letting it reach the broad
  4787. ``except`` would write a full traceback every time the check runs.
  4788. """
  4789. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4790. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4791. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4792. if not assignments:
  4793. return {}
  4794. client = await get_spoolman_client()
  4795. if client is None:
  4796. return {}
  4797. try:
  4798. all_spools = await client.get_all_spools()
  4799. except SpoolmanUnavailableError as e:
  4800. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4801. return {}
  4802. by_id: dict[int, dict] = {}
  4803. for raw in all_spools:
  4804. raw_id = raw.get("id")
  4805. if isinstance(raw_id, int):
  4806. by_id[raw_id] = raw
  4807. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4808. for assignment in assignments:
  4809. raw = by_id.get(assignment.spoolman_spool_id)
  4810. if raw is None:
  4811. continue
  4812. try:
  4813. mapped = _map_spoolman_spool(raw)
  4814. except ValueError:
  4815. continue
  4816. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4817. if pct is None:
  4818. continue
  4819. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4820. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4821. return slots
  4822. async def _emit_filament_low(
  4823. self,
  4824. db: AsyncSession,
  4825. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4826. *,
  4827. notify: bool = True,
  4828. relay: bool = False,
  4829. ) -> None:
  4830. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4831. printers: dict[int, Printer] = {}
  4832. for key, (pct, threshold, color) in slots.items():
  4833. printer_id, ams_id, tray_id, spool_id = key
  4834. if pct >= threshold:
  4835. # Back above the line: re-arm rather than expire on a timer, so a
  4836. # refilled slot can alert again and a spool sitting just under the
  4837. # threshold stays quiet.
  4838. self._notified_filament_low.discard(key)
  4839. self._relayed_filament_low.discard(key)
  4840. continue
  4841. send_notification = notify and key not in self._notified_filament_low
  4842. # Only while connected, so a crossing the relay missed reaches it
  4843. # after the reconnect.
  4844. send_relay = relay and key not in self._relayed_filament_low
  4845. if not send_notification and not send_relay:
  4846. continue
  4847. # Marked before sending, which is a choice rather than the only
  4848. # option, and it is the opposite failure mode from the one the
  4849. # debounce argues against: one transient provider failure loses this
  4850. # alert until the spool goes back above the threshold and crosses it
  4851. # again. Marking after a successful send would trade that for
  4852. # re-alerting on every pass while a provider is down -- which is the
  4853. # repetition the whole debounce exists to prevent, and the louder of
  4854. # the two failures. A spool that is low stays low, so the next real
  4855. # signal is not far away; a provider stuck retrying is a signal that
  4856. # never stops.
  4857. if send_notification:
  4858. self._notified_filament_low.add(key)
  4859. if send_relay:
  4860. self._relayed_filament_low.add(key)
  4861. if printer_id not in printers:
  4862. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4863. if printer is None:
  4864. continue
  4865. printers[printer_id] = printer
  4866. printer = printers[printer_id]
  4867. slot = _ams_slot_label(ams_id, tray_id)
  4868. if send_notification:
  4869. try:
  4870. await notification_service.on_filament_low(
  4871. printer_id,
  4872. printer.name,
  4873. slot,
  4874. int(pct),
  4875. db,
  4876. color=color,
  4877. )
  4878. except Exception as e:
  4879. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4880. if send_relay:
  4881. try:
  4882. await mqtt_relay.on_filament_low(
  4883. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  4884. )
  4885. except Exception as e:
  4886. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  4887. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4888. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4889. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4890. a schema field, a template and a UI toggle, and nothing that computes the
  4891. condition -- the Forecast panel does it in the browser, so with no page
  4892. open nothing could ever alert. This runs the same arithmetic
  4893. (``stock_forecast``) from the scheduler loop.
  4894. An alert is sent when a SKU *moves into* a condition, once, and again
  4895. after the condition has cleared. A SKU that worsens from reorder to break
  4896. alerts again as a break, because the panel treats the two as exclusive; one
  4897. that eases from break back to reorder does not alert again.
  4898. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4899. while it is still low tells you.
  4900. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4901. loop runs every 3 s while an upload is in flight, and the whole spool
  4902. collection is read over HTTP in Spoolman mode. Both events default to off
  4903. on every provider, so nothing is read unless a provider wants one.
  4904. """
  4905. now = time.monotonic()
  4906. if now < self._stock_forecast_next_check:
  4907. return
  4908. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4909. try:
  4910. if self._stock_alerts_persisted is None:
  4911. await self._load_stock_alerts(db)
  4912. wanted = {
  4913. "reorder": bool(
  4914. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  4915. ),
  4916. "break": bool(
  4917. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  4918. ),
  4919. }
  4920. if not any(wanted.values()):
  4921. # Nobody wants either event. Forget what was sent, so whoever
  4922. # switches one on is told about the SKUs that are low now.
  4923. self._notified_stock_alerts.clear()
  4924. await self._save_stock_alerts(db)
  4925. return
  4926. forecasts = await self._stock_forecasts(db)
  4927. if forecasts is None:
  4928. # Spoolman unreachable. Deliberately not clearing the notified
  4929. # set: a brief outage would otherwise re-alert every SKU when it
  4930. # came back.
  4931. return
  4932. await self._emit_stock_alerts(db, forecasts, wanted)
  4933. await self._save_stock_alerts(db)
  4934. except Exception as e:
  4935. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4936. def _serialize_stock_alerts(self) -> str:
  4937. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4938. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4939. return json.dumps(rows)
  4940. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4941. """Read the notified set saved by the last run, once per process.
  4942. A missing or unreadable row is an empty set: the worst that does is one
  4943. repeat of what a restart used to cause every time.
  4944. """
  4945. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4946. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4947. if raw and raw.value:
  4948. try:
  4949. for key, kind, events in json.loads(raw.value):
  4950. if len(key) == 4 and kind in ("reorder", "break"):
  4951. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4952. except (ValueError, TypeError):
  4953. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4954. loaded = {}
  4955. self._notified_stock_alerts = loaded
  4956. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4957. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4958. """Write the notified set to its settings row if it changed since it was last read or written."""
  4959. serialized = self._serialize_stock_alerts()
  4960. if serialized == self._stock_alerts_persisted:
  4961. return
  4962. from backend.app.core.db_dialect import upsert_setting
  4963. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4964. await db.commit()
  4965. self._stock_alerts_persisted = serialized
  4966. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4967. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4968. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4969. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4970. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4971. sku_settings = {
  4972. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4973. lead_time_days=row.lead_time_days,
  4974. safety_margin_value=row.safety_margin_value,
  4975. safety_margin_unit=row.safety_margin_unit,
  4976. alerts_snoozed=bool(row.alerts_snoozed),
  4977. )
  4978. for row in sku_rows
  4979. }
  4980. if await self._get_bool_setting(db, "spoolman_enabled"):
  4981. spools = await self._stock_spools_spoolman()
  4982. if spools is None:
  4983. return None
  4984. # Spoolman owns the usage in this mode and Bambuddy's own history
  4985. # table holds nothing for those spools, so the rate is always the
  4986. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4987. # are local spool ids, and a Spoolman id that happens to match one
  4988. # (left over from before Spoolman was switched on) would borrow an
  4989. # unrelated spool's history.
  4990. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4991. else:
  4992. spools = await self._stock_spools_internal(db)
  4993. history = await self._stock_usage_history(db)
  4994. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4995. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4996. from backend.app.models.spool import Spool
  4997. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4998. return [
  4999. stock_forecast.StockSpool(
  5000. id=spool.id,
  5001. material=spool.material,
  5002. subtype=spool.subtype,
  5003. brand=spool.brand,
  5004. color_name=spool.color_name,
  5005. label_weight=float(spool.label_weight or 0),
  5006. weight_used=float(spool.weight_used or 0),
  5007. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5008. created_at=spool.created_at,
  5009. )
  5010. for spool in rows
  5011. ]
  5012. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  5013. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5014. rows = (
  5015. await db.execute(
  5016. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5017. .order_by(SpoolUsageHistory.created_at.desc())
  5018. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5019. )
  5020. ).all()
  5021. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5022. for spool_id, created_at, weight_used in rows:
  5023. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5024. # filtered before the limit, so the window matches the forecast panel's.
  5025. if created_at is None or spool_id is None:
  5026. continue
  5027. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5028. return history
  5029. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5030. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5031. ``get_all_spools`` leaves archived spools out unless asked, which is the
  5032. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  5033. is the same mapping the Inventory page (and so the panel) reads.
  5034. """
  5035. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5036. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5037. client = await get_spoolman_client()
  5038. if client is None:
  5039. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5040. return None
  5041. try:
  5042. raw_spools = await client.get_all_spools()
  5043. except SpoolmanUnavailableError as e:
  5044. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5045. return None
  5046. spools: list[stock_forecast.StockSpool] = []
  5047. for raw in raw_spools:
  5048. try:
  5049. mapped = _map_spoolman_spool(raw)
  5050. except ValueError:
  5051. continue
  5052. created_at = None
  5053. if mapped.get("created_at"):
  5054. try:
  5055. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  5056. except ValueError:
  5057. created_at = None
  5058. spools.append(
  5059. stock_forecast.StockSpool(
  5060. id=mapped["id"],
  5061. material=mapped["material"],
  5062. subtype=mapped.get("subtype"),
  5063. brand=mapped.get("brand"),
  5064. color_name=mapped.get("color_name"),
  5065. label_weight=float(mapped.get("label_weight") or 0),
  5066. weight_used=float(mapped.get("weight_used") or 0),
  5067. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5068. created_at=created_at,
  5069. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5070. )
  5071. )
  5072. return spools
  5073. async def _emit_stock_alerts(
  5074. self,
  5075. db: AsyncSession,
  5076. forecasts: stock_forecast.ForecastMap,
  5077. wanted: dict[str, bool],
  5078. ) -> None:
  5079. """Send the notifications for each SKU that has moved into a stock alert condition.
  5080. A SKU in break has also reached its reorder point, so both events apply to
  5081. it: the break event goes to providers that have it on, and the reorder event
  5082. to the providers that have only that one on. A provider with both on gets the
  5083. break and no second message.
  5084. What is remembered per SKU is the condition and which events had a
  5085. subscriber when it was sent. An event with no subscriber is forgotten, so
  5086. switching it on later reports the SKUs already in that condition.
  5087. """
  5088. active_events = {event for event, on in wanted.items() if on}
  5089. for key, (forecast, spool) in forecasts.items():
  5090. kind: str | None = None
  5091. if not forecast.snoozed:
  5092. if forecast.stock_break_alert:
  5093. kind = "break"
  5094. elif forecast.reorder_alert:
  5095. kind = "reorder"
  5096. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5097. events = applicable & active_events
  5098. if not events:
  5099. self._notified_stock_alerts.pop(key, None)
  5100. continue
  5101. previous = self._notified_stock_alerts.get(key)
  5102. told = (previous[1] & active_events) if previous else frozenset()
  5103. # Trimmed to the events this condition can send. That is what makes easing from
  5104. # break back to reorder silent (the reorder event was told with the break) and
  5105. # worsening again news again (the break event is no longer remembered).
  5106. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5107. # Recorded before sending, for the reason _emit_filament_low gives: a
  5108. # provider that is down should lose this alert, not repeat it every hour.
  5109. to_send = events - told
  5110. # Both flags imply a positive rate and so a day count.
  5111. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5112. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5113. color = None if spool.color_name_is_synthesized else spool.color_name
  5114. try:
  5115. if "break" in to_send:
  5116. await notification_service.on_stock_break_alert(
  5117. spool.material,
  5118. spool.brand,
  5119. forecast.remaining_g,
  5120. rate,
  5121. days_left,
  5122. forecast.effective_lead_time_days,
  5123. db,
  5124. subtype=spool.subtype,
  5125. color=color,
  5126. )
  5127. if "reorder" in to_send:
  5128. await notification_service.on_stock_reorder_alert(
  5129. spool.material,
  5130. spool.brand,
  5131. forecast.remaining_g,
  5132. rate,
  5133. days_left,
  5134. db,
  5135. subtype=spool.subtype,
  5136. color=color,
  5137. skip_break_subscribers=kind == "break",
  5138. )
  5139. except Exception as e:
  5140. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5141. # A SKU with no spools left is no longer alerting.
  5142. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5143. del self._notified_stock_alerts[key]
  5144. @staticmethod
  5145. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5146. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5147. from backend.app.core.auth import is_auth_enabled
  5148. if user_id is None or not await is_auth_enabled(db):
  5149. return ALL_PRINTERS
  5150. return await resolve_user_id_printer_scope(db, user_id)
  5151. async def _model_job_printer_ids(
  5152. self,
  5153. db: AsyncSession,
  5154. item: PrintQueueItem,
  5155. scope: PrinterScope,
  5156. cache: dict[tuple[str, str | None, int | None], set[int]],
  5157. ) -> set[int]:
  5158. """Every printer an "Any <model>" job could land on: the active printers
  5159. of each of its candidate models, in its location, that its creator may use.
  5160. ``cache`` holds one lookup per model, location and creator for the pass,
  5161. so a long queue of model jobs does not query once per job."""
  5162. printer_ids: set[int] = set()
  5163. for candidate in _candidates_for(item):
  5164. if not candidate.target_model:
  5165. continue
  5166. key = (candidate.target_model, item.target_location, item.created_by_id)
  5167. if key not in cache:
  5168. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5169. cache[key] = {printer.id for printer in printers}
  5170. printer_ids |= cache[key]
  5171. return printer_ids
  5172. async def _check_auto_drying(
  5173. self,
  5174. db: AsyncSession,
  5175. queue_items: list[PrintQueueItem],
  5176. dispatching_printers: set[int],
  5177. ):
  5178. """Start drying on idle printers based on humidity.
  5179. Three modes (can all be enabled independently):
  5180. - queue_drying_enabled: Dry between scheduled queue prints
  5181. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5182. - print_drying_enabled: Also evaluate printers that are currently printing,
  5183. when model+firmware supports "Print While Drying" (gated by
  5184. supports_drying_while_printing). Drying temperature is capped at
  5185. max(40, preset_temp - 5) to protect spools mid-print.
  5186. """
  5187. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5188. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5189. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5190. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5191. # The wait belongs to ambient drying: the settings UI only shows it while
  5192. # ambient drying is on, so a value left behind when ambient is turned off
  5193. # must not keep delaying the one path that still reaches the wait gate
  5194. # without it (a mid-print start under print_drying).
  5195. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5196. # Clear every streak as soon as the wait is inactive. An early return (or
  5197. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5198. # a quick toggle-on inherit an old streak.
  5199. if not sustained_wait_active:
  5200. self._auto_dry_above.clear()
  5201. if not queue_drying_enabled and not ambient_drying_enabled:
  5202. # Stop active drying on all printers if both features disabled
  5203. if self._drying_in_progress:
  5204. for pid in list(self._drying_in_progress):
  5205. if pid in self._scheduled_drying_printer_ids:
  5206. continue
  5207. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5208. await self._stop_drying(pid)
  5209. return
  5210. # Update drying state from printer status (handles backend restart)
  5211. self._sync_drying_state()
  5212. # Find printers with scheduled items (for queue drying mode)
  5213. # An "Any <model>" job counts for every printer it could land on.
  5214. printers_with_scheduled: set[int] = set()
  5215. # Printers with a job that could start now: the ones block mode keeps
  5216. # a new cycle off. A job waiting for its start time is what queue
  5217. # drying dries ahead of.
  5218. printers_with_ready_items: set[int] = set()
  5219. now_utc = datetime.now(timezone.utc)
  5220. creator_scopes: dict[int | None, PrinterScope] = {}
  5221. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5222. for item in queue_items:
  5223. if item.printer_id:
  5224. item_printers = {item.printer_id}
  5225. elif item.target_model or item.variants:
  5226. if item.created_by_id not in creator_scopes:
  5227. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5228. item_printers = await self._model_job_printer_ids(
  5229. db, item, creator_scopes[item.created_by_id], model_printers
  5230. )
  5231. else:
  5232. continue
  5233. if item.scheduled_time and not item.manual_start:
  5234. printers_with_scheduled |= item_printers
  5235. sched = item.scheduled_time
  5236. if sched is not None and sched.tzinfo is None:
  5237. sched = sched.replace(tzinfo=timezone.utc)
  5238. if sched is None or sched <= now_utc:
  5239. printers_with_ready_items |= item_printers
  5240. # If only queue mode is on and no printers have scheduled items, stop drying
  5241. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5242. # may still be eligible for mid-print drying regardless of queue state).
  5243. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5244. for pid in list(self._drying_in_progress):
  5245. if pid in self._scheduled_drying_printer_ids:
  5246. continue
  5247. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5248. await self._stop_drying(pid)
  5249. return
  5250. # Get humidity threshold (global fallback)
  5251. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5252. setting = result.scalar_one_or_none()
  5253. global_humidity_threshold = int(setting.value) if setting else 60
  5254. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5255. # to the global threshold for every AMS unit.
  5256. per_type_thresholds = await self._get_humidity_thresholds(db)
  5257. # Get drying presets
  5258. presets = await self._get_drying_presets(db)
  5259. # Determine if drying should be skipped for printers with pending items
  5260. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5261. # Get all active printers
  5262. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5263. for printer in all_printers.scalars():
  5264. pid = printer.id
  5265. # Resolve model+firmware up front — needed to decide whether this printer
  5266. # qualifies for mid-print drying (busy printer on capable hardware).
  5267. state = printer_manager.get_status(pid)
  5268. if not state:
  5269. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5270. continue
  5271. model = printer_manager.get_model(pid)
  5272. firmware = state.firmware_version
  5273. # "Mid-print" has to mean the printer is actually printing (#2801).
  5274. # It used to be inferred from the dispatch set, which also holds
  5275. # printers that merely could not be dispatched to -- so a printer
  5276. # sitting in FINISH behind an unacknowledged plate was treated as
  5277. # printing, had its drying temperature capped by the mid-print
  5278. # spool protection, and was logged as (mid-print) while idle.
  5279. is_printing = state.state in _ACTIVE_PRINT_STATES
  5280. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5281. # A printer whose print is running or imminent is left alone unless
  5282. # it can dry through it. `dispatching_printers` is deliberately the
  5283. # narrow set: running, held post-dispatch, or mid-upload.
  5284. if (is_printing or pid in dispatching_printers) and not mid_print:
  5285. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5286. continue
  5287. if not mid_print:
  5288. # In queue-only mode, only dry printers that have scheduled prints
  5289. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5290. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5291. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5292. await self._stop_drying(pid)
  5293. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5294. continue
  5295. # When block mode is on, don't START new drying on printers with
  5296. # a job that could start now: the cycle would hold it. One
  5297. # scheduled for later may pre-dry; if the cycle is still running
  5298. # at its time, the hold applies then. Already-drying printers go
  5299. # through so humidity auto-stop logic still runs.
  5300. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5301. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5302. continue
  5303. if not printer_manager.is_connected(pid):
  5304. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5305. continue
  5306. # Plate-clear is deliberately ignored here (#2801). It answers
  5307. # "is the bed ready for the next job", which says nothing about
  5308. # whether the AMS may heat -- and the gap between a finished print
  5309. # and the acknowledgment is exactly when drying is most useful,
  5310. # because the printer is free and nobody is waiting on it. Leaving
  5311. # the plate unacknowledged is also how people hold the queue by
  5312. # hand, and that hold should not cost them their drying.
  5313. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5314. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5315. continue
  5316. # Check drying capability. For mid-print path, supports_drying_while_printing
  5317. # was already verified when computing mid_print above.
  5318. if not mid_print and not supports_drying(model, firmware):
  5319. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5320. continue
  5321. # Check each AMS unit from raw_data
  5322. ams_list = state.raw_data.get("ams", [])
  5323. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5324. for ams_data in ams_list:
  5325. module_type = str(ams_data.get("module_type") or "")
  5326. ams_id = int(ams_data.get("id", 0))
  5327. # Only n3f/n3s support drying
  5328. if module_type not in ("n3f", "n3s"):
  5329. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5330. continue
  5331. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5332. # Most-restrictive of all loaded tray types; falls back to the
  5333. # global threshold when no overrides are configured.
  5334. trays = ams_data.get("tray", []) or []
  5335. humidity_threshold = self.resolve_humidity_threshold(
  5336. trays, per_type_thresholds, global_humidity_threshold
  5337. )
  5338. dry_time = int(ams_data.get("dry_time") or 0)
  5339. # Read humidity as a percentage. The 1-5 index is never
  5340. # substituted: it is inverted, and being unable to exceed any
  5341. # threshold it would read as "dry" forever (#3140). ``None``
  5342. # already means "skip this unit" everywhere below.
  5343. humidity_pct = ams_humidity_percent(ams_data)
  5344. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5345. unit_key = (pid, ams_id)
  5346. unit_state = self._auto_dry_units.get(unit_key)
  5347. # Already drying — let it run to its configured duration (#1892).
  5348. #
  5349. # We deliberately do NOT stop drying from a humidity re-check here.
  5350. # Relative humidity drops steeply in heated air, so the AMS sensor
  5351. # reads ~15-20% within minutes of the dryer starting even while the
  5352. # filament is still saturated. A humidity-based early-stop therefore
  5353. # always fires at the minimum-time floor, truncating both user-started
  5354. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5355. # The firmware stops when the configured duration elapses; scheduling
  5356. # stops (print takes priority, queue no longer needs drying) are
  5357. # handled separately via _stop_drying().
  5358. if dry_time > 0:
  5359. if pid not in self._drying_in_progress:
  5360. # Drying we didn't start (manual or from before restart) —
  5361. # track it so scheduling stops still apply; never auto-stop it.
  5362. self._drying_in_progress[pid] = time.monotonic()
  5363. if unit_state is not None:
  5364. unit_state["running"] = True
  5365. logger.debug(
  5366. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5367. pid,
  5368. ams_id,
  5369. dry_time,
  5370. humidity,
  5371. )
  5372. continue
  5373. # Nothing is drying. Close out a cycle we armed ourselves and
  5374. # judge whether it achieved anything (#2770).
  5375. #
  5376. # "Achieved anything" is measured against the LOWEST reading any
  5377. # cycle on this unit has ended at, not against the threshold and
  5378. # not against the previous cycle. A spool that is genuinely wet
  5379. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5380. # allowed to keep going for as long as it is still coming down,
  5381. # however far it still is from the threshold. What must not
  5382. # continue is a cycle that ends exactly where the last one did,
  5383. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5384. # Comparing against the running minimum rather than the previous
  5385. # end is what stops a sensor oscillating by one point between two
  5386. # values from reading as progress every other cycle.
  5387. if unit_state is not None and unit_state.pop("running", False):
  5388. unit_state["ended_at"] = time.monotonic()
  5389. # The streak that armed this cycle is spent; the next one
  5390. # starts fresh (and accumulates through the re-arm cooldown
  5391. # below, so the wait overlaps the cooldown, never stacks on
  5392. # top of it).
  5393. self._auto_dry_above.pop(unit_key, None)
  5394. if humidity is not None and humidity > humidity_threshold:
  5395. best = unit_state.get("best_end_humidity")
  5396. if isinstance(best, int) and humidity < best:
  5397. # Still coming down. Keep going, however far the
  5398. # threshold still is.
  5399. unproductive = 0
  5400. else:
  5401. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5402. if not isinstance(best, int) or humidity < best:
  5403. unit_state["best_end_humidity"] = humidity
  5404. unit_state["unproductive"] = unproductive
  5405. logger.info(
  5406. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5407. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5408. pid,
  5409. ams_id,
  5410. humidity,
  5411. humidity_threshold,
  5412. unit_state.get("best_end_humidity"),
  5413. unproductive,
  5414. )
  5415. # A cycle that ended at or below the threshold needs no
  5416. # counter reset here: the branch below drops the whole entry.
  5417. # Humidity below threshold — no need to start drying. This is
  5418. # also the only thing that lifts a suspension: the reading we
  5419. # gave up on has come down, so auto-drying works again and the
  5420. # unit goes back to having no history at all.
  5421. if humidity is None or humidity <= humidity_threshold:
  5422. if unit_state is not None and unit_state.get("suspended"):
  5423. logger.info(
  5424. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5425. "threshold, resuming automatic drying",
  5426. pid,
  5427. ams_id,
  5428. humidity,
  5429. humidity_threshold,
  5430. )
  5431. # Clear the judgement, keep the clock (#2801). Dropping the
  5432. # whole entry also dropped `ended_at`, and with it the
  5433. # 30-minute cooldown -- so a reading that dips to the
  5434. # threshold as the AMS cools and comes back above it once
  5435. # warm wiped its own history and re-armed immediately. That
  5436. # oscillation is the very thing #2770's cooldown exists to
  5437. # ride out, and it is worst at exactly the margin that makes
  5438. # a unit dry repeatedly: a point or two above the threshold.
  5439. if unit_state is not None:
  5440. unit_state.pop("suspended", None)
  5441. unit_state.pop("unproductive", None)
  5442. unit_state.pop("best_end_humidity", None)
  5443. # A real below-threshold reading ends any sustained-wait
  5444. # streak (#2518) -- "continuously above" means exactly that.
  5445. # An absent reading (humidity is None) is no-information and
  5446. # leaves the streak alone; the observation-gap guard handles
  5447. # a prolonged sensor silence.
  5448. if humidity is not None:
  5449. _above = self._auto_dry_above.pop(unit_key, None)
  5450. if _above is not None and sustained_wait_active:
  5451. logger.info(
  5452. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5453. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5454. pid,
  5455. ams_id,
  5456. humidity,
  5457. time.monotonic() - _above["since"],
  5458. sustained_minutes,
  5459. humidity_threshold,
  5460. )
  5461. logger.debug(
  5462. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5463. pid,
  5464. ams_id,
  5465. humidity,
  5466. humidity_threshold,
  5467. )
  5468. continue
  5469. # Sustained-humidity streak (#2518): updated on every pass that
  5470. # observes the reading above the threshold, BEFORE the
  5471. # suspension/cooldown gates below -- a suspended or cooling-down
  5472. # unit still accumulates streak time, so the wait overlaps those
  5473. # gates instead of stacking after them. Inert when the feature
  5474. # is off: no entries are written, and an entry left over from a
  5475. # toggle-off is dropped so it cannot seed a stale streak later.
  5476. if sustained_wait_active:
  5477. _now = time.monotonic()
  5478. # Four missed scheduler passes, floored: a single slow pass
  5479. # must not void a streak, but the ceiling has to scale with
  5480. # the cadence or a slow loop silently restarts every streak.
  5481. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5482. _above = self._auto_dry_above.get(unit_key)
  5483. if _above is None:
  5484. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5485. elif _now - _above["last"] > _gap_ceiling:
  5486. # Restart, and say so at the same level as the dip
  5487. # reset: a silent restart voids the streak invisibly,
  5488. # and a user who set a long wait and never gets a dry
  5489. # has no way to see why.
  5490. logger.info(
  5491. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5492. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5493. pid,
  5494. ams_id,
  5495. _now - _above["last"],
  5496. _gap_ceiling,
  5497. sustained_minutes,
  5498. )
  5499. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5500. else:
  5501. _above["last"] = _now
  5502. else:
  5503. self._auto_dry_above.pop(unit_key, None)
  5504. if unit_state is not None:
  5505. if unit_state.get("suspended"):
  5506. logger.debug(
  5507. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5508. "above the %d%% threshold",
  5509. pid,
  5510. ams_id,
  5511. int(unit_state.get("unproductive", 0)),
  5512. humidity_threshold,
  5513. )
  5514. continue
  5515. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5516. unit_state["suspended"] = True
  5517. logger.warning(
  5518. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5519. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5520. "higher while it is warm, so a threshold in that range can never be reached and "
  5521. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5522. pid,
  5523. ams_id,
  5524. int(unit_state.get("unproductive", 0)),
  5525. humidity,
  5526. humidity_threshold,
  5527. )
  5528. await self._notify_auto_drying_suspended(
  5529. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5530. )
  5531. continue
  5532. ended_at = unit_state.get("ended_at")
  5533. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5534. logger.debug(
  5535. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5536. "cycle before the humidity reading is worth acting on",
  5537. pid,
  5538. ams_id,
  5539. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5540. )
  5541. continue
  5542. # Check cannot-dry reasons (power constraints etc.). Sits
  5543. # ahead of the sustained wait so a unit the firmware refuses
  5544. # to dry never logs a wait it was never going to cash in.
  5545. sf_reasons = ams_data.get("dry_sf_reason", [])
  5546. if sf_reasons:
  5547. logger.debug(
  5548. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5549. pid,
  5550. ams_id,
  5551. sf_reasons,
  5552. )
  5553. continue
  5554. # Sustained-humidity wait (#2518): ambient-triggered starts
  5555. # wait; only a printer with a scheduled queue item pending
  5556. # keeps the instant behavior, because that drying has a real
  5557. # deadline. Mid-print is deliberately NOT exempt while ambient
  5558. # drying is on: a humidity start on a printer that happens to be
  5559. # printing is as vulnerable to a lid-open spike as one on an idle
  5560. # printer (proven live: a 2-point threshold crossing mid-print
  5561. # bought a parked 12h command). Inactive when ambient drying is
  5562. # off: print_drying then still starts mid-print cycles on its own
  5563. # (#1816, "regardless of queue state"), and those stay instant.
  5564. if sustained_wait_active and pid not in printers_with_scheduled:
  5565. _above = self._auto_dry_above.get(unit_key)
  5566. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5567. if _waited < sustained_minutes * 60:
  5568. logger.debug(
  5569. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5570. "threshold for %.0fs of the required %dm",
  5571. pid,
  5572. ams_id,
  5573. humidity,
  5574. humidity_threshold,
  5575. _waited,
  5576. sustained_minutes,
  5577. )
  5578. continue
  5579. # Get conservative drying params for mixed filaments
  5580. params = self._get_conservative_drying_params(trays, module_type, presets)
  5581. if not params:
  5582. logger.debug(
  5583. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5584. )
  5585. continue
  5586. temp, duration_hours, filament_type = params
  5587. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5588. # "drying temperature must not exceed the filament's softening temperature"
  5589. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5590. # ineffective and firmware will reject anyway.
  5591. if mid_print:
  5592. temp = max(40, temp - 5)
  5593. # Start drying
  5594. logger.info(
  5595. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5596. "starting %s drying at %d°C for %dh%s",
  5597. pid,
  5598. ams_id,
  5599. humidity,
  5600. humidity_threshold,
  5601. filament_type,
  5602. temp,
  5603. duration_hours,
  5604. " (mid-print)" if mid_print else "",
  5605. )
  5606. success = printer_manager.send_drying_command(
  5607. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5608. )
  5609. if success:
  5610. self._drying_in_progress[pid] = time.monotonic()
  5611. armed = self._auto_dry_units.setdefault(
  5612. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5613. )
  5614. armed["running"] = True
  5615. async def _notify_auto_drying_suspended(
  5616. self,
  5617. db: AsyncSession,
  5618. printer: Printer,
  5619. ams_id: int,
  5620. humidity: int,
  5621. threshold: int,
  5622. cycles: int,
  5623. ) -> None:
  5624. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5625. Fires once per suspension — the caller sets ``suspended`` before calling
  5626. and every later pass short-circuits on it — because the whole point is
  5627. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5628. building needs that to reach them, and the hourly humidity alarm they
  5629. are already getting says the opposite of what happened here.
  5630. Never raises: a notification provider being down must not stop the
  5631. suspension itself from taking effect.
  5632. """
  5633. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5634. try:
  5635. await notification_service.on_ams_drying_suspended(
  5636. printer.id,
  5637. printer.name,
  5638. ams_label,
  5639. float(humidity),
  5640. float(threshold),
  5641. cycles,
  5642. db,
  5643. )
  5644. except Exception as e:
  5645. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5646. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5647. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5648. The unproductive-cycle counter exists to notice that *drying* is not
  5649. moving the humidity reading. A cycle that ended because somebody sent a
  5650. stop says nothing about that — it was cut short before it had a chance —
  5651. so counting it would suspend auto-drying for a reason that has nothing to
  5652. do with the loop the counter is there to break.
  5653. Two callers, both of them a stop Bambuddy is responsible for: the
  5654. print-takes-priority stop below, and the manual Stop button. Left
  5655. uncalled, an install that dries between queue jobs would suspend its own
  5656. auto-drying after two prints interrupted a dry — exactly the install
  5657. queue-drying exists for.
  5658. The rest of the unit's history is kept: the cooldown before re-arming
  5659. still applies, and an earlier count still stands.
  5660. """
  5661. state = self._auto_dry_units.get((printer_id, ams_id))
  5662. if state is not None:
  5663. state.pop("running", None)
  5664. state["ended_at"] = time.monotonic()
  5665. # A stopped cycle spends the streak that armed it, same as a completed
  5666. # one (#2518).
  5667. self._auto_dry_above.pop((printer_id, ams_id), None)
  5668. def _sync_drying_state(self):
  5669. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5670. One direction only: it prunes, it never adds. A printer drying without an
  5671. entry here — because the user started the cycle from Studio, the printer's
  5672. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5673. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5674. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5675. That is deliberate for now rather than an oversight: populating this from
  5676. telemetry would hand the scheduler authority to stop drying a user started
  5677. by hand. It also means the backend-restart case this used to claim to
  5678. handle is not handled.
  5679. """
  5680. to_remove = []
  5681. for pid in self._drying_in_progress:
  5682. state = printer_manager.get_status(pid)
  5683. if not state:
  5684. to_remove.append(pid)
  5685. continue
  5686. # Check if any AMS unit is still drying
  5687. ams_list = state.raw_data.get("ams", [])
  5688. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5689. if not any_drying:
  5690. to_remove.append(pid)
  5691. for pid in to_remove:
  5692. self._drying_in_progress.pop(pid, None)
  5693. # A printer that has gone away entirely takes its per-AMS auto-drying
  5694. # history with it (#2770), so a printer deleted and re-added does not
  5695. # inherit a suspension it never earned.
  5696. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5697. self._auto_dry_units.pop(key, None)
  5698. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5699. # printer starts a fresh wait, and vanished printers do not leak
  5700. # entries.
  5701. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5702. self._auto_dry_above.pop(key, None)
  5703. @staticmethod
  5704. def _drying_is_only_parked(printer_id: int) -> bool:
  5705. """True when every AMS unit with a drying timer on this printer is parked.
  5706. A parked timer (#2896: the command was taken but the countdown never
  5707. runs) does not end on its own, so nothing may wait on it. False when no
  5708. unit reports a timer yet -- a command just sent that the firmware has not
  5709. reported back is real drying about to begin.
  5710. """
  5711. state = printer_manager.get_status(printer_id)
  5712. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5713. timed = []
  5714. for unit in units:
  5715. try:
  5716. if int(unit.get("dry_time") or 0) > 0:
  5717. timed.append(unit)
  5718. except (TypeError, ValueError):
  5719. continue
  5720. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5721. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5722. """True when a running cycle can be left alone while the next print runs.
  5723. Some hardware dries happily through a print and #2758 settled that we
  5724. should not tear those cycles down: the X2D there was refusing to
  5725. *start* a job, which is a different problem, and stopping drying before
  5726. every dispatch would throw away cycles the printer was content to run.
  5727. Where the model cannot do it, or the user has not enabled it, the print
  5728. takes priority and the cycle stops -- which is what the queue_drying_block
  5729. setting has always promised in its off position.
  5730. """
  5731. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5732. return False
  5733. status = printer_manager.get_status(printer_id)
  5734. return supports_drying_while_printing(
  5735. printer_manager.get_model(printer_id),
  5736. status.firmware_version if status else None,
  5737. )
  5738. async def _stop_drying(self, printer_id: int):
  5739. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5740. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5741. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5742. enough to kill a cycle the user had started by hand on a *different*
  5743. unit of the same printer (#2801). That contradicted the contract
  5744. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5745. only knows about cycles Bambuddy began, so the action must not reach
  5746. past them either.
  5747. """
  5748. state = printer_manager.get_status(printer_id)
  5749. if not state:
  5750. self._drying_in_progress.pop(printer_id, None)
  5751. return
  5752. ams_list = state.raw_data.get("ams", [])
  5753. for ams_data in ams_list:
  5754. dry_time = int(ams_data.get("dry_time") or 0)
  5755. if dry_time > 0:
  5756. ams_id = int(ams_data.get("id", 0))
  5757. if (printer_id, ams_id) not in self._auto_dry_units:
  5758. logger.debug(
  5759. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5760. printer_id,
  5761. ams_id,
  5762. )
  5763. continue
  5764. logger.info(
  5765. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5766. printer_id,
  5767. ams_id,
  5768. )
  5769. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5770. self.forget_auto_dry_cycle(printer_id, ams_id)
  5771. self._drying_in_progress.pop(printer_id, None)
  5772. # Scheduled manual drying (#2638) -----------------------------------
  5773. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5774. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5775. async def _check_scheduled_dryings(self, db: AsyncSession):
  5776. """Dispatch due scheduled drying runs and track running ones."""
  5777. now = utcnow_naive()
  5778. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5779. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5780. since_prune = time.monotonic()
  5781. if (
  5782. self._last_scheduled_drying_prune is None
  5783. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5784. ):
  5785. self._last_scheduled_drying_prune = since_prune
  5786. await db.execute(
  5787. delete(ScheduledDrying).where(
  5788. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5789. ScheduledDrying.completed_at.is_not(None),
  5790. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5791. )
  5792. )
  5793. # Same order as the list route: with two rows due on one printer the
  5794. # earliest scheduled wins rather than whatever the DB hands back first.
  5795. result = await db.execute(
  5796. select(ScheduledDrying)
  5797. .where(ScheduledDrying.status.in_(("pending", "running")))
  5798. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5799. )
  5800. rows = list(result.scalars().all())
  5801. # Rebuild from the DB every tick so route-side cancels and completions
  5802. # show up. Auto-drying's stop-all branches check this set before
  5803. # stopping anything (#2638).
  5804. # Kept from the previous pass so a run that ended between passes — a
  5805. # cancel through the route, say — can still be released below.
  5806. previously_running = self._scheduled_drying_printer_ids
  5807. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5808. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5809. # Model and firmware come from the printer row, not the live state.
  5810. printer_ids = {row.printer_id for row in rows}
  5811. printers_by_id: dict[int, Printer] = {}
  5812. if printer_ids:
  5813. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5814. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5815. for row in rows:
  5816. if row.status == "running":
  5817. self._update_running_scheduled_drying(row, now)
  5818. continue
  5819. if row.start_after is not None and row.start_after > now:
  5820. continue
  5821. state = printer_manager.get_status(row.printer_id)
  5822. if not state:
  5823. row.waiting_reason = "printer_offline"
  5824. continue
  5825. # Same preflight the immediate endpoint runs. Without it the publish
  5826. # succeeds, the row goes to running, the printer ignores the command
  5827. # and the run silently cancels itself after the grace window.
  5828. printer = printers_by_id.get(row.printer_id)
  5829. unsupported = drying_preflight.check_drying_supported(
  5830. printer.model if printer else None, state.firmware_version
  5831. )
  5832. if unsupported:
  5833. row.status = "failed"
  5834. row.error_message = unsupported
  5835. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5836. row.completed_at = now
  5837. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5838. continue
  5839. if (
  5840. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5841. ) or row.printer_id in running_printer_ids:
  5842. row.waiting_reason = "already_drying"
  5843. continue
  5844. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5845. row.waiting_reason = "printer_busy"
  5846. continue
  5847. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5848. if target is None:
  5849. row.waiting_reason = "ams_not_found"
  5850. continue
  5851. blocking = drying_preflight.blocking_reason_codes(target)
  5852. if blocking:
  5853. # Keep the power case distinct; it needs the user to act, so the
  5854. # card can say so instead of waiting silently.
  5855. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5856. continue
  5857. filament = drying_preflight.resolve_filament(target, row.filament)
  5858. logger.info(
  5859. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5860. row.id,
  5861. row.printer_id,
  5862. row.ams_id,
  5863. row.temp,
  5864. row.duration_hours,
  5865. )
  5866. success = printer_manager.send_drying_command(
  5867. row.printer_id,
  5868. row.ams_id,
  5869. row.temp,
  5870. row.duration_hours,
  5871. mode=1,
  5872. filament=filament,
  5873. rotate_tray=row.rotate_tray,
  5874. )
  5875. if success:
  5876. row.status = "running"
  5877. row.started_at = now
  5878. row.waiting_reason = None
  5879. row.filament = filament
  5880. self._drying_in_progress[row.printer_id] = time.monotonic()
  5881. self._scheduled_drying_printer_ids.add(row.printer_id)
  5882. running_printer_ids.add(row.printer_id)
  5883. else:
  5884. row.waiting_reason = "printer_offline"
  5885. # Release the printers whose run has ended. `_drying_in_progress` is
  5886. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5887. # but that call sits behind the auto-drying enabled check, and this
  5888. # method is the one writer that runs whether auto-drying is on or not.
  5889. # With it off, nothing would ever drop the entry short of a print being
  5890. # dispatched to the same printer, so the next scheduled run would wait
  5891. # on "already_drying" forever and `queue_drying_block` would hold the
  5892. # printer's prints too. Covers a run that ended during this pass and one
  5893. # cancelled through the route between passes.
  5894. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5895. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5896. self._drying_in_progress.pop(printer_id, None)
  5897. await db.commit()
  5898. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5899. """Detect completion or interruption of a running scheduled drying.
  5900. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5901. drying. Within the grace window after start we ignore dry_time==0
  5902. (the status lags the command). After that, dry_time==0 near the end
  5903. of the configured duration means completed. Much earlier means the
  5904. run was stopped: re-queue it if a print preempted the dryer, but a
  5905. stop while the printer is idle was deliberate, so cancel the row
  5906. rather than restart drying the user just stopped.
  5907. """
  5908. if row.started_at is None:
  5909. row.started_at = now
  5910. return
  5911. elapsed = (now - row.started_at).total_seconds()
  5912. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5913. return
  5914. state = printer_manager.get_status(row.printer_id)
  5915. if not state:
  5916. return # offline mid-dry; resolve when it reconnects
  5917. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5918. # throw on a malformed id would cost the whole pass including print
  5919. # dispatch, every tick.
  5920. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5921. try:
  5922. dry_time = int(target.get("dry_time") or 0) if target else 0
  5923. except (TypeError, ValueError):
  5924. dry_time = 0
  5925. if dry_time > 0 and is_countdown_parked(target):
  5926. # The printer took the command but the countdown is not running
  5927. # (#2896) and will never reach 0, so the run would stay "running"
  5928. # forever. A print in progress is the likely cause (the power budget
  5929. # is spent), so re-queue it like any interruption; the next start
  5930. # waits for the printer to be idle. Parked on an idle printer is a
  5931. # refusal, not something a retry fixes. The timer itself is left on
  5932. # the printer: it may yet start once power frees up.
  5933. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5934. logger.info(
  5935. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5936. row.id,
  5937. row.ams_id,
  5938. )
  5939. row.status = "pending"
  5940. row.started_at = None
  5941. row.waiting_reason = "interrupted"
  5942. else:
  5943. logger.warning(
  5944. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5945. row.id,
  5946. row.ams_id,
  5947. )
  5948. row.status = "failed"
  5949. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5950. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5951. row.completed_at = now
  5952. return
  5953. if dry_time > 0:
  5954. return
  5955. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5956. row.status = "completed"
  5957. row.completed_at = now
  5958. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5959. row.status = "pending"
  5960. row.started_at = None
  5961. row.waiting_reason = "interrupted"
  5962. else:
  5963. row.status = "cancelled"
  5964. row.completed_at = now
  5965. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5966. """Get all smart plugs associated with a printer."""
  5967. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5968. return list(result.scalars().all())
  5969. @staticmethod
  5970. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5971. """Pick the plug to power-cycle a printer back online with (#2629).
  5972. Only a plug flagged ``controls_printer_power`` can actually bring the
  5973. printer back; waiting for a boot on an accessory (filter fan, lights)
  5974. just burns the power-on timeout and fails the dispatch. Falls back to
  5975. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5976. Callers must pass a non-empty list.
  5977. """
  5978. for plug in auto_on_plugs:
  5979. if plug.controls_printer_power:
  5980. return plug
  5981. return auto_on_plugs[0]
  5982. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5983. # chamber-temperature recommendations BambuStudio ships for the matching
  5984. # filament profile; users can override via Settings → Workflow → Preheat
  5985. # card. "default" applies when a loaded tray's normalised type isn't in
  5986. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5987. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5988. "PLA": 0,
  5989. "PETG": 0,
  5990. "PETG-CF": 40,
  5991. "ABS": 45,
  5992. "ASA": 45,
  5993. "PA": 50,
  5994. "PA-CF": 55,
  5995. "PC": 50,
  5996. "PC-FR": 50,
  5997. "TPU": 0,
  5998. "PVA": 0,
  5999. "default": 0,
  6000. }
  6001. @classmethod
  6002. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6003. """The bundled map under the same key casing a parsed one gets.
  6004. The constant is declared with a lowercase ``default`` because that is
  6005. the key the Settings editor writes and displays. Every read of the map
  6006. happens after ``str(key).upper()``, so handing the constant back as
  6007. declared broke the contract the parser documents: an install that had
  6008. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6009. and the resolution loop's fallback silently found nothing. It read the
  6010. right number only because the bundled default happens to be 0 -- change
  6011. that constant and every unconfigured install would keep preheating to
  6012. zero with no way to tell why.
  6013. """
  6014. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6015. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6016. """Parse the user-configured filament→chamber-target map, falling back
  6017. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6018. are uppercased and the 'default' fallback is always present in the
  6019. returned dict so the resolution loop can index it unconditionally."""
  6020. raw = await self._get_setting(db, "preheat_filament_targets")
  6021. if not raw:
  6022. return self._bundled_preheat_targets()
  6023. try:
  6024. parsed = json.loads(raw)
  6025. if not isinstance(parsed, dict):
  6026. raise ValueError("not an object")
  6027. except (json.JSONDecodeError, ValueError) as exc:
  6028. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6029. return self._bundled_preheat_targets()
  6030. # Coerce values to int; drop unparseable rows so a stray string
  6031. # doesn't crash the loop.
  6032. out: dict[str, int] = {}
  6033. for key, value in parsed.items():
  6034. try:
  6035. out[str(key).upper()] = int(value)
  6036. except (TypeError, ValueError):
  6037. continue
  6038. if "DEFAULT" not in out:
  6039. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6040. return out
  6041. @staticmethod
  6042. def _normalize_filament_type(tray_type: str) -> str:
  6043. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6044. existing drying-preset normalisation (split-at-space, upper-case) so
  6045. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6046. "PA-CF" (no space to split on).
  6047. This is the first stage of ``_resolve_filament_key``, which goes on to
  6048. drop the suffix and consult the alias map; on its own it only decides
  6049. what the tray is called, not which row answers for it.
  6050. Indexing the split rather than testing the input: a tray_type of spaces
  6051. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6052. it through to an IndexError.
  6053. """
  6054. words = (tray_type or "").split()
  6055. return words[0].upper() if words else ""
  6056. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6057. """Per-filament chamber target for one tray's reported type, or 0 when
  6058. the tray is empty / RFID-less and reports no type at all.
  6059. A filled or foamed variant wants its base material's chamber when the
  6060. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6061. not the 0 an unknown type falls to. The specific type is still tried
  6062. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6063. (#2902).
  6064. That lookup is now the shared one, which adds the polyamide aliases on
  6065. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6066. too, rather than the catch-all it was landing on (#3067).
  6067. """
  6068. if not self._normalize_filament_type(tray_type or ""):
  6069. return 0
  6070. key = self._resolve_filament_key(tray_type, targets)
  6071. if key is not None:
  6072. return targets[key]
  6073. # A type the map does not list at all, which is not the same as a tray
  6074. # with nothing in it -- that already returned 0 above.
  6075. return targets.get("DEFAULT", 0)
  6076. def _derive_chamber_target(
  6077. self,
  6078. printer: Printer,
  6079. targets: dict[str, int],
  6080. item: PrintQueueItem | None = None,
  6081. ) -> int:
  6082. """Chamber target for the trays this print actually loads: the max of
  6083. their per-filament targets. Returns 0 when there is nothing to read (no
  6084. status, no AMS telemetry — e.g. external-spool prints) or when every
  6085. tray considered maps to 0, and the chamber phase then short-circuits in
  6086. the main loop.
  6087. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6088. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6089. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6090. plus soak burned ahead of each upload, on a printer whose chamber never
  6091. reaches the target anyway (#2886). An item with no usable mapping falls
  6092. back to scanning every loaded tray: that is the only signal left, and
  6093. narrowing to nothing would skip preheat on prints that genuinely need
  6094. it.
  6095. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6096. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6097. less slots have empty `tray_type` and contribute nothing. The external
  6098. spool is consulted only when the mapping names it (>= 254); it stays
  6099. out of the unnarrowed scan, so an item without a mapping derives from
  6100. the AMS alone exactly as before.
  6101. """
  6102. state = printer_manager.get_status(printer.id)
  6103. if state is None:
  6104. return 0
  6105. raw_data = state.raw_data or {}
  6106. used = _used_global_tray_ids(item)
  6107. ams_list = raw_data.get("ams")
  6108. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6109. if isinstance(ams_list, dict):
  6110. ams_list = ams_list.get("ams") or []
  6111. if not isinstance(ams_list, list):
  6112. ams_list = []
  6113. best = 0
  6114. for ams in ams_list:
  6115. if not isinstance(ams, dict):
  6116. continue
  6117. ams_id = _int_or(ams.get("id"), 0)
  6118. for tray in ams.get("tray") or []:
  6119. # A non-dict entry has never been seen from real firmware, but
  6120. # `.get` on one raises, and nothing between here and
  6121. # `_dispatch_one`'s try/finally catches it — the item would be
  6122. # left holding its dispatch claim. Preheat is best-effort by
  6123. # contract, so step over it instead.
  6124. if not isinstance(tray, dict):
  6125. continue
  6126. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6127. continue
  6128. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6129. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6130. for vt in raw_data.get("vt_tray") or []:
  6131. if not isinstance(vt, dict):
  6132. continue
  6133. # `_build_loaded_filaments` addresses external feeds by the id
  6134. # the firmware reports — 255 main, 254 deputy — defaulting to
  6135. # 254 when the field is absent. Same expression here so the two
  6136. # agree on which entry a mapping's 254/255 refers to.
  6137. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6138. continue
  6139. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6140. return best
  6141. def _release_keep_warm(self, pid: int) -> None:
  6142. """Release keep-warm on a printer that left the candidate set.
  6143. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6144. reports the target we set (``entry.held_target``), so a user or
  6145. subsequent print that changed the bed target since is not clobbered.
  6146. Best-effort, never raises.
  6147. The entry is kept, not dropped, when the printer cannot be reached
  6148. right now: a printer that is briefly offline still has a hot bed, and
  6149. holding the entry is what keeps the max-duration timeout applying and
  6150. lets a later tick retry the release. Only a printer that has left the
  6151. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6152. """
  6153. entry = self._keep_warm.get(pid)
  6154. if entry is None:
  6155. return
  6156. state = printer_manager.get_status(pid)
  6157. client = printer_manager.get_client(pid)
  6158. if state is None or client is None:
  6159. logger.debug(
  6160. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6161. pid,
  6162. )
  6163. return
  6164. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6165. if int(cur_bed_target) != entry.held_target:
  6166. # Someone else owns the bed now, so there is nothing of ours to
  6167. # undo and nothing left to track.
  6168. logger.info(
  6169. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6170. pid,
  6171. int(cur_bed_target),
  6172. entry.held_target,
  6173. )
  6174. self._keep_warm.pop(pid, None)
  6175. return
  6176. try:
  6177. client.set_bed_temperature(0)
  6178. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6179. self._keep_warm.pop(pid, None)
  6180. except Exception as exc:
  6181. # Keep the entry so the next tick tries again rather than leaving
  6182. # the bed hot with nothing tracking it.
  6183. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6184. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6185. """Release printers that dropped out of the keep-warm candidate set.
  6186. Called from ``_apply_keep_warm`` on every tick (with the current
  6187. candidate set), and from ``check_queue``'s no-pending-items early
  6188. return (with an empty candidate set) so orphaned holds still get
  6189. released when the queue empties. Also called with an empty candidate
  6190. set when any of the three gate settings toggles off, so a printer
  6191. whose feature was disabled mid-hold gets its bed released.
  6192. Printers being dispatched this tick are excluded from the bed-off
  6193. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6194. transient 0 in between would just churn against preheat. Ownership of
  6195. the hot bed transfers to the preheat rollback pin instead — if the
  6196. dispatch aborts before the print starts (failed upload, cancelled
  6197. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6198. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6199. is the ONLY thing standing between an aborted dispatch and a bed
  6200. left hot with no owner. A successful print start clears the pin and
  6201. the print's own gcode takes over, as usual.
  6202. """
  6203. for _pid in list(self._keep_warm):
  6204. if _pid in active_candidates:
  6205. continue
  6206. if _pid in dispatched:
  6207. handed_over = self._keep_warm.pop(_pid, None)
  6208. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6209. if handed_over is not None:
  6210. self._preheat_pin_bed[_pid] = handed_over.held_target
  6211. continue
  6212. self._release_keep_warm(_pid)
  6213. async def _apply_keep_warm(
  6214. self,
  6215. db: AsyncSession,
  6216. items: list[PrintQueueItem],
  6217. dispatch_ids: list[int] | set[int],
  6218. busy_printers: set[int],
  6219. require_plate_clear: bool,
  6220. ) -> None:
  6221. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6222. When a printer just finished a job (FINISH state) and the next queued
  6223. item needs chamber heating, hold the bed hot so the chamber stays warm
  6224. during the bed-clearing window. The bed is the chamber's heating
  6225. element here, not a print surface — nothing is printing during the
  6226. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6227. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6228. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6229. aftermarket chamber heaters), raised to the item's own parsed
  6230. bed_temperature when that is higher. Items whose archive metadata has
  6231. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6232. get a hold — chamber need is what gates the feature, not metadata.
  6233. Skips entirely for filaments that map to a 0°C chamber target
  6234. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6235. names, so a hot-chamber spool it never touches does not hold the bed of
  6236. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6237. whole unit, as every item was before. Printers being dispatched this
  6238. cycle are excluded:
  6239. ``_preheat_and_soak`` already handles their bed temperature.
  6240. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6241. released to 0 and the entry is latched ``expired=True`` so
  6242. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6243. MQTT: publish is skipped when firmware already has the target.
  6244. The release sweep runs BEFORE the engagement gate so a printer that
  6245. was owned by keep-warm still gets its bed released when any of the
  6246. three gate settings is toggled off mid-hold. The
  6247. ``check_queue`` early-return-when-no-items path also calls
  6248. ``_sweep_keep_warm`` directly to release orphaned holds.
  6249. """
  6250. dispatch_set = set(dispatch_ids)
  6251. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6252. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6253. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6254. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6255. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6256. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6257. # Release sweep first — must run even when gate_open is False so a
  6258. # printer owned by keep-warm when a gate toggles off gets released.
  6259. self._sweep_keep_warm(
  6260. active_candidates=warm_candidates if gate_open else set(),
  6261. dispatched=dispatched_printers,
  6262. )
  6263. if not gate_open:
  6264. return
  6265. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6266. max_hold_seconds = (
  6267. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6268. )
  6269. now_mono = time.monotonic()
  6270. filament_targets: dict[str, int] | None = None
  6271. for pid in warm_candidates:
  6272. entry = self._keep_warm.get(pid)
  6273. # Latched-expired: max-duration timeout already fired for this
  6274. # printer. Skip until the release sweep drops the entry (i.e.
  6275. # until the printer leaves the candidate set).
  6276. if entry is not None and entry.expired:
  6277. continue
  6278. # These two guards sit ahead of the max-duration check below, so an
  6279. # engaged hold only ages out while its printer is still reachable
  6280. # and still in FINISH. That is deliberate rather than a hole: with
  6281. # no status or no client there is no M140 to send anyway, and the
  6282. # elapsed check runs off `entry.started` so it fires on the first
  6283. # tick after the printer comes back. Leaving FINISH means the plate
  6284. # was cleared, which drops the printer out of `warm_candidates` and
  6285. # hands it to `_release_keep_warm` instead. The invariant worth
  6286. # preserving if this is ever reordered: every path out of an
  6287. # engaged hold ends in a bed-off, whether by timeout or release.
  6288. state = printer_manager.get_status(pid)
  6289. if state is None or state.state != "FINISH":
  6290. continue
  6291. client = printer_manager.get_client(pid)
  6292. if client is None:
  6293. continue
  6294. next_item = next((it for it in items if it.printer_id == pid), None)
  6295. if next_item is None:
  6296. continue
  6297. # Hold temperature: the configured keep-warm temp, raised to the
  6298. # item's own bed temp when the metadata reports a higher one. A
  6299. # missing bed_temperature (Orca gcode.3mf exports parse without
  6300. # one) does NOT skip the hold — chamber need gates the feature.
  6301. archive = next_item.archive
  6302. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6303. bed_target = max(item_bed, hold_temp)
  6304. if bed_target <= 0:
  6305. continue
  6306. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6307. if explicit is not None:
  6308. chamber_needed = int(explicit) > 0
  6309. else:
  6310. if filament_targets is None:
  6311. filament_targets = await self._get_preheat_filament_targets(db)
  6312. printer_obj = await self._get_printer(db, pid)
  6313. chamber_needed = (
  6314. printer_obj is not None
  6315. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6316. )
  6317. if not chamber_needed:
  6318. continue
  6319. # Seed the timer on first engagement; keep it on subsequent ticks
  6320. # (never re-seed — that would defeat the max-duration cap).
  6321. if entry is None:
  6322. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6323. self._keep_warm[pid] = entry
  6324. elapsed = now_mono - entry.started
  6325. if elapsed > max_hold_seconds:
  6326. # Timeout: publish bed → 0 once (if firmware still holds our
  6327. # target) and latch expired. The entry stays until the release
  6328. # sweep drops it, preventing the next tick from re-seeding.
  6329. logger.warning(
  6330. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6331. pid,
  6332. elapsed,
  6333. )
  6334. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6335. if int(cur_bed_target) == entry.held_target:
  6336. try:
  6337. client.set_bed_temperature(0)
  6338. except Exception as exc:
  6339. logger.warning(
  6340. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6341. pid,
  6342. exc,
  6343. )
  6344. else:
  6345. logger.info(
  6346. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6347. pid,
  6348. int(cur_bed_target),
  6349. entry.held_target,
  6350. )
  6351. entry.expired = True
  6352. continue
  6353. # Idempotence: skip publish when firmware already has our target.
  6354. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6355. if int(cur_bed_target) == bed_target:
  6356. entry.held_target = bed_target
  6357. continue
  6358. try:
  6359. client.set_bed_temperature(bed_target)
  6360. entry.held_target = bed_target
  6361. logger.info(
  6362. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6363. bed_target,
  6364. pid,
  6365. )
  6366. except Exception as exc:
  6367. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6368. def _sample_chamber_temps(self) -> None:
  6369. """Record a chamber temperature sample for every connected printer.
  6370. Called once per scheduler tick (every 3–30 s). Entries older than
  6371. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6372. Also evicts per-printer state whose printer_id is no longer registered
  6373. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6374. """
  6375. now = time.monotonic()
  6376. cutoff = now - self._chamber_history_ttl
  6377. statuses = printer_manager.get_all_statuses()
  6378. known_pids = set(statuses.keys())
  6379. for pid, status in statuses.items():
  6380. if status is None or not status.connected:
  6381. continue
  6382. temps = status.temperatures or {}
  6383. chamber = temps.get("chamber")
  6384. if chamber is None:
  6385. continue
  6386. hist = self._chamber_history.setdefault(pid, deque())
  6387. hist.append((now, float(chamber)))
  6388. while hist and hist[0][0] < cutoff:
  6389. hist.popleft()
  6390. # Evict state for printers that are no longer registered with the manager.
  6391. # This is the one place a keep-warm entry is dropped without releasing
  6392. # the bed: the printer is gone from the manager, so there is no client
  6393. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6394. # for printers that are merely unreachable, which is what makes this
  6395. # the terminal case rather than a silent leak.
  6396. for pid in list(self._chamber_history):
  6397. if pid not in known_pids:
  6398. self._chamber_history.pop(pid, None)
  6399. for pid in list(self._keep_warm):
  6400. if pid not in known_pids:
  6401. logger.info(
  6402. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6403. pid,
  6404. )
  6405. self._keep_warm.pop(pid, None)
  6406. for pid in list(self._preheat_pin):
  6407. if pid not in known_pids:
  6408. self._preheat_pin.pop(pid, None)
  6409. self._preheat_pin_bed.pop(pid, None)
  6410. def _chamber_soak_remaining(
  6411. self,
  6412. printer_id: int,
  6413. chamber_target: float,
  6414. soak_seconds: int,
  6415. tolerance: float = 2.0,
  6416. ) -> int:
  6417. """Return how many seconds of soak time are still needed.
  6418. Credits the time the chamber has already spent at temperature against
  6419. the configured soak. The credit may not start earlier than any of:
  6420. * **The newest sample.** Nothing recent means the printer stopped
  6421. reporting mid-observation and the chamber may have cooled unseen, so
  6422. the full soak is required. (A 2 h history whose last reading is half
  6423. an hour old is not evidence of anything — the measured cooling rate
  6424. is fast enough to cross the threshold in that time.)
  6425. * **The most recent contiguous run of samples.** A gap wider than
  6426. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6427. far side is not evidence of temperature.
  6428. * **The end of the most recent real dip below the threshold.**
  6429. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6430. — see that constant for the thermal reasoning. A stray low reading is
  6431. an artifact, and treating it as cooling would discard a soak that
  6432. actually happened.
  6433. Returns ``soak_seconds`` when nothing can be credited (no history,
  6434. stale history, or the chamber is below the threshold right now) and 0
  6435. once the credited time covers the whole soak.
  6436. """
  6437. hist = self._chamber_history.get(printer_id)
  6438. if not hist:
  6439. return soak_seconds
  6440. now = time.monotonic()
  6441. newest_ts, newest_temp = hist[-1]
  6442. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6443. return soak_seconds # stale — no fresh evidence to credit
  6444. threshold = chamber_target - tolerance
  6445. if newest_temp < threshold:
  6446. return soak_seconds # below target right now; nothing is soaked
  6447. samples = list(hist)
  6448. # Earliest point we have unbroken observations for.
  6449. credit_from = samples[-1][0]
  6450. for i in range(len(samples) - 1, 0, -1):
  6451. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6452. break
  6453. credit_from = samples[i - 1][0]
  6454. # Pull the credit forward to the end of the last significant dip. Each
  6455. # excursion is measured between the in-range readings that bracket it,
  6456. # so a lone stray sample is charged one sampling interval rather than
  6457. # zero, and the comparison errs towards calling a dip real.
  6458. i = 0
  6459. while i < len(samples):
  6460. if samples[i][1] >= threshold:
  6461. i += 1
  6462. continue
  6463. j = i
  6464. while j < len(samples) and samples[j][1] < threshold:
  6465. j += 1
  6466. # `newest_temp >= threshold` was checked above, so j is in range.
  6467. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6468. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6469. # Credit resumes at the last below-threshold sample rather than
  6470. # the first good one after it, so a recovered dip over-credits
  6471. # by up to one sampling interval — the opposite lean to the
  6472. # bracketing above. Both are bounded by the sample cadence and
  6473. # dwarfed by the grace period, so neither is worth the extra
  6474. # arithmetic to remove.
  6475. credit_from = max(credit_from, samples[j - 1][0])
  6476. i = j
  6477. return max(0, soak_seconds - int(now - credit_from))
  6478. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6479. """Tell an in-flight dispatch that its item no longer wants to print.
  6480. Called by the queue's cancel and delete routes. Those only write to the
  6481. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6482. observe — so preheat would keep heating for the rest of max_wait + soak
  6483. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6484. blocking every other queued item behind a print that is not happening.
  6485. Signalling in memory rather than re-reading the row keeps this off the
  6486. database entirely: no second session, no transaction held across a long
  6487. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6488. Bambuddy serves from a single uvicorn process with one scheduler task,
  6489. so the route and the dispatch always share this object. The flag is
  6490. advisory — dropping it (e.g. after a restart) only costs a wasted
  6491. preheat, never a wrongly-abandoned print.
  6492. Only ids with a dispatch actually in flight are recorded, so the set
  6493. stays bounded by the upload pool rather than growing once per cancelled
  6494. item for the life of the process. Skipping the rest loses nothing: an
  6495. item that is not in flight cannot start heating later either, because
  6496. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6497. the caller has already committed a terminal status (or deleted the row)
  6498. before calling this.
  6499. """
  6500. if item_id in self._inflight:
  6501. self._cancelled_dispatches.add(item_id)
  6502. # A print sent for it earlier that never started is not one any more.
  6503. self._forget_unstarted_print(item_id, unless_printing=False)
  6504. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6505. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6506. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6507. while it is parked, so the wait is chopped into
  6508. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6509. """
  6510. remaining = float(seconds)
  6511. while remaining > 0:
  6512. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6513. await asyncio.sleep(slice_secs)
  6514. remaining -= slice_secs
  6515. if item_id in self._cancelled_dispatches:
  6516. return False
  6517. return True
  6518. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6519. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6520. The full preheat stage does this as part of its own dispatch: an H2D
  6521. left in heating mode by the ABS job before it would otherwise cook the
  6522. PLA that follows. The skip path never reaches that code, so it calls
  6523. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6524. add to the rollback pin, because a flap set to cooling for a print that
  6525. needs no heat is where it should have been either way.
  6526. Best-effort like everything else in the stage: a refused command logs
  6527. and the dispatch carries on.
  6528. """
  6529. model = printer.model or ""
  6530. if not supports_airduct(model):
  6531. return
  6532. state = printer_manager.get_status(printer.id)
  6533. current = getattr(state, "airduct_mode", None) if state else None
  6534. if current == _AIRDUCT_MODE_COOLING:
  6535. return
  6536. client = printer_manager.get_client(printer.id)
  6537. if client is None:
  6538. return
  6539. try:
  6540. client.set_airduct_mode("cooling")
  6541. except Exception as exc:
  6542. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6543. async def _preheat_and_soak(
  6544. self,
  6545. db: AsyncSession,
  6546. item: PrintQueueItem,
  6547. printer: Printer,
  6548. archive: PrintArchive | None,
  6549. ) -> bool:
  6550. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6551. Returns True when the dispatch should carry on to the upload — including
  6552. every case where preheat is skipped, since a skipped preheat is not a
  6553. reason to abandon the print. Returns False only when the item stopped
  6554. wanting to be printed while the stage was waiting (cancelled or
  6555. deleted); the caller must then abandon the dispatch, and
  6556. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6557. Resolution order:
  6558. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6559. to the global `preheat_enabled` setting; 'on' forces the stage on
  6560. even if the global is off.
  6561. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6562. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6563. across the trays `item.ams_mapping` names (every loaded slot when
  6564. it names none).
  6565. 3. A target of 0 off the filament map skips the whole stage: the
  6566. materials this print loads want no chamber, so there is nothing to
  6567. soak for and the bed phase would only delay the upload (#3041).
  6568. An explicit 0 typed into the per-item override, or a per-item
  6569. 'on', still runs the bed phase and the soak — both are the user
  6570. asking for a warm bed in so many words.
  6571. 4. Three hardware tiers branch the wait loop:
  6572. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6573. send M141 to the resolved target, then wait for the chamber sensor
  6574. to reach it (or the max-wait timeout to elapse).
  6575. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6576. no M141; the bed is the only heat source, so we wait for the chamber
  6577. sensor to rise via bed radiation OR fall through on timeout.
  6578. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6579. temperature; the function just heats the bed and holds for the
  6580. configured soak duration.
  6581. The bed target comes from the archive's parsed metadata
  6582. (`bed_temperature`); if missing the preheat stage logs and returns
  6583. without dispatching anything, rather than guessing at a default that
  6584. might wreck filament setup.
  6585. Failures are logged but never re-raised — preheat is best-effort. A
  6586. printer that goes offline mid-soak, a refused gcode command, or a
  6587. missing temperature reading must not turn into a failed queue item; the
  6588. normal upload + start path runs immediately after this method returns.
  6589. """
  6590. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6591. if override == "off":
  6592. return True
  6593. if override == "inherit":
  6594. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6595. if not enabled:
  6596. return True
  6597. # override == "on" forces the stage on regardless of the global setting.
  6598. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6599. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6600. # Chamber target resolution:
  6601. # 1. Explicit per-item override beats everything (user knows best).
  6602. # 2. Otherwise derive from the filament types this print loads, via
  6603. # the per-filament target map. A PLA-only print derives 0 and the
  6604. # block below skips the stage without the user touching anything,
  6605. # even when an ASA spool is sitting in another slot of the same
  6606. # AMS (#2886).
  6607. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6608. if explicit_target is not None and explicit_target > 0:
  6609. chamber_target = int(explicit_target)
  6610. chamber_source = "item-override"
  6611. elif explicit_target == 0:
  6612. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6613. chamber_source = "item-override-zero"
  6614. else:
  6615. targets = await self._get_preheat_filament_targets(db)
  6616. chamber_target = self._derive_chamber_target(printer, targets, item)
  6617. chamber_source = "filament-map"
  6618. # Nothing to preheat *for*. A zero that came out of the filament map is
  6619. # the map saying this print's materials want no chamber conditioning --
  6620. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6621. # anyway heated the bed and then held it for the full soak, which
  6622. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6623. # own G-code sets the bed the moment it starts, so preheating it here
  6624. # only moves that heating ahead of the upload instead of overlapping
  6625. # with it, and the soak has no chamber to condition (#3041).
  6626. #
  6627. # An explicit statement from the user still runs the stage. Forcing the
  6628. # per-item override to 'on', or typing a chamber target of exactly 0,
  6629. # both mean "preheat the bed for this print" -- the second is
  6630. # documented as doing precisely that. Only the automatic path, the
  6631. # global toggle plus the filament map, short-circuits here.
  6632. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6633. logger.info(
  6634. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6635. "target, so there is nothing to soak for (override=%s model=%s)",
  6636. item.id,
  6637. override,
  6638. printer.model or "",
  6639. )
  6640. self._preheat_flap_to_cooling(item.id, printer)
  6641. return True
  6642. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6643. if bed_target <= 0:
  6644. # No bed temperature in the slicer metadata. When the print needs a
  6645. # hot chamber the bed is simply how we heat it, so fall back to the
  6646. # configured chamber-heating bed temperature rather than skipping
  6647. # the whole stage — otherwise the print starts with a cold chamber,
  6648. # which is exactly what preheat exists to prevent. Without a chamber
  6649. # requirement there is nothing to preheat *for*, so skip as before
  6650. # rather than guess a bed temperature for the print itself.
  6651. if chamber_target <= 0:
  6652. logger.info(
  6653. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6654. item.id,
  6655. )
  6656. return True
  6657. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6658. logger.info(
  6659. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6660. "%d°C to drive the chamber to %d°C",
  6661. item.id,
  6662. bed_target,
  6663. chamber_target,
  6664. )
  6665. client = printer_manager.get_client(printer.id)
  6666. if client is None:
  6667. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6668. return True
  6669. model = printer.model or ""
  6670. has_heater = supports_chamber_heater(model)
  6671. has_sensor = supports_chamber_temp(model)
  6672. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6673. # Fast path: if the chamber has been continuously above target for at
  6674. # least soak_seconds and the bed is already at temperature, skip the
  6675. # entire preheat stage. Typical case: keep-warm held the bed between
  6676. # consecutive same-material prints and the chamber never dropped.
  6677. if do_chamber and has_sensor and soak_seconds > 0:
  6678. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6679. if remaining == 0:
  6680. cur = printer_manager.get_status(printer.id)
  6681. if cur:
  6682. cur_temps = cur.temperatures or {}
  6683. if (
  6684. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6685. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6686. ):
  6687. logger.info(
  6688. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6689. "and bed is already at temperature (chamber history fast-path)",
  6690. item.id,
  6691. chamber_target,
  6692. soak_seconds,
  6693. )
  6694. # Still set targets to prevent cooling during the 3MF upload window.
  6695. # Register each successful set in the preheat pin so `_dispatch_one`
  6696. # unwinds them on any non-success exit.
  6697. pin = self._preheat_pin.setdefault(printer.id, set())
  6698. try:
  6699. client.set_bed_temperature(bed_target)
  6700. pin.add("bed")
  6701. self._preheat_pin_bed[printer.id] = bed_target
  6702. except Exception as exc:
  6703. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6704. if supports_airduct(model):
  6705. cur_airduct = getattr(cur, "airduct_mode", None)
  6706. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6707. try:
  6708. client.set_airduct_mode("heating")
  6709. # Only undo what we can see we replaced. `None`
  6710. # means no mode has been observed yet, and
  6711. # rolling that back to cooling would assert a
  6712. # state the printer never reported.
  6713. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6714. pin.add("airduct")
  6715. except Exception as exc:
  6716. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6717. if has_heater:
  6718. try:
  6719. client.set_chamber_temperature(chamber_target)
  6720. pin.add("chamber")
  6721. except Exception as exc:
  6722. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6723. return True
  6724. logger.info(
  6725. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6726. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6727. item.id,
  6728. bed_target,
  6729. chamber_target if do_chamber else 0,
  6730. chamber_source,
  6731. override,
  6732. model,
  6733. has_heater,
  6734. has_sensor,
  6735. max_wait,
  6736. soak_seconds,
  6737. )
  6738. # Preheat rollback registry: everything we set below is recorded here so
  6739. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6740. # (bed off, chamber off, airduct back to cooling) on any non-success
  6741. # exit. Populated as each command succeeds; consumed and cleared by
  6742. # `_dispatch_one`.
  6743. pin = self._preheat_pin.setdefault(printer.id, set())
  6744. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6745. # cache the target locally so the polling reads below see consistent
  6746. # state (firmware MQTT echoes lag by ~1s).
  6747. try:
  6748. client.set_bed_temperature(bed_target)
  6749. pin.add("bed")
  6750. self._preheat_pin_bed[printer.id] = bed_target
  6751. except Exception as exc:
  6752. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6753. return True
  6754. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6755. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6756. # left it on, regardless of M141. Default cooling actively vents the
  6757. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6758. # cooling never converges — the heater fights the open exhaust. We
  6759. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6760. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6761. # on an H2D that was previously running ABS would otherwise stay in
  6762. # heating mode and overheat PLA). The current-state read keeps the
  6763. # command idempotent — no MQTT chatter when the flap is already where
  6764. # we want it.
  6765. if supports_airduct(model):
  6766. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6767. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6768. current_state = printer_manager.get_status(printer.id)
  6769. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6770. if current_airduct != desired_id:
  6771. try:
  6772. client.set_airduct_mode(desired_airduct)
  6773. # As in the fast path: only pin a rollback for a flap we
  6774. # saw in cooling. `current_airduct` of None means no mode
  6775. # has been observed, so there is nothing to restore to.
  6776. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6777. pin.add("airduct")
  6778. except Exception as exc:
  6779. logger.warning(
  6780. "Queue item %s: preheat airduct %s mode failed: %s",
  6781. item.id,
  6782. desired_airduct,
  6783. exc,
  6784. )
  6785. if do_chamber and has_heater:
  6786. try:
  6787. client.set_chamber_temperature(chamber_target)
  6788. pin.add("chamber")
  6789. except Exception as exc:
  6790. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6791. # Release the pooled DB connection before the (potentially many-minute)
  6792. # heat-soak wait below (#2572). Every setting this method needs is read
  6793. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6794. # it never touches the DB. Without this the caller's transaction sat
  6795. # "idle in transaction" for the whole soak, pinning one pooled connection
  6796. # per preheating printer. expire_on_commit=False keeps item/printer
  6797. # readable afterwards; there are no pending writes to lose here.
  6798. await db.commit()
  6799. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6800. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6801. # Poll every 3s — frequent enough for responsive logging without
  6802. # spamming the MQTT state stream. The "converged" predicate is:
  6803. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6804. # AND
  6805. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6806. BED_TOLERANCE = 2.0
  6807. CHAMBER_TOLERANCE = 2.0
  6808. POLL_INTERVAL = 3.0
  6809. deadline = asyncio.get_event_loop().time() + max_wait
  6810. while True:
  6811. state = printer_manager.get_status(printer.id)
  6812. if state is None:
  6813. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6814. break
  6815. temps = state.temperatures or {}
  6816. bed_now = float(temps.get("bed", 0) or 0)
  6817. chamber_now = float(temps.get("chamber", 0) or 0)
  6818. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6819. if not do_chamber:
  6820. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6821. elif not has_sensor:
  6822. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6823. else:
  6824. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6825. if bed_ok and chamber_ok:
  6826. logger.info(
  6827. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6828. item.id,
  6829. bed_now,
  6830. chamber_now,
  6831. )
  6832. break
  6833. if asyncio.get_event_loop().time() >= deadline:
  6834. logger.info(
  6835. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6836. item.id,
  6837. bed_now,
  6838. bed_target,
  6839. chamber_now,
  6840. chamber_target if do_chamber else 0,
  6841. )
  6842. break
  6843. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6844. logger.info(
  6845. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6846. item.id,
  6847. )
  6848. return False
  6849. if soak_seconds > 0:
  6850. if do_chamber and has_sensor:
  6851. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6852. else:
  6853. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6854. if remaining > 0:
  6855. logger.info(
  6856. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6857. "has been above target for ~%ds already)",
  6858. item.id,
  6859. remaining,
  6860. soak_seconds,
  6861. soak_seconds - remaining,
  6862. )
  6863. if not await self._preheat_sleep(item.id, remaining):
  6864. logger.info(
  6865. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6866. item.id,
  6867. )
  6868. return False
  6869. else:
  6870. logger.info(
  6871. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6872. item.id,
  6873. chamber_target,
  6874. soak_seconds,
  6875. )
  6876. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6877. return True
  6878. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6879. """Turn on smart plug and wait for printer to connect.
  6880. Returns True if printer connected successfully within timeout.
  6881. """
  6882. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6883. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6884. # Check current plug state
  6885. status = await service.get_status(plug)
  6886. if not status.get("reachable"):
  6887. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6888. return False
  6889. # Turn on if not already on
  6890. if status.get("state") != "ON":
  6891. success = await service.turn_on(plug)
  6892. if not success:
  6893. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6894. return False
  6895. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  6896. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6897. # Get printer from database for connection
  6898. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6899. printer = result.scalar_one_or_none()
  6900. if not printer:
  6901. logger.error("Printer %s not found in database", printer_id)
  6902. return False
  6903. # End the pass's transaction before waiting up to minutes for the boot:
  6904. # held open, it pins a pooled connection idle in transaction
  6905. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  6906. # through it.
  6907. await db.commit()
  6908. # Wait for printer to boot (give it some time before trying to connect)
  6909. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6910. await asyncio.sleep(30)
  6911. # Try to connect to the printer periodically
  6912. elapsed = 30 # Already waited 30s
  6913. while elapsed < self._power_on_wait_time:
  6914. # Try to connect
  6915. logger.info("Attempting to connect to printer %s...", printer_id)
  6916. try:
  6917. connected = await printer_manager.connect_printer(printer)
  6918. if connected:
  6919. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6920. # Give it a moment to stabilize and get status
  6921. await asyncio.sleep(5)
  6922. return True
  6923. except Exception as e:
  6924. logger.debug("Connection attempt failed: %s", e)
  6925. await asyncio.sleep(self._power_on_check_interval)
  6926. elapsed += self._power_on_check_interval
  6927. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6928. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6929. return False
  6930. async def _check_previous_success(
  6931. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  6932. ) -> bool:
  6933. """Check if the previous print on this printer succeeded.
  6934. ``printer_id`` names the printer to look at when the item has none yet
  6935. (a job for any printer of a model, checked against the one offered).
  6936. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6937. deliberate action, not a failure, so subsequent items should still
  6938. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6939. a skip isn't an actual print attempt, so it must not gate downstream
  6940. items — counting it as a failed predecessor was the cascade bug that
  6941. let a single cancellation block 18 items over 3 days for the reporter.
  6942. Only `failed` and `aborted` — real print-attempt failures — block.
  6943. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6944. action — #1818) are also excluded from the lookback so the user can
  6945. clear the gate after fixing the physical issue without having to
  6946. re-queue every downstream job.
  6947. """
  6948. result = await db.execute(
  6949. select(PrintQueueItem)
  6950. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  6951. .where(PrintQueueItem.id != item.id)
  6952. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6953. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6954. # A row ended without a completion time must not count as the
  6955. # latest: PostgreSQL sorts NULL first in a descending order.
  6956. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  6957. .limit(1)
  6958. )
  6959. prev_item = result.scalar_one_or_none()
  6960. # If no previous item, assume success (first in queue)
  6961. if not prev_item:
  6962. return True
  6963. return prev_item.status in ("completed", "cancelled")
  6964. async def _repoint_siblings_at_archive(
  6965. self,
  6966. db: AsyncSession,
  6967. *,
  6968. consumed_library_file_id: int,
  6969. archive_id: int,
  6970. dispatched_item_id: int,
  6971. ) -> int:
  6972. """Move the other queue items off a library row that is about to be deleted (#2819).
  6973. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6974. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6975. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6976. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6977. clones, so the first dispatch could pull the file out from under rows that
  6978. had not run yet. What those rows did next depended on the database, and
  6979. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6980. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6981. they were left pointing at a row that no longer existed, failing with
  6982. "Library file not found" whenever someone started them -- or sitting
  6983. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6984. constraint, so there the rows were deleted outright and the queued copies
  6985. simply vanished, with no error and no history.
  6986. The archive holds its own copy of the 3MF, so the remaining copies can print
  6987. from it instead. Two things happen here, and both must happen *before* the
  6988. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6989. * every row still naming the file has ``library_file_id`` cleared, which is
  6990. what takes it out of the cascade's reach. That covers rows this cannot
  6991. re-point as well -- a copy already printing from its own archive, and the
  6992. finished ones, which are not spare parts but the record a batch order
  6993. counts its progress from.
  6994. * the rows that still need something to print are pointed at the archive.
  6995. Returns how many items were re-pointed.
  6996. """
  6997. variant_item_ids = (
  6998. (
  6999. await db.execute(
  7000. select(PrintQueueVariant.queue_item_id).where(
  7001. PrintQueueVariant.library_file_id == consumed_library_file_id
  7002. )
  7003. )
  7004. )
  7005. .scalars()
  7006. .all()
  7007. )
  7008. # Candidate rows naming the consumed file have to go rather than be
  7009. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7010. # one out of the cascade. This is what PostgreSQL already does, and
  7011. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7012. # outcome changes -- the two backends simply stop disagreeing about
  7013. # whether the row is still there.
  7014. #
  7015. # It also has to happen before the re-point below: a cross-model item
  7016. # (#671) picks a variant every pass and folds it onto the row, and
  7017. # _resolve_variant clears archive_id as it does so, which would undo the
  7018. # re-point on the very next lap.
  7019. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7020. # An item left with other candidates still has somewhere to go, and those
  7021. # carry their own target model -- pointing it at this archive would print a
  7022. # file the matcher never chose. It is excluded from the re-point and simply
  7023. # re-resolves against what is left.
  7024. surviving_variant_item_ids = set(
  7025. (
  7026. await db.execute(
  7027. select(PrintQueueVariant.queue_item_id).where(
  7028. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7029. )
  7030. )
  7031. )
  7032. .scalars()
  7033. .all()
  7034. )
  7035. repoint_ids = set(
  7036. (
  7037. await db.execute(
  7038. select(PrintQueueItem.id)
  7039. .where(PrintQueueItem.id != dispatched_item_id)
  7040. .where(PrintQueueItem.archive_id.is_(None))
  7041. # "skipped" belongs here with the two live states: it is not
  7042. # terminal. Clearing a printer's previous-success gate puts
  7043. # every item skipped by it back to "pending"
  7044. # (resume_after_failure), and one restored onto a deleted
  7045. # file is the same orphan by a slower route. "failed",
  7046. # "cancelled", "aborted" and "completed" never return.
  7047. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7048. .where(
  7049. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7050. )
  7051. .where(
  7052. or_(
  7053. PrintQueueItem.library_file_id == consumed_library_file_id,
  7054. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7055. )
  7056. )
  7057. )
  7058. )
  7059. .scalars()
  7060. .all()
  7061. )
  7062. if repoint_ids:
  7063. await db.execute(
  7064. update(PrintQueueItem)
  7065. .where(PrintQueueItem.id.in_(repoint_ids))
  7066. .values(
  7067. archive_id=archive_id,
  7068. library_file_id=None,
  7069. # The file this flag named is already consumed. Leaving it set
  7070. # would arm every re-pointed copy to delete whatever library
  7071. # row it is next given.
  7072. cleanup_library_after_dispatch=False,
  7073. )
  7074. )
  7075. logger.info(
  7076. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7077. sorted(repoint_ids),
  7078. archive_id,
  7079. consumed_library_file_id,
  7080. dispatched_item_id,
  7081. )
  7082. # Everything else that still names the file: taken out of the cascade's
  7083. # reach without touching what it prints. The file is gone either way; what
  7084. # this preserves is the row.
  7085. await db.execute(
  7086. update(PrintQueueItem)
  7087. .where(PrintQueueItem.id != dispatched_item_id)
  7088. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7089. .values(library_file_id=None)
  7090. )
  7091. return len(repoint_ids)
  7092. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7093. """Schedule power-off if the queue item enabled auto_off_after.
  7094. Delegates to the smart-plug manager so the off honours each plug's
  7095. configured strategy (time delay or temperature threshold), is cancelled
  7096. if the printer starts printing again, and never cuts power on a loaded
  7097. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7098. powered off on the timeout regardless of print state.
  7099. """
  7100. if not item.auto_off_after:
  7101. return
  7102. try:
  7103. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7104. except Exception as e:
  7105. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7106. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7107. """Get a human-readable name for a queue item."""
  7108. if item.archive_id:
  7109. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7110. archive = result.scalar_one_or_none()
  7111. if archive:
  7112. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7113. if item.library_file_id:
  7114. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7115. library_file = result.scalar_one_or_none()
  7116. if library_file:
  7117. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7118. # A cross-model item (#671) holds no file of its own until a printer is
  7119. # picked, so name it after its first candidate — otherwise every waiting
  7120. # notification for one reads "Job #12". Queried rather than read off
  7121. # item.variants because callers outside the selection loop have not
  7122. # eager-loaded them, and a lazy load raises in async.
  7123. first_variant_name = (
  7124. await db.execute(
  7125. select(LibraryFile.filename)
  7126. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7127. .where(PrintQueueVariant.queue_item_id == item.id)
  7128. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7129. .limit(1)
  7130. )
  7131. ).scalar_one_or_none()
  7132. if first_variant_name:
  7133. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7134. return f"Job #{item.id}"
  7135. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7136. """Get printer by ID."""
  7137. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7138. return result.scalar_one_or_none()
  7139. async def _notify_dispatch_gave_up(
  7140. self,
  7141. queue_item_id: int,
  7142. printer_id: int,
  7143. created_by_id: int | None,
  7144. reason: str = "Printer accepted the file but never started printing",
  7145. ) -> None:
  7146. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7147. Called from the watchdog, which is a background task with no session of
  7148. its own — hence the fresh one here. Best-effort throughout: the row is
  7149. already marked failed and that is the load-bearing part; a notification
  7150. provider being down must not resurrect the retry loop we just stopped.
  7151. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7152. path passes its own, because "accepted the file but never started" is the
  7153. opposite of what happened there — the printer refused it outright (#2732).
  7154. """
  7155. try:
  7156. async with async_session() as db:
  7157. item = await db.get(PrintQueueItem, queue_item_id)
  7158. if not item:
  7159. return
  7160. job_name = await self._get_job_name(db, item)
  7161. printer = await self._get_printer(db, printer_id)
  7162. await notification_service.on_queue_job_failed(
  7163. job_name=job_name,
  7164. printer_id=printer_id,
  7165. printer_name=printer.name if printer else "Unknown",
  7166. reason=reason,
  7167. db=db,
  7168. )
  7169. except Exception as e:
  7170. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7171. try:
  7172. await ws_manager.send_queue_item_failed(
  7173. user_id=created_by_id,
  7174. queue_item_id=queue_item_id,
  7175. printer_id=printer_id,
  7176. reason="never_started",
  7177. )
  7178. except Exception:
  7179. pass # toast is best-effort
  7180. async def _filament_short_on(
  7181. self,
  7182. db: AsyncSession,
  7183. item: PrintQueueItem,
  7184. printer_id: int,
  7185. *,
  7186. require_known: bool = False,
  7187. ) -> bool:
  7188. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7189. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7190. assigned there, with the mapping the item would get there, but changes
  7191. nothing. The model-based matcher uses it to prefer a printer whose
  7192. spools can finish the job.
  7193. False whenever the gate would let the item through: "Print Anyway",
  7194. no mapping, or a check that fails. With ``require_known`` all three of
  7195. those, and any printed slot whose remaining amount is unknown, count
  7196. as short instead: releasing a held job starts it with nobody asked, so
  7197. it needs the amount on record, not merely nothing against it.
  7198. """
  7199. if item.skip_filament_check:
  7200. return False
  7201. try:
  7202. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7203. if not mapping:
  7204. return require_known
  7205. deficit = await compute_deficit_for_queue_item(
  7206. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7207. )
  7208. except Exception as e:
  7209. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7210. return require_known
  7211. return bool(deficit)
  7212. async def _release_short_model_hold(
  7213. self,
  7214. db: AsyncSession,
  7215. item: PrintQueueItem,
  7216. unavailable: set[int],
  7217. require_plate_clear: bool,
  7218. printer_scope: PrinterScope,
  7219. ) -> bool:
  7220. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7221. The deficit gate holds a model-based job on the printer the matcher
  7222. gave it, because "Print Anyway" needs a printer to print on. When
  7223. another idle printer of the job's model has the filament, the job is
  7224. moved to that printer and its hold lifted, and the fixed-printer
  7225. branch dispatches it in this same pass, through the same checks a
  7226. held job meets when the user presses Start. It is moved rather than
  7227. put back in the pool because the model-based branch would pick again
  7228. without requiring the amounts on record (below), and could pick a
  7229. different printer. Only the deficit gate sets ``filament_short``, so a
  7230. job held for any other reason stays held.
  7231. The printer it is held on is left out: a spool loaded there is started
  7232. with Start, as before, rather than while someone may still be loading
  7233. the next one. Each job is checked at most every
  7234. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7235. on each idle printer again.
  7236. Cross-model jobs (#671) stay held: checking a variant writes its file
  7237. onto the item, which would leave a job that is not moved holding
  7238. another variant's file for the printer it waits on.
  7239. A printer qualifies only on a positive finding: every slot the plate
  7240. prints mapped to a spool whose remaining amount is on record and
  7241. enough. A printer whose spools Bambuddy does not track is not one.
  7242. Returns True when the job was moved. A check that fails keeps the hold
  7243. rather than stopping the queue pass.
  7244. """
  7245. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7246. return False
  7247. if not item.target_model or item.variants:
  7248. return False
  7249. now = time.monotonic()
  7250. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7251. return False
  7252. self._short_hold_checked_at[item.id] = now
  7253. try:
  7254. candidates = _candidates_for(item)
  7255. if not candidates:
  7256. return False
  7257. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7258. async def is_short(pid: int) -> bool:
  7259. return await self._filament_short_on(db, item, pid, require_known=True)
  7260. match_id, _ = await self._find_idle_printer_for_model(
  7261. db,
  7262. item.target_model,
  7263. unavailable | {item.printer_id},
  7264. effective_types,
  7265. item.target_location,
  7266. filament_overrides=filament_overrides,
  7267. require_plate_clear=require_plate_clear,
  7268. printer_scope=printer_scope,
  7269. is_short=is_short,
  7270. )
  7271. # Every idle printer short comes back as the first of them.
  7272. if match_id is None or await is_short(match_id):
  7273. return False
  7274. except Exception as e:
  7275. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7276. return False
  7277. logger.info(
  7278. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7279. item.id,
  7280. match_id,
  7281. item.printer_id,
  7282. )
  7283. self._short_hold_checked_at.pop(item.id, None)
  7284. item.printer_id = match_id
  7285. # Resolved against the printer it leaves (#3239): the tray mapping and
  7286. # the nozzle positions.
  7287. drop_printer_resolved(item)
  7288. item.manual_start = False
  7289. item.filament_short = False
  7290. item.waiting_reason = None
  7291. await db.commit()
  7292. try:
  7293. printer = await self._get_printer(db, match_id)
  7294. await notification_service.on_queue_job_assigned(
  7295. job_name=await self._get_job_name(db, item),
  7296. printer_id=match_id,
  7297. printer_name=printer.name if printer else "Unknown",
  7298. target_model=item.target_model,
  7299. db=db,
  7300. )
  7301. except Exception as e:
  7302. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7303. return True
  7304. async def _block_on_filament_deficit(
  7305. self,
  7306. db: AsyncSession,
  7307. item: PrintQueueItem,
  7308. ) -> bool:
  7309. """Promote the item to manual_start when the assigned spool is short (#1496).
  7310. Returns True when this dispatch attempt was blocked, False when the
  7311. item is clear to start. A previously-flagged item whose spool has
  7312. since been swapped to one with enough material clears the flag here
  7313. so the next scheduler tick dispatches it.
  7314. """
  7315. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7316. # don't re-flag, don't even compute. Without this short-circuit the
  7317. # scheduler bounces between "user said anyway" (route clears
  7318. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7319. # on identical spool state) (#1698-followup).
  7320. if item.skip_filament_check:
  7321. # #1762 diagnostic: surface the short-circuit at INFO so a
  7322. # future "Print Anyway didn't work" report (e.g. issue #1762
  7323. # comment 3) has actionable evidence in the support bundle
  7324. # without needing DEBUG enabled.
  7325. logger.info(
  7326. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7327. item.id,
  7328. )
  7329. return False
  7330. try:
  7331. deficit = await compute_deficit_for_queue_item(db, item)
  7332. except Exception as e:
  7333. # Never let a flaky deficit check wedge the queue — log and let
  7334. # dispatch proceed. The PrintModal-side check still runs on the
  7335. # manual paths.
  7336. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7337. return False
  7338. if deficit:
  7339. item.filament_short = True
  7340. item.manual_start = True
  7341. await db.commit()
  7342. job_name = await self._get_job_name(db, item)
  7343. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7344. logger.info(
  7345. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7346. item.id,
  7347. len(deficit),
  7348. )
  7349. try:
  7350. await notification_service.on_queue_job_waiting(
  7351. job_name=job_name,
  7352. target_model=(printer.model if printer else "") or "",
  7353. waiting_reason="filament_short",
  7354. db=db,
  7355. printer_id=item.printer_id,
  7356. )
  7357. except Exception as e:
  7358. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7359. return True
  7360. # No deficit — clear any stale flag from a previous tick.
  7361. if item.filament_short:
  7362. item.filament_short = False
  7363. await db.commit()
  7364. return False
  7365. async def _block_on_unmatched_filament(
  7366. self,
  7367. db: AsyncSession,
  7368. item: PrintQueueItem,
  7369. release_assignment: bool = False,
  7370. ) -> bool:
  7371. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7372. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7373. goes ahead, letting the printer choose — which is how a job prints in the
  7374. wrong material without anyone being asked. Holding is the same answer the
  7375. deficit gate already gives for "the spool is too light", so it reuses the
  7376. same promote-and-notify machinery.
  7377. Keyed off unresolved slots in the *computed* mapping intersected with the
  7378. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7379. read: on its own it also pads slots this plate does not print, so the
  7380. array alone would hold perfectly good jobs. Reading the mapping rather
  7381. than the printer's loaded filament types also inherits the matcher's
  7382. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7383. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7384. type-only scan would wave that through.
  7385. A mapping that resolved *nothing* is the same finding arriving as an
  7386. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7387. could not replace, and dispatch then goes out as ``use_ams`` with no
  7388. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7389. That is held too, but only once live status positively reports loaded
  7390. trays: #2589's mapping is bogus precisely because the AMS was not known
  7391. yet, and its empty loaded list is that ignorance rather than a miss.
  7392. ``release_assignment`` is for the model-based path, which commits its
  7393. printer choice before the gates run. Holding an "any P2S" job would
  7394. otherwise pin it to the one P2S that could not run it.
  7395. Returns True when this dispatch attempt was blocked.
  7396. """
  7397. if item.skip_filament_check or not item.printer_id:
  7398. return False
  7399. if item.ams_mapping:
  7400. try:
  7401. mapping = json.loads(item.ams_mapping)
  7402. except (json.JSONDecodeError, TypeError):
  7403. return False
  7404. if not isinstance(mapping, list):
  7405. return False
  7406. else:
  7407. # Nothing resolved, or nothing survived revalidation. Only a printer
  7408. # that reported loaded trays makes that a finding — see the
  7409. # docstring on why an empty list is not one.
  7410. status = printer_manager.get_status(item.printer_id)
  7411. if status is None or not self._build_loaded_filaments(status):
  7412. return False
  7413. # Every required slot reads unresolved against an empty mapping.
  7414. mapping = []
  7415. required = await self._get_filament_requirements(db, item)
  7416. if not required:
  7417. return False
  7418. self._apply_filament_overrides(item, required)
  7419. unmatched = _unresolved_required(required, mapping)
  7420. if not unmatched:
  7421. # No cleanup needed here: once start is pressed the item is no
  7422. # longer staged, and whichever exit runs next overwrites the reason
  7423. # (`hold_item` on the fixed-printer branch, the assignment on the
  7424. # model-based one), as does dispatch.
  7425. return False
  7426. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7427. held_by = item.printer_id
  7428. item.manual_start = True
  7429. # Human-readable: this renders on the queue row.
  7430. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7431. if release_assignment:
  7432. # "Any P2S" means any, so the job returns to the pool rather than
  7433. # waiting on the printer that could not take it. The mapping goes
  7434. # with the assignment: its tray IDs were resolved against the
  7435. # printer being released and mean nothing on the next one (#2799),
  7436. # and keeping them would hold the job again even on a printer that
  7437. # has the filament, since an unresolved slot is deliberately not a
  7438. # conflict worth recomputing over.
  7439. item.printer_id = None
  7440. drop_printer_resolved(item)
  7441. await db.commit()
  7442. job_name = await self._get_job_name(db, item)
  7443. printer = await self._get_printer(db, held_by)
  7444. logger.info(
  7445. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7446. item.id,
  7447. held_by,
  7448. wanted,
  7449. )
  7450. try:
  7451. await notification_service.on_queue_job_waiting(
  7452. job_name=job_name,
  7453. target_model=(printer.model if printer else "") or "",
  7454. waiting_reason=f"needs {wanted}",
  7455. db=db,
  7456. # Released to the pool: no printer holds it any more.
  7457. printer_id=None if release_assignment else held_by,
  7458. )
  7459. except Exception as e:
  7460. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7461. return True
  7462. @staticmethod
  7463. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7464. """The queue item's owner as the row has it now.
  7465. item.created_by_id was read before preheat and upload, which can take
  7466. minutes; deleting the user clears the row, not this session's copy.
  7467. """
  7468. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7469. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7470. """Hand the queue item's owner to printer_manager so the
  7471. print-complete callback can credit the user in PrintLogEntry (#1670).
  7472. No-ops when the item has no `created_by_id` or the referenced user
  7473. row is missing (e.g. user deleted between queue-add and dispatch —
  7474. in that case the print log row falls back to the existing un-credited
  7475. behaviour rather than crashing the dispatch).
  7476. """
  7477. from backend.app.models.user import User
  7478. # Read from the row, not item.created_by_id or db.get: both can still
  7479. # hold a user deleted during the upload, after delete_user forgot them
  7480. # (on SQLite the id may be someone new's by the time the print ends).
  7481. # Joined with the printer too: one deleted during the upload was
  7482. # forgotten as well, and this would write the owner back under its id.
  7483. owner = (
  7484. await db.execute(
  7485. select(User.id, User.username)
  7486. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7487. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7488. .where(PrintQueueItem.id == item.id)
  7489. )
  7490. ).first()
  7491. if owner:
  7492. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7493. if item.printer_id is not None:
  7494. self._unconfirmed_print_user[item.id] = item.printer_id
  7495. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7496. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7497. A cancel lands in another session while the upload runs (the edit route
  7498. even tells users to cancel a job that is being sent). An unconditional
  7499. write here would turn that cancellation into a failure, with a failure
  7500. notification, and block the next job that needs the previous print to
  7501. have succeeded. Returns whether the item was marked failed.
  7502. """
  7503. result = cast(
  7504. CursorResult,
  7505. await db.execute(
  7506. update(PrintQueueItem)
  7507. .where(PrintQueueItem.id == item.id)
  7508. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7509. .values(status="failed", error_message=message, completed_at=datetime.now(timezone.utc))
  7510. .execution_options(synchronize_session=False)
  7511. ),
  7512. )
  7513. await db.commit()
  7514. if result.rowcount == 0:
  7515. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7516. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7517. return False
  7518. await db.refresh(item)
  7519. from backend.app.services.print_batch import refresh_batches_after
  7520. await refresh_batches_after([item.id])
  7521. return True
  7522. @staticmethod
  7523. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7524. """Put a job whose printer turned busy before the start back in the queue.
  7525. Only if it is still printing: a stop that landed meanwhile stands.
  7526. """
  7527. await db.execute(
  7528. update(PrintQueueItem)
  7529. .where(PrintQueueItem.id == item.id)
  7530. .where(PrintQueueItem.status == "printing")
  7531. .values(status="pending", started_at=None)
  7532. .execution_options(synchronize_session=False)
  7533. )
  7534. await db.commit()
  7535. @staticmethod
  7536. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7537. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7538. try:
  7539. await ws_manager.send_queue_item_failed(
  7540. user_id=toast_uid,
  7541. queue_item_id=item.id,
  7542. printer_id=item.printer_id,
  7543. reason="cancelled_mid_dispatch",
  7544. )
  7545. except Exception:
  7546. pass # toast is best-effort
  7547. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7548. """Upload file and start print for a queue item.
  7549. Supports two sources:
  7550. - archive_id: Print from an existing archive
  7551. - library_file_id: Print from a library file (file manager)
  7552. """
  7553. logger.info("Starting queue item %s", item.id)
  7554. # Also covers a reservation left active by a process interruption
  7555. # during an earlier attempt. `_dispatch_one` releases this marker on
  7556. # every exit unless start_print() confirms that the command was sent.
  7557. self._unconfirmed_budget_reservations.add(item.id)
  7558. try:
  7559. from backend.app.models.user import User
  7560. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7561. # Recompute at the final authorization boundary as well as enqueue
  7562. # time. This covers rows created before the server-side estimate
  7563. # migration and prevents any alternate write path from weakening
  7564. # the budget reservation.
  7565. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7566. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7567. item.estimated_cost = await estimate_queue_source_cost(
  7568. db,
  7569. archive=archive,
  7570. library_file=library_file,
  7571. plate_id=item.plate_id,
  7572. ams_mapping=item.ams_mapping,
  7573. printer_id=item.printer_id,
  7574. )
  7575. await validate_print_budget(
  7576. db,
  7577. cost_center_id=item.cost_center_id,
  7578. estimated_cost=item.estimated_cost,
  7579. current_user=queue_user,
  7580. exclude_queue_item_id=item.id,
  7581. exclude_reservation_source_type="print_queue",
  7582. exclude_reservation_source_id=item.id,
  7583. )
  7584. budget_reservation = await create_budget_reservation(
  7585. db,
  7586. cost_center_id=item.cost_center_id,
  7587. estimated_cost=item.estimated_cost,
  7588. current_user=queue_user,
  7589. source_type="print_queue",
  7590. source_id=item.id,
  7591. print_archive_id=item.archive_id,
  7592. exclude_queue_item_id=item.id,
  7593. )
  7594. await db.commit()
  7595. except HTTPException as exc:
  7596. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7597. return
  7598. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7599. await self._power_off_if_needed(db, item)
  7600. return
  7601. # Get printer first (needed for both paths)
  7602. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7603. printer = result.scalar_one_or_none()
  7604. if not printer:
  7605. if not await self._fail_dispatch(db, item, "Printer not found"):
  7606. return
  7607. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7608. await self._power_off_if_needed(db, item)
  7609. return
  7610. # Check printer is connected
  7611. if not printer_manager.is_connected(item.printer_id):
  7612. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7613. return
  7614. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7615. await self._power_off_if_needed(db, item)
  7616. return
  7617. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7618. # `items` was taken at the top of check_queue, but the user can /cancel
  7619. # any pending row in the gap before we reach this point. Re-read the
  7620. # row and bail out cleanly instead of starting an FTP upload for a row
  7621. # that's already cancelled. The atomic CAS at the pending→printing
  7622. # transition (below, before start_print) is the load-bearing guard;
  7623. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7624. await db.refresh(item)
  7625. if item.status != "pending":
  7626. logger.info(
  7627. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7628. item.id,
  7629. item.status,
  7630. )
  7631. return
  7632. # Busy-printer guard (#2598). check_queue gates dispatch on
  7633. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7634. # keep reporting FINISH for tens of seconds *after* it accepted a
  7635. # project_file (see the watchdog's phase-B note). A watchdog revert
  7636. # (#2555) also releases the dispatch hold, so a re-selected item can
  7637. # reach here while its printer has actually started printing. Uploading
  7638. # and dispatching then collides with the live job — the firmware answers
  7639. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7640. # live state right before the expensive FTP upload: if the printer is
  7641. # busy, leave the item pending and let a later tick dispatch it once the
  7642. # printer is genuinely idle. No wasted upload, no collision.
  7643. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7644. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7645. logger.info(
  7646. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7647. "leaving item pending for a later tick (#2598)",
  7648. item.id,
  7649. item.printer_id,
  7650. pre_dispatch_state,
  7651. )
  7652. return
  7653. # Determine source: archive or library file
  7654. archive = None
  7655. library_file = None
  7656. file_path = None
  7657. filename = None
  7658. cleanup_disk_paths: list[Path] = []
  7659. # Set when a dispatch consumes its library file, so the photos can be
  7660. # carried over after the commit that removes the row (#3077).
  7661. consumed_library_file_id: int | None = None
  7662. consumed_photos: list[str] = []
  7663. if item.archive_id:
  7664. # Print from archive
  7665. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7666. archive = result.scalar_one_or_none()
  7667. if not archive:
  7668. if not await self._fail_dispatch(db, item, "Archive not found"):
  7669. return
  7670. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7671. await self._power_off_if_needed(db, item)
  7672. return
  7673. # Persist the queue item's selected plate onto the archive so Print
  7674. # History can show the actual plate after cancel/fail/complete (#2603).
  7675. # Only when the archive doesn't already carry one, so a reprint of a
  7676. # plate-specific archive isn't relabelled by a differently-plated
  7677. # queue row.
  7678. if archive.plate_id is None and item.plate_id is not None:
  7679. archive.plate_id = item.plate_id
  7680. # Ask-for-outcome opt-in rides from the queue item to the archive
  7681. # the same way (#1898); never cleared here so a reprint of an
  7682. # archive that already asked keeps asking.
  7683. if item.confirm_outcome:
  7684. archive.confirm_requested = True
  7685. file_path = settings.base_dir / archive.file_path
  7686. filename = archive.filename
  7687. elif item.library_file_id:
  7688. # Print from library file (file manager)
  7689. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7690. library_file = result.scalar_one_or_none()
  7691. if not library_file:
  7692. # "Not found" covers two different situations and only one of
  7693. # them is recoverable, so say which. A trashed file is still
  7694. # there and restoring it makes a re-queued job work; a file that
  7695. # is really gone needs a different one. Neither is knowable from
  7696. # the queue, which is the whole complaint about this message.
  7697. trashed = (
  7698. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7699. ).scalar_one_or_none()
  7700. if not await self._fail_dispatch(
  7701. db,
  7702. item,
  7703. (
  7704. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7705. if trashed
  7706. else "Library file not found — it was deleted after this job was queued"
  7707. ),
  7708. ):
  7709. return
  7710. logger.error(
  7711. "Queue item %s: library file %s is %s",
  7712. item.id,
  7713. item.library_file_id,
  7714. "in the trash" if trashed else "gone",
  7715. )
  7716. await self._power_off_if_needed(db, item)
  7717. return
  7718. # Library files store absolute paths
  7719. lib_path = Path(library_file.file_path)
  7720. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7721. filename = library_file.filename
  7722. # Create archive from library file so usage tracking has access to the 3MF
  7723. queue_item_id = item.id
  7724. # Held separately: a cleanup dispatch clears item.library_file_id
  7725. # below, and the log line at the end of this block reported that
  7726. # cleared field -- so every consumed print logged "from library
  7727. # file None", which is the one case worth being able to trace.
  7728. source_library_file_id = item.library_file_id
  7729. try:
  7730. from backend.app.services.archive import ArchiveService
  7731. archive_service = ArchiveService(db)
  7732. archive = await archive_service.archive_print(
  7733. printer_id=item.printer_id,
  7734. source_file=file_path,
  7735. original_filename=filename,
  7736. created_by_id=item.created_by_id,
  7737. project_id=item.project_id,
  7738. cost_center_id=item.cost_center_id,
  7739. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7740. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7741. )
  7742. if archive:
  7743. item.archive_id = archive.id
  7744. if item.confirm_outcome:
  7745. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7746. if budget_reservation is not None:
  7747. budget_reservation.print_archive_id = archive.id
  7748. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7749. consumed_library_file_id = library_file.id
  7750. item.library_file_id = None
  7751. cleanup_disk_paths.append(file_path)
  7752. if library_file.thumbnail_path:
  7753. thumb_path = Path(library_file.thumbnail_path)
  7754. if not thumb_path.is_absolute():
  7755. thumb_path = settings.base_dir / library_file.thumbnail_path
  7756. cleanup_disk_paths.append(thumb_path)
  7757. # Before the delete, not after: on PostgreSQL the FK
  7758. # cascade would already have taken these rows (#2819).
  7759. await self._repoint_siblings_at_archive(
  7760. db,
  7761. consumed_library_file_id=consumed_library_file_id,
  7762. archive_id=archive.id,
  7763. dispatched_item_id=item.id,
  7764. )
  7765. # Read while the row is still here; the photos move
  7766. # below, once the delete has actually committed.
  7767. consumed_photos = list(library_file.photos or [])
  7768. # The delete clears the link on the earlier archives of
  7769. # this file (ON DELETE SET NULL; core/sqlite_fk on
  7770. # SQLite). This one is loaded, so set it here too, or it
  7771. # keeps the stale id in the session.
  7772. archive.library_file_id = None
  7773. await db.delete(library_file)
  7774. file_path = settings.base_dir / archive.file_path
  7775. filename = archive.filename
  7776. # Commit, not flush — flush opens the SQLite write
  7777. # transaction (item.archive_id update + library_file
  7778. # delete) and would hold the WAL writer lock through the
  7779. # FTP upload below, causing "database is locked" cascades
  7780. # for sensor history + concurrent cancels (#1853).
  7781. await db.commit()
  7782. logger.info(
  7783. "Queue item %s: Created archive %s from library file %s",
  7784. item.id,
  7785. archive.id,
  7786. source_library_file_id,
  7787. )
  7788. except Exception as e:
  7789. logger.warning(
  7790. "Queue item %s: Failed to create archive from library file: %s",
  7791. queue_item_id,
  7792. e,
  7793. exc_info=True,
  7794. )
  7795. await db.rollback()
  7796. item = await db.get(PrintQueueItem, queue_item_id)
  7797. if item:
  7798. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7799. return
  7800. await self._power_off_if_needed(db, item)
  7801. return
  7802. if not archive:
  7803. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  7804. return
  7805. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7806. await self._power_off_if_needed(db, item)
  7807. return
  7808. # The photos follow the file into the archive that replaces it, for
  7809. # the same reason the siblings do (#3077). After the commit above,
  7810. # never before it: that commit can fail ("database is locked",
  7811. # #1853) and roll the library row back, and photos already moved
  7812. # would leave it naming a directory that no longer exists. The
  7813. # file and thumbnail unlinks are deferred for the same reason.
  7814. if consumed_library_file_id is not None and consumed_photos:
  7815. # Held as a plain int, read here while the session is still
  7816. # healthy, because the handler below may not touch an ORM
  7817. # instance at all. The commit it exists for fails inside the
  7818. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7819. # first DML statement, so a busy writer surfaces as "database
  7820. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7821. # internally through safe_reraise before re-raising, which
  7822. # expires every loaded instance and leaves the session in
  7823. # pending-rollback state -- so `archive.id` inside the except
  7824. # would itself raise PendingRollbackError and the rollback
  7825. # below would never be reached.
  7826. archive_id = archive.id
  7827. try:
  7828. carried_photos = move_library_photos(
  7829. consumed_library_file_id,
  7830. consumed_photos,
  7831. archive_photos_dir(archive),
  7832. )
  7833. if carried_photos:
  7834. archive.photos = list(archive.photos or []) + carried_photos
  7835. await db.commit()
  7836. except Exception as e:
  7837. # The archive and the delete are already committed; the
  7838. # print goes ahead either way. Worst case the pictures sit
  7839. # unnamed in the archive's own directory.
  7840. #
  7841. # Ints only until the rollback has run, per the note above,
  7842. # which is why this logs queue_item_id and not item.id --
  7843. # the sibling handler forty lines up does the same.
  7844. logger.warning(
  7845. "Queue item %s: failed to carry library photos into archive %s: %s",
  7846. queue_item_id,
  7847. archive_id,
  7848. e,
  7849. )
  7850. await db.rollback()
  7851. # rollback() expires every loaded instance, and in async
  7852. # SQLAlchemy the next plain attribute read is lazy IO
  7853. # outside the greenlet -- MissingGreenlet, which would turn
  7854. # this cosmetic failure into a dispatch crash in exactly the
  7855. # "database is locked" case the block exists for (#1853).
  7856. # The nozzle guard, the upload and the start all keep
  7857. # reading item, archive and printer, so all three go back
  7858. # into the session before falling through.
  7859. item = await db.get(PrintQueueItem, queue_item_id)
  7860. archive = await db.get(PrintArchive, archive_id)
  7861. printer = await db.get(Printer, item.printer_id) if item else None
  7862. if not item or not archive or not printer:
  7863. logger.error(
  7864. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7865. queue_item_id,
  7866. archive_id,
  7867. )
  7868. return
  7869. else:
  7870. # Neither archive nor library file specified
  7871. if not await self._fail_dispatch(db, item, "No source file specified"):
  7872. return
  7873. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7874. await self._power_off_if_needed(db, item)
  7875. return
  7876. # Check file exists on disk
  7877. if not file_path.exists():
  7878. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  7879. return
  7880. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7881. await self._power_off_if_needed(db, item)
  7882. return
  7883. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7884. # size dispatched to a printer with a different nozzle installed is
  7885. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7886. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7887. # gives the user no idea what went wrong. Catch it here, before we spend
  7888. # time preheating and uploading, and fail with an actionable message.
  7889. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7890. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7891. # the printer hasn't reported its nozzles yet, we fall through and let the
  7892. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7893. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7894. # as one of the two hotends is a 0.6.
  7895. #
  7896. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7897. # (#2885): the printer fetches one as part of starting the print, so the
  7898. # set to test against is "reachable", not "currently mounted". This runs
  7899. # well before the rack picker at the bottom of this method, so without
  7900. # the rack in scope here that picker never got the chance to run.
  7901. sliced_nozzle = archive.nozzle_diameter if archive else None
  7902. if sliced_nozzle:
  7903. nozzle_status = printer_manager.get_status(item.printer_id)
  7904. installed = _installed_nozzle_diameters(nozzle_status)
  7905. rack = _rack_nozzle_diameters(nozzle_status)
  7906. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7907. if mismatch_msg:
  7908. if not await self._fail_dispatch(db, item, mismatch_msg):
  7909. return
  7910. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7911. await notification_service.on_queue_job_failed(
  7912. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7913. printer_id=printer.id,
  7914. printer_name=printer.name,
  7915. reason=mismatch_msg,
  7916. db=db,
  7917. )
  7918. try:
  7919. await ws_manager.send_queue_item_failed(
  7920. user_id=item.created_by_id,
  7921. queue_item_id=item.id,
  7922. printer_id=item.printer_id,
  7923. reason="nozzle_mismatch",
  7924. )
  7925. except Exception:
  7926. pass
  7927. await self._power_off_if_needed(db, item)
  7928. return
  7929. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7930. # bed (and chamber, if applicable) is at temperature when the firmware
  7931. # starts the actual print routine. Best-effort: any failure logs and
  7932. # falls through to the normal upload+start path rather than turning a
  7933. # configuration issue into a failed queue item.
  7934. # Returns False only when the item was cancelled or deleted while the
  7935. # stage was holding at temperature. Uploading and starting it anyway
  7936. # would print a job the user has already called off, so abandon the
  7937. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7938. if not await self._preheat_and_soak(db, item, printer, archive):
  7939. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7940. return
  7941. # See `_effective_plate_id` for why this is resolved once here rather
  7942. # than each site below repeating `item.plate_id or 1`.
  7943. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7944. # G-code injection for auto-print systems (#422)
  7945. injected_path = None
  7946. # #2547: tracked separately from `injected_path`, which is also set when
  7947. # only a START snippet was injected. Only an END snippet changes what the
  7948. # camera sees at print completion.
  7949. end_gcode_injected = False
  7950. if item.gcode_injection:
  7951. try:
  7952. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7953. if snippets_raw:
  7954. snippets = json.loads(snippets_raw)
  7955. model_snippets = snippets.get(printer.model, {})
  7956. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7957. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7958. if start_gc or end_gc:
  7959. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7960. injected_path = inject_gcode_into_3mf(
  7961. file_path, effective_plate_id, start_gc or None, end_gc or None
  7962. )
  7963. if injected_path:
  7964. file_path = injected_path
  7965. end_gcode_injected = bool(end_gc)
  7966. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7967. else:
  7968. logger.warning(
  7969. "Queue item %s: G-code injection returned no result, using original", item.id
  7970. )
  7971. except Exception as e:
  7972. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7973. # #2547: the finish-photo path can't learn from telemetry that this print
  7974. # ends with user End G-code — which means the plate may be gone by the
  7975. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7976. # the print once the printer confirms it running.
  7977. if end_gcode_injected:
  7978. print_dispatch_context.mark_pending(printer.id)
  7979. # Upload to root directory (not /cache/) - the start_print command references
  7980. # files by name only (ftp://{filename}), so they must be in the root
  7981. remote_filename = derive_remote_filename(filename)
  7982. remote_path = f"/{remote_filename}"
  7983. # Get FTP retry settings
  7984. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7985. logger.info(
  7986. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7987. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7988. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7989. )
  7990. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7991. # Every read this method needs (printer, archive/library, preheat) is
  7992. # done, and the library-file branch already committed its archive
  7993. # creation. Without this the transaction opened by the first SELECT above
  7994. # stays "idle in transaction" for the entire upload — multiple seconds
  7995. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7996. # a farm dispatching many jobs at once then exhausts the pool. This was
  7997. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7998. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7999. # readable; the status writes below (upload-failure path and the
  8000. # pending->printing CAS) transparently open a fresh transaction.
  8001. # The owner is read here, after preheat, so the commit releases this read too.
  8002. toast_uid = await self._queue_owner_id(db, item)
  8003. await db.commit()
  8004. # Delete existing file if present (avoids 553 error on overwrite)
  8005. try:
  8006. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8007. delete_result = await delete_file_async(
  8008. printer.ip_address,
  8009. printer.access_code,
  8010. remote_path,
  8011. socket_timeout=ftp_timeout,
  8012. printer_model=printer.model,
  8013. # This delete and the upload below are one bounded, user-initiated
  8014. # unit -- at most nine connections -- so neither skips on the
  8015. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8016. # trace this delete took the TLS failure and armed the cool-off,
  8017. # and the upload's four attempts were then spent against it
  8018. # without a socket being opened.
  8019. respect_handshake_cooloff=False,
  8020. )
  8021. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8022. except Exception as e:
  8023. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8024. # Dispatch toast — announce the upload start with the total byte
  8025. # count so the frontend can render an honest progress bar.
  8026. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8027. try:
  8028. total_bytes = file_path.stat().st_size
  8029. except OSError:
  8030. total_bytes = 0
  8031. try:
  8032. await ws_manager.send_queue_item_uploading(
  8033. user_id=toast_uid,
  8034. queue_item_id=item.id,
  8035. printer_id=item.printer_id,
  8036. printer_name=printer.name,
  8037. file_name=toast_file_name,
  8038. total_bytes=total_bytes,
  8039. )
  8040. except Exception:
  8041. pass # toast is best-effort
  8042. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8043. # A deadline expiry gets its own message: "check your SD card" is the
  8044. # wrong advice for a link that was simply too slow to finish (#2529).
  8045. upload_error: str | None = None
  8046. # Why the upload failed, straight from the client rather than inferred.
  8047. # Owned here, so a background fetch for another print cannot overwrite
  8048. # it between the failure and the sentence built from it (#2899).
  8049. upload_failure = FtpFailureReport()
  8050. try:
  8051. if ftp_retry_enabled:
  8052. uploaded = await with_ftp_retry(
  8053. upload_file_async,
  8054. printer.ip_address,
  8055. printer.access_code,
  8056. file_path,
  8057. remote_path,
  8058. socket_timeout=ftp_timeout,
  8059. printer_model=printer.model,
  8060. progress_callback=progress_bridge,
  8061. respect_handshake_cooloff=False,
  8062. failure=upload_failure,
  8063. max_retries=ftp_retry_count,
  8064. retry_delay=ftp_retry_delay,
  8065. operation_name=f"Upload print to {printer.name}",
  8066. )
  8067. else:
  8068. uploaded = await upload_file_async(
  8069. printer.ip_address,
  8070. printer.access_code,
  8071. file_path,
  8072. remote_path,
  8073. socket_timeout=ftp_timeout,
  8074. printer_model=printer.model,
  8075. progress_callback=progress_bridge,
  8076. respect_handshake_cooloff=False,
  8077. failure=upload_failure,
  8078. )
  8079. except UploadCancelled as e:
  8080. uploaded = False
  8081. upload_error = (
  8082. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8083. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8084. )
  8085. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8086. except Exception as e:
  8087. uploaded = False
  8088. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8089. # Clean up injected temp file after upload attempt
  8090. if injected_path and injected_path.exists():
  8091. injected_path.unlink(missing_ok=True)
  8092. # Again after the upload, which can take minutes: an owner deleted
  8093. # meanwhile gets no more toasts, and neither does whoever has their id.
  8094. toast_uid = await self._queue_owner_id(db, item)
  8095. # The printer's copy at this path was replaced (or deleted above): the
  8096. # file browser's previews must not show the old one.
  8097. from backend.app.services.printer_file_cache import printer_file_cache
  8098. printer_file_cache.forget(printer.id, remote_path)
  8099. if not uploaded:
  8100. # This used to be one string for every upload failure, telling
  8101. # everyone to check the SD card. The client knows which of seven
  8102. # things went wrong and logs each one differently; it just had no
  8103. # way to say so here, so the card got named even for a TLS
  8104. # handshake that never reached the printer's filesystem (#2899).
  8105. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8106. failure = upload_failure.failure
  8107. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8108. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  8109. return
  8110. if not await self._fail_dispatch(db, item, error_msg):
  8111. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8112. return
  8113. logger.error(
  8114. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8115. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8116. )
  8117. # Send failure notification
  8118. await notification_service.on_queue_job_failed(
  8119. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8120. printer_id=printer.id,
  8121. printer_name=printer.name,
  8122. # The same sentence the queue shows. A push notification saying
  8123. # something different from the UI is its own small bug (#2899).
  8124. reason=error_msg,
  8125. db=db,
  8126. )
  8127. try:
  8128. await ws_manager.send_queue_item_failed(
  8129. user_id=toast_uid,
  8130. queue_item_id=item.id,
  8131. printer_id=item.printer_id,
  8132. reason="upload_failed",
  8133. )
  8134. except Exception:
  8135. pass
  8136. await self._power_off_if_needed(db, item)
  8137. return
  8138. # The printer took a file, so any run of refused uploads is over: the
  8139. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8140. self._upload_refusals.pop(printer.id, None)
  8141. self._upload_refusal_notified.discard(printer.id)
  8142. # Parse AMS mapping if stored
  8143. ams_mapping = None
  8144. if item.ams_mapping:
  8145. try:
  8146. ams_mapping = json.loads(item.ams_mapping)
  8147. except json.JSONDecodeError:
  8148. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8149. # Register as expected print so we don't create a duplicate archive
  8150. # Only applicable for archive-based prints
  8151. if archive:
  8152. from backend.app.main import register_expected_print
  8153. register_expected_print(
  8154. item.printer_id,
  8155. remote_filename,
  8156. archive.id,
  8157. ams_mapping=ams_mapping,
  8158. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8159. # no print-start email, and neither does whoever has their id.
  8160. created_by_id=toast_uid,
  8161. cost_center_id=item.cost_center_id,
  8162. # The plate actually dispatched, not the queue item's raw
  8163. # column: on None, `register_expected_print` stores nothing,
  8164. # and `extract_filament_usage_from_3mf` then books every
  8165. # filament in the file rather than the one plate that printed.
  8166. plate_id=effective_plate_id,
  8167. )
  8168. # Registration happens before the print command by necessity (the
  8169. # printer can report the print before the send returns), so record
  8170. # what to undo if we never get as far as sending. `_dispatch_one`
  8171. # rolls back anything still pending here on every exit — exception,
  8172. # early return, or cancel winning the CAS below.
  8173. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8174. # Propagate the queue item's owner into printer_manager so the
  8175. # print-complete callback can credit the user in the PrintLogEntry
  8176. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8177. # items) or when the user clicks the manual-start button.
  8178. await self._propagate_owner_to_printer_manager(db, item)
  8179. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8180. # This prevents phantom reprints if the backend crashes/restarts after the
  8181. # print command is sent but before the status update is committed.
  8182. # If we crash after this commit but before start_print(), the item will be
  8183. # in "printing" status without actually printing - but that's safer than
  8184. # accidentally reprinting the same file hours later.
  8185. #
  8186. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8187. # initial pending read at the top of check_queue and this point) flips
  8188. # the row to "cancelled" in a separate session. Without the WHERE
  8189. # status='pending' clause, the unconditional update here would silently
  8190. # overwrite that cancellation and we'd ship the MQTT start_print below
  8191. # — printer obeys, user sees "I pressed cancel and the print started".
  8192. # rowcount==0 means the user won the race; bail out, best-effort delete
  8193. # the file we just uploaded, do NOT send start_print.
  8194. now_utc = datetime.now(timezone.utc)
  8195. billing_run_id = str(uuid.uuid4())
  8196. cas = await db.execute(
  8197. update(PrintQueueItem)
  8198. .where(PrintQueueItem.id == item.id)
  8199. .where(PrintQueueItem.status == "pending")
  8200. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  8201. )
  8202. await db.commit()
  8203. if cas.rowcount == 0:
  8204. logger.info(
  8205. "Queue item %s no longer pending at print-command time "
  8206. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8207. item.id,
  8208. )
  8209. try:
  8210. await delete_file_async(
  8211. printer.ip_address,
  8212. printer.access_code,
  8213. remote_path,
  8214. socket_timeout=ftp_timeout,
  8215. printer_model=printer.model,
  8216. )
  8217. except Exception as cleanup_err:
  8218. logger.debug(
  8219. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8220. item.id,
  8221. cleanup_err,
  8222. )
  8223. try:
  8224. await ws_manager.send_queue_item_failed(
  8225. user_id=toast_uid,
  8226. queue_item_id=item.id,
  8227. printer_id=item.printer_id,
  8228. reason="cancelled_mid_dispatch",
  8229. )
  8230. except Exception:
  8231. pass
  8232. return
  8233. # Sync the in-memory item so subsequent code that reads item.status /
  8234. # item.started_at sees the values we just persisted.
  8235. item.status = "printing"
  8236. item.started_at = now_utc
  8237. item.billing_run_id = billing_run_id
  8238. if archive is not None:
  8239. archive.billing_run_id = billing_run_id
  8240. # Legacy transaction deletion used an archive-wide skip flag.
  8241. # A newly dispatched run has its own UUID/tombstone, so it must be
  8242. # billable independently of any older deleted run on this archive.
  8243. archive.wallet_charge_skipped = False
  8244. # Persist before MQTT send so completion and restart recovery can
  8245. # always recover the internal billing identity.
  8246. await db.commit()
  8247. for cleanup_path in cleanup_disk_paths:
  8248. try:
  8249. if cleanup_path.exists():
  8250. cleanup_path.unlink()
  8251. except OSError as cleanup_err:
  8252. logger.warning(
  8253. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8254. json.dumps(
  8255. {
  8256. "queue_item_id": item.id,
  8257. "path": str(cleanup_path),
  8258. "error": str(cleanup_err),
  8259. },
  8260. sort_keys=True,
  8261. ),
  8262. )
  8263. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8264. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8265. # #1898: with the opt-in default-good setting, moving on to the next
  8266. # print resolves the previous print's unanswered outcome prompt as
  8267. # "good" — this path also covers the camera-based plate detection,
  8268. # which releases the gate by allowing dispatch rather than by an
  8269. # explicit acknowledgment. Rides on the dispatch transaction.
  8270. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8271. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8272. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8273. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8274. # Capture state before dispatch so the watchdog can detect whether the
  8275. # printer actually transitioned (#967). Also capture subtask_id so the
  8276. # watchdog can recognise "command landed but state hasn't flipped yet"
  8277. # on slow H2D transitions (#1078).
  8278. pre_status = printer_manager.get_status(item.printer_id)
  8279. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8280. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8281. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8282. # #1721: respect the user's explicit timelapse choice. The #1397
  8283. # force-on at dispatch was removed because it caused per-layer nozzle
  8284. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8285. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8286. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8287. # FINISH-state fallback — no need to force a video.
  8288. effective_timelapse = bool(item.timelapse)
  8289. # Nozzle-rack fallback (#2800). A job that never passed through the
  8290. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8291. # dispatches with no nozzle field at all and chooses for itself — which
  8292. # is how a print levelled on one hotend and then printed on another,
  8293. # millimetres above the plate. Derive the per-slot extruder assignment
  8294. # from the file being dispatched.
  8295. #
  8296. # Done here rather than at queue time because this is the first point
  8297. # that knows both the actual printer and the actual file: an item can
  8298. # be created without a printer (model-based assignment), reassigned
  8299. # afterwards, or have its file swapped for a G-code-injected copy just
  8300. # above. Every queue-creation path — the print dialog, a bulk library
  8301. # add, the webhook, a pipeline run — is covered by the one call.
  8302. # Skipped when the item already carries a Bambu Studio capture: that
  8303. # one wins downstream anyway, so reading the 3MF again would be work
  8304. # thrown away on every dispatch.
  8305. # Rack position resolution (#1784), tried before the #2800 fallback
  8306. # below because it can express what that one cannot: a plate wanting a
  8307. # *different* hotend off the rack per filament group. The position per
  8308. # group is the operator's pick — the 3MF states it nowhere, proven by
  8309. # sending one plate twice with different picks and finding the two
  8310. # files identical bar float noise — so it is resolved here against the
  8311. # rack as it stands right now, after the upload, not at queue time.
  8312. resolved_nozzle_mapping = None
  8313. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8314. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8315. if rack_plan is not None:
  8316. try:
  8317. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8318. except (json.JSONDecodeError, TypeError):
  8319. stored_choice = {}
  8320. logger.warning(
  8321. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8322. item.id,
  8323. item.nozzle_rack_choice,
  8324. )
  8325. # JSON object keys are strings; the groups are ints.
  8326. choice: dict[int, int] = {}
  8327. for key, value in (stored_choice or {}).items():
  8328. try:
  8329. choice[int(key)] = int(value)
  8330. except (TypeError, ValueError):
  8331. continue
  8332. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8333. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8334. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8335. )
  8336. if resolved_nozzle_mapping is None and choice:
  8337. # An explicit pick that no longer holds stops the print. The
  8338. # operator named a hotend; printing from a different one is
  8339. # how a plate gets levelled on one nozzle and drawn with
  8340. # another, millimetres above the bed. Nothing has been sent
  8341. # to the printer yet, so failing here costs only the upload.
  8342. # The file is already on the SD card by this point, and a
  8343. # 3MF left there is a phantom print waiting to be started
  8344. # from the touchscreen. Same cleanup the start_print
  8345. # failure path below does, for the same reason.
  8346. try:
  8347. await delete_file_async(
  8348. printer.ip_address,
  8349. printer.access_code,
  8350. remote_path,
  8351. printer_model=printer.model,
  8352. )
  8353. except Exception:
  8354. pass # Best-effort — don't fail the error handler
  8355. if not await self._fail_dispatch(
  8356. db,
  8357. item,
  8358. (
  8359. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8360. "Edit the item to choose another position."
  8361. ),
  8362. ):
  8363. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8364. return
  8365. logger.warning(
  8366. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8367. item.id,
  8368. printer.name,
  8369. rack_error,
  8370. choice,
  8371. [slot.get("id") for slot in live_rack],
  8372. )
  8373. await notification_service.on_queue_job_failed(
  8374. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8375. printer_id=printer.id,
  8376. printer_name=printer.name,
  8377. reason=item.error_message,
  8378. db=db,
  8379. )
  8380. try:
  8381. await ws_manager.send_queue_item_failed(
  8382. user_id=toast_uid,
  8383. queue_item_id=item.id,
  8384. printer_id=item.printer_id,
  8385. reason="nozzle_rack_pick_stale",
  8386. )
  8387. except Exception:
  8388. pass # Best-effort — don't fail the error handler
  8389. return
  8390. if resolved_nozzle_mapping is None:
  8391. # Nothing was picked and nothing could be assigned. Falls
  8392. # through to the #2800 path, which is what ran before this
  8393. # existed — strictly not worse than today.
  8394. logger.info(
  8395. "Queue item %s: no rack positions assignable (%s); falling back",
  8396. item.id,
  8397. rack_error,
  8398. )
  8399. else:
  8400. logger.info(
  8401. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8402. item.id,
  8403. resolved_nozzle_mapping,
  8404. rack_plan.slot_groups,
  8405. choice or "auto",
  8406. )
  8407. nozzle_slot_extruders = None
  8408. if (
  8409. not item.nozzle_mapping
  8410. and resolved_nozzle_mapping is None
  8411. and file_path is not None
  8412. and is_nozzle_rack_model(printer.model)
  8413. ):
  8414. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8415. if slot_extruders:
  8416. nozzle_slot_extruders = json.dumps(slot_extruders)
  8417. # Every filament this plate prints is on the external spool -> the print
  8418. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8419. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8420. # table", which is what held the reporter's P1S at Heatbed preheating
  8421. # for ten minutes before it gave up (#3087). The MQTT command builder
  8422. # already downgrades a mapping that is *only* external ([254]), but a
  8423. # multi-filament project pads the slots this plate does not print with
  8424. # -1 — BambuStudio's own convention — and down there a -1 is
  8425. # indistinguishable from a slot that never resolved, which must never be
  8426. # sent to the spool holder (#2589). Here the plate's filament list says
  8427. # which is which, so the answer is exact rather than a guess.
  8428. #
  8429. # Deliberately narrow: this fires only when every consumed slot is an
  8430. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8431. # alone and the firmware still rejects the print, exactly as today. And
  8432. # only for single-nozzle printers, mirroring the builder's own reconcile
  8433. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8434. # whether to use the AMS, so it is not ours to rewrite.
  8435. effective_use_ams = item.use_ams
  8436. plate_uses_only_external = False
  8437. if (
  8438. ams_mapping
  8439. and file_path is not None
  8440. # Cheap gate before opening the file: with nothing on the spool
  8441. # holder anywhere in the mapping, no subset of it can be all
  8442. # external, so most dispatches never pay for the parse. The
  8443. # isinstance also keeps a malformed stored mapping (a bare number
  8444. # from a hand-edited row) failing where it always failed, in the
  8445. # command builder, rather than here.
  8446. and isinstance(ams_mapping, list)
  8447. and any(_is_external_tray(t) for t in ams_mapping)
  8448. and not _might_be_dual_nozzle(printer.model, pre_status)
  8449. ):
  8450. from backend.app.services.filament_requirements import extract_filament_requirements
  8451. consumed = _consumed_mapping_entries(
  8452. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8453. )
  8454. if consumed and all(_is_external_tray(t) for t in consumed):
  8455. # Exact for this plate: the command builder must not turn the
  8456. # AMS back on for a real tray another plate of the file uses,
  8457. # whether the job asked for the AMS or already had it off.
  8458. plate_uses_only_external = True
  8459. if plate_uses_only_external and effective_use_ams:
  8460. effective_use_ams = False
  8461. logger.info(
  8462. "Queue item %s: every filament plate %s prints is on the external spool "
  8463. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8464. item.id,
  8465. effective_plate_id,
  8466. ams_mapping,
  8467. )
  8468. # A slot that lost its K-profile selection (a power cycle resets every
  8469. # slot to the default K) would print on the default. The idle check in
  8470. # the status handler normally restores it first, but nothing guarantees
  8471. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8472. # Never allowed to stop the print it is protecting.
  8473. try:
  8474. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8475. except Exception:
  8476. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8477. # Start the print with AMS mapping, plate_id and print options.
  8478. # nozzle_mapping rides through verbatim — JSON string captured from
  8479. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8480. # parses + injects it only for dual-nozzle models so a null on every
  8481. # other model is a transparent pass-through. The rack fallback is
  8482. # resolved down there too, where the live rack position is known.
  8483. started = printer_manager.start_print(
  8484. item.printer_id,
  8485. remote_filename,
  8486. plate_id=effective_plate_id,
  8487. ams_mapping=ams_mapping,
  8488. bed_levelling=item.bed_levelling,
  8489. flow_cali=item.flow_cali,
  8490. vibration_cali=item.vibration_cali,
  8491. layer_inspect=item.layer_inspect,
  8492. timelapse=effective_timelapse,
  8493. use_ams=effective_use_ams,
  8494. plate_uses_only_external=plate_uses_only_external,
  8495. nozzle_offset_cali=item.nozzle_offset_cali,
  8496. nozzle_mapping=item.nozzle_mapping
  8497. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8498. nozzle_slot_extruders=nozzle_slot_extruders,
  8499. )
  8500. if started:
  8501. # The command is away, so the expectation is now legitimate and must
  8502. # survive. Anything still in this dict when _dispatch_one exits gets
  8503. # rolled back.
  8504. self._unconfirmed_expected_print.pop(item.id, None)
  8505. self._unconfirmed_budget_reservations.discard(item.id)
  8506. self._unconfirmed_print_user.pop(item.id, None)
  8507. if item.printer_id is not None:
  8508. self._sent_unstarted_print[item.id] = (
  8509. item.printer_id,
  8510. remote_filename if archive else None,
  8511. archive.id if archive else None,
  8512. )
  8513. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8514. # target, chamber target, airduct heating) — the gcode owns
  8515. # heater/flap control from here. Clearing the pin prevents
  8516. # `_dispatch_one`'s finally from unwinding a live print.
  8517. self._preheat_pin.pop(item.printer_id, None)
  8518. self._preheat_pin_bed.pop(item.printer_id, None)
  8519. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8520. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8521. # status='processing' from upload start until the printer acked
  8522. # (or timed out). The frontend derives "Awaiting printer…" purely
  8523. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8524. # event would push the status chip out of 'PROCESSING' prematurely
  8525. # — which is exactly what the screenshot at #1625-followup
  8526. # complained about.
  8527. # Register the local 3MF in the cover-cache so /cover skips FTP
  8528. # (#1166 follow-up). file_path was resolved earlier from either the
  8529. # archive or the library file row.
  8530. if file_path is not None:
  8531. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8532. # Hold the printer against further dispatches until the watchdog
  8533. # confirms the printer transitioned (or until the hard timeout).
  8534. # Prevents multi-plate batches from triple-dispatching onto the
  8535. # same H2D Pro while it digests the first project_file (#1157).
  8536. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8537. # Watchdog: if the printer never transitions out of pre_state AND
  8538. # never advances subtask_id, the MQTT publish was accepted locally but
  8539. # didn't reach the printer (half-broken session — same shape as
  8540. # #887/#936). Revert the queue item so the next dispatch can pick it
  8541. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8542. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8543. # that would otherwise cause the item to re-dispatch as a reprint
  8544. # of the just-finished job (#1078).
  8545. if pre_state:
  8546. spawn_background_task(
  8547. self._watchdog_print_start(
  8548. item.id,
  8549. item.printer_id,
  8550. pre_state,
  8551. pre_subtask_id,
  8552. pre_gcode_file,
  8553. created_by_id=toast_uid,
  8554. ),
  8555. name=f"watchdog-print-start-{item.id}",
  8556. )
  8557. # Get estimated time for notification.
  8558. #
  8559. # This used to fall back to `library_file.print_time_seconds`, a column
  8560. # LibraryFile does not have — the print time it knows about lives in
  8561. # `file_metadata`. So a library print whose archive carried no parseable
  8562. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8563. # AttributeError right here, *after* the printer had already been sent
  8564. # the job: the started-notification never fired, and the exception
  8565. # unwound the whole queue pass, so every other printer still waiting to
  8566. # be dispatched on that tick silently missed its turn.
  8567. #
  8568. # The queue item caches the print time at creation ("Cached from
  8569. # archive/library"), which is the value this was reaching for.
  8570. estimated_time = None
  8571. if archive and archive.print_time_seconds:
  8572. estimated_time = archive.print_time_seconds
  8573. elif item.print_time_seconds:
  8574. estimated_time = item.print_time_seconds
  8575. # Send job started notification
  8576. await notification_service.on_queue_job_started(
  8577. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8578. printer_id=printer.id,
  8579. printer_name=printer.name,
  8580. db=db,
  8581. estimated_time=estimated_time,
  8582. )
  8583. # MQTT relay - publish queue job started
  8584. try:
  8585. await mqtt_relay.on_queue_job_started(
  8586. job_id=item.id,
  8587. filename=filename,
  8588. printer_id=printer.id,
  8589. printer_name=printer.name,
  8590. printer_serial=printer.serial_number,
  8591. )
  8592. except Exception:
  8593. pass # Don't fail if MQTT fails
  8594. else:
  8595. # Clean up uploaded file from SD card to prevent phantom prints
  8596. try:
  8597. await delete_file_async(
  8598. printer.ip_address,
  8599. printer.access_code,
  8600. remote_path,
  8601. printer_model=printer.model,
  8602. )
  8603. except Exception:
  8604. pass # Best-effort — don't fail the error handler
  8605. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8606. # state can flip from idle to active in the window between the
  8607. # pre-dispatch check above and this publish (the FTP upload takes
  8608. # seconds); start_print() then refuses to send project_file to the
  8609. # now-busy printer and returns False. Failing the item here would be
  8610. # wrong — the printer is fine, it is simply busy — so revert to
  8611. # pending and let a later tick dispatch it once the printer is idle,
  8612. # exactly like the pre-dispatch guard. Only a start_print() False on
  8613. # an idle/unknown printer is a genuine command failure.
  8614. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8615. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8616. logger.info(
  8617. "Queue item %s: printer %s became busy (state=%s) before the start "
  8618. "command was sent — deferring, reverting item to pending (#2598)",
  8619. item.id,
  8620. item.printer_id,
  8621. post_dispatch_state,
  8622. )
  8623. await self._defer_until_printer_idle(db, item)
  8624. return
  8625. # Print command failed - revert status
  8626. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8627. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8628. return
  8629. logger.error(
  8630. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8631. f"printer_manager.start_print() returned False. "
  8632. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8633. f"Check printer status and backend logs for details."
  8634. )
  8635. # Send failure notification
  8636. await notification_service.on_queue_job_failed(
  8637. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8638. printer_id=printer.id,
  8639. printer_name=printer.name,
  8640. reason="Failed to send print command to printer - check printer connection and status",
  8641. db=db,
  8642. )
  8643. try:
  8644. await ws_manager.send_queue_item_failed(
  8645. user_id=toast_uid,
  8646. queue_item_id=item.id,
  8647. printer_id=item.printer_id,
  8648. reason="start_command_failed",
  8649. )
  8650. except Exception:
  8651. pass
  8652. await self._power_off_if_needed(db, item)
  8653. @staticmethod
  8654. async def _watchdog_print_start(
  8655. queue_item_id: int,
  8656. printer_id: int,
  8657. pre_state: str,
  8658. pre_subtask_id: str | None = None,
  8659. pre_gcode_file: str | None = None,
  8660. timeout: float = 90.0,
  8661. phase_b_timeout: float = 180.0,
  8662. poll_interval: float = 3.0,
  8663. created_by_id: int | None = None,
  8664. ) -> None:
  8665. """Revert a queue item if the printer never acknowledges the start command.
  8666. Bambuddy optimistically marks the queue item as "printing" right after the
  8667. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8668. Phase A (up to ``timeout``): wait for either an active-state transition
  8669. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8670. primary signal; subtask_id advance handles the H2D case where state can
  8671. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8672. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8673. was lost on a half-broken session (#887/#936) — revert and force
  8674. reconnect (the #967 recovery path).
  8675. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8676. alone): keep watching for the active-state transition. subtask_id alone
  8677. proves the file landed but not that the printer started — and a printer
  8678. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8679. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8680. used to leave the queue item stuck in 'printing' forever because the
  8681. old watchdog returned success as soon as subtask_id advanced. If Phase
  8682. B times out, revert the queue item so the user can retry without
  8683. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8684. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8685. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8686. transitions that also don't emit an early subtask_id tick.
  8687. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8688. refuses to verify our commands will never start this job or any other,
  8689. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8690. burns an upload slot the rest of the farm is queued behind — that path
  8691. is for a printer that might still come good, which this one cannot
  8692. (#2732). It fails the item on the spot with the actual reason instead.
  8693. """
  8694. last_status = None
  8695. landed_on_subtask = False
  8696. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8697. # every push carrying an `hms` key, so the fault can come and go between
  8698. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8699. command_rejected = False
  8700. # Latched for the same reason as command_rejected: drying can finish, or
  8701. # be stopped by the user, part-way through the dispatch window. Seeing it
  8702. # once is what matters — it is the state the printer was in when it
  8703. # declined to start (#2758).
  8704. drying_ams_ids: list[int] = []
  8705. deadline = time.monotonic() + timeout
  8706. while time.monotonic() < deadline:
  8707. await asyncio.sleep(poll_interval)
  8708. status = printer_manager.get_status(printer_id)
  8709. if not status:
  8710. # Printer disconnected — don't mess with the DB. Drop the
  8711. # in-memory dispatch hold too so a fresh dispatch can retry
  8712. # once the printer comes back; the hard timeout would
  8713. # otherwise hold the printer unnecessarily.
  8714. scheduler._release_dispatch_hold(printer_id)
  8715. return
  8716. last_status = status
  8717. if status.state in _ACTIVE_PRINT_STATES:
  8718. # Printer is actively processing the job — release the
  8719. # post-dispatch hold so the next pending item for this printer
  8720. # can be evaluated normally. We do NOT accept arbitrary state
  8721. # transitions: a printer going FINISH -> IDLE (user dismissed
  8722. # the post-print prompt without accepting our project_file)
  8723. # would otherwise look like "command landed" and leave the
  8724. # queue item stuck in 'printing' forever (#1370).
  8725. scheduler._release_dispatch_hold(printer_id)
  8726. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8727. try:
  8728. await ws_manager.send_queue_item_acked(
  8729. user_id=created_by_id,
  8730. queue_item_id=queue_item_id,
  8731. printer_id=printer_id,
  8732. )
  8733. except Exception:
  8734. pass
  8735. return
  8736. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8737. # Checked only after the active-state exit above: a stale HMS left
  8738. # over from an earlier job must never abort a print that is visibly
  8739. # running. An actually-refused command leaves the printer idle, so
  8740. # this ordering costs the detection nothing.
  8741. if _mqtt_commands_rejected(status):
  8742. command_rejected = True
  8743. break
  8744. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8745. # Phase A exit — printer accepted the file (subtask_id flipped
  8746. # to our submission id). Don't return yet: the printer may
  8747. # have accepted the command but never actually start (e.g.
  8748. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8749. # B watches for the active-state transition.
  8750. landed_on_subtask = True
  8751. break
  8752. if landed_on_subtask and not command_rejected:
  8753. phase_b_deadline = time.monotonic() + phase_b_timeout
  8754. while time.monotonic() < phase_b_deadline:
  8755. await asyncio.sleep(poll_interval)
  8756. status = printer_manager.get_status(printer_id)
  8757. if not status:
  8758. scheduler._release_dispatch_hold(printer_id)
  8759. return
  8760. last_status = status
  8761. if status.state in _ACTIVE_PRINT_STATES:
  8762. scheduler._release_dispatch_hold(printer_id)
  8763. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8764. try:
  8765. await ws_manager.send_queue_item_acked(
  8766. user_id=created_by_id,
  8767. queue_item_id=queue_item_id,
  8768. printer_id=printer_id,
  8769. )
  8770. except Exception:
  8771. pass
  8772. return
  8773. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8774. # Same ordering rule as Phase A: a running print wins over a
  8775. # lingering HMS.
  8776. if _mqtt_commands_rejected(status):
  8777. command_rejected = True
  8778. break
  8779. # No active-state transition. Revert the item so the scheduler can retry.
  8780. # Drop the in-memory hold so the retry isn't blocked by it.
  8781. scheduler._release_dispatch_hold(printer_id)
  8782. # Logged on every failed dispatch window, not just the last one, so a
  8783. # support bundle shows the correlation from the first attempt rather than
  8784. # only after the retry budget is spent (#2758).
  8785. if drying_ams_ids:
  8786. logger.info(
  8787. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8788. queue_item_id,
  8789. printer_id,
  8790. ", ".join(str(i) for i in drying_ams_ids),
  8791. )
  8792. # Four outcomes from the revert attempt, each routed differently:
  8793. # "reverted": row flipped from printing -> pending, run recovery
  8794. # "gave_up": same, but the retry budget is spent — row failed
  8795. # rather than pending, so it stops going round again
  8796. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8797. # on_print_complete or user). Skip recovery entirely
  8798. # — the print clearly landed somewhere even if the
  8799. # watchdog didn't see the active-state transition.
  8800. # "revert_failed": SQLite contention exhausted retries. Still run
  8801. # recovery so the MQTT session gets a fresh client_id
  8802. # on the half-broken-session path.
  8803. #
  8804. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8805. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8806. # the watchdog again. For a printer that is genuinely wedged that loop never
  8807. # ends — the reporter had one printer "since this morning still not launch"
  8808. # — and each lap also consumes an upload slot that the other printers in the
  8809. # farm are waiting on. Retrying is right; retrying forever is not.
  8810. async def _do_revert(db):
  8811. item = await db.get(PrintQueueItem, queue_item_id)
  8812. if not item or item.status != "printing":
  8813. return "already_moved_on"
  8814. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8815. item.started_at = None
  8816. # Charge the attempt to the candidate that was actually dispatched, so
  8817. # a cross-model item (#671) reaches for its other file next lap instead
  8818. # of retrying the printer that just failed to start. Matched by file
  8819. # because that is what the resolver copied onto the row.
  8820. if item.library_file_id is not None:
  8821. await db.execute(
  8822. update(PrintQueueVariant)
  8823. .where(PrintQueueVariant.queue_item_id == item.id)
  8824. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8825. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8826. )
  8827. if command_rejected:
  8828. # No retry budget for this one: the printer refused to verify the
  8829. # command, and re-uploading the same 3MF to the same printer will
  8830. # be refused the same way. Fail now with the fix rather than after
  8831. # three laps of a message about SD cards (#2732).
  8832. item.status = "failed"
  8833. item.error_message = (
  8834. "The printer rejected the print command: MQTT command verification failed "
  8835. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8836. "then start the job again."
  8837. )
  8838. item.completed_at = datetime.now(timezone.utc)
  8839. await db.commit()
  8840. return "command_rejected"
  8841. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8842. item.status = "failed"
  8843. if drying_ams_ids:
  8844. # #2758: the generic message below sent the reporter looking
  8845. # at the SD card while the actual obstacle — AMS units in a
  8846. # drying cycle — was on screen the whole time. Name what we
  8847. # observed and let the user judge it; Bambuddy does not stop
  8848. # the cycle itself, because on this hardware drying can run
  8849. # alongside a print and stopping it may not be the fix.
  8850. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8851. item.error_message = (
  8852. f"The printer accepted the file but never started printing, after "
  8853. f"{item.dispatch_attempts} attempts. {units} "
  8854. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8855. f"some printers refuse to begin a print while an AMS is in a drying "
  8856. f"cycle, and an AMS drying without its external power supply can also "
  8857. f"leave too little power for the start-of-print calibration. Stop the "
  8858. f"drying, or connect the AMS power supply, and start the job again."
  8859. )
  8860. else:
  8861. item.error_message = (
  8862. f"The printer accepted the file but never started printing, after "
  8863. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8864. f"prompt or error, confirm its SD card is readable, and start the job again."
  8865. )
  8866. item.completed_at = datetime.now(timezone.utc)
  8867. await release_budget_reservation(
  8868. db,
  8869. source_type="print_queue",
  8870. source_id=item.id,
  8871. status="released",
  8872. )
  8873. await db.commit()
  8874. return "gave_up"
  8875. item.status = "pending"
  8876. await db.commit()
  8877. return "reverted"
  8878. try:
  8879. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8880. except Exception as e:
  8881. logger.warning(
  8882. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8883. "scheduler may keep treating this item as in-flight",
  8884. queue_item_id,
  8885. printer_id,
  8886. e,
  8887. )
  8888. revert_outcome = "revert_failed"
  8889. if revert_outcome in ("command_rejected", "gave_up"):
  8890. # The item is failed: its print user and expected print must not
  8891. # pass the printer's next print off as Bambuddy's.
  8892. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  8893. from backend.app.services.print_batch import refresh_batches_after
  8894. await refresh_batches_after([queue_item_id])
  8895. elif revert_outcome == "reverted":
  8896. # Another try claims the printer again. Until then no print on it
  8897. # is vouched for as this item's, except a late start of its file.
  8898. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  8899. elif revert_outcome == "already_moved_on":
  8900. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  8901. if revert_outcome == "already_moved_on":
  8902. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8903. # other path) already moved the item past 'printing', don't run the
  8904. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8905. # session breaks ongoing prints on the same printer.
  8906. return
  8907. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8908. if revert_outcome == "command_rejected":
  8909. logger.error(
  8910. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8911. "failed) — the print command was rejected, not lost. Failing the item "
  8912. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8913. queue_item_id,
  8914. printer_id,
  8915. HMS_MQTT_VERIFY_FAILED,
  8916. )
  8917. await scheduler._notify_dispatch_gave_up(
  8918. queue_item_id,
  8919. printer_id,
  8920. created_by_id,
  8921. reason="Printer rejected the print command (MQTT command verification failed)",
  8922. )
  8923. # Same reasoning as the landed_on_subtask path below: the file is on
  8924. # the printer and a forced reconnect would only add 0500_4003 to a
  8925. # problem that has nothing to do with the MQTT session (#1150).
  8926. return
  8927. if revert_outcome == "gave_up":
  8928. logger.error(
  8929. "Queue item %s: printer %d never started the print after %d dispatch "
  8930. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8931. "re-uploading it again (#2555)",
  8932. queue_item_id,
  8933. printer_id,
  8934. DISPATCH_MAX_ATTEMPTS,
  8935. total_timeout,
  8936. )
  8937. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8938. elif revert_outcome == "reverted":
  8939. if landed_on_subtask:
  8940. logger.warning(
  8941. "Queue item %s: printer %d accepted project_file (subtask_id "
  8942. "advanced) but never transitioned to an active state within "
  8943. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8944. "for retry (#1678)",
  8945. queue_item_id,
  8946. printer_id,
  8947. total_timeout,
  8948. )
  8949. else:
  8950. logger.warning(
  8951. "Queue item %s: printer %d did not respond to print command within "
  8952. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8953. "for retry (#967)",
  8954. queue_item_id,
  8955. printer_id,
  8956. timeout,
  8957. pre_state,
  8958. pre_subtask_id,
  8959. )
  8960. # Phase B was entered iff subtask_id advanced, which means the
  8961. # project_file landed on the printer. A forced reconnect at this point
  8962. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8963. # skip the recovery entirely.
  8964. if landed_on_subtask:
  8965. return
  8966. # Phase A timeout path: if the printer's gcode_file changed since
  8967. # pre-dispatch, the project_file command landed and the printer is
  8968. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8969. # If gcode_file is unchanged, the publish was silently swallowed
  8970. # (#887/#936) and force_reconnect recovery is what we want.
  8971. client = printer_manager.get_client(printer_id)
  8972. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8973. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8974. if publish_landed:
  8975. logger.warning(
  8976. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8977. "received the command and is parsing slowly. Skipping forced "
  8978. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8979. queue_item_id,
  8980. current_gcode_file,
  8981. pre_gcode_file,
  8982. )
  8983. elif client and hasattr(client, "force_reconnect_stale_session"):
  8984. client.force_reconnect_stale_session(
  8985. f"queue print command unacknowledged after {timeout:.0f}s "
  8986. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8987. )
  8988. # Global scheduler instance
  8989. scheduler = PrintScheduler()