print_scheduler.py 518 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Awaitable, Callable, Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from typing import cast
  14. from fastapi import HTTPException
  15. from sqlalchemy import delete, false, func, or_, select, true, update
  16. from sqlalchemy.engine import CursorResult
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from sqlalchemy.orm import selectinload
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import async_session, run_with_retry
  21. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
  22. from backend.app.core.tasks import spawn_background_task
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile
  26. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.scheduled_drying import ScheduledDrying
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.spool_assignment import SpoolAssignment
  32. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  33. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  34. from backend.app.services.bambu_ftp import (
  35. FtpFailureKind,
  36. FtpFailureReport,
  37. UploadCancelled,
  38. cache_3mf_download,
  39. delete_file_async,
  40. describe_upload_failure,
  41. get_ftp_retry_settings,
  42. upload_file_async,
  43. with_ftp_retry,
  44. )
  45. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  46. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  47. from backend.app.services.finance_budget import (
  48. create_budget_reservation,
  49. release_budget_reservation,
  50. validate_print_budget,
  51. )
  52. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  53. from backend.app.services.mqtt_relay import mqtt_relay
  54. from backend.app.services.notification_service import notification_service
  55. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  56. from backend.app.services.printer_manager import (
  57. printer_manager,
  58. supports_airduct,
  59. supports_chamber_heater,
  60. supports_chamber_temp,
  61. supports_drying,
  62. supports_drying_while_printing,
  63. )
  64. from backend.app.services.queue_item_printer import drop_printer_resolved
  65. from backend.app.services.slot_nozzle import reports_two_nozzles
  66. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  67. from backend.app.services.spool_assignment_notifications import (
  68. _global_tray_from_assignment,
  69. _slot_label_from_global_tray,
  70. )
  71. from backend.app.utils.ams_drying import is_countdown_parked
  72. from backend.app.utils.ams_humidity import ams_humidity_percent
  73. from backend.app.utils.archive_paths import archive_photos_dir
  74. from backend.app.utils.color_utils import perceptual_color_distance
  75. from backend.app.utils.filament_types import canonical_filament_type
  76. from backend.app.utils.filename import derive_remote_filename
  77. from backend.app.utils.library_paths import move_library_photos
  78. from backend.app.utils.local_time import utcnow_naive
  79. from backend.app.utils.printer_models import (
  80. is_dual_nozzle_model,
  81. is_gcode_compatible,
  82. is_nozzle_rack_model,
  83. normalize_printer_model,
  84. )
  85. from backend.app.utils.threemf_tools import (
  86. default_plate_number,
  87. extract_rack_plan_from_3mf,
  88. extract_slot_extruders_from_3mf,
  89. plate_bed_temperature,
  90. select_plate_gcode_name,
  91. )
  92. logger = logging.getLogger(__name__)
  93. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  94. """Human slot name for an assignment tuple, in the spelling already in use.
  95. Composed from the notification side's own pair rather than spelled out again
  96. here. The hand-rolled version this replaces got three real slot kinds wrong:
  97. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  98. ``chr(191)``; both externals collapsed to one label, because an external
  99. assignment stores ams_id 255 with tray_id picking left or right
  100. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  101. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  102. Naming the same slot two ways is its own defect once an alert and the
  103. Inventory page are meant to be talking about the same tray, so this defers
  104. rather than adding a fifth spelling.
  105. """
  106. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  107. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  108. # interval: the fast path runs every 3 s while an upload is in flight, and a
  109. # low spool does not need answering at that resolution (#2913).
  110. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  111. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  112. # days, so a finer check would only repeat the same answer.
  113. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  114. # The settings row that holds which stock alerts have already been sent (#2955).
  115. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  116. # The Inventory page asks for this many usage records and the forecast panel
  117. # builds its rates from them; the alert reads the same window so the two agree.
  118. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  119. def _spoolman_time(value: object) -> datetime | None:
  120. """A Spoolman ISO timestamp, or None when missing or unreadable."""
  121. if not value:
  122. return None
  123. try:
  124. return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
  125. except ValueError:
  126. return None
  127. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  128. """Remaining filament as a percentage of the label weight.
  129. The same arithmetic the Inventory page's Low Stock count uses, and it works
  130. unchanged in both inventory modes: internal spools store ``weight_used``
  131. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  132. ``remaining_weight`` so the shape matches. Returns None when there is no
  133. label weight to be a percentage of -- a spool that cannot say how full it
  134. started cannot say how empty it is.
  135. """
  136. if not label_weight or label_weight <= 0:
  137. return None
  138. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  139. return remaining / float(label_weight) * 100.0
  140. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  141. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  142. # byte gate) from before the scheduler unification. Time gate keeps small
  143. # files from going silent (a single 8 KB chunk fires once and that's it);
  144. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  145. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  146. # sub-200 ms files.
  147. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  148. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  149. # How far back chamber temperature samples are retained. 2h comfortably spans
  150. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  151. # before the next print.
  152. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  153. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  154. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  155. # who clear plates promptly will want far less than this; it is deliberately
  156. # the cautious end, since the cost of it being too short is only a re-soak.
  157. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  158. # Max acceptable gap between two consecutive chamber samples before we treat
  159. # the older one as belonging to a separate observation run (printer went
  160. # offline and came back). Above ~30s cadence with a safety margin.
  161. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  162. # How long the chamber must read below target before we accept that it really
  163. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  164. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  165. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  166. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  167. # sub-target readings are therefore a door opening or noise, not lost soak,
  168. # and a plate swap (exactly when keep-warm is running) produces one. Six
  169. # minutes clears the longest such artifact observed (~5 min once bracketed by
  170. # its neighbouring samples) and still sits far below the 23-minute floor for
  171. # real cooling.
  172. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  173. # How often the preheat stage re-checks that the item it is heating for still
  174. # wants to be printed. Cancelling only writes `status` to the database — it
  175. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  176. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  177. # and the printer stays in `busy_printers`, blocking every other queued item
  178. # behind a print that is not happening.
  179. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  180. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  181. _AIRDUCT_MODE_COOLING = 0
  182. _AIRDUCT_MODE_HEATING = 1
  183. # How long a queue row may stay 'printing' while its printer sits in a terminal
  184. # state before the scheduler closes it itself (#2829).
  185. #
  186. # A real completion arrives within seconds of the printer going terminal, so
  187. # five minutes is far outside the normal path — this only ever sees a row whose
  188. # completion was refused or never delivered. It is the whole cost of the
  189. # failure to the user, though: a stranded row blocks every later job for that
  190. # printer, so it should not be raised without reason.
  191. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  192. # gcode_state values that mean the print is over, mapped to the queue status
  193. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  194. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  195. # which the queue calls cancelled) so a recovered row cannot disagree with one
  196. # closed by the normal path.
  197. _TERMINAL_STATE_QUEUE_STATUS = {
  198. "FINISH": "completed",
  199. "FAILED": "failed",
  200. "IDLE": "cancelled",
  201. }
  202. def _terminal_queue_status(state) -> str | None:
  203. """Queue status implied by *state*, or None if the print is not over.
  204. None for a disconnected printer as well as a busy one: a printer we are not
  205. talking to has a stale ``state`` field that proves nothing about what it is
  206. doing now.
  207. """
  208. if state is None or not getattr(state, "connected", False):
  209. return None
  210. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  211. @dataclass
  212. class _KeepWarmEntry:
  213. """Per-printer keep-warm state.
  214. - ``started``: monotonic time when keep-warm first fired for this printer.
  215. Used by the max-duration timeout.
  216. - ``held_target``: last bed target we successfully published. On release
  217. we only send bed-off when firmware still reports this value, so a user
  218. or subsequent print that changed the target isn't clobbered.
  219. - ``expired``: latched True when the max-duration timeout fires. Prevents
  220. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  221. release sweep drops the entry entirely once the printer leaves the
  222. candidate set.
  223. """
  224. started: float
  225. held_target: int
  226. expired: bool = False
  227. # Auto-drying re-arm guards (#2770).
  228. #
  229. # An AMS reports HIGHER relative humidity while it is warm than once it has
  230. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  231. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  232. # threshold set inside that band therefore cannot be satisfied while the box is
  233. # hot, and the firmware is free to end a cycle whenever it decides the filament
  234. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  235. # the threshold and arms another cycle. The reporter's log has five 12-hour
  236. # cycles armed inside four hours, one of them six seconds after the previous
  237. # ended.
  238. #
  239. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  240. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  241. # manual or firmware-run dry is untouched.
  242. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  243. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  244. # Sustained-humidity wait (#2518): an above-threshold streak is only
  245. # "continuous" if some pass observed it within the gap ceiling. A unit that
  246. # goes unobserved longer (print running, printer disconnected, sensor silent)
  247. # restarts its streak rather than inheriting a stale one. The ceiling is
  248. # derived from the scheduler cadence — four missed passes — with this floor so
  249. # a fast-polling configuration does not void streaks on a single hiccup.
  250. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  251. # How long a finished scheduled drying row is kept before it is pruned.
  252. SCHEDULED_DRYING_RETENTION_DAYS = 7
  253. # How often that prune actually runs. The check itself is called on every queue
  254. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  255. # write transaction, which SQLite serialises against every other writer. Rows
  256. # only become prunable a week after they finish, so anything short of hourly is
  257. # paying that cost for nothing.
  258. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  259. class _UploadProgressBridge:
  260. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  261. ``upload_file_async`` runs the FTP transfer in an executor thread and
  262. invokes its ``progress_callback`` from that thread, so the callback
  263. body cannot ``await`` directly. This bridge captures the asyncio loop
  264. at construction (on the scheduler thread) and uses
  265. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  266. matches the legacy background_dispatch.py path 1:1 so the toast feels
  267. identical to the pre-#1625 experience.
  268. Failures inside the emit are swallowed — progress is a UX nicety, the
  269. upload itself must not fail because of a WS hiccup.
  270. """
  271. def __init__(self, user_id: int | None, queue_item_id: int):
  272. self._user_id = user_id
  273. self._queue_item_id = queue_item_id
  274. try:
  275. self._loop = asyncio.get_running_loop()
  276. except RuntimeError:
  277. self._loop = None
  278. self._last_emit_bytes = 0
  279. self._last_emit_monotonic = 0.0
  280. self._has_emitted = False
  281. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  282. if self._loop is None or total_bytes <= 0:
  283. return
  284. now = time.monotonic()
  285. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  286. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  287. # the four matter most: first-call so the user sees something even
  288. # for sub-chunk-size files; uploaded >= total so the bar locks at
  289. # 100% even when the throttle would otherwise eat it.
  290. should_emit = (
  291. not self._has_emitted
  292. or bytes_transferred >= total_bytes
  293. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  294. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  295. )
  296. if not should_emit:
  297. return
  298. self._has_emitted = True
  299. self._last_emit_bytes = bytes_transferred
  300. self._last_emit_monotonic = now
  301. try:
  302. asyncio.run_coroutine_threadsafe(
  303. ws_manager.send_queue_item_upload_progress(
  304. user_id=self._user_id,
  305. queue_item_id=self._queue_item_id,
  306. bytes_transferred=bytes_transferred,
  307. total_bytes=total_bytes,
  308. ),
  309. self._loop,
  310. )
  311. except Exception:
  312. pass # progress is best-effort, never block the upload
  313. # Bambu firmware states that mean the project_file has actually been accepted
  314. # and the printer is now processing / running / paused mid-print. Used by the
  315. # dispatch watchdog (#1370): a transition into one of these states means the
  316. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  317. # a post-print prompt) is NOT a valid "command landed" signal even though the
  318. # state value did change. SLICING is included because some firmwares park
  319. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  320. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  321. # How many times the start-watchdog may revert an item to 'pending' before it
  322. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  323. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  324. # both never recovers and starves the other printers of dispatch slots. Three
  325. # is chosen to clear the transient causes the watchdog already recovers from —
  326. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  327. # force-reconnect on the very next attempt — while still bounding the loop.
  328. DISPATCH_MAX_ATTEMPTS = 3
  329. # Upload failures that mean the file never reached the printer's storage: the
  330. # file service refused or never answered (#3210). These put the item back in
  331. # the queue instead of failing it, because nothing about the job is wrong --
  332. # and failing it left the printer idle, so the next pass handed it the next
  333. # item, which failed the same way. One P2S whose file service was out of
  334. # connection slots ate 43 queued jobs in ten minutes that way.
  335. #
  336. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  337. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  338. # and an upload that overran its deadline -- each of those would fail the same
  339. # way on every retry.
  340. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  341. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  342. )
  343. # How long a printer whose upload was put back stays out of dispatch (#3210).
  344. # The first window matches the FTP client's own handshake cool-off, so the
  345. # retry lands after the client would talk to the printer again anyway. Each
  346. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  347. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  348. # five connection attempts and a page of log. A successful upload resets it.
  349. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  350. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  351. def _upload_backoff_seconds(refusals: int) -> int:
  352. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  353. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  354. @dataclass(slots=True)
  355. class _ModelCandidate:
  356. """One (file, printer model) pair the model-based matcher may try.
  357. Model-based assignment used to have exactly one of these per item, held
  358. directly in the item's own columns. Cross-model queue items (#671) have
  359. several, held in ``print_queue_variants``. Both shapes are normalised into
  360. this so the matching, the cross-model gate and the waiting-reason handling
  361. are written once and an item without variants provably takes the same path
  362. it took before variants existed.
  363. ``variant`` is None for the item's own columns and set for a real variant
  364. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  365. item once that candidate wins.
  366. """
  367. target_model: str | None
  368. sliced_for: str | None
  369. required_filament_types: str | None
  370. filament_overrides: str | None
  371. variant: "PrintQueueVariant | None" = None
  372. def _sliced_for_model(archive, library_file) -> str | None:
  373. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  374. if archive is not None:
  375. return archive.sliced_for_model
  376. if library_file is not None and library_file.file_metadata:
  377. return library_file.file_metadata.get("sliced_for_model")
  378. return None
  379. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  380. """The filament a candidate needs, as ``(types, overrides)``.
  381. Both columns are JSON text written by the slicer step. Malformed content is
  382. treated as no constraint rather than as an error: a job whose overrides
  383. cannot be parsed still prints, it just gets no filament-based narrowing.
  384. Overrides carry their own types, so the returned type list is the union of
  385. the two — an override on one slot must not drop the requirements of the
  386. slots it says nothing about.
  387. Shared by the matcher and by the smart-plug wake step so both ask a printer
  388. for the same filament (#2876). Waking a printer the matcher would then
  389. reject on colour is the bug this exists to prevent.
  390. """
  391. required_types = None
  392. if candidate.required_filament_types:
  393. try:
  394. required_types = json.loads(candidate.required_filament_types)
  395. except json.JSONDecodeError:
  396. pass
  397. filament_overrides = None
  398. if candidate.filament_overrides:
  399. try:
  400. filament_overrides = json.loads(candidate.filament_overrides)
  401. except json.JSONDecodeError:
  402. pass
  403. effective_types = required_types
  404. if filament_overrides:
  405. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  406. if override_types:
  407. effective_types = sorted(set(required_types or []) | set(override_types))
  408. return effective_types, filament_overrides
  409. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  410. """Whether ``item`` was competing for the printer another item just took.
  411. The SJF starvation guard marks a job as jumped when a shorter one lower in
  412. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  413. compete for the same printer, so the guard has to look across both lanes
  414. (#3200); looking only inside the dispatched item's own lane let a stream of
  415. short model-based jobs hold a longer pinned job back indefinitely.
  416. Location filters are not checked: over-marking only lifts an item that was
  417. going to wait anyway, while under-marking is the starvation this prevents.
  418. """
  419. if item.printer_id is not None:
  420. return item.printer_id == printer_id
  421. if not printer_model:
  422. return False
  423. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  424. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  425. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  426. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  427. """Candidate files for ``item``, best first.
  428. An item with no variant rows yields exactly one candidate built from its own
  429. columns — the pre-#671 behaviour, unchanged.
  430. Variants come back least-attempted first, ties broken by the user's
  431. ``position``. On the first pass every count is zero, so this is purely the
  432. user's priority order. After a start-watchdog bounce the printer that failed
  433. drops behind, so the next lap tries the other machine rather than spending the
  434. item's whole retry budget on the one that is wedged. Once every candidate has
  435. been tried equally often they cycle again, which keeps the item-level
  436. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  437. still gives up, it just does not give up without trying them.
  438. """
  439. if not item.variants:
  440. if not item.archive_id and not item.library_file_id:
  441. # Nothing to print at all. Dispatching would fail deep in the upload
  442. # on "No archive_id or library_file_id"; the caller holds the item
  443. # with an explanation instead.
  444. return []
  445. return [
  446. _ModelCandidate(
  447. target_model=item.target_model,
  448. sliced_for=_sliced_for_model(item.archive, item.library_file),
  449. required_filament_types=item.required_filament_types,
  450. filament_overrides=item.filament_overrides,
  451. )
  452. ]
  453. # Drop candidates whose file is gone or in the trash. Both are reachable and
  454. # neither is covered by the schema: library deletes are soft (the row lives
  455. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  456. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  457. # fires there and a hard delete leaves the variant row pointing at nothing.
  458. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  459. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  460. return [
  461. _ModelCandidate(
  462. target_model=v.target_model,
  463. sliced_for=_sliced_for_model(None, v.library_file),
  464. required_filament_types=v.required_filament_types,
  465. filament_overrides=v.filament_overrides,
  466. variant=v,
  467. )
  468. for v in ordered
  469. ]
  470. # Why a job for any printer of a model waits when every free one's last print
  471. # failed. The queue page matches it to offer Resume for the model.
  472. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  473. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  474. """Fold one waiting reason per candidate into a single line for the item.
  475. A cross-model item produces a reason per candidate, and pasting them
  476. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  477. — on which machine?). Each reason is prefixed with its model, except in the
  478. single-candidate case where the item already displays its target model and
  479. the prefix would be noise.
  480. Identical reasons collapse rather than repeat, so three idle-less models
  481. read as one clause.
  482. When *every* candidate is merely busy the parts are joined with the ``" | "``
  483. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  484. unprefixed. That case must keep testing busy-only: a fleet that is simply
  485. printing needs no user action, and labelling the clauses would turn each pass
  486. over a two-model item into a "job waiting" notification.
  487. """
  488. reasons = [(model, reason) for model, reason in per_model if reason]
  489. if not reasons:
  490. return None
  491. if len(reasons) == 1:
  492. return reasons[0][1]
  493. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  494. if len(distinct) == 1:
  495. return distinct[0]
  496. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  497. return " | ".join(distinct)
  498. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  499. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  500. """Human label for the models an item is waiting on ("H2S or H2C").
  501. Notifications take a single target model. For a cross-model item the item's
  502. own ``target_model`` is whichever variant happens to be first, which reads as
  503. a lie once it is the H2C that actually runs — so name all of them.
  504. """
  505. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  506. if not models:
  507. return None
  508. return " or ".join(models)
  509. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  510. """True if ``mapping`` is a non-empty list whose every entry is the
  511. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  512. Such a mapping is a bug artifact: a frontend status-load race can serialize
  513. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  514. recomputed from live status at dispatch rather than trusted, otherwise it
  515. reaches the print command and is silently downgraded to external-spool mode.
  516. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  517. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  518. explicit external selection (``>= 254``) is NOT unresolved either — those
  519. keep their meaning.
  520. """
  521. if not isinstance(mapping, list) or not mapping:
  522. return False
  523. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  524. def _is_tray_id(value: object) -> bool:
  525. """True when ``value`` can be read as a global tray ID.
  526. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  527. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  528. against whatever happens to be loaded there.
  529. """
  530. return isinstance(value, int) and not isinstance(value, bool)
  531. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  532. # stages an item (#2799). The manual_start branch clears every other reason on
  533. # a staged item (#3074); this one is the reason it was staged, so it stays.
  534. _UNMATCHED_HOLD_PREFIX = "Needs "
  535. # How often an "any model" job held for low filament looks for another printer
  536. # of its model that has enough (#3137). Each look matches its filament on every
  537. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  538. _SHORT_HOLD_RECHECK_SECONDS = 120
  539. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  540. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  541. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  542. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  543. """The item's force_color_match overrides as filament requirements (#3280).
  544. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  545. read, so the checks after it judge the same list.
  546. """
  547. try:
  548. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  549. except (json.JSONDecodeError, TypeError):
  550. return []
  551. if not isinstance(overrides, list):
  552. return []
  553. return [
  554. {
  555. "slot_id": o.get("slot_id"),
  556. "type": o.get("type", ""),
  557. "color": o.get("color", ""),
  558. "tray_info_idx": o.get("tray_info_idx", ""),
  559. "force_color_match": True,
  560. }
  561. for o in overrides
  562. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  563. ]
  564. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  565. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  566. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  567. for a filament this plate does not use. A slot past the end of the mapping
  568. is unresolved too.
  569. """
  570. unresolved = []
  571. for req in required:
  572. slot_id = req.get("slot_id") or 0
  573. if slot_id <= 0:
  574. continue
  575. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  576. if not _is_tray_id(tray) or tray < 0:
  577. unresolved.append(req)
  578. return unresolved
  579. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  580. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  581. # on `_mapping_is_all_unresolved`.
  582. _EXTERNAL_TRAY_ID_MIN = 254
  583. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  584. """The ``mapping`` entries for the slots this plate actually prints.
  585. ``required`` comes from ``extract_filament_requirements``, which drops any
  586. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  587. consumes, and one absent from it is padding. That distinction is why this
  588. decision lives here and not in the MQTT command builder: a ``-1`` in the
  589. mapping means either "this plate does not print filament N" or "we never
  590. worked out which tray", and only the plate's own filament list separates
  591. them. The builder sees both as the same byte, which is how a plate whose one
  592. printed filament sat on the external spool went out as `use_ams=true` with a
  593. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  594. with 07FF_8012 (#3087).
  595. Returns None whenever the two cannot be lined up — no mapping, no parsed
  596. requirements, or a requirement the mapping is too short to cover — so every
  597. caller falls back to existing behaviour rather than acting on a guess.
  598. """
  599. if not isinstance(mapping, list) or not mapping or not required:
  600. return None
  601. entries = []
  602. for filament in required:
  603. slot_id = filament.get("slot_id")
  604. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  605. # The mapping and the requirements disagree about how many filaments
  606. # the file has. They came from different reads, so judge nothing.
  607. return None
  608. entries.append(mapping[slot_id - 1])
  609. return entries or None
  610. def _is_external_tray(tray_id) -> bool:
  611. """True for an explicit external-spool selection (254/255), not for an
  612. unresolved slot and not for an AMS tray."""
  613. if tray_id is None:
  614. return False
  615. try:
  616. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  617. except (TypeError, ValueError):
  618. return False
  619. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  620. """Whether this printer could have two extruders, judged generously.
  621. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  622. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  623. why the MQTT command builder skips its own use_ams reconcile there. Anything
  624. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  625. with, external spools or not.
  626. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  627. behaviour it has always had, while a wrong "no" would rewrite a field that
  628. steers which nozzle prints. The model name is the first answer (it is what
  629. the command builder falls back to as well), then the same live evidence the
  630. dispatcher's extruder annotation uses — a second nozzle reporting a
  631. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  632. since a single-nozzle printer has exactly one.
  633. """
  634. if is_dual_nozzle_model(printer_model):
  635. return True
  636. nozzles = getattr(status, "nozzles", None) or []
  637. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  638. return True
  639. raw = getattr(status, "raw_data", None) or {}
  640. if raw.get("ams_extruder_map"):
  641. return True
  642. vt_trays = raw.get("vt_tray") or []
  643. return isinstance(vt_trays, list) and len(vt_trays) > 1
  644. def _int_or(value, default: int) -> int:
  645. """``int(value)``, or ``default`` when the field is missing or junk.
  646. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  647. the next — and a tray id that fails to parse must not take the whole
  648. derivation down with it.
  649. """
  650. try:
  651. return int(value)
  652. except (TypeError, ValueError):
  653. return default
  654. # What a queue job's dispatch is worked out from, and an edit can change.
  655. _DISPATCH_INPUTS = (
  656. "printer_id",
  657. "status",
  658. "ams_mapping",
  659. "plate_id",
  660. "filament_overrides",
  661. "skip_filament_check",
  662. "target_model",
  663. "target_location",
  664. )
  665. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  666. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  667. The pass works on the jobs as loaded at its start, and it may have waited
  668. since: a plug powering a printer on takes minutes. A job edited meanwhile
  669. (moved to another printer, given a mapping or another plate, cancelled)
  670. is left to the next pass, which reads it fresh: deciding from the stale
  671. copy would overwrite the edit, or send the job where it no longer goes.
  672. The query flushes the pass's own pending changes first, so those don't
  673. count as edits.
  674. """
  675. row = (
  676. await db.execute(
  677. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  678. )
  679. ).one_or_none()
  680. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  681. return False
  682. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  683. return True
  684. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  685. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  686. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  687. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  688. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  689. agree or a mapping cannot be read back against live tray telemetry.
  690. """
  691. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  692. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  693. """The global tray ids ``item`` actually prints from, or None if unknown.
  694. ``ams_mapping`` is the array the print command carries: position = filament
  695. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  696. not use. None means "no usable statement" — no mapping, unparseable JSON,
  697. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  698. documents), or one that resolves to no tray at all. Callers must treat None
  699. as "consider every loaded tray" rather than "consider none": narrowing on
  700. an absent mapping would silently drop requirements the print really has.
  701. """
  702. raw = getattr(item, "ams_mapping", None)
  703. if not raw:
  704. return None
  705. if isinstance(raw, str):
  706. try:
  707. mapping = json.loads(raw)
  708. except (json.JSONDecodeError, TypeError):
  709. return None
  710. else:
  711. mapping = raw
  712. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  713. return None
  714. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  715. return used or None
  716. def _mqtt_commands_rejected(status) -> bool:
  717. """True when the printer is currently reporting that it refused a command.
  718. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  719. a control command it could not verify. Queries still answer, so the printer
  720. looks connected and idle while project_file, gcode_line and
  721. ams_change_filament are all dropped — no amount of waiting or re-uploading
  722. changes that (#2732).
  723. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  724. ``print_error`` path builds HMSError differently), so this is safe to call on
  725. every watchdog poll.
  726. """
  727. for err in getattr(status, "hms_errors", None) or []:
  728. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  729. return True
  730. return False
  731. def _drying_ams_ids(status) -> list[int]:
  732. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  733. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  734. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  735. started (#2758) — it is a diagnostic, not a gate.
  736. Deliberately not used to block or stop drying before dispatch. This printer
  737. class supports drying concurrently with an active print
  738. (``supports_drying_while_printing``), so drying is not incompatible with
  739. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  740. while two AMS units were drying, one of them without its external PSU. Until
  741. it is known whether the blocker is drying itself or the power budget
  742. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  743. hardware is perfectly happy to continue.
  744. """
  745. ids: list[int] = []
  746. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  747. if not isinstance(unit, dict):
  748. continue
  749. try:
  750. if int(unit.get("dry_time") or 0) > 0:
  751. ids.append(int(unit.get("id", 0)))
  752. except (TypeError, ValueError):
  753. continue
  754. return ids
  755. def _parse_diameter(raw) -> float | None:
  756. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  757. try:
  758. value = float(raw)
  759. except (TypeError, ValueError):
  760. return None
  761. return value if value > 0 else None
  762. def _nozzle_info_by_id(status) -> dict[int, dict]:
  763. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  764. The field name is historical: on the H2 series ``nozzle_info`` carries an
  765. entry for *every* nozzle the printer knows about — the L/R hotends under
  766. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  767. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  768. :func:`_installed_nozzle_diameters` each take the half they need.
  769. """
  770. by_id: dict[int, dict] = {}
  771. for entry in getattr(status, "nozzle_rack", None) or []:
  772. if not isinstance(entry, dict):
  773. continue
  774. try:
  775. by_id[int(entry.get("id"))] = entry
  776. except (TypeError, ValueError):
  777. continue
  778. return by_id
  779. # What the firmware puts in a nozzle's serial number when the carriage or dock
  780. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  781. # its nozzle back in the rack (#2885).
  782. _EMPTY_NOZZLE_SERIAL = "N/A"
  783. def _nozzle_is_mounted(entry: dict | None) -> bool:
  784. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  785. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  786. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  787. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  788. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  789. the dock. So the diameter is not a presence signal (#2885).
  790. Emptiness has to be stated, not merely unstated. The serial must be the
  791. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  792. absent — an empty serial only means the printer didn't say, and a firmware
  793. that reports neither field normalises to exactly that. Treating "didn't
  794. say" as "empty" would silently switch the #1899 guard off on any such
  795. machine, so everything we cannot positively call empty counts as mounted.
  796. """
  797. if entry is None:
  798. return True
  799. serial = str(entry.get("serial_number") or "").strip().upper()
  800. if serial != _EMPTY_NOZZLE_SERIAL:
  801. return True
  802. try:
  803. max_temp = float(entry.get("max_temp") or 0)
  804. except (TypeError, ValueError):
  805. return True
  806. return max_temp > 0
  807. def _installed_nozzle_diameters(status) -> list[float]:
  808. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  809. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  810. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  811. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  812. told us its nozzle hardware" — callers must treat that as unknown, not as a
  813. mismatch, so we never block a print on missing data.
  814. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  815. though ``nozzles`` still carries a diameter for it: that value is stale, and
  816. counting it would let a slice match a nozzle the machine does not have
  817. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  818. """
  819. info = _nozzle_info_by_id(status)
  820. diameters: list[float] = []
  821. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  822. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  823. try:
  824. value = float(raw)
  825. except (TypeError, ValueError):
  826. continue
  827. if value > 0 and _nozzle_is_mounted(info.get(index)):
  828. diameters.append(value)
  829. return diameters
  830. def _rack_nozzle_diameters(status) -> list[float]:
  831. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  832. Keyed off the nozzle ids themselves rather than the printer model: only a
  833. rack machine ever reports ids 16-21, so there is no model registry to keep
  834. in sync. An empty dock is simply absent from the payload — measured on an
  835. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  836. present — so appearing here already means "a nozzle is in that dock".
  837. ``stat`` is deliberately not interpreted: its values aren't known, and
  838. reading it wrongly could hide a nozzle the printer would happily fetch.
  839. """
  840. diameters: list[float] = []
  841. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  842. if nozzle_id not in _RACK_NOZZLE_IDS:
  843. continue
  844. # PrinterState spells it "diameter"; the REST schema renames it to
  845. # "nozzle_diameter". Accept either so a caller holding the serialised
  846. # shape gets the same answer.
  847. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  848. if value is not None:
  849. diameters.append(value)
  850. return diameters
  851. def _format_diameters(diameters: list[float]) -> str:
  852. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  853. Deduplicated because a loaded rack holds several nozzles of the same size,
  854. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  855. short form doesn't. Matching still runs over the full list.
  856. """
  857. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  858. def _nozzle_mismatch_message(
  859. sliced_nozzle: float | None,
  860. installed: list[float],
  861. rack: list[float] | None = None,
  862. ) -> str | None:
  863. """Return an actionable error message when the sliced nozzle can't be
  864. printed on any nozzle the machine can reach, else None (#1899).
  865. Fail-safe: returns None whenever we lack the data to judge — no sliced
  866. diameter, or the printer reported no nozzles — so a print is only ever
  867. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  868. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  869. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  870. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  871. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  872. as reachable: the printer fetches one as part of starting the print, so a
  873. slice that matches a docked nozzle is not a mismatch. Without this the
  874. guard blocked every job whose nozzle happened not to be on a hotend at
  875. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  876. diameter already mounted could ever print, and the user had to fetch the
  877. nozzle by hand on the printer's own UI first (#2885).
  878. """
  879. reachable = [*installed, *(rack or [])]
  880. if not sliced_nozzle or not reachable:
  881. return None
  882. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  883. return None
  884. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  885. if rack:
  886. where += f" and {_format_diameters(rack)} in the nozzle rack"
  887. return (
  888. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  889. f"{where}. Re-slice for an available nozzle, or fit the matching "
  890. f"nozzle before printing."
  891. )
  892. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  893. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  894. Shared by the required and loaded sides, which name their extruder
  895. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  896. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  897. 1 the left/deputy — and both are absent on single-nozzle printers, where
  898. naming a nozzle would be noise.
  899. """
  900. parts = [(entry.get("type") or "filament").upper()]
  901. if entry.get("color"):
  902. parts.append(str(entry["color"]))
  903. nozzle = entry.get(nozzle_key)
  904. if nozzle == 0:
  905. parts.append("(right nozzle)")
  906. elif nozzle == 1:
  907. parts.append("(left nozzle)")
  908. return " ".join(parts)
  909. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  910. """Explain that nothing loaded matches what the file needs (#2771).
  911. Only ever built for a printer with no AMS, where the loaded list is short
  912. enough to quote in full and there is no "load another spool and hit Resume"
  913. recovery — the external spool holder is all there is, so the user needs to
  914. be told which filament to put on it.
  915. """
  916. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  917. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  918. return (
  919. f"No filament loaded on this printer matches the file. It needs {want}; "
  920. f"the printer has {have} and no AMS. Load the required filament on the "
  921. f"external spool holder, or send this job to a printer that has it."
  922. )
  923. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  924. """Bed temperature for the plate a queued job prints, 0 when unknown.
  925. The archive stores the highest bed temperature of any filament in the
  926. project, while the job may print another plate than the one archived: a
  927. PLA plate of a project that also holds PETG is heated for PLA. Read from
  928. the archive's file for the job's own plate, falling back to the stored
  929. value when the file can't be read.
  930. """
  931. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  932. if archive is None or not archive.file_path:
  933. return stored
  934. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  935. return temperature or stored
  936. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  937. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  938. every call site below it: G-code injection, usage registration, rack-plan
  939. lookup, slot-extruder lookup, the external-spool check, and the actual
  940. print command.
  941. A positive explicit ``plate_id`` on the queue item always wins. A
  942. non-positive one is treated as "not set" and resolved from the archive,
  943. the way the rest of the queue code already reads it (``if item.plate_id:``
  944. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  945. field, and passing a 0 straight through would build a print command for
  946. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  947. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  948. Falling back to a bare ``1`` instead of reading the archive assumes a
  949. single-plate file's one G-code is numbered 1, which only holds for a
  950. plate exported on its own: one cut out of a larger project keeps its
  951. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  952. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  953. the file, throws an HMS error, and sits wedged in IDLE until
  954. power-cycled (#2947).
  955. The call sites agreed on a fallback only by accident before this:
  956. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  957. the archive's own default plate internally whenever the plate id it's
  958. handed isn't in the file, so it could silently inject into a different
  959. plate than the one the print command itself asked for.
  960. Falls back to 1 when the archive can't be read, holds no G-code member at
  961. all, or its default member doesn't follow the ``plate_N`` naming
  962. convention (a slicer that doesn't use it has no number to dispatch).
  963. An explicit plate the archive doesn't hold is logged and then sent
  964. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  965. to a plate that is in the file would print a model nobody asked for,
  966. which is the worse of the two.
  967. """
  968. try:
  969. with zipfile.ZipFile(file_path, "r") as zf:
  970. names = zf.namelist()
  971. except (OSError, zipfile.BadZipFile) as exc:
  972. logger.warning(
  973. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  974. "is unavailable; dispatching plate %s",
  975. file_path,
  976. exc,
  977. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  978. )
  979. names = None
  980. if explicit_plate_id is not None and explicit_plate_id > 0:
  981. if (
  982. names is not None
  983. and default_plate_number(names) is not None
  984. and select_plate_gcode_name(names, explicit_plate_id) is None
  985. ):
  986. logger.warning(
  987. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  988. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  989. "file, since printing a different plate would print the wrong model (#2947)",
  990. file_path,
  991. explicit_plate_id,
  992. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  993. explicit_plate_id,
  994. )
  995. return explicit_plate_id
  996. resolved = default_plate_number(names) if names is not None else None
  997. return resolved if resolved is not None else 1
  998. class PrintScheduler:
  999. """Background scheduler that processes the print queue."""
  1000. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  1001. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  1002. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  1003. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  1004. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  1005. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  1006. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1007. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1008. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1009. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1010. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1011. }
  1012. def __init__(self):
  1013. self._running = False
  1014. self._check_interval = 30 # seconds
  1015. # After a pass that actually dispatched something, loop again almost
  1016. # immediately instead of sleeping the full interval (#2555). A dispatch
  1017. # changes printer state — a batch launch fans out over several passes as
  1018. # printers free up, a wedged head-of-line job reverts to pending, an
  1019. # upload slot opens — and the next batch of ready work should not have to
  1020. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1021. # pending items are behind printers that are genuinely busy printing),
  1022. # there is nothing to react to, so we fall back to the normal interval;
  1023. # that also means this can never tight-loop, since fast ticks only
  1024. # continue while dispatches keep happening and the queue is draining.
  1025. self._fast_check_interval = 3 # seconds
  1026. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1027. self._power_on_check_interval = 10 # seconds between connection checks
  1028. # Printers whose class-target power-on failed, mapped to the monotonic
  1029. # time their cool-off expires (#2786).
  1030. #
  1031. # Without this, one printer with an unreachable plug starves every
  1032. # sibling of its model forever: the wake step walks candidates in id
  1033. # order, spends the pass's single attempt on the same broken printer
  1034. # every time, and the healthy one two slots down is never reached. It
  1035. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1036. # which delays the whole queue, not just this job.
  1037. #
  1038. # Entries expire on read rather than being cleared on success: a printer
  1039. # inside its cool-off is skipped before the power-on is reached, so a
  1040. # live entry can never be overwritten by a success anyway. A printer
  1041. # that comes back by any other route stops being a wake candidate the
  1042. # moment it connects.
  1043. self._wake_failures: dict[int, float] = {}
  1044. self._wake_failure_cooloff = 600 # seconds
  1045. # Printers whose last upload never reached them, mapped to the monotonic
  1046. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1047. # as `_wake_failures`. Without it, a printer that cannot take files is
  1048. # idle on every pass, so it is picked on every pass.
  1049. self._upload_backoff: dict[int, float] = {}
  1050. # Refused uploads in a row per printer, which sets the next backoff
  1051. # window. Cleared by a successful upload to that printer.
  1052. self._upload_refusals: dict[int, int] = {}
  1053. # Printers whose current run of refusals has already sent its one
  1054. # "job waiting" notification. Each retry clears the item's waiting
  1055. # reason and the next refusal sets it again, which `hold_item` reads as
  1056. # a new reason; without this, every retry would notify. Cleared with
  1057. # `_upload_refusals`.
  1058. self._upload_refusal_notified: set[int] = set()
  1059. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1060. self._drying_in_progress: dict[int, float] = {}
  1061. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1062. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1063. # cycle and the humidity finally coming down, so the normal steady
  1064. # state is an empty dict. Fields:
  1065. # running — a cycle we armed is (or should be) on the firmware
  1066. # ended_at — monotonic when we observed that cycle end
  1067. # unproductive — consecutive armed cycles that ended with the reading
  1068. # still above the threshold
  1069. # suspended — we have stopped arming this unit and said so
  1070. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1071. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1072. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1073. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1074. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1075. # arming setdefault all act on that meaning -- a unit that is merely
  1076. # waiting out its streak must not become stoppable or judgeable.
  1077. # since -- monotonic stamp when the current continuous above-threshold
  1078. # streak began
  1079. # last -- monotonic stamp of the last pass that observed the streak
  1080. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1081. # Slots already notified as low on filament:
  1082. # {(printer_id, ams_id, tray_id, spool_id)}.
  1083. # Cleared when the slot goes back above its threshold rather than on a
  1084. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1085. # boundary must not produce an alert on every pass, and a slot that has
  1086. # been refilled has to be able to alert again. See #2913.
  1087. #
  1088. # The spool id is part of the key because the slot alone cannot clear
  1089. # itself. Pull a low spool and put a different part-used one in the same
  1090. # slot: the key survives the pass where the slot resolves to nothing --
  1091. # deliberately, so a brief Spoolman outage does not re-alert everything
  1092. # when it returns -- and the replacement never goes above the threshold,
  1093. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1094. # different key and the stale one is inert.
  1095. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1096. # The same, for the MQTT relay's filament/low event: its own record, so
  1097. # one channel having been told never silences the other.
  1098. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1099. # Earliest monotonic time the next low-filament check may run (#2913).
  1100. self._filament_low_next_check: float = 0.0
  1101. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1102. # condition is "reorder" or "break", the events are those that had a
  1103. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1104. # condition clears, so it can alert again, and when nobody wants either
  1105. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1106. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1107. # re-send one message per SKU that is still low.
  1108. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1109. # The JSON last read from or written to that row; None until it has been read.
  1110. self._stock_alerts_persisted: str | None = None
  1111. # Earliest monotonic time the next stock forecast check may run (#2955).
  1112. self._stock_forecast_next_check: float = 0.0
  1113. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1114. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1115. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1116. # both features share _drying_in_progress.
  1117. self._scheduled_drying_printer_ids: set[int] = set()
  1118. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1119. # the first pass after a restart reaps anything left behind.
  1120. self._last_scheduled_drying_prune: float | None = None
  1121. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1122. # a project_file command must not get a second dispatch until either it
  1123. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1124. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1125. # during that window the DB busy_printers seed is empirically unreliable
  1126. # (multi-plate batches double-/triple-dispatched onto the same printer
  1127. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1128. # or revert.
  1129. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1130. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1131. # Minimum cooldown between dispatches to the same printer (covers the
  1132. # H2D's project_file digestion window).
  1133. self._dispatch_min_cooldown = 60.0
  1134. # Hard timeout — drop the hold even if we never observed a transition,
  1135. # so a lost MQTT session can't lock a printer out of the queue forever.
  1136. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1137. # watchdog runs first on the unhappy path.
  1138. self._dispatch_max_hold = 180.0
  1139. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1140. # an earlier pass and is still running. `_start_print` flips the row
  1141. # pending -> printing only *after* the upload completes, so until then
  1142. # the row stays `pending`: each tick, check_queue excludes these
  1143. # item_ids from re-selection and their printers from new dispatch /
  1144. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1145. # freed slots refill on the next fast tick. check_queue is the sole,
  1146. # sequential caller and the prune done-callbacks run in the same
  1147. # event-loop thread, so this dict needs no lock.
  1148. # item_id -> (task, printer_id)
  1149. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1150. # Expected prints registered by `_start_print` that have not yet had a
  1151. # print command sent. Populated at registration, dropped once
  1152. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1153. # other exit. Same threading argument as `_inflight` above: one
  1154. # sequential caller, callbacks on the same loop, so no lock.
  1155. # item_id -> (printer_id, remote_filename, archive_id)
  1156. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1157. # Budget reservations created for a dispatch whose print command has
  1158. # not been confirmed yet. `_dispatch_one` releases these on every
  1159. # unsuccessful exit; a successful start removes the item id and leaves
  1160. # the reservation for finance_billing to consume with the archive.
  1161. self._unconfirmed_budget_reservations: set[int] = set()
  1162. # The print user `_start_print` handed to printer_manager for an item
  1163. # whose print command has not been sent yet (item_id -> printer_id).
  1164. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1165. # expected print above: it marks the printer's next print as Bambuddy's.
  1166. self._unconfirmed_print_user: dict[int, int] = {}
  1167. # Prints whose command went out but which the printer has not been
  1168. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1169. # the file and archive None for a library print. The watchdog drops the
  1170. # entry once the print runs, and withdraws what it stands for when the
  1171. # print never starts (see `_forget_unstarted_print`).
  1172. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1173. # Chamber temperature history for smart soak-time reduction.
  1174. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1175. # Entries older than _chamber_history_ttl are pruned on write.
  1176. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1177. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1178. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1179. # Populated on engagement in `_apply_keep_warm`, cleared by
  1180. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1181. # when a gate setting toggles off mid-hold — the release publishes
  1182. # bed → 0 first).
  1183. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1184. # Preheat rollback registry: printer_id -> subset of
  1185. # {"bed", "chamber", "airduct"} listing which preheat commands
  1186. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1187. # every entry still present at exit unless the print successfully
  1188. # started, so a failed upload / cancel / exception never leaves the
  1189. # printer heating for a job that isn't happening.
  1190. self._preheat_pin: dict[int, set[str]] = {}
  1191. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1192. # rollback can tell its own target from one someone else has since
  1193. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1194. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1195. self._preheat_pin_bed: dict[int, int] = {}
  1196. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1197. # its preheat was still holding at temperature. Set by
  1198. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1199. # `_preheat_sleep`, and cleared when the dispatch exits.
  1200. self._cancelled_dispatches: set[int] = set()
  1201. # printer_id -> monotonic time it was first seen terminal while one of
  1202. # its queue rows was still 'printing'. Reset by any non-terminal
  1203. # observation, so it measures an unbroken run rather than a total.
  1204. # In-memory on purpose: a restart re-arms the grace period, which only
  1205. # delays a recovery that is already the exceptional path (#2829).
  1206. self._terminal_since: dict[int, float] = {}
  1207. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1208. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1209. # across idle printers repeats that for every one of them in a single
  1210. # pass. Cleared at the top of each pass so a re-sliced file is never
  1211. # served from a previous tick.
  1212. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1213. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1214. # matcher about every idle candidate, and a pass can ask again for the
  1215. # same job and printer (another variant, a previous-print retry, the
  1216. # low-filament move). Cleared with the requirement memo.
  1217. self._unmatched_memo: dict[tuple, list[str]] = {}
  1218. # When each "any model" job held for low filament last looked for
  1219. # another printer (#3137), by queue item id.
  1220. self._short_hold_checked_at: dict[int, float] = {}
  1221. async def run(self):
  1222. """Main loop - check queue every interval."""
  1223. self._running = True
  1224. logger.info("Print scheduler started")
  1225. await self._clear_stale_dispatch_claims(at_startup=True)
  1226. while self._running:
  1227. dispatched = False
  1228. try:
  1229. self._sample_chamber_temps()
  1230. # No-op while any upload is in flight; on a quiet tick it releases
  1231. # a claim whose best-effort clear failed (e.g. the database was
  1232. # briefly unreachable), instead of leaving the row wedged until
  1233. # the next restart.
  1234. await self._clear_stale_dispatch_claims()
  1235. await self._close_stranded_printing_items()
  1236. dispatched = await self.check_queue()
  1237. except Exception as e:
  1238. logger.error("Scheduler error: %s", e)
  1239. # Re-check quickly after a productive pass so a draining batch does
  1240. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1241. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1242. async def _close_stranded_printing_items(self) -> None:
  1243. """Close a ``printing`` row the completion event never closed (#2829).
  1244. ``on_print_complete`` refuses to close a row when the completion's
  1245. subtask name disagrees with the file the row was dispatched with, so a
  1246. completion meant for something else (the printer's own
  1247. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1248. The refusal has no way back, though: nothing else ever closes the row,
  1249. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1250. one bad comparison wedges that printer's queue until a human presses
  1251. cancel. That is what #2829's reporters hit, and the guard's own
  1252. docstring already called stranding the worse of the two failures.
  1253. This is the way back. When a row has been ``printing`` while its
  1254. printer sat in a terminal state for the whole grace period, the print
  1255. is over however the event was read, and the row is closed with the
  1256. status the printer's own state implies.
  1257. Deliberately conservative:
  1258. * Only a connected printer counts. A disconnected one has a stale
  1259. ``state`` and proves nothing.
  1260. * The clock is reset by any non-terminal observation, so this cannot
  1261. fire on a printer that is merely between stages.
  1262. * The grace period is far longer than the gap between a printer
  1263. finishing and its completion arriving, so the normal path always
  1264. wins the race and this only ever sees genuine strandings.
  1265. What it does *not* do is replay the completion's side effects --
  1266. notifications, billing, auto-off. It restores the queue, which is the
  1267. harm being undone; the archive was updated by the normal path
  1268. regardless, since only the queue block refuses. A recovery that
  1269. silently re-fired notifications minutes late would be its own bug.
  1270. """
  1271. try:
  1272. async with async_session() as db:
  1273. result = await db.execute(
  1274. select(PrintQueueItem)
  1275. .where(PrintQueueItem.status == "printing")
  1276. .where(PrintQueueItem.printer_id.is_not(None))
  1277. )
  1278. items = list(result.scalars().all())
  1279. if not items:
  1280. self._terminal_since.clear()
  1281. return
  1282. now = time.monotonic()
  1283. seen_printers: set[int] = set()
  1284. closed = False
  1285. for item in items:
  1286. printer_id = item.printer_id
  1287. seen_printers.add(printer_id)
  1288. state = printer_manager.get_status(printer_id)
  1289. status = _terminal_queue_status(state)
  1290. if status is None:
  1291. self._terminal_since.pop(printer_id, None)
  1292. continue
  1293. since = self._terminal_since.setdefault(printer_id, now)
  1294. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1295. continue
  1296. item.status = status
  1297. item.completed_at = datetime.now(timezone.utc)
  1298. closed = True
  1299. # The printer is idle: nothing it prints next is this item's.
  1300. self._forget_unstarted_print(item.id, unless_printing=True)
  1301. logger.warning(
  1302. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1303. "closing it as %s. Its completion event was never matched to it, which blocks "
  1304. "every later job for this printer (#2829).",
  1305. item.id,
  1306. printer_id,
  1307. getattr(state, "state", None),
  1308. now - since,
  1309. status,
  1310. )
  1311. if closed:
  1312. await db.commit()
  1313. from backend.app.services.print_batch import refresh_batches_after
  1314. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1315. for printer_id in list(self._terminal_since):
  1316. if printer_id not in seen_printers:
  1317. del self._terminal_since[printer_id]
  1318. except Exception as e:
  1319. # Best-effort, same as the claim sweep beside it: a recovery path
  1320. # that can itself break the scheduler loop is worse than the strand.
  1321. logger.error("Stranded-item sweep failed: %s", e)
  1322. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1323. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1324. A claim is only ever held by a live dispatch coroutine, so when this
  1325. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1326. is stale. At startup that is trivially true — no coroutine survives a
  1327. restart. It is equally true on any later tick where no upload is running,
  1328. which is what makes this safe to repeat rather than only run once.
  1329. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1330. the database is briefly unreachable at exactly the moment dispatch ends,
  1331. the claim survives and the row is wedged out of the selection query. That
  1332. used to last until the next restart (#2702 follow-up, seen when
  1333. PostgreSQL refused a connection mid-dispatch).
  1334. ``_inflight`` is populated when the task is spawned, before the coroutine
  1335. claims its row, and pruned by a done-callback that cannot run before the
  1336. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1337. race window and needs no age threshold. A size-derived upload deadline
  1338. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1339. """
  1340. if self._inflight:
  1341. return
  1342. try:
  1343. async with async_session() as db:
  1344. res = await db.execute(
  1345. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1346. )
  1347. await db.commit()
  1348. if res.rowcount:
  1349. logger.info(
  1350. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1351. res.rowcount,
  1352. " at startup" if at_startup else "",
  1353. )
  1354. except Exception as exc:
  1355. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1356. def stop(self):
  1357. """Stop the scheduler."""
  1358. self._running = False
  1359. logger.info("Print scheduler stopped")
  1360. def forget_printer(self, printer_id: int) -> None:
  1361. """Drop what is kept for a deleted printer, so the next printer given its
  1362. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1363. would keep it out of dispatch for up to an hour.
  1364. A dispatch already in flight keeps its own state (_inflight, the preheat
  1365. pins, unconfirmed prints): it unwinds that when it ends.
  1366. """
  1367. for keyed in (
  1368. self._upload_backoff,
  1369. self._upload_refusals,
  1370. self._wake_failures,
  1371. self._drying_in_progress,
  1372. self._dispatch_holds,
  1373. self._chamber_history,
  1374. self._keep_warm,
  1375. self._terminal_since,
  1376. ):
  1377. keyed.pop(printer_id, None)
  1378. self._upload_refusal_notified.discard(printer_id)
  1379. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1380. for key in [key for key in keyed if key[0] == printer_id]:
  1381. del keyed[key]
  1382. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1383. del self._sent_unstarted_print[item_id]
  1384. async def check_queue(self) -> bool:
  1385. """Check for prints ready to start.
  1386. Returns True if this pass dispatched at least one item, so the caller
  1387. can loop again quickly instead of sleeping the full interval (#2555).
  1388. """
  1389. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1390. self._filament_req_memo.clear()
  1391. self._unmatched_memo.clear()
  1392. async with async_session() as db:
  1393. # Check if shortest-job-first scheduling is enabled
  1394. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1395. # Get all pending items in the one order the queue page shows them
  1396. # in (#3200). The first eligible item takes a printer, so this order
  1397. # decides who wins a printer that a pinned job and an "Any <model>"
  1398. # job both want. It used to start with ``printer_id``, which made the
  1399. # lane outrank the position: SQLite sorts NULL first, so model-based
  1400. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1401. # Neither is what the user dragged into place.
  1402. if sjf_enabled:
  1403. # SJF: items already jumped get top priority (starvation guard),
  1404. # then sort by print_time ascending. Items with no print time go
  1405. # last, and position breaks ties.
  1406. result = await db.execute(
  1407. select(PrintQueueItem)
  1408. .where(PrintQueueItem.status == "pending")
  1409. # Never re-select a row a dispatch worker has already claimed
  1410. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1411. # below, and the guard that lets an orphaned claim be ignored
  1412. # until startup reconciliation clears it.
  1413. .where(PrintQueueItem.dispatching_at.is_(None))
  1414. # archive/library_file are read by the cross-model gate
  1415. # (#2578); eager-load once per pass instead of a lazy-load
  1416. # (which would raise in async) per item.
  1417. .options(
  1418. selectinload(PrintQueueItem.archive),
  1419. selectinload(PrintQueueItem.library_file),
  1420. # Cross-model candidates (#671), plus each candidate's file
  1421. # for the same cross-model gate. Lazy-loading either would
  1422. # raise in async.
  1423. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1424. )
  1425. .order_by(
  1426. PrintQueueItem.been_jumped.desc(),
  1427. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1428. PrintQueueItem.position,
  1429. PrintQueueItem.id,
  1430. )
  1431. )
  1432. else:
  1433. result = await db.execute(
  1434. select(PrintQueueItem)
  1435. .where(PrintQueueItem.status == "pending")
  1436. # Skip rows already claimed by a dispatch worker (#2615).
  1437. .where(PrintQueueItem.dispatching_at.is_(None))
  1438. .options(
  1439. selectinload(PrintQueueItem.archive),
  1440. selectinload(PrintQueueItem.library_file),
  1441. # Cross-model candidates (#671), plus each candidate's file
  1442. # for the same cross-model gate. Lazy-loading either would
  1443. # raise in async.
  1444. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1445. )
  1446. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1447. )
  1448. items = list(result.scalars().all())
  1449. # Drop rows whose upload is still in flight from an earlier pass
  1450. # (#2602). They stay `pending` until the upload finishes, so without
  1451. # this a fast tick would re-select and re-dispatch the same row.
  1452. # Belt-and-suspenders with the printer exclusion below.
  1453. if self._inflight:
  1454. inflight_ids = set(self._inflight)
  1455. items = [it for it in items if it.id not in inflight_ids]
  1456. # Read plate-clear setting once per queue check. Default MUST be
  1457. # False to match the schema (SettingsSchema.require_plate_clear
  1458. # defaults False) and the frontend (toggle + card badge both treat a
  1459. # missing value as off). When no settings row exists, a True default
  1460. # here re-enabled the plate-clear gate the UI showed as disabled,
  1461. # blocking dispatch to FINISH-state printers forever with no UI path
  1462. # to clear it (#1865).
  1463. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1464. # Dispatch and track scheduled drying runs (#2638)
  1465. await self._check_scheduled_dryings(db)
  1466. if not items:
  1467. # No dispatchable pending items — still check auto-drying on idle
  1468. # printers, but keep any printer with an upload still in flight
  1469. # from an earlier pass out of it (#2602): its print is imminent,
  1470. # so it must not be auto-dried in the gap before the row flips to
  1471. # printing. Report the pass as productive while uploads run so the
  1472. # loop stays on the fast interval.
  1473. #
  1474. # Also release any keep-warm holds that got orphaned by the queue
  1475. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1476. # this early return, so call it directly with an empty candidate
  1477. # set. Without this, a printer whose queued item was cancelled or
  1478. # deleted would keep its bed at target until the max-duration
  1479. # timeout expired.
  1480. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1481. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1482. await self._check_auto_drying(db, [], inflight_printers)
  1483. await self._check_filament_low(db)
  1484. await self._check_stock_forecast(db)
  1485. return bool(self._inflight)
  1486. logger.info(
  1487. "Queue check: found %d pending items: %s",
  1488. len(items),
  1489. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1490. )
  1491. # Forget jobs that left the queue since they were last checked.
  1492. pending_ids = {i.id for i in items}
  1493. self._short_hold_checked_at = {
  1494. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1495. }
  1496. # Seed busy_printers with printers that already have an item in 'printing'
  1497. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1498. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1499. # lag several seconds behind the print command, so the next check_queue
  1500. # tick still sees IDLE and would double-dispatch onto the same printer.
  1501. # Without this guard, two pending items targeting the same printer
  1502. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1503. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1504. busy_result = await db.execute(
  1505. select(PrintQueueItem.printer_id)
  1506. .where(PrintQueueItem.status == "printing")
  1507. .where(PrintQueueItem.printer_id.is_not(None))
  1508. )
  1509. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1510. # Why each printer left this pass, recorded where the decision is
  1511. # made rather than re-derived when the summary is logged. #3018's
  1512. # bundle shows what the old summary produced: "printer 1 not
  1513. # available -- connected=True, state=IDLE" immediately followed by a
  1514. # dispatch to printer 1. Two things went wrong at once. The line read
  1515. # live state at log time, which by then no longer matched the state
  1516. # the decision was made on; and `busy_printers` holds both printers
  1517. # that cannot take work and printers this pass has claimed for it,
  1518. # which are opposite facts. It is the first line anyone greps for
  1519. # "why did my item not go out", so it has to say which.
  1520. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1521. # Printers this pass is dispatching to. They are in busy_printers so
  1522. # nothing else in the pass targets them -- that is a reservation, not
  1523. # an obstruction, and the summary says so.
  1524. claimed_printers: set[int] = set()
  1525. def mark_busy(printer_id: int, reason: str) -> None:
  1526. """Take ``printer_id`` out of this pass, recording why.
  1527. First reason wins: a printer already excluded by a stronger fact
  1528. -- a print running on it -- must not be relabelled by a weaker
  1529. check that ran later and would have excluded it anyway.
  1530. """
  1531. busy_printers.add(printer_id)
  1532. busy_reasons.setdefault(printer_id, reason)
  1533. def claim_printer(printer_id: int) -> None:
  1534. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1535. claimed_printers.add(printer_id)
  1536. mark_busy(printer_id, "selected for dispatch in this pass")
  1537. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1538. # worded for a different audience: the log wants "still inside its
  1539. # post-dispatch hold window", the queue row wants to know the printer
  1540. # is taken and nothing is broken. Only the cases that would read wrong
  1541. # as a plain "Busy" are recorded here; the rest fall back to it.
  1542. item_hold_reasons: dict[int, str] = {}
  1543. # Names and models for the printers this pass may have to write a
  1544. # waiting reason about, read once rather than per skip per tick. The
  1545. # model-based branch already has its names from `_printers_for_model`.
  1546. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1547. pinned_printers: dict[int, tuple[str, str]] = {}
  1548. if pinned_printer_ids:
  1549. pinned_rows = await db.execute(
  1550. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1551. )
  1552. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1553. def printer_label(printer_id: int) -> str:
  1554. """What to call this printer in a queue row."""
  1555. entry = pinned_printers.get(printer_id)
  1556. return (entry[0] if entry else "") or f"printer {printer_id}"
  1557. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1558. """Record why *item* is not going out, in the words the queue row shows.
  1559. The fixed-printer branch's single writer for ``waiting_reason``
  1560. (#3074). Before this, the sensor interlock was the only thing that
  1561. wrote the field there, so an item pinned to a printer that was
  1562. merely printing sat at `pending` with nothing to show for it —
  1563. indistinguishable from a queue that had stopped working — while
  1564. the same job queued as "Any <model>" explained itself.
  1565. Every exit from that branch now calls this, which is also what
  1566. replaced the interlock's old habit of clearing the field up front:
  1567. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1568. because whichever exit runs next overwrites it and the dispatch
  1569. path clears it.
  1570. A notification goes out when this item starts asking for
  1571. something, and only then: the new reason needs the user, and what
  1572. it replaced did not. "What it replaced did not" has to include a
  1573. busy-only reason, not just an empty one. The sequence this branch
  1574. actually produces is a print running (``Busy: X1C-01``) and then
  1575. the plate it left behind (``Waiting for plate confirmation``), and
  1576. testing "was the field empty" would call that no transition at all
  1577. and stay quiet through the one case worth saying out loud.
  1578. The cost is that a printer dropping offline, coming back busy and
  1579. dropping again asks twice rather than once. That is the honest
  1580. reading — it went wrong twice — and the alternative was a rule
  1581. that never fired for the case this was built for.
  1582. *notify* is how a caller opts out. The sensor interlock does: it
  1583. has never sent this notification, and a change about what the
  1584. queue *displays* is not the place to start (#1148).
  1585. """
  1586. if item.waiting_reason == reason:
  1587. return
  1588. # Busy-only and empty are the same thing here: neither is the
  1589. # queue asking the user for anything.
  1590. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1591. item.waiting_reason = reason
  1592. await db.commit()
  1593. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1594. return
  1595. try:
  1596. job_name = await self._get_job_name(db, item)
  1597. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1598. await notification_service.on_queue_job_waiting(
  1599. job_name=job_name,
  1600. target_model=(entry[1] if entry else "") or "",
  1601. waiting_reason=reason,
  1602. db=db,
  1603. printer_id=item.printer_id,
  1604. )
  1605. except Exception as e:
  1606. # A queue that cannot say why it is waiting is the bug being
  1607. # fixed here; a queue that stops dispatching because a
  1608. # notification provider is down would be a worse one.
  1609. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1610. async def hold_for_printer(
  1611. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1612. ) -> None:
  1613. """Take *printer_id* out of this pass and tell the item's owner why."""
  1614. mark_busy(printer_id, log_reason)
  1615. item_hold_reasons.setdefault(printer_id, item_reason)
  1616. await hold_item(item, item_reason)
  1617. # Defense-in-depth (#1157): augment busy_printers with any printer
  1618. # still in its post-dispatch hold window. Empirically, the DB seed
  1619. # above can miss in-flight items in a multi-plate batch — same-file
  1620. # plates were being dispatched 30 s apart while the H2D was still
  1621. # digesting the first project_file. The hold is keyed in-memory and
  1622. # released by the watchdog on the success path, so it adds a layer
  1623. # that doesn't depend on DB row visibility or completion-callback
  1624. # timing.
  1625. for held_printer_id in list(self._dispatch_holds.keys()):
  1626. if self._printer_in_dispatch_hold(held_printer_id):
  1627. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1628. # Exclude printers whose upload is still in flight from an earlier
  1629. # pass (#2602). The row is `pending` until the upload finishes and
  1630. # the printing-state seed / dispatch hold above only arm once the
  1631. # upload completes, so this is what holds the printer (and, via
  1632. # busy_printers, its auto-drying) out of the pass during the upload.
  1633. for _task, inflight_pid in self._inflight.values():
  1634. if inflight_pid is not None:
  1635. mark_busy(inflight_pid, "an upload to it is still in flight")
  1636. # Snapshot taken here, before the item loop adds anything (#2801).
  1637. #
  1638. # The three sources above all mean the same thing: a print on this
  1639. # printer is running or imminent. Everything the loop adds below
  1640. # means only "the queue could not dispatch to it this pass", which
  1641. # is a different statement -- a printer waiting on a plate-clear
  1642. # acknowledgment, an offline printer, one with no matching file.
  1643. #
  1644. # Auto-drying must only see the first kind. Reading the whole set
  1645. # as "is currently printing" is what put a plate-held printer down
  1646. # the mid-print path: it capped the drying temperature, logged the
  1647. # cycle as (mid-print), and skipped the very gate that was supposed
  1648. # to hold it. The interlock block below already documents the same
  1649. # hazard and works around it by staying out of busy_printers; this
  1650. # generalises that workaround instead of repeating it per case.
  1651. dispatching_printers: set[int] = set(busy_printers)
  1652. # Printers whose last upload never reached them (#3210). After the
  1653. # snapshot above on purpose: such a printer is idle, not about to
  1654. # print, and auto-drying must keep treating it as idle.
  1655. now_mono = time.monotonic()
  1656. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1657. # can leave them out: there is no print to keep a bed warm for.
  1658. backoff_printers: set[int] = set()
  1659. # In backoff, and the "job waiting" notification for this run of
  1660. # refusals has gone out already. Their holds are written silently.
  1661. silent_hold_printers: set[int] = set()
  1662. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1663. if now_mono >= retry_at:
  1664. del self._upload_backoff[backoff_pid]
  1665. continue
  1666. backoff_printers.add(backoff_pid)
  1667. if backoff_pid in self._upload_refusal_notified:
  1668. silent_hold_printers.add(backoff_pid)
  1669. else:
  1670. self._upload_refusal_notified.add(backoff_pid)
  1671. mark_busy(
  1672. backoff_pid,
  1673. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1674. )
  1675. item_hold_reasons.setdefault(
  1676. backoff_pid,
  1677. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1678. )
  1679. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1680. # enclosure door left open, say. The fixed-printer branch turns
  1681. # this into a waiting_reason the user can act on; the model-based
  1682. # branch hides these printers from the matcher so an "Any <model>"
  1683. # job runs on a sibling instead of queueing behind the held one.
  1684. #
  1685. # Deliberately NOT merged into busy_printers, even though that set
  1686. # already means "unavailable this pass". _check_auto_drying reads
  1687. # it as "is currently printing" and would put an idle-but-held
  1688. # printer down the mid-print drying path, which caps the drying
  1689. # temperature and skips the queue-only gating. A held printer is
  1690. # idle; it should dry exactly as it did before.
  1691. #
  1692. # Only sensors we actually read and found alerting appear here; see
  1693. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1694. # holds nothing.
  1695. interlocked: dict[int, str] = {}
  1696. try:
  1697. interlocked = await ha_sensor_manager.blocked_printers(db)
  1698. except Exception as e:
  1699. # Never let the interlock stop the queue running. A broken
  1700. # lookup means no holds, not no dispatches.
  1701. logger.warning("Home Assistant interlock check failed: %s", e)
  1702. interlocked = {}
  1703. # Printers a smart plug can bring back, read once for the whole pass
  1704. # (#2786). Used by the model-based branch both to word "Offline" in
  1705. # the waiting reason and to decide what the wake step may switch on.
  1706. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1707. # At most one power-on per queue check. Each one blocks this loop
  1708. # for the boot wait, so a queue of ten class-targeted jobs must not
  1709. # switch on ten printers inside a single pass — the next pass wakes
  1710. # the next one (#2786).
  1711. power_on_attempted = False
  1712. # Log skip reasons once per queue check (not per item)
  1713. skip_reasons: dict[str, int] = {}
  1714. # Items selected for dispatch in this pass, one per printer. The
  1715. # loop below only *decides* — the uploads happen afterwards, in
  1716. # parallel (#2555). See _dispatch_selected().
  1717. dispatch_ids: list[int] = []
  1718. # Library rows queued with `cleanup_library_after_dispatch` (the
  1719. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1720. # that prints them: the row is deleted and the 3MF is unlinked from
  1721. # disk. That was safe only because dispatch was serial. Run two of
  1722. # them against the same row at once and the second DELETE matches no
  1723. # row (StaleDataError), and the winner's unlink can pull the file out
  1724. # from under the loser's in-flight upload.
  1725. #
  1726. # Only the cleanup flag mutates the row. An ordinary library print
  1727. # just reads it, so the common fan-out — one file, many printers,
  1728. # which is exactly the reporter's workload — still goes out fully in
  1729. # parallel. Narrow the guard to the mutating case; do not serialise
  1730. # the case the whole fix exists for.
  1731. dispatch_libs: set[int] = set()
  1732. consumed_libs: set[int] = set()
  1733. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1734. """True if dispatching `candidate` now would race another item's cleanup."""
  1735. lib_id = candidate.library_file_id
  1736. if lib_id is None:
  1737. return False
  1738. if candidate.cleanup_library_after_dispatch:
  1739. # We would delete a row someone else in this pass is reading.
  1740. return lib_id in dispatch_libs
  1741. # Someone else in this pass will delete the row out from under us.
  1742. return lib_id in consumed_libs
  1743. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1744. lib_id = candidate.library_file_id
  1745. if lib_id is None:
  1746. return
  1747. dispatch_libs.add(lib_id)
  1748. if candidate.cleanup_library_after_dispatch:
  1749. consumed_libs.add(lib_id)
  1750. # Printer scope of each job's creator (#1727), so an "any <model>"
  1751. # job only lands on a printer its creator may use. Loaded lazily,
  1752. # once per creator per pass.
  1753. from backend.app.core.auth import is_auth_enabled
  1754. scope_auth_enabled = await is_auth_enabled(db)
  1755. creator_scopes: dict[int, PrinterScope] = {}
  1756. # Printers a model job passes over while drying blocks the queue,
  1757. # as a pinned job waits for its own. A parked timer never ends,
  1758. # so it does not hold (#2896).
  1759. drying_held: set[int] = (
  1760. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1761. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1762. else set()
  1763. )
  1764. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1765. if not scope_auth_enabled or user_id is None:
  1766. return ALL_PRINTERS
  1767. if user_id not in creator_scopes:
  1768. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1769. return creator_scopes[user_id]
  1770. for item in items:
  1771. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1772. if item.scheduled_time:
  1773. sched = item.scheduled_time
  1774. if sched.tzinfo is None:
  1775. sched = sched.replace(tzinfo=timezone.utc)
  1776. if sched > datetime.now(timezone.utc):
  1777. # Waiting on the clock, not on a printer.
  1778. await hold_item(item, None)
  1779. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1780. continue
  1781. # Skip items that require manual start, except an "any model"
  1782. # job held for low filament that another idle printer can now
  1783. # run: that one is moved there and carries on below (#3137).
  1784. if item.manual_start and not (
  1785. item.filament_short
  1786. and await self._release_short_model_hold(
  1787. db,
  1788. item,
  1789. busy_printers | interlocked.keys() | drying_held,
  1790. require_plate_clear,
  1791. await _creator_scope(item.created_by_id),
  1792. )
  1793. ):
  1794. # Waiting on the user, not on a printer. Cleared here because
  1795. # this is the last pass that will look at the row: a staged
  1796. # item never reaches the branches below again, so a reason
  1797. # left from before it was staged would stand forever (#3074).
  1798. # The one exception is the unmatched-filament hold, whose
  1799. # reason was written at staging and is why the item waits:
  1800. # it names the filament to load (#2799). Pressing start
  1801. # clears manual_start, and the branches below overwrite it.
  1802. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1803. await hold_item(item, keep)
  1804. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1805. continue
  1806. if item.printer_id and item.printer_id not in pinned_printers:
  1807. # Moved by the release above to a printer no row named when
  1808. # the labels were read.
  1809. moved_to = await self._get_printer(db, item.printer_id)
  1810. if moved_to is not None:
  1811. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1812. if item.printer_id:
  1813. # Its creator may no longer use this printer (#1727): an
  1814. # admin took it away from their group after the job was
  1815. # queued, say to keep it free for a training session. Held,
  1816. # not failed, so it starts if access comes back or the user
  1817. # moves it to a printer they still have.
  1818. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1819. await hold_item(
  1820. item,
  1821. "Its owner no longer has access to this printer — move it to another printer",
  1822. notify=False,
  1823. )
  1824. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1825. continue
  1826. # Held by a sensor interlock (#1148). Checked before the
  1827. # busy_printers test that would otherwise swallow it
  1828. # silently — "waiting for a printer" and "waiting for you
  1829. # to shut the enclosure" need to read differently, and only
  1830. # one of them is something the user can fix.
  1831. #
  1832. # It used to be the only thing that wrote a waiting_reason on
  1833. # this branch, and it cleared the field up front so a lifted
  1834. # hold could not leave a shut door reading "Waiting on
  1835. # Enclosure Door". `hold_item` carries that guarantee now —
  1836. # every exit below writes — so the clear is gone and the
  1837. # interlock is an ordinary hold like the rest (#3074).
  1838. interlock_reason = interlocked.get(item.printer_id)
  1839. if interlock_reason:
  1840. # Silent, exactly as it has always been. #1148 built this
  1841. # as a hold that shows on the row, never as an alert, and
  1842. # routing it through the shared writer must not quietly
  1843. # turn every open door into a notification.
  1844. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1845. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1846. continue
  1847. # Specific printer assignment (existing behavior)
  1848. if item.printer_id in busy_printers:
  1849. # Whatever took the printer out of this pass — a print
  1850. # already running on it, a post-dispatch hold, an upload
  1851. # still in flight, an item ahead of this one in the same
  1852. # pass — reads the same way from the queue: the printer is
  1853. # taken and this item is in line for it. The exceptions
  1854. # that do not (an offline printer, say) recorded their own
  1855. # wording in `item_hold_reasons` when they held it.
  1856. await hold_item(
  1857. item,
  1858. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1859. notify=item.printer_id not in silent_hold_printers,
  1860. )
  1861. continue
  1862. # Check if printer is idle
  1863. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1864. printer_connected = printer_manager.is_connected(item.printer_id)
  1865. # If printer not connected, try to power on via smart plug
  1866. if not printer_connected:
  1867. plugs = await self._get_smart_plugs(db, item.printer_id)
  1868. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1869. if auto_on_plugs:
  1870. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1871. # Power on using the plug that actually feeds the printer, and
  1872. # wait for it to boot on that one only (#2629).
  1873. primary_plug = self._pick_power_plug(auto_on_plugs)
  1874. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1875. if powered_on:
  1876. # Also turn on any remaining auto_on plugs (e.g., filter)
  1877. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1878. try:
  1879. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1880. if await service.turn_on(extra_plug):
  1881. await publish_plug_state(
  1882. extra_plug.id,
  1883. extra_plug.name,
  1884. extra_plug.printer_id,
  1885. on=True,
  1886. ha_entity_id=extra_plug.ha_entity_id,
  1887. )
  1888. logger.info(
  1889. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1890. )
  1891. except Exception as e:
  1892. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1893. printer_connected = True
  1894. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1895. else:
  1896. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1897. await hold_for_printer(
  1898. item,
  1899. item.printer_id,
  1900. "smart-plug power-on failed",
  1901. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1902. )
  1903. continue
  1904. else:
  1905. # No plug or auto_on disabled. Worded exactly as the
  1906. # model-based branch words it (#2786): this is the one
  1907. # entry on that list the user has to act on, because
  1908. # Bambuddy will never switch this printer on itself.
  1909. await hold_for_printer(
  1910. item,
  1911. item.printer_id,
  1912. "offline, with no smart plug to power it on",
  1913. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1914. )
  1915. continue
  1916. # Check if printer is idle (busy with another print)
  1917. if not printer_idle:
  1918. await hold_for_printer(
  1919. item,
  1920. item.printer_id,
  1921. "not idle",
  1922. self._pinned_hold_reason(
  1923. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1924. ),
  1925. )
  1926. continue
  1927. # Drying blocks the queue, if the user asked it to. A hold
  1928. # is a skip like any other, so it belongs here with the
  1929. # rest of the availability checks.
  1930. # A parked timer (#2896) never ends, so it must not hold the
  1931. # queue; it stays tracked so the stop paths still reach it.
  1932. if (
  1933. self._drying_in_progress.get(item.printer_id)
  1934. and not self._drying_is_only_parked(item.printer_id)
  1935. and await self._get_bool_setting(db, "queue_drying_block")
  1936. ):
  1937. # Busy-shaped on purpose: the cycle ends on its own and
  1938. # the job goes out, so there is nothing to alert about.
  1939. await hold_for_printer(
  1940. item,
  1941. item.printer_id,
  1942. "drying, and drying is set to block the queue",
  1943. f"Busy: {printer_label(item.printer_id)} (drying)",
  1944. )
  1945. continue
  1946. # Check condition (previous print success)
  1947. if item.require_previous_success:
  1948. if not await self._check_previous_success(db, item):
  1949. item.status = "skipped"
  1950. item.error_message = "Previous print failed or was aborted"
  1951. item.completed_at = datetime.now(timezone.utc)
  1952. # Not pending any more, so not waiting for anything.
  1953. item.waiting_reason = None
  1954. await db.commit()
  1955. logger.info("Skipped queue item %s - previous print failed", item.id)
  1956. # Send notification
  1957. job_name = await self._get_job_name(db, item)
  1958. printer = await self._get_printer(db, item.printer_id)
  1959. await notification_service.on_queue_job_skipped(
  1960. job_name=job_name,
  1961. printer_id=item.printer_id,
  1962. printer_name=printer.name if printer else "Unknown",
  1963. reason="Previous print failed or was aborted",
  1964. db=db,
  1965. )
  1966. continue
  1967. # Resolve the AMS mapping when it's missing OR unresolved
  1968. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1969. # frontend status-load race can persist [-1] (#2589) — and
  1970. # must be recomputed from live trays rather than trusted.
  1971. if await _edited_since_loaded(db, item):
  1972. continue
  1973. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1974. if unmappable:
  1975. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1976. continue
  1977. # Filament-deficit pre-dispatch check (#1496). If the
  1978. # assigned spool can't satisfy any required slot grams,
  1979. # promote the item to manual_start so the user must
  1980. # acknowledge via the ▶ button (which re-checks live).
  1981. if await self._block_on_filament_deficit(db, item):
  1982. # Now staged for the user to start by hand, and the row
  1983. # shows the filament-short badge instead. Cleared because
  1984. # a staged item never reaches this branch again.
  1985. await hold_item(item, None)
  1986. continue
  1987. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1988. # than let the printer pick a substitute for a slot the
  1989. # matcher could not resolve on this printer.
  1990. if await self._block_on_unmatched_filament(db, item):
  1991. continue
  1992. # Hold this item back for the next pass rather than racing
  1993. # another dispatch over the same transient library row. The
  1994. # printer is still marked busy so a later item does not jump
  1995. # its place in this printer's queue.
  1996. if _library_row_conflict(item):
  1997. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1998. await hold_for_printer(
  1999. item,
  2000. item.printer_id,
  2001. "holding its place while another item releases a library row",
  2002. f"Busy: {printer_label(item.printer_id)}",
  2003. )
  2004. continue
  2005. # Print takes priority: stop a cycle Bambuddy armed, now
  2006. # that this item is definitely going out.
  2007. #
  2008. # Placement is the whole point (#2801). This used to sit up
  2009. # with the availability checks, inside the not-idle branch
  2010. # -- so it fired only on the passes where the print was NOT
  2011. # going to start, and never on the ones where it was.
  2012. # Drying is not one of the things `_is_printer_idle` looks
  2013. # at, so a stop could never have unblocked that printer
  2014. # anyway; the cycle was spent for nothing, auto-drying
  2015. # re-armed on the next tick, and a plate left
  2016. # unacknowledged turned that into a loop on the scheduler
  2017. # interval. Every skip between there and here -- a failed
  2018. # previous print, an unmappable item, a filament deficit, a
  2019. # contested library row -- is another way to lose a cycle
  2020. # for a print that never happens, which is why this waits
  2021. # until the decision is actually made.
  2022. if self._drying_in_progress.get(
  2023. item.printer_id
  2024. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2025. await self._stop_drying(item.printer_id)
  2026. # Queue the dispatch instead of running it here — see
  2027. # _dispatch_selected(). busy_printers still gets the printer
  2028. # immediately, so nothing else in this pass can target it.
  2029. #
  2030. # The reason goes first: this item is not waiting for anything
  2031. # any more, and the model-based branch clears its own at the
  2032. # equivalent moment (#3074).
  2033. await hold_item(item, None)
  2034. _claim_library_row(item)
  2035. dispatch_ids.append(item.id)
  2036. claim_printer(item.printer_id)
  2037. # SJF starvation guard: mark items that were jumped
  2038. if sjf_enabled and item.print_time_seconds is not None:
  2039. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2040. for other in items:
  2041. if (
  2042. other.id != item.id
  2043. and other.id not in dispatch_ids
  2044. and other.status == "pending"
  2045. and _could_take_printer(other, item.printer_id, pinned_model)
  2046. and not other.been_jumped
  2047. and other.position < item.position
  2048. and (
  2049. other.print_time_seconds is None
  2050. or other.print_time_seconds > item.print_time_seconds
  2051. )
  2052. ):
  2053. other.been_jumped = True
  2054. await db.commit()
  2055. elif item.target_model or item.variants:
  2056. # Model-based assignment - find any idle printer of matching model.
  2057. # A plain model-based item has exactly one candidate, built from
  2058. # its own columns. A cross-model item (#671) has one per sliced
  2059. # variant and takes the first that matches, walking them in the
  2060. # user's priority order so the pick is reproducible when more
  2061. # than one printer is free in the same pass.
  2062. candidates = _candidates_for(item)
  2063. item_scope = await _creator_scope(item.created_by_id)
  2064. printer_id = None
  2065. chosen: _ModelCandidate | None = None
  2066. per_model_reasons: list[tuple[str | None, str]] = []
  2067. # Candidates that cleared the cross-model gate below. The
  2068. # smart-plug wake step may only consider these — waking a
  2069. # printer for a file that can never legally run on it is
  2070. # worse than not waking at all (#2786).
  2071. wakeable_candidates: list[_ModelCandidate] = []
  2072. # Printers passed over because their last print failed.
  2073. gate_blocked: set[int] = set()
  2074. if not candidates:
  2075. # Every candidate file has been deleted or trashed out from
  2076. # under this item. Hold it with something the user can act
  2077. # on rather than letting it look dispatchable forever.
  2078. per_model_reasons.append(
  2079. (
  2080. item.target_model,
  2081. "Every file for this job has been deleted — add a file back or remove the item",
  2082. )
  2083. )
  2084. for candidate in candidates:
  2085. effective_types, filament_overrides = _filament_constraints(candidate)
  2086. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2087. # for an incompatible model to a printer, no matter how the
  2088. # row got into the DB (old rows, direct API writes). Held
  2089. # as pending with an actionable waiting_reason — the user
  2090. # fixes it by editing the item's target model.
  2091. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2092. per_model_reasons.append(
  2093. (
  2094. candidate.target_model,
  2095. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2096. f"{candidate.target_model} — edit the item and fix its target model",
  2097. )
  2098. )
  2099. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2100. continue
  2101. wakeable_candidates.append(candidate)
  2102. async def is_short(
  2103. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2104. ) -> bool:
  2105. # The check reads the file and plate off the item,
  2106. # so it must hold this candidate's. Resolving is
  2107. # safe to repeat, and the winner is resolved again
  2108. # below.
  2109. self._resolve_variant(item, candidate)
  2110. return await self._filament_short_on(db, item, pid)
  2111. async def unmatched_on(
  2112. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2113. ) -> list[str]:
  2114. self._resolve_variant(item, candidate)
  2115. return await self._unmatched_on(db, item, pid)
  2116. while True:
  2117. match_id, match_reason = await self._find_idle_printer_for_model(
  2118. db,
  2119. candidate.target_model,
  2120. # Sensor-held printers are unavailable to the
  2121. # matcher but stay out of busy_printers itself
  2122. # (#1148) — see where `interlocked` is built.
  2123. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2124. effective_types,
  2125. item.target_location,
  2126. filament_overrides=filament_overrides,
  2127. require_plate_clear=require_plate_clear,
  2128. wakeable_ids=wakeable_printer_ids,
  2129. printer_scope=item_scope,
  2130. is_short=is_short,
  2131. drying_ids=drying_held,
  2132. unmatched_on=unmatched_on,
  2133. )
  2134. # "Only if the previous print succeeded" is about the
  2135. # printer the job lands on: one whose last print failed
  2136. # is passed over for another of the model.
  2137. if (
  2138. match_id
  2139. and item.require_previous_success
  2140. and not await self._check_previous_success(db, item, printer_id=match_id)
  2141. ):
  2142. gate_blocked.add(match_id)
  2143. continue
  2144. break
  2145. if match_id:
  2146. printer_id = match_id
  2147. chosen = candidate
  2148. break
  2149. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2150. # Nothing is available and nothing has been woken this pass:
  2151. # switch one matching printer on. Assignment is left to the
  2152. # next pass, which sees the booted printer's live state
  2153. # instead of guessing at it seconds after connect (#2786).
  2154. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2155. woken_id, attempted_id = await self._wake_printer_for_model(
  2156. db,
  2157. wakeable_candidates,
  2158. item.target_location,
  2159. busy_printers | interlocked.keys(),
  2160. wakeable_printer_ids,
  2161. require_plate_clear,
  2162. printer_scope=item_scope,
  2163. )
  2164. # An attempt spends the pass's one wake whether or not
  2165. # it worked: it has already blocked the queue loop for
  2166. # the boot wait. A failed printer is held out of later
  2167. # passes by its own cool-off, deliberately NOT by
  2168. # busy_printers — it is off, not busy, and labelling it
  2169. # busy would both misdescribe it in every later item's
  2170. # waiting reason and suppress the notification, since
  2171. # an all-busy reason is treated as needing no action.
  2172. power_on_attempted = attempted_id is not None
  2173. if woken_id is not None:
  2174. # Hold this item back rather than dispatching onto a
  2175. # printer whose AMS has not reported yet.
  2176. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2177. continue
  2178. if printer_id is None and gate_blocked:
  2179. # The matcher reports the printers passed over as busy;
  2180. # what holds the job is their failed last print.
  2181. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2182. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2183. # Fold the winning variant's file and settings onto the item
  2184. # before anything else looks at them — the guards below and
  2185. # every step of the dispatch read the item's own columns.
  2186. if chosen is not None:
  2187. self._resolve_variant(item, chosen)
  2188. # Update waiting_reason if changed and send notification when first waiting
  2189. if item.waiting_reason != waiting_reason:
  2190. was_waiting = item.waiting_reason is not None
  2191. previous_reason = item.waiting_reason
  2192. item.waiting_reason = waiting_reason
  2193. await db.commit()
  2194. # Send waiting notification only when transitioning to waiting state
  2195. # and the reason requires user action (not just "all printers busy")
  2196. # Also when a job that only waited for a busy printer
  2197. # now waits on something the user has to do.
  2198. if (
  2199. waiting_reason
  2200. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2201. and not self._is_busy_only(waiting_reason)
  2202. ):
  2203. job_name = await self._get_job_name(db, item)
  2204. await notification_service.on_queue_job_waiting(
  2205. job_name=job_name,
  2206. target_model=_candidate_model_label(candidates) or item.target_model,
  2207. waiting_reason=waiting_reason,
  2208. db=db,
  2209. )
  2210. if printer_id:
  2211. # Before claiming the printer: hold back rather than race
  2212. # another dispatch over the same transient library row.
  2213. # Checked here so a held item does not get a printer
  2214. # assigned and then sit on it. See _library_row_conflict().
  2215. #
  2216. # No busy_printers.add() here, unlike the fixed-printer
  2217. # branch above: that one protects its printer's own queue
  2218. # ordering, but this item was never assigned to `printer_id`
  2219. # — the matcher merely offered it. Marking it busy would
  2220. # strand an idle printer for the rest of the pass.
  2221. if _library_row_conflict(item):
  2222. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2223. continue
  2224. if await _edited_since_loaded(db, item):
  2225. continue
  2226. # Assign printer and start - clear waiting reason
  2227. item.printer_id = printer_id
  2228. item.waiting_reason = None
  2229. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2230. # Send assignment notification
  2231. job_name = await self._get_job_name(db, item)
  2232. printer = await self._get_printer(db, printer_id)
  2233. await notification_service.on_queue_job_assigned(
  2234. job_name=job_name,
  2235. printer_id=printer_id,
  2236. printer_name=printer.name if printer else "Unknown",
  2237. target_model=item.target_model,
  2238. db=db,
  2239. )
  2240. # A mapping on this item was not made for the printer just
  2241. # picked: it came with a job moved here from a fixed
  2242. # printer, or from a variant. Its tray IDs can name a
  2243. # tray of the right type in another colour here, which
  2244. # the fit check lets through (#3239). Match afresh, by
  2245. # type and colour.
  2246. if item.ams_mapping:
  2247. logger.info(
  2248. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2249. item.id,
  2250. item.ams_mapping,
  2251. printer_id,
  2252. )
  2253. item.ams_mapping = None
  2254. # On a nozzle-rack printer its own nozzle mapping likewise
  2255. # (set through the API or an order's plate spec): it names
  2256. # rack positions, and the dispatch sends a stored one as-is
  2257. # instead of resolving this printer's rack. Elsewhere it
  2258. # holds extruder indices, the same on every printer of the
  2259. # model (an H2D VP keeps the slicer's for that reason), and
  2260. # one that came with the chosen variant belongs to that
  2261. # variant's file: both stay.
  2262. if (
  2263. (chosen is None or chosen.variant is None)
  2264. and printer is not None
  2265. and is_nozzle_rack_model(printer.model)
  2266. ):
  2267. item.nozzle_mapping = None
  2268. # Resolve the AMS mapping for the assigned printer. It is
  2269. # always missing here, so this computes it, and it also
  2270. # self-heals a bogus stored [-1] (#2589).
  2271. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2272. if unmappable:
  2273. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2274. continue
  2275. # Filament-deficit pre-dispatch check (#1496).
  2276. if await self._block_on_filament_deficit(db, item):
  2277. continue
  2278. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2279. # selection already filters on filament type, so this is a
  2280. # backstop for an AMS that changed between assignment and
  2281. # dispatch, and for a type loaded on the wrong nozzle.
  2282. # The assignment made above is released with the hold —
  2283. # this item asked for a model, not this printer.
  2284. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2285. continue
  2286. # As for a pinned job: drying stops once the print is
  2287. # decided, unless it may run through it.
  2288. if self._drying_in_progress.get(
  2289. printer_id
  2290. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2291. await self._stop_drying(printer_id)
  2292. _claim_library_row(item)
  2293. dispatch_ids.append(item.id)
  2294. claim_printer(printer_id)
  2295. # SJF starvation guard: mark items that were jumped
  2296. if sjf_enabled and item.print_time_seconds is not None:
  2297. for other in items:
  2298. if (
  2299. other.id != item.id
  2300. and other.id not in dispatch_ids
  2301. and other.status == "pending"
  2302. and _could_take_printer(other, printer_id, item.target_model)
  2303. and not other.been_jumped
  2304. and other.position < item.position
  2305. and (
  2306. other.print_time_seconds is None
  2307. or other.print_time_seconds > item.print_time_seconds
  2308. )
  2309. ):
  2310. other.been_jumped = True
  2311. await db.commit()
  2312. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2313. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2314. # skip summary that only lands after the transfers have finished is
  2315. # useless for working out why an item did not go out.
  2316. if skip_reasons:
  2317. logger.info("Queue skip summary: %s", skip_reasons)
  2318. for pid in sorted(busy_printers):
  2319. reason = busy_reasons.get(pid, "no reason recorded")
  2320. if pid in claimed_printers:
  2321. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2322. continue
  2323. # The three live fields stay, because they are what someone
  2324. # reading a bundle wants next -- but they are labelled as read
  2325. # now, not as the state the decision was made on, which is what
  2326. # made the old line contradict itself.
  2327. state = printer_manager.get_status(pid)
  2328. logger.info(
  2329. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2330. pid,
  2331. reason,
  2332. printer_manager.is_connected(pid),
  2333. state.state if state else "NO_STATUS",
  2334. printer_manager.is_awaiting_plate_clear(pid),
  2335. )
  2336. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2337. # selection and `_launch_uploads`, so anything raising here would
  2338. # discard this tick's selections — computed AMS mappings and all —
  2339. # and, on a persistent fault, stop the queue dispatching entirely.
  2340. # Same reasoning as the deficit check's guard below: never let an
  2341. # auxiliary check wedge the queue. The bed simply stays wherever it
  2342. # was, and the next tick tries again.
  2343. try:
  2344. await self._apply_keep_warm(
  2345. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2346. )
  2347. except Exception as e:
  2348. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2349. # Read the concurrency limit BEFORE the commit below, not inside
  2350. # _dispatch_selected(). A SELECT on this session after the commit
  2351. # implicitly opens a fresh transaction that nothing then closes, and
  2352. # it would stay open for the whole dispatch — minutes of "idle in
  2353. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2354. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2355. # checkpointed while every dispatch is writing to it.
  2356. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2357. # Selection is done; every decision above is recorded on `db`
  2358. # (model-based printer assignment, computed ams_mapping). Flush it
  2359. # before the dispatch tasks open their own sessions, or they will
  2360. # read a row that still says printer_id=None. This also releases the
  2361. # connection back to the pool for the duration of the dispatch.
  2362. await db.commit()
  2363. if dispatch_ids:
  2364. item_printers = {it.id: it.printer_id for it in items}
  2365. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2366. # Auto-drying: start drying on idle printers that have no pending queue items
  2367. await self._check_auto_drying(db, items, dispatching_printers)
  2368. # Low filament: alert on assigned spools that have crossed their
  2369. # low-stock threshold (#2913). Runs on both paths out of this method
  2370. # for the same reason auto-drying does — an empty queue does not mean
  2371. # the spools in the printers stopped mattering.
  2372. await self._check_filament_low(db)
  2373. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2374. # is about to run out before a replenishment could arrive (#2955).
  2375. await self._check_stock_forecast(db)
  2376. # Keep the loop on the fast interval while any upload is in flight so
  2377. # a slot freed mid-tick refills within seconds rather than after the
  2378. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2379. # deferred because the pool was full) also counts as productive.
  2380. return bool(dispatch_ids) or bool(self._inflight)
  2381. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2382. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2383. Dispatch used to happen inline in the selection loop: ``await
  2384. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2385. performs the FTP upload, that serialized every printer behind every
  2386. other printer's transfer even though the printers are independent
  2387. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2388. gather was awaited before ``check_queue`` returned, so the run loop
  2389. stayed blocked until the *slowest* upload in the batch finished — a
  2390. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2391. 93-printer farm even as other printers came free (#2602).
  2392. Each upload now runs as an independent background task tracked in
  2393. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2394. `pending` until their upload completes) and their printers from the
  2395. next pass's selection, and this method launches at most
  2396. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2397. the next fast tick instead of waiting out the whole batch. The bound
  2398. exists because the printers are independent but the host is not: each
  2399. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2400. file handle.
  2401. The no-overlapping-dispatch invariant the batch-await used to provide
  2402. is now carried by the in-flight exclusion in check_queue. Everything
  2403. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2404. per-printer hold, and each item's independent failure handling — still
  2405. lives in ``_start_print`` and runs per task exactly as before.
  2406. Synchronous on purpose: it registers every launched task into
  2407. ``self._inflight`` before returning, so the next (sequential) tick sees
  2408. an accurate in-flight count with no interleaving await.
  2409. """
  2410. free = limit - len(self._inflight)
  2411. if free <= 0:
  2412. logger.info(
  2413. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2414. len(self._inflight),
  2415. limit,
  2416. len(item_ids),
  2417. item_ids,
  2418. )
  2419. return
  2420. to_launch = item_ids[:free]
  2421. deferred = item_ids[free:]
  2422. logger.info(
  2423. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2424. len(to_launch),
  2425. len(self._inflight),
  2426. limit,
  2427. f" — deferring {deferred} to a later tick" if deferred else "",
  2428. )
  2429. for item_id in to_launch:
  2430. task = spawn_background_task(
  2431. self._dispatch_one(item_id, item_printers.get(item_id)),
  2432. name=f"queue-upload-{item_id}",
  2433. )
  2434. self._inflight[item_id] = (task, item_printers.get(item_id))
  2435. # Prune on completion so the freed slot is refillable next tick.
  2436. # spawn_background_task already logs any uncaught exception; this
  2437. # only reclaims the pool slot (fires on success, failure, or cancel).
  2438. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2439. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2440. """Upload + start one queue item in its own session (pool worker, #2602).
  2441. Its own session: pool workers run concurrently and an AsyncSession is
  2442. not safe to share across tasks; it also keeps a slow upload from pinning
  2443. the scheduler's session (and, on SQLite, its transaction) open for the
  2444. transfer's duration.
  2445. ``selected_printer_id`` is the printer this item was selected for, taken
  2446. from the same snapshot the caller used. It exists so the preheat pin can
  2447. be unwound on the paths that never reach the ``finally`` below — see the
  2448. claim failure a few lines down. Optional so the direct-call tests keep
  2449. working; when it is absent those paths simply behave as they did before.
  2450. """
  2451. async with async_session() as item_db:
  2452. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2453. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2454. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2455. # routes reject reassignment (409), so printer_id can't change out from
  2456. # under the in-flight upload and split the queue row from the
  2457. # archive/expected-print/physical command.
  2458. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2459. logger.info(
  2460. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2461. item_id,
  2462. )
  2463. # This return is outside the try/finally below, so the rollback
  2464. # has to happen here. Selecting this item already handed any
  2465. # keep-warm hold on its printer over to the preheat pin
  2466. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2467. # unwind it. Bailing without doing so leaves the bed hot with
  2468. # nothing tracking it: the keep-warm entry is gone, so the
  2469. # max-duration cap no longer applies, and if this was the
  2470. # printer's last pending item nothing else will ever turn it
  2471. # off. Reachable whenever a cancel or delete lands between
  2472. # selection and the claim.
  2473. if selected_printer_id is not None:
  2474. self._rollback_preheat_pin(item_id, selected_printer_id)
  2475. return
  2476. # Seeded from the caller's snapshot so the `item vanished` return
  2477. # below still unwinds the pin; overwritten with the row's own
  2478. # printer_id as soon as we have it.
  2479. item_printer_id: int | None = selected_printer_id
  2480. try:
  2481. item = await item_db.get(PrintQueueItem, item_id)
  2482. if not item:
  2483. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2484. return
  2485. item_printer_id = item.printer_id
  2486. await self._start_print(item_db, item)
  2487. finally:
  2488. # Undo an expected-print registration whose print command never
  2489. # went out. One choke point covers every way `_start_print` can
  2490. # end without sending: a raised exception (a DB failure mid-
  2491. # dispatch is the reported case), an early return, a cancel
  2492. # winning the #1853 CAS, or `start_print()` returning False.
  2493. # A confirmed send removes the entry itself, so this is a no-op
  2494. # on the happy path.
  2495. self._rollback_unconfirmed_expected_print(item_id)
  2496. # Likewise the print user it set: the printer's next print is
  2497. # not this item's.
  2498. self._rollback_unconfirmed_print_user(item_id)
  2499. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2500. # reservation survives only after start_print() accepted the
  2501. # command. Failure, cancellation, deferral, and exceptions all
  2502. # release it here.
  2503. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2504. # Unwind preheat state (bed/chamber/airduct) if the
  2505. # dispatch aborted before the print's own gcode took over.
  2506. # `_start_print` clears the pin on successful `start_print()`;
  2507. # anything still present here is by definition an aborted
  2508. # dispatch and gets rolled back so the printer isn't left
  2509. # heating for a job that isn't happening.
  2510. if item_printer_id is not None:
  2511. self._rollback_preheat_pin(item_id, item_printer_id)
  2512. # The cancellation flag only has meaning while this dispatch is
  2513. # running; drop it so the set cannot grow without bound and a
  2514. # re-queued item never inherits a stale cancellation.
  2515. self._cancelled_dispatches.discard(item_id)
  2516. # Release the claim on every exit. Once dispatch has finished the
  2517. # row's status carries the lock (printing/failed/cancelled are all
  2518. # != pending), so the token is only needed for the duration of the
  2519. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2520. # dispatchable again on the next tick.
  2521. await self._clear_dispatch_claim(item_db, item_id)
  2522. async def _requeue_after_upload_refused(
  2523. self,
  2524. db: AsyncSession,
  2525. item: PrintQueueItem,
  2526. printer: Printer,
  2527. error_msg: str,
  2528. toast_uid: int | None,
  2529. ) -> None:
  2530. """Put an item back in the queue after its file never reached the printer (#3210).
  2531. The item keeps its printer. Its AMS mapping was computed against that
  2532. printer's trays, and nothing on the row says whether a mapping was
  2533. computed or set by the user, so moving it to a sibling could print from
  2534. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2535. keeps every other item away from it; this one waits there and is the
  2536. only thing that knocks again, once per backoff window. The window
  2537. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2538. `dispatch_attempts` is not charged: that budget bounds a printer that
  2539. takes the file and then never starts, which this is not.
  2540. """
  2541. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2542. self._upload_refusals[printer.id] = refusals
  2543. backoff = _upload_backoff_seconds(refusals)
  2544. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2545. # The row is still `pending` -- it only moves to `printing` after a
  2546. # successful upload -- so there is no status to write back. Writing one
  2547. # anyway would undo a cancel that landed during the upload.
  2548. if item.error_message:
  2549. item.error_message = None
  2550. await db.commit()
  2551. logger.warning(
  2552. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2553. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2554. item.id,
  2555. printer.id,
  2556. printer.name,
  2557. error_msg,
  2558. refusals,
  2559. backoff,
  2560. )
  2561. try:
  2562. # Closes the dispatch toast for this attempt. Without it the toast
  2563. # keeps spinning on an upload that has ended.
  2564. await ws_manager.send_queue_item_failed(
  2565. user_id=toast_uid,
  2566. queue_item_id=item.id,
  2567. printer_id=item.printer_id,
  2568. reason="upload_failed",
  2569. )
  2570. except Exception:
  2571. pass # toast is best-effort
  2572. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2573. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2574. if printer_id is not None:
  2575. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2576. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2577. """Withdraw the expected print and print user of a sent print that never started.
  2578. Both tell the rest of Bambuddy that the printer's next print is this
  2579. item's: left behind, a print started by hand later is taken for it.
  2580. With ``unless_printing``, a printer that is printing after all keeps
  2581. them, as that print is most likely this one starting late.
  2582. ``keep_expected`` withdraws only the print user, which vouches for any
  2583. print on the printer. The expected print names this item's file, so a
  2584. late start of it is still matched to its archive.
  2585. """
  2586. sent = self._sent_unstarted_print.get(item_id)
  2587. if sent is None:
  2588. return
  2589. printer_id, remote_filename, archive_id = sent
  2590. if unless_printing:
  2591. status = printer_manager.get_status(printer_id)
  2592. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2593. return
  2594. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2595. if keep_expected:
  2596. return
  2597. del self._sent_unstarted_print[item_id]
  2598. if remote_filename is not None and archive_id is not None:
  2599. try:
  2600. from backend.app.main import unregister_expected_print
  2601. unregister_expected_print(printer_id, remote_filename, archive_id)
  2602. except Exception:
  2603. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2604. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2605. """Drop an expectation for a print command that was never sent.
  2606. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2607. where the interesting exception is usually the one already propagating.
  2608. """
  2609. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2610. if pending is None:
  2611. return
  2612. printer_id, remote_filename, archive_id = pending
  2613. try:
  2614. from backend.app.main import unregister_expected_print
  2615. unregister_expected_print(printer_id, remote_filename, archive_id)
  2616. except Exception:
  2617. logger.warning(
  2618. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2619. item_id,
  2620. printer_id,
  2621. remote_filename,
  2622. archive_id,
  2623. exc_info=True,
  2624. )
  2625. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2626. """Release a queue reservation without touching the dispatch session."""
  2627. if item_id not in self._unconfirmed_budget_reservations:
  2628. return
  2629. for attempt in range(1, 4):
  2630. async with async_session() as cleanup_db:
  2631. try:
  2632. await release_budget_reservation(
  2633. cleanup_db,
  2634. source_type="print_queue",
  2635. source_id=item_id,
  2636. status="released",
  2637. )
  2638. await cleanup_db.commit()
  2639. self._unconfirmed_budget_reservations.discard(item_id)
  2640. return
  2641. except Exception as exc:
  2642. try:
  2643. await cleanup_db.rollback()
  2644. except Exception:
  2645. pass
  2646. if attempt == 3:
  2647. logger.error(
  2648. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2649. item_id,
  2650. attempt,
  2651. exc,
  2652. )
  2653. return
  2654. await asyncio.sleep(0.5 * attempt)
  2655. @staticmethod
  2656. def _reported_bed_target(printer_id: int) -> int | None:
  2657. """The bed target firmware currently reports, or None if it can't be read.
  2658. None means "no evidence", not "zero" — callers must not treat it as a
  2659. temperature. Deliberately total: this feeds cleanup paths that run in a
  2660. ``finally``, where a malformed status must not become the exception the
  2661. caller sees.
  2662. """
  2663. try:
  2664. state = printer_manager.get_status(printer_id)
  2665. if state is None:
  2666. return None
  2667. temps = state.temperatures
  2668. if not isinstance(temps, dict):
  2669. return None
  2670. return int(float(temps.get("bed_target", 0) or 0))
  2671. except (TypeError, ValueError, AttributeError):
  2672. return None
  2673. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2674. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2675. Turns the bed heater off, the chamber heater off, and opens the
  2676. airduct flap back to cooling — for whichever of those preheat
  2677. actually applied. `_start_print` clears the pin on successful
  2678. `start_print()`; anything still present when `_dispatch_one` exits
  2679. is by definition an aborted dispatch and gets rolled back here.
  2680. The bed is the one action that can be declined: if firmware has since
  2681. been given a target other than the one we pinned, it belongs to someone
  2682. else and is left alone. See the comment at that branch.
  2683. Also called directly from `_dispatch_one`'s claim-failure return, which
  2684. never reaches the ``finally``.
  2685. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2686. """
  2687. pin = self._preheat_pin.pop(printer_id, set())
  2688. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2689. if not pin:
  2690. return
  2691. client = printer_manager.get_client(printer_id)
  2692. if client is None:
  2693. logger.info(
  2694. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2695. item_id,
  2696. printer_id,
  2697. )
  2698. return
  2699. if "bed" in pin:
  2700. # Only undo our own target. If firmware reports something else, the
  2701. # user or another writer owns the bed now and zeroing it would
  2702. # clobber their choice -- the same guard `_release_keep_warm`
  2703. # applies to a keep-warm hold.
  2704. #
  2705. # Every uncertain case switches the bed off rather than leaving it:
  2706. # no recorded target (a pin written before this bookkeeping, or a
  2707. # setter that raised after pinning) and an unreadable status both
  2708. # fall through. A bed left hot with no owner is the worse failure,
  2709. # and this runs in a `finally` where raising would mask the real
  2710. # exception.
  2711. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2712. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2713. logger.info(
  2714. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2715. item_id,
  2716. printer_id,
  2717. cur_bed_target,
  2718. pinned_bed,
  2719. )
  2720. else:
  2721. try:
  2722. client.set_bed_temperature(0)
  2723. except Exception as exc:
  2724. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2725. if "chamber" in pin:
  2726. try:
  2727. client.set_chamber_temperature(0)
  2728. except Exception as exc:
  2729. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2730. if "airduct" in pin:
  2731. try:
  2732. client.set_airduct_mode("cooling")
  2733. except Exception as exc:
  2734. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2735. logger.info(
  2736. "Dispatch item %s (printer %d): preheat rollback → %s",
  2737. item_id,
  2738. printer_id,
  2739. sorted(pin),
  2740. )
  2741. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2742. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2743. Returns True if this call won the claim, False if the row was already
  2744. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2745. the load-bearing guard against reassign-during-dispatch (#2615).
  2746. ``printer_id`` is the printer the item was selected for: a row moved to
  2747. another printer since is not claimed, and the next pass selects it for
  2748. that one."""
  2749. query = (
  2750. update(PrintQueueItem)
  2751. .where(PrintQueueItem.id == item_id)
  2752. .where(PrintQueueItem.status == "pending")
  2753. .where(PrintQueueItem.dispatching_at.is_(None))
  2754. )
  2755. if printer_id is not None:
  2756. query = query.where(PrintQueueItem.printer_id == printer_id)
  2757. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2758. await db.commit()
  2759. return res.rowcount > 0
  2760. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2761. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2762. mask the dispatch outcome.
  2763. Retried, because the failure mode in practice is transient and narrow: a
  2764. database that is momentarily unreachable — PostgreSQL out of connection
  2765. slots is the observed case — refuses this write for a second or two while
  2766. the dispatch that just ended is still holding the row out of the selection
  2767. query. One attempt was enough to wedge the item; a couple of spaced
  2768. attempts clear it. Each attempt rolls back first, since a failed write
  2769. leaves the session needing it before it can be reused.
  2770. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2771. on the next quiet tick.
  2772. """
  2773. for attempt in range(1, 4):
  2774. try:
  2775. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2776. await db.commit()
  2777. return
  2778. except Exception as exc:
  2779. try:
  2780. await db.rollback()
  2781. except Exception:
  2782. pass
  2783. if attempt == 3:
  2784. logger.warning(
  2785. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2786. "— a later quiet tick will release it",
  2787. item_id,
  2788. attempt,
  2789. exc,
  2790. )
  2791. return
  2792. await asyncio.sleep(0.5 * attempt)
  2793. async def _printers_for_model(
  2794. self,
  2795. db: AsyncSession,
  2796. model: str,
  2797. target_location: str | None = None,
  2798. printer_scope: PrinterScope = ALL_PRINTERS,
  2799. ) -> list[Printer]:
  2800. """Active printers of *model*, optionally narrowed to one location.
  2801. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2802. answer "which printers can this job run on" from one query — a job can
  2803. only be woken onto a printer the matcher would also have considered.
  2804. ``printer_scope`` is the job creator's (#1727).
  2805. """
  2806. normalized_model = normalize_printer_model(model) or model
  2807. query = (
  2808. select(Printer)
  2809. .where(func.lower(Printer.model) == normalized_model.lower())
  2810. .where(Printer.is_active == True) # noqa: E712
  2811. )
  2812. if target_location:
  2813. query = query.where(Printer.location == target_location)
  2814. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2815. query = query.where(clause)
  2816. result = await db.execute(query)
  2817. return list(result.scalars().all())
  2818. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2819. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2820. Read once per queue check rather than per printer: it decides both
  2821. whether the wake step has anything to do and how an offline printer is
  2822. worded in the waiting reason — "Offline" and "offline with no Auto On
  2823. plug" are different problems, and the second is the one the user has to
  2824. fix themselves (#2786).
  2825. """
  2826. result = await db.execute(
  2827. select(SmartPlug.printer_id)
  2828. .where(SmartPlug.printer_id.is_not(None))
  2829. .where(SmartPlug.enabled == True) # noqa: E712
  2830. .where(SmartPlug.auto_on == True) # noqa: E712
  2831. )
  2832. return {pid for (pid,) in result.all() if pid is not None}
  2833. def _wake_recently_failed(self, printer_id: int) -> bool:
  2834. """True while this printer's failed power-on is still cooling off (#2786)."""
  2835. deadline = self._wake_failures.get(printer_id)
  2836. if deadline is None:
  2837. return False
  2838. if time.monotonic() >= deadline:
  2839. del self._wake_failures[printer_id]
  2840. return False
  2841. return True
  2842. async def _wake_printer_for_model(
  2843. self,
  2844. db: AsyncSession,
  2845. candidates: list[_ModelCandidate],
  2846. target_location: str | None,
  2847. exclude_ids: set[int],
  2848. wakeable_ids: set[int],
  2849. require_plate_clear: bool,
  2850. printer_scope: PrinterScope = ALL_PRINTERS,
  2851. ) -> tuple[int | None, int | None]:
  2852. """Power on one offline printer a model-based item could run on (#2786).
  2853. The fixed-printer branch has powered a printer on since smart plugs
  2854. existed. The model-based branch never could: its matcher drops an
  2855. offline printer into the "Offline:" waiting reason and nothing looks at
  2856. its plugs, so a class-targeted job with every matching printer switched
  2857. off sat pending forever. The reporter's log is the controlled
  2858. experiment — the same item, same plug, same Auto On setting, dispatched
  2859. the moment they edited it onto a specific printer.
  2860. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2861. power-on was actually tried, so the caller can tell "nothing here was
  2862. wakeable" (both None — cheap, other items may still find something)
  2863. from "we tried and it did not come up" (only ``attempted_id`` — the
  2864. boot timeout has already been spent).
  2865. A printer whose last known trays cannot satisfy the job is passed over
  2866. rather than woken (#2876): the colours are readable while it is off, so
  2867. switching a farm on one machine at a time to discover them wakes
  2868. printers that could never have taken the job.
  2869. Deliberately does NOT go on to match the job once a printer is up: AMS
  2870. trays arrive with the first status push after connect, so a filament
  2871. check against a printer that booted seconds ago can reject the printer
  2872. we just woke. The next queue pass matches it with live state.
  2873. At most one printer per pass. Each wake blocks the queue loop for the
  2874. boot wait, and a queue of ten class-targeted jobs must not switch on
  2875. ten printers inside one check.
  2876. """
  2877. for candidate in candidates:
  2878. if not candidate.target_model:
  2879. continue
  2880. required_types, filament_overrides = _filament_constraints(candidate)
  2881. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2882. for printer in sorted(printers, key=lambda p: p.id):
  2883. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2884. continue
  2885. if printer_manager.is_connected(printer.id):
  2886. continue
  2887. if self._wake_recently_failed(printer.id):
  2888. # Its plug did not bring it back a moment ago. Move on to a
  2889. # sibling instead of spending this pass — and every pass —
  2890. # on the same printer.
  2891. continue
  2892. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2893. # Waking this one buys nothing: it would boot into IDLE and
  2894. # then be held by the plate-clear gate, which is exactly
  2895. # what the reporter's log shows happening for 80 minutes
  2896. # after a fixed-printer wake. The flag is Bambuddy-side and
  2897. # persisted, so it is readable while the printer is off.
  2898. logger.info(
  2899. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2900. printer.id,
  2901. candidate.target_model,
  2902. )
  2903. continue
  2904. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2905. if shortfall:
  2906. logger.info(
  2907. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2908. printer.id,
  2909. candidate.target_model,
  2910. ", ".join(shortfall),
  2911. )
  2912. continue
  2913. plugs = await self._get_smart_plugs(db, printer.id)
  2914. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2915. if not auto_on_plugs:
  2916. # wakeable_ids said otherwise — the plug changed under us
  2917. # mid-pass. Nothing to do but move on.
  2918. continue
  2919. logger.info(
  2920. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2921. candidate.target_model,
  2922. printer.id,
  2923. )
  2924. primary_plug = self._pick_power_plug(auto_on_plugs)
  2925. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2926. logger.warning(
  2927. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2928. printer.id,
  2929. self._wake_failure_cooloff,
  2930. )
  2931. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2932. return None, printer.id
  2933. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2934. try:
  2935. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2936. if await service.turn_on(extra_plug):
  2937. await publish_plug_state(
  2938. extra_plug.id,
  2939. extra_plug.name,
  2940. extra_plug.printer_id,
  2941. on=True,
  2942. ha_entity_id=extra_plug.ha_entity_id,
  2943. )
  2944. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2945. except Exception as e:
  2946. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2947. return printer.id, printer.id
  2948. return None, None
  2949. async def _find_idle_printer_for_model(
  2950. self,
  2951. db: AsyncSession,
  2952. model: str,
  2953. exclude_ids: set[int],
  2954. required_filament_types: list[str] | None = None,
  2955. target_location: str | None = None,
  2956. filament_overrides: list[dict] | None = None,
  2957. require_plate_clear: bool = True,
  2958. wakeable_ids: set[int] | None = None,
  2959. printer_scope: PrinterScope = ALL_PRINTERS,
  2960. is_short: Callable[[int], Awaitable[bool]] | None = None,
  2961. drying_ids: set[int] | None = None,
  2962. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  2963. ) -> tuple[int | None, str | None]:
  2964. """Find an idle, connected printer matching the model with compatible filaments.
  2965. Args:
  2966. db: Database session
  2967. model: Printer model to match (e.g., "X1C", "P1S")
  2968. exclude_ids: Printer IDs to exclude (already busy)
  2969. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2970. If provided, only printers with all required types loaded will match.
  2971. target_location: Optional location filter. If provided, only printers in this location are considered.
  2972. filament_overrides: Optional list of override dicts. Each entry may include
  2973. ``force_color_match: true`` to require an exact type+color match
  2974. on the printer for that slot. Without the flag the existing
  2975. colour-preference logic applies.
  2976. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2977. offline printer is worded: one Bambuddy will switch on reads
  2978. differently from one the user has to go and switch on themselves.
  2979. is_short: Says whether a printer's spools are too light for the job (#3137).
  2980. A printer it flags is passed over while another eligible one
  2981. is not. When every eligible printer is short, the first is
  2982. returned all the same, so the deficit gate holds the job there
  2983. and "Print Anyway" still has a printer to print on.
  2984. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  2985. in the reason, as a pinned job's wait is.
  2986. unmatched_on: Names the filaments the slot matcher would leave without a
  2987. tray on a printer (#3280). A printer it names any for is
  2988. passed over like one missing a filament type: the checks
  2989. above only ask whether each type and forced colour is
  2990. loaded somewhere, not on the right nozzle or once per slot.
  2991. Returns:
  2992. Tuple of (printer_id, waiting_reason):
  2993. - (printer_id, None) if a matching printer was found
  2994. - (None, reason) if no printer is available, with explanation
  2995. """
  2996. normalized_model = normalize_printer_model(model) or model
  2997. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  2998. location_suffix = f" in {target_location}" if target_location else ""
  2999. if not printers:
  3000. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3001. # Separate force-matched overrides from preference-only overrides
  3002. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3003. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3004. # Track reasons for skipping printers
  3005. printers_busy = []
  3006. printers_offline = []
  3007. printers_offline_no_plug = []
  3008. printers_missing_filament: list[tuple[str, list[str]]] = []
  3009. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3010. # The first eligible printer that is short on filament, kept in case
  3011. # every eligible printer is (#3137).
  3012. short_fallback: int | None = None
  3013. for printer in printers:
  3014. if printer.id in exclude_ids:
  3015. # Printer is already claimed by another job in this scheduling run.
  3016. # For force-color jobs, still check if the color would match — if not,
  3017. # report it as a color mismatch rather than plain "Busy" so the user
  3018. # knows the job needs a filament change, not just to wait for availability.
  3019. if force_overrides and not pref_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. continue
  3024. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3025. continue
  3026. is_connected = printer_manager.is_connected(printer.id)
  3027. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3028. if not is_connected:
  3029. # An offline printer whose last known filament cannot run this
  3030. # job is reported as needing filament rather than as offline
  3031. # (#2876). It is also the printer the smart-plug step will now
  3032. # decline to switch on, and "Offline:" on its own would leave
  3033. # that decision looking like nothing happening at all.
  3034. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3035. if shortfall:
  3036. printers_missing_filament.append((printer.name, shortfall))
  3037. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3038. printers_offline_no_plug.append(printer.name)
  3039. else:
  3040. printers_offline.append(printer.name)
  3041. continue
  3042. if not is_idle:
  3043. # Printer is currently printing. For force-color jobs, check whether the
  3044. # loaded color would satisfy the requirement — if not, surface it as a
  3045. # color-mismatch reason rather than plain "Busy" so the user understands
  3046. # that the job is waiting for a filament change, not just printer availability.
  3047. if force_overrides and not pref_overrides:
  3048. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3049. if missing_colors:
  3050. printers_missing_filament.append((printer.name, missing_colors))
  3051. logger.debug(
  3052. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3053. printer.id,
  3054. printer.name,
  3055. missing_colors,
  3056. )
  3057. continue
  3058. printers_busy.append(printer.name)
  3059. continue
  3060. # Validate filament compatibility if required types are specified
  3061. if required_filament_types:
  3062. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3063. if missing:
  3064. # When force_overrides are present, enrich missing entries with color info
  3065. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3066. if force_overrides:
  3067. force_color_map = {
  3068. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3069. for o in force_overrides
  3070. }
  3071. missing_enriched = [
  3072. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3073. for t in missing
  3074. ]
  3075. printers_missing_filament.append((printer.name, missing_enriched))
  3076. else:
  3077. printers_missing_filament.append((printer.name, missing))
  3078. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3079. continue
  3080. # Force color match: ALL flagged slots must have an exact type+color match
  3081. if force_overrides:
  3082. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3083. if missing_colors:
  3084. printers_missing_filament.append((printer.name, missing_colors))
  3085. logger.debug(
  3086. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3087. printer.id,
  3088. printer.name,
  3089. missing_colors,
  3090. )
  3091. continue
  3092. # The matcher has the last word: a printer it cannot map would be
  3093. # held and given back, then chosen again on the next pass (#3280).
  3094. if unmatched_on is not None:
  3095. unmatched = await unmatched_on(printer.id)
  3096. if unmatched:
  3097. printers_missing_filament.append((printer.name, unmatched))
  3098. logger.debug(
  3099. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3100. printer.id,
  3101. printer.name,
  3102. unmatched,
  3103. )
  3104. continue
  3105. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3106. if pref_overrides:
  3107. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3108. if color_matches > 0:
  3109. candidates.append((printer.id, color_matches))
  3110. else:
  3111. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3112. printers_missing_filament.append((printer.name, override_colors))
  3113. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3114. continue
  3115. else:
  3116. # No preference ordering needed: the first eligible printer
  3117. # wins, unless its spools are too light for the job (#3137).
  3118. if is_short is not None and await is_short(printer.id):
  3119. if short_fallback is None:
  3120. short_fallback = printer.id
  3121. logger.info(
  3122. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3123. printer.id,
  3124. printer.name,
  3125. )
  3126. continue
  3127. return printer.id, None
  3128. # If we have candidates from preference override matching, pick the one with most color matches
  3129. if candidates:
  3130. candidates.sort(key=lambda c: c[1], reverse=True)
  3131. if is_short is not None:
  3132. for candidate_id, _ in candidates:
  3133. if not await is_short(candidate_id):
  3134. return candidate_id, None
  3135. logger.info(
  3136. "Model-based assignment: passing over printer %s, not enough filament",
  3137. candidate_id,
  3138. )
  3139. return candidates[0][0], None
  3140. if short_fallback is not None:
  3141. return short_fallback, None
  3142. # Build waiting reason from what we found
  3143. reasons = []
  3144. if printers_missing_filament:
  3145. # Filament/color mismatch is most actionable - show first
  3146. if force_overrides and not pref_overrides:
  3147. # All mismatches are force-color failures — use descriptive message only;
  3148. # but only if there are no busy printers that DO have the matching color.
  3149. # If a printer has the right color but is busy, surface "Busy" instead so
  3150. # the user knows the job will start automatically once that printer is free.
  3151. # Same for a printer that is merely offline: Bambuddy switches that one on
  3152. # by itself, so the job is not actually waiting on anybody to change a
  3153. # spool (#2876 — offline printers reach this list now that a switched-off
  3154. # printer's own filament is read).
  3155. if not printers_busy and not printers_offline:
  3156. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3157. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3158. # else: fall through — the self-resolving entries are appended below
  3159. else:
  3160. names_and_missing = [
  3161. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3162. ]
  3163. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3164. if printers_busy:
  3165. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3166. if printers_offline:
  3167. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3168. if printers_offline_no_plug:
  3169. # Named separately because it is the one entry on this list the
  3170. # user has to act on: no enabled Auto On plug means Bambuddy will
  3171. # never power this printer on for the queue (#2786).
  3172. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3173. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3174. @staticmethod
  3175. def _is_busy_only(waiting_reason: str) -> bool:
  3176. """Check if the waiting reason only contains 'Busy' entries.
  3177. When all matching printers are simply busy printing, the queued job
  3178. will start automatically once a printer finishes — no user action
  3179. is required, so we skip the notification.
  3180. """
  3181. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3182. return all(p.startswith("Busy:") for p in parts)
  3183. def _get_missing_force_color_slots(
  3184. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3185. ) -> list[str]:
  3186. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3187. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3188. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3189. with an exact type+color match.
  3190. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3191. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3192. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3193. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3194. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3195. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3196. setups are unaffected.
  3197. Returns:
  3198. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3199. """
  3200. if raw_data is None:
  3201. status = printer_manager.get_status(printer_id)
  3202. if not status:
  3203. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3204. raw_data = status.raw_data
  3205. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3206. loaded: list[tuple[str, str, str]] = []
  3207. for ams_unit in raw_data.get("ams", []):
  3208. for tray in ams_unit.get("tray", []):
  3209. tray_type = tray.get("tray_type")
  3210. if tray_type:
  3211. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3212. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3213. for vt in raw_data.get("vt_tray") or []:
  3214. vt_type = vt.get("tray_type")
  3215. if vt_type:
  3216. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3217. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3218. # One spool per slot, the way the matcher assigns them: two slots asking
  3219. # for the same filament need two spools of it (#3280). Slots naming a
  3220. # variant go first and take that variant before a spool naming none, so
  3221. # a slot open to any variant cannot use up the one a later slot needs.
  3222. missing = []
  3223. taken: set[int] = set()
  3224. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3225. o_type = canonical_filament_type(o.get("type") or "")
  3226. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3227. o_idx = o.get("tray_info_idx") or ""
  3228. fits = [
  3229. i
  3230. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3231. if i not in taken
  3232. and t_type == o_type
  3233. and t_color == o_color
  3234. and (not o_idx or not t_idx or o_idx == t_idx)
  3235. ]
  3236. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3237. if pick is not None:
  3238. taken.add(pick)
  3239. else:
  3240. color_label = o.get("color_name") or o.get("color", "?")
  3241. missing.append(f"{o_type} ({color_label})")
  3242. return missing
  3243. def _get_missing_filament_types(
  3244. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3245. ) -> list[str]:
  3246. """Get the list of required filament types that are not loaded on the printer.
  3247. Args:
  3248. printer_id: The printer ID
  3249. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3250. Returns:
  3251. List of missing filament types (empty if all are loaded)
  3252. """
  3253. if raw_data is None:
  3254. status = printer_manager.get_status(printer_id)
  3255. if not status:
  3256. return required_types # Can't determine, assume all missing
  3257. raw_data = status.raw_data
  3258. # Collect all filament types loaded on this printer (AMS units + external spool)
  3259. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3260. loaded_types: set[str] = set()
  3261. # Check AMS units (stored in raw_data["ams"])
  3262. ams_data = raw_data.get("ams", [])
  3263. if ams_data:
  3264. for ams_unit in ams_data:
  3265. for tray in ams_unit.get("tray", []):
  3266. tray_type = tray.get("tray_type")
  3267. if tray_type:
  3268. loaded_types.add(canonical_filament_type(tray_type))
  3269. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3270. for vt in raw_data.get("vt_tray") or []:
  3271. vt_type = vt.get("tray_type")
  3272. if vt_type:
  3273. loaded_types.add(canonical_filament_type(vt_type))
  3274. # Find which required types are missing (using canonical type for equivalence)
  3275. missing = []
  3276. for req_type in required_types:
  3277. if canonical_filament_type(req_type) not in loaded_types:
  3278. missing.append(req_type)
  3279. return missing
  3280. def _count_override_color_matches(
  3281. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3282. ) -> int:
  3283. """Count how many filament overrides have an exact color match on the printer.
  3284. Used to prefer printers that already have the desired override colors loaded.
  3285. """
  3286. if raw_data is None:
  3287. status = printer_manager.get_status(printer_id)
  3288. if not status:
  3289. return 0
  3290. raw_data = status.raw_data
  3291. # Collect loaded filaments' type+color pairs
  3292. loaded: set[tuple[str, str]] = set()
  3293. for ams_unit in raw_data.get("ams", []):
  3294. for tray in ams_unit.get("tray", []):
  3295. tray_type = tray.get("tray_type")
  3296. # `or ""`, not a dict default: a slot can carry the key with a
  3297. # null value, and this now runs against switched-off printers
  3298. # too, where nobody is watching for the AttributeError.
  3299. tray_color = tray.get("tray_color") or ""
  3300. if tray_type:
  3301. color_norm = tray_color.replace("#", "").lower()[:6]
  3302. loaded.add((canonical_filament_type(tray_type), color_norm))
  3303. for vt in raw_data.get("vt_tray") or []:
  3304. vt_type = vt.get("tray_type")
  3305. if vt_type:
  3306. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3307. loaded.add((canonical_filament_type(vt_type), color_norm))
  3308. # Types compared as the type check compares them: a PA12-CF override
  3309. # is met by PA-CF in its colour.
  3310. matches = 0
  3311. for o in overrides:
  3312. o_type = canonical_filament_type(o.get("type") or "")
  3313. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3314. if (o_type, o_color) in loaded:
  3315. matches += 1
  3316. return matches
  3317. @staticmethod
  3318. def _tray_reading(printer_id: int) -> dict:
  3319. """The best tray reading available for a printer that is not printing.
  3320. Live status first: a printer keeps its last status after the power
  3321. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3322. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3323. for when the client itself has been dropped and taken its status with
  3324. it — which is what every power-on attempt does.
  3325. An empty result means "we have never heard", not "nothing is loaded":
  3326. the two are indistinguishable from here, and only the second would be
  3327. safe to act on.
  3328. """
  3329. status = printer_manager.get_status(printer_id)
  3330. raw = (status.raw_data if status else None) or {}
  3331. for ams_unit in raw.get("ams") or []:
  3332. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3333. return raw
  3334. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3335. return raw
  3336. return printer_manager.last_known_trays(printer_id)
  3337. def _cached_filament_shortfall(
  3338. self,
  3339. printer_id: int,
  3340. required_types: list[str] | None,
  3341. filament_overrides: list[dict] | None,
  3342. ) -> list[str]:
  3343. """What a switched-off printer's last known filament cannot provide (#2876).
  3344. The smart-plug wake step used to consider only the model, so a job for a
  3345. colour loaded on the last printer in ID order switched on every earlier
  3346. one in turn, evaluated it, rejected it on colour and left it running.
  3347. Bambuddy knew those colours the whole time. This asks the same three
  3348. questions the matcher asks a live printer — required types, forced
  3349. colours, preferred colours — of the trays it last reported, and returns
  3350. the answers in the same shape the "Waiting for filament" reason uses.
  3351. Empty means the printer may still be able to take the job.
  3352. Fails open, and deliberately: with no tray reading (never connected
  3353. since Bambuddy started, or the cache dropped by a reconnect) this
  3354. returns nothing to report and the printer is treated as it was before.
  3355. A farm restarted while its printers were off must not conclude that
  3356. none of them can print.
  3357. """
  3358. if not required_types and not filament_overrides:
  3359. return []
  3360. raw_data = self._tray_reading(printer_id)
  3361. if not raw_data:
  3362. return []
  3363. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3364. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3365. if required_types:
  3366. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3367. if missing:
  3368. # Same enrichment the live path applies: a bare "PLA" is not
  3369. # much help when what is missing is a particular PLA.
  3370. force_color_map = {
  3371. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3372. }
  3373. return [
  3374. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3375. for t in missing
  3376. ]
  3377. if force_overrides:
  3378. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3379. if missing_colors:
  3380. return missing_colors
  3381. # Preference overrides read as a preference but the matcher treats zero
  3382. # matches as a skip, so a printer with none of the wanted colours is
  3383. # rejected there too. Waking it would only produce that same rejection.
  3384. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3385. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3386. return []
  3387. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3388. """Fold the winning candidate's file and settings onto the queue row (#671).
  3389. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3390. never escapes the selection loop. By the time the pass commits, the row
  3391. looks exactly like an ordinary single-file model-based item, so the upload,
  3392. archive creation, expected-print registration, print history and reprint
  3393. paths need no knowledge that variants exist.
  3394. No-ops for a non-variant candidate, which is already the item's own columns.
  3395. Safe to run and re-run: the item's file columns are only ever *read* when it
  3396. has no variants, so an item that gets resolved and then skipped (library-row
  3397. conflict, previous-print gate) is simply resolved again on the next pass.
  3398. """
  3399. variant = candidate.variant
  3400. if variant is None:
  3401. return
  3402. item.library_file_id = variant.library_file_id
  3403. item.library_file = variant.library_file
  3404. # The dispatcher checks archive_id first and would print that instead of
  3405. # the file we just picked. Creation refuses to combine the two, so this
  3406. # only ever fires on a hand-written row — clear it rather than silently
  3407. # dispatch something the matcher never considered.
  3408. item.archive_id = None
  3409. item.archive = None
  3410. item.target_model = variant.target_model
  3411. item.plate_id = variant.plate_id
  3412. item.ams_mapping = variant.ams_mapping
  3413. item.nozzle_mapping = variant.nozzle_mapping
  3414. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3415. item.filament_overrides = variant.filament_overrides
  3416. item.required_filament_types = variant.required_filament_types
  3417. if variant.print_time_seconds is not None:
  3418. # The row carried the shortest candidate's estimate so SJF could order
  3419. # it before a printer was known; now that one is chosen, record what is
  3420. # actually going to run so history and the ETA agree with reality.
  3421. item.print_time_seconds = variant.print_time_seconds
  3422. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3423. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3424. Recomputes from live printer status when the stored mapping is missing OR
  3425. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3426. frontend status-load race can serialize [-1] before the printer's AMS
  3427. trays are known (#2589) — and must not be trusted: downstream it would be
  3428. silently downgraded to external-spool mode and print against an empty
  3429. feed. A resolved mapping is re-checked against the target printer's
  3430. live trays before it is trusted (#2799) and recomputed when it does not
  3431. fit. When it does fit, its resolved slots are kept as they are and only
  3432. the slots the plate prints that are still unresolved are matched again;
  3433. all of it is left alone when the user has acknowledged it with "Print
  3434. Anyway".
  3435. When recompute cannot resolve it either (no compatible tray loaded), the
  3436. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3437. external selection. On a printer that reported loaded trays,
  3438. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3439. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3440. and the firmware surfaces a clear AMS-mapping error instead of silently
  3441. printing to the empty external feed.
  3442. Returns an actionable message when that firmware error is the only
  3443. possible outcome — the matcher ran, matched nothing, and the printer has
  3444. no AMS to load a different spool into (#2771). The caller fails the item
  3445. on it instead of spending an upload on a print that cannot start.
  3446. Returns None everywhere else, including every case where we simply lack
  3447. the data to judge, so dispatch is only ever blocked on a positive
  3448. finding.
  3449. """
  3450. stored_mapping: list | None = None
  3451. if item.ams_mapping:
  3452. try:
  3453. stored_mapping = json.loads(item.ams_mapping)
  3454. except (json.JSONDecodeError, TypeError):
  3455. stored_mapping = None
  3456. # Present and resolved. Global tray IDs only mean something relative to
  3457. # the printer they were resolved against, so "resolved" is not the same
  3458. # as "resolved *here*" — check the mapping still fits the printer that
  3459. # is about to run this item before trusting it (#2799). "Print anyway"
  3460. # is the user overriding exactly this judgement, so it short-circuits.
  3461. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3462. if item.skip_filament_check:
  3463. return None
  3464. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3465. if conflict is None:
  3466. # It fits, but a slot the plate prints may still be empty: the
  3467. # spool was missing when it was mapped, and has perhaps been
  3468. # loaded since. Nothing else would ever look at that slot again,
  3469. # so a job held for it would be held again on every Start.
  3470. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3471. if filled is not None:
  3472. item.ams_mapping = json.dumps(filled)
  3473. logger.info(
  3474. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3475. item.id,
  3476. stored_mapping,
  3477. printer_id,
  3478. filled,
  3479. )
  3480. await db.commit()
  3481. return None
  3482. logger.warning(
  3483. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3484. item.id,
  3485. stored_mapping,
  3486. printer_id,
  3487. conflict,
  3488. )
  3489. # Drop it before recomputing so a failed recompute cannot fall back
  3490. # to the mapping we just rejected.
  3491. item.ams_mapping = None
  3492. stored_mapping = None
  3493. await db.commit()
  3494. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3495. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3496. item.ams_mapping = json.dumps(computed_mapping)
  3497. logger.info(
  3498. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3499. item.id,
  3500. printer_id,
  3501. computed_mapping,
  3502. )
  3503. await db.commit()
  3504. return None
  3505. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3506. if external_only is not None:
  3507. item.ams_mapping = json.dumps(external_only)
  3508. logger.info(
  3509. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3510. "mapping every filament to it: %s",
  3511. item.id,
  3512. printer_id,
  3513. external_only,
  3514. )
  3515. await db.commit()
  3516. return None
  3517. if _mapping_is_all_unresolved(stored_mapping):
  3518. logger.warning(
  3519. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3520. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3521. item.id,
  3522. stored_mapping,
  3523. printer_id,
  3524. )
  3525. item.ams_mapping = None
  3526. await db.commit()
  3527. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3528. async def _external_spool_only_mapping(
  3529. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3530. ) -> list[int] | None:
  3531. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3532. A printer without an AMS prints from its external spool, and an external
  3533. spool whose filament was never set reports no type, so the matcher has
  3534. nothing to match. Sent without a mapping, the print goes out with the AMS
  3535. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3536. to carry such a job through; a job placed by model or location no longer
  3537. keeps one, and one queued that way never had one.
  3538. Only on a positive report: the printer has said it has no AMS, it has a
  3539. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3540. is not ours to pick), and no feed has a filament set — with one set, the
  3541. matcher has already given its answer. Not for a job that asked for its
  3542. colours to be matched strictly: a spool without a filament set has no
  3543. colour to check. Returns None otherwise.
  3544. """
  3545. if item.filament_overrides:
  3546. try:
  3547. overrides = json.loads(item.filament_overrides)
  3548. except (json.JSONDecodeError, TypeError):
  3549. return None
  3550. if not isinstance(overrides, list) or any(
  3551. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3552. ):
  3553. return None
  3554. status = printer_manager.get_status(printer_id)
  3555. if status is None or not isinstance(status.raw_data, dict):
  3556. return None
  3557. ams_units = status.raw_data.get("ams")
  3558. if not isinstance(ams_units, list) or ams_units:
  3559. return None
  3560. vt_trays = status.raw_data.get("vt_tray")
  3561. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3562. return None
  3563. if self._build_loaded_filaments(status):
  3564. return None
  3565. printer = await self._get_printer(db, printer_id)
  3566. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3567. return None
  3568. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3569. if external < _EXTERNAL_TRAY_ID_MIN:
  3570. return None
  3571. required = await self._get_filament_requirements(db, item)
  3572. slot_ids = [r.get("slot_id") for r in required or []]
  3573. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3574. if not slot_ids:
  3575. return None
  3576. mapping = [-1] * max(slot_ids)
  3577. for slot_id in slot_ids:
  3578. mapping[slot_id - 1] = external
  3579. return mapping
  3580. async def _fill_unresolved_slots(
  3581. self,
  3582. db: AsyncSession,
  3583. printer_id: int,
  3584. item: PrintQueueItem,
  3585. stored_mapping: list | None,
  3586. ) -> list | None:
  3587. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3588. Every resolved entry is kept, so a tray the user picked by hand stays
  3589. picked. Only the plate's unresolved slots are matched, and only against
  3590. trays the mapping does not already use: the matcher never gives two
  3591. slots one tray, and filling a gap with a tray the user assigned to
  3592. another slot would print that slot's filament twice.
  3593. Returns None when there is nothing to fill or nothing could be filled.
  3594. """
  3595. if not isinstance(stored_mapping, list) or not stored_mapping:
  3596. return None
  3597. required = await self._get_filament_requirements(db, item)
  3598. if not required:
  3599. return None
  3600. self._apply_filament_overrides(item, required)
  3601. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3602. if not gaps:
  3603. return None
  3604. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3605. computed = await self._compute_ams_mapping_for_printer(
  3606. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3607. )
  3608. if not computed:
  3609. return None
  3610. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3611. filled = False
  3612. for slot_id in gaps:
  3613. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3614. if _is_tray_id(tray) and tray >= 0:
  3615. merged[slot_id - 1] = tray
  3616. filled = True
  3617. return merged if filled else None
  3618. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3619. """What a staged item would be held for if it were started now (#2799).
  3620. The Start button asks this before releasing an item, so that a job whose
  3621. filament is still not loaded offers "Print Anyway" instead of being
  3622. released, held again by the scheduler and leaving no way past the hold.
  3623. It reaches the same answer the dispatch path would: a stored mapping
  3624. that fits is kept and only its gaps are matched again, and one that
  3625. does not fit (or is missing) is replaced by a fresh match.
  3626. Returns the missing filaments, described the way the queue row
  3627. describes them, or None when nothing is missing or there is not enough
  3628. evidence to say: no printer yet (a model-based item picks one at
  3629. dispatch), no status, no trays reported, or no readable 3MF.
  3630. """
  3631. if item.skip_filament_check or not item.printer_id:
  3632. return None
  3633. status = printer_manager.get_status(item.printer_id)
  3634. if status is None or not self._build_loaded_filaments(status):
  3635. return None
  3636. # Called from a request, not from a pass: drop whatever the last pass
  3637. # memoised so this reads the file as it is now. A pass running at the
  3638. # same time only loses its cache.
  3639. self._filament_req_memo.clear()
  3640. mapping: list | None = None
  3641. if item.ams_mapping:
  3642. try:
  3643. mapping = json.loads(item.ams_mapping)
  3644. except (json.JSONDecodeError, TypeError):
  3645. mapping = None
  3646. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3647. mapping = None
  3648. if mapping is not None:
  3649. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3650. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3651. else:
  3652. mapping = None
  3653. if mapping is None:
  3654. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3655. required = await self._get_filament_requirements(db, item)
  3656. if required:
  3657. self._apply_filament_overrides(item, required)
  3658. else:
  3659. # The same fallback the hold uses, or Start would release a job the
  3660. # next pass holds again (#3280).
  3661. required = _forced_override_requirements(item)
  3662. if not required:
  3663. return None
  3664. missing = _unresolved_required(required, mapping)
  3665. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3666. async def _stored_mapping_conflict(
  3667. self,
  3668. db: AsyncSession,
  3669. printer_id: int,
  3670. item: PrintQueueItem,
  3671. stored_mapping: list | None,
  3672. ) -> str | None:
  3673. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3674. A mapping is a list of global tray IDs, and those are only meaningful
  3675. relative to the printer they were resolved against — the same rule
  3676. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3677. arrives at a printer it was not resolved for:
  3678. * the print dialog stamps one mapping onto every selected printer, so a
  3679. mapping computed against the first printer is dispatched verbatim to
  3680. the rest, whose AMS slot order differs;
  3681. * a spool is moved between queueing and dispatch.
  3682. Both end the same way: the slot index still resolves, so nothing looks
  3683. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3684. the firmware's own type check, so a PETG slot happily prints in ASA.
  3685. Returns a short reason when the mapping names a tray this printer does
  3686. not have loaded, points a slot at a tray holding a different filament
  3687. type, or points it at an external spool this printer reports empty while
  3688. its AMS holds that slot's filament (#3239). Returns None when the
  3689. mapping fits, and — deliberately — whenever we lack the evidence to
  3690. judge, so a recompute only ever follows a positive finding.
  3691. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3692. matcher had nothing, not that the mapping belongs to another printer,
  3693. and destroying a partially hand-resolved mapping over it would lose the
  3694. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3695. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3696. item when that finds nothing.
  3697. """
  3698. if not isinstance(stored_mapping, list) or not stored_mapping:
  3699. return None
  3700. status = printer_manager.get_status(printer_id)
  3701. if status is None:
  3702. return None
  3703. loaded = self._build_loaded_filaments(status)
  3704. if not loaded:
  3705. # Nothing reported yet (reconnect, first push pending). Saying
  3706. # "tray not loaded" here would recompute against an AMS we cannot
  3707. # see, which is how #2589 produced a bogus all-[-1] in the first
  3708. # place.
  3709. return None
  3710. by_tray = {f["global_tray_id"]: f for f in loaded}
  3711. # Cheap pass first, on live status alone: every tray the mapping names
  3712. # has to exist here. This catches a foreign mapping without opening the
  3713. # 3MF, which is worth doing because the parse below is neither cached
  3714. # nor free.
  3715. for index, tray in enumerate(stored_mapping):
  3716. if not _is_tray_id(tray) or tray < 0:
  3717. continue
  3718. if tray in by_tray:
  3719. continue
  3720. if tray >= 254:
  3721. # An external feed we have not heard about is absence of
  3722. # evidence about *that slot* — the rest of the mapping is still
  3723. # worth judging, so skip it rather than abandoning the pass.
  3724. continue
  3725. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3726. # Only now is the 3MF worth opening: the type check needs to know what
  3727. # each slot actually asked for. The external spool is checked the same
  3728. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3729. # two printers with different filament in the external feed is the same
  3730. # failure this method exists to catch.
  3731. required = await self._get_filament_requirements(db, item)
  3732. if not required:
  3733. return None
  3734. self._apply_filament_overrides(item, required)
  3735. # External feeds the printer reports and reports as empty. That is
  3736. # evidence, unlike an external feed it says nothing about (#3239).
  3737. empty_external: set[int] = set()
  3738. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3739. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3740. if isinstance(vt, dict) and not vt.get("tray_type"):
  3741. try:
  3742. empty_external.add(int(vt.get("id", 254)))
  3743. except (TypeError, ValueError):
  3744. continue
  3745. for req in required:
  3746. slot_id = req.get("slot_id") or 0
  3747. if slot_id <= 0:
  3748. continue
  3749. if slot_id > len(stored_mapping):
  3750. return f"slot {slot_id} is not covered by the mapping"
  3751. tray = stored_mapping[slot_id - 1]
  3752. if not _is_tray_id(tray) or tray < 0:
  3753. continue
  3754. loaded_tray = by_tray.get(tray)
  3755. if loaded_tray is None:
  3756. # A mapping made for a printer that feeds this slot from its
  3757. # external spool, sent to one whose external spool is empty and
  3758. # whose AMS holds the filament (#3239). Only then: an external
  3759. # spool can be loaded without its filament set, and on a printer
  3760. # with nothing else to offer that job printed before. The colour
  3761. # has to match too: with only another colour in the AMS, the
  3762. # printer asking for the spool beats printing in that colour.
  3763. want = canonical_filament_type(req.get("type"))
  3764. if tray >= 254 and tray in empty_external and want:
  3765. ams_tray = next(
  3766. (
  3767. f
  3768. for f in loaded
  3769. if not f.get("is_external")
  3770. and canonical_filament_type(f.get("type")) == want
  3771. and self._colors_are_similar(f.get("color"), req.get("color"))
  3772. ),
  3773. None,
  3774. )
  3775. if ams_tray is not None:
  3776. return (
  3777. f"slot {slot_id} points at the external spool, which is empty, "
  3778. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3779. )
  3780. continue
  3781. want = canonical_filament_type(req.get("type"))
  3782. have = canonical_filament_type(loaded_tray.get("type"))
  3783. if want and have and want != have:
  3784. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3785. # A forced slot fits only a tray the matcher would give it (#3280).
  3786. if req.get("force_color_match"):
  3787. want_idx = req.get("tray_info_idx") or ""
  3788. have_idx = loaded_tray.get("tray_info_idx") or ""
  3789. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3790. loaded_tray.get("color")
  3791. ) or (want_idx and have_idx and want_idx != have_idx):
  3792. return (
  3793. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3794. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3795. )
  3796. return None
  3797. async def _unmappable_without_ams_message(
  3798. self,
  3799. db: AsyncSession,
  3800. printer_id: int,
  3801. item: PrintQueueItem,
  3802. computed_mapping: list[int] | None,
  3803. ) -> str | None:
  3804. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3805. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3806. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3807. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3808. uploaded several megabytes and burned its dispatch retries. This method
  3809. speaks only for the AMS-less case: there is nothing to resume into — the
  3810. external spool holder is the whole inventory — so the useful answer is to
  3811. say which filament is missing and stop. With an AMS attached it returns
  3812. None: where live status reported loaded trays,
  3813. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3814. reported none the print goes out and the firmware error is the answer —
  3815. the user can load the right spool and press Resume.
  3816. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3817. every branch that lacks the evidence to be sure returns None.
  3818. """
  3819. # None means the matcher never ran (no requirements parsed from the 3MF,
  3820. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3821. # dispatch as they always have.
  3822. if not _mapping_is_all_unresolved(computed_mapping):
  3823. return None
  3824. status = printer_manager.get_status(printer_id)
  3825. if status is None:
  3826. return None
  3827. # "No AMS" has to be a fact the printer stated, not the absence of a
  3828. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3829. # handled and is preserved across partial pushes thereafter, so a missing
  3830. # key means we have not heard yet — most likely a reconnect, where the
  3831. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3832. # empty list is the positive report of a printer with no AMS.
  3833. ams_units = status.raw_data.get("ams")
  3834. if not isinstance(ams_units, list) or ams_units:
  3835. return None
  3836. required = await self._get_filament_requirements(db, item)
  3837. loaded = self._build_loaded_filaments(status)
  3838. if not required or not loaded:
  3839. # Both were non-empty moments ago or the matcher could not have run.
  3840. # If the picture changed under us, say nothing rather than fail an
  3841. # item on stale evidence.
  3842. return None
  3843. self._apply_filament_overrides(item, required)
  3844. if any(r.get("force_color_match") for r in required):
  3845. # A forced colour is a spool the user can load on the external
  3846. # holder, so the unmatched hold stages the job instead (#3280).
  3847. return None
  3848. return _unmatched_filament_message(required, loaded)
  3849. async def _fail_unmappable_item(
  3850. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3851. ) -> None:
  3852. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3853. This replaces a failure, not a success: without it the item is uploaded,
  3854. rejected by the firmware with 0700_8012, retried twice more and failed
  3855. anyway with "never started the print after N dispatch attempts". So this
  3856. applies on the model-based path too. There it is rarely reached: choosing
  3857. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  3858. over one it cannot map, so an "Any <model>" job tries its siblings and
  3859. otherwise waits; this remains for a match that failed at selection time.
  3860. """
  3861. item.status = "failed"
  3862. item.error_message = message
  3863. item.completed_at = datetime.now(timezone.utc)
  3864. item.waiting_reason = None
  3865. await db.commit()
  3866. from backend.app.services.print_batch import refresh_batches_after
  3867. await refresh_batches_after([item.id])
  3868. logger.warning(
  3869. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3870. item.id,
  3871. printer_id,
  3872. message,
  3873. )
  3874. job_name = await self._get_job_name(db, item)
  3875. printer = await self._get_printer(db, printer_id)
  3876. await notification_service.on_queue_job_failed(
  3877. job_name=job_name,
  3878. printer_id=printer_id,
  3879. printer_name=printer.name if printer else "Unknown",
  3880. reason=message,
  3881. db=db,
  3882. )
  3883. try:
  3884. await ws_manager.send_queue_item_failed(
  3885. user_id=item.created_by_id,
  3886. queue_item_id=item.id,
  3887. printer_id=printer_id,
  3888. reason="filament_unmappable",
  3889. )
  3890. except Exception:
  3891. pass
  3892. async def _compute_ams_mapping_for_printer(
  3893. self,
  3894. db: AsyncSession,
  3895. printer_id: int,
  3896. item: PrintQueueItem,
  3897. *,
  3898. only_slots: set[int] | None = None,
  3899. reserved_trays: set[int] | None = None,
  3900. ) -> list[int] | None:
  3901. """Compute AMS mapping for a printer based on filament requirements.
  3902. Called when a queue item has no ams_mapping set — either for model-based
  3903. items after printer assignment, or printer-specific items (e.g. from VP).
  3904. Args:
  3905. db: Database session
  3906. printer_id: The assigned printer ID
  3907. item: The queue item (contains archive_id or library_file_id)
  3908. only_slots: Match only these filament slots; every other slot comes
  3909. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3910. reserved_trays: Global tray IDs to leave out of the match, because
  3911. the stored mapping already gives them to another slot.
  3912. Returns:
  3913. AMS mapping array or None if no mapping needed/possible
  3914. """
  3915. # Get printer status
  3916. status = printer_manager.get_status(printer_id)
  3917. if not status:
  3918. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3919. return None
  3920. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3921. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3922. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3923. # an AMS on the *other* nozzle, and the matcher falls through to a
  3924. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3925. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3926. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3927. # Get filament requirements from source file
  3928. filament_reqs = await self._get_filament_requirements(db, item)
  3929. if not filament_reqs:
  3930. # When the 3MF can't be read but force-color overrides are present, build a
  3931. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3932. if item.filament_overrides:
  3933. try:
  3934. overrides = json.loads(item.filament_overrides)
  3935. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3936. if force_overrides:
  3937. logger.info(
  3938. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3939. "force-color override(s)",
  3940. item.id,
  3941. len(force_overrides),
  3942. )
  3943. return self._build_override_direct_mapping(force_overrides, status)
  3944. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3945. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3946. logger.debug("No filament requirements found for queue item %s", item.id)
  3947. return None
  3948. self._apply_filament_overrides(item, filament_reqs)
  3949. if only_slots is not None:
  3950. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3951. if not filament_reqs:
  3952. return None
  3953. # Build loaded filaments from printer status
  3954. loaded_filaments = self._build_loaded_filaments(status)
  3955. if reserved_trays:
  3956. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3957. if not loaded_filaments:
  3958. logger.debug("No filaments loaded on printer %s", printer_id)
  3959. return None
  3960. # Check if user prefers lowest remaining filament when multiple spools match
  3961. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3962. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3963. # Without backup, the printer will not switch to a second spool when the
  3964. # picked one runs out — so sorting toward the lowest leaves the print
  3965. # at risk of running dry mid-job. None (unknown: no status report with
  3966. # cfg or home_flag yet) preserves today's behaviour intentionally.
  3967. if prefer_lowest and status.ams_filament_backup is False:
  3968. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3969. prefer_lowest = False
  3970. # When the preference is on, surface Bambuddy's inventory-side
  3971. # remaining for each slot that's bound to a tracked spool, so the
  3972. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3973. # entirely when the preference is off — no behaviour change for
  3974. # users who haven't opted in.
  3975. inventory_remain_overrides: dict[int, float] | None = None
  3976. if prefer_lowest:
  3977. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3978. # Compute mapping: match required filaments to available slots
  3979. return self._match_filaments_to_slots(
  3980. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3981. )
  3982. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3983. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3984. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3985. diagnosis (#2771) describes the filament the matcher actually looked
  3986. for, not the one the 3MF was sliced with — naming the pre-override
  3987. filament in a user-facing error would send the user to load the wrong
  3988. spool.
  3989. """
  3990. if not item.filament_overrides:
  3991. return
  3992. try:
  3993. overrides = json.loads(item.filament_overrides)
  3994. override_map = {o["slot_id"]: o for o in overrides}
  3995. for req in filament_reqs:
  3996. if req["slot_id"] in override_map:
  3997. override = override_map[req["slot_id"]]
  3998. req["type"] = override["type"]
  3999. req["color"] = override["color"]
  4000. # A manual/preference override SWAPS the slot's filament, so the
  4001. # 3MF's original tray_info_idx now points at the old spool and must
  4002. # be cleared — matching then falls back to type+colour. A
  4003. # force_color_match override is not a swap: it carries the 3MF's
  4004. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4005. # it here too, letting the matcher pin the correct variant slot on a
  4006. # printer holding two same-colour spools of different variants (#2650).
  4007. # A spool that names no variant still counts; one naming another
  4008. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4009. req["tray_info_idx"] = (
  4010. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4011. )
  4012. # The matcher satisfies a forced slot only the way
  4013. # `_get_missing_force_color_slots` does, never by a similar
  4014. # colour or the type alone (#3280).
  4015. req["force_color_match"] = bool(override.get("force_color_match"))
  4016. logger.debug(
  4017. "Queue item %s: Override slot %d -> %s %s",
  4018. item.id,
  4019. req["slot_id"],
  4020. override["type"],
  4021. override["color"],
  4022. )
  4023. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4024. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4025. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4026. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4027. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4028. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4029. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4030. treated as the filament requirement for that slot and matched against the
  4031. current AMS state of the printer.
  4032. Returns the same format as ``_match_filaments_to_slots``, or None when
  4033. the AMS has no loaded filaments.
  4034. """
  4035. loaded = self._build_loaded_filaments(status)
  4036. if not loaded:
  4037. return None
  4038. reqs = [
  4039. {
  4040. "slot_id": o["slot_id"],
  4041. "type": o.get("type", ""),
  4042. "color": o.get("color", ""),
  4043. # These are all force_color_match overrides, so the idx (when the
  4044. # 3MF carried one) is the intended variant, not a stale swap —
  4045. # keep it so the matcher pins the right variant slot (#2650); a
  4046. # spool naming another variant does not satisfy it (#3280).
  4047. "tray_info_idx": o.get("tray_info_idx", ""),
  4048. "force_color_match": True,
  4049. }
  4050. for o in force_overrides
  4051. ]
  4052. return self._match_filaments_to_slots(reqs, loaded)
  4053. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4054. """Resolve the queue item's source 3MF and parse the per-slot
  4055. filament requirements out of it. Thin DB-resolver wrapper around
  4056. ``filament_requirements.extract_filament_requirements`` so the VP
  4057. queue-mode write path (#1188) can reuse the same parser at upload
  4058. time.
  4059. """
  4060. from backend.app.services.filament_requirements import extract_filament_requirements
  4061. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4062. # so every caller gets its own copy — a shared list would leak one
  4063. # item's overrides into the next item that happens to print the same
  4064. # plate.
  4065. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4066. if memo_key in self._filament_req_memo:
  4067. cached = self._filament_req_memo[memo_key]
  4068. return [dict(r) for r in cached] if cached else None
  4069. file_path: Path | None = None
  4070. if item.archive_id:
  4071. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4072. archive = result.scalar_one_or_none()
  4073. if archive:
  4074. file_path = settings.base_dir / archive.file_path
  4075. elif item.library_file_id:
  4076. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4077. library_file = result.scalar_one_or_none()
  4078. if library_file:
  4079. lib_path = Path(library_file.file_path)
  4080. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4081. if not file_path or not file_path.exists():
  4082. self._filament_req_memo[memo_key] = None
  4083. return None
  4084. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4085. self._filament_req_memo[memo_key] = filaments or None
  4086. return [dict(r) for r in filaments] if filaments else None
  4087. def _build_loaded_filaments(self, status) -> list[dict]:
  4088. """Build list of loaded filaments from printer status.
  4089. Args:
  4090. status: PrinterState from printer_manager
  4091. Returns:
  4092. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4093. """
  4094. filaments = []
  4095. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4096. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4097. # Routes external spools to an extruder (#2771). Mirrors
  4098. # `buildLoadedFilaments` in the frontend.
  4099. vt_trays = status.raw_data.get("vt_tray") or []
  4100. is_dual_nozzle = reports_two_nozzles(status)
  4101. # Parse AMS units from raw_data
  4102. ams_data = status.raw_data.get("ams", [])
  4103. for ams_unit in ams_data:
  4104. ams_id = int(ams_unit.get("id", 0))
  4105. trays = ams_unit.get("tray", [])
  4106. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4107. for tray in trays:
  4108. tray_type = tray.get("tray_type")
  4109. if tray_type:
  4110. tray_id = int(tray.get("id", 0))
  4111. tray_color = tray.get("tray_color", "")
  4112. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4113. tray_info_idx = tray.get("tray_info_idx", "")
  4114. # Normalize color: remove alpha, add hash
  4115. color = self._normalize_color(tray_color)
  4116. # Calculate global tray ID
  4117. # AMS-HT units have IDs starting at 128 with a single tray
  4118. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4119. filaments.append(
  4120. {
  4121. "type": tray_type,
  4122. "color": color,
  4123. # `color` reads a missing colour as #808080; this
  4124. # says whether the printer reported one at all.
  4125. "color_known": bool(tray_color),
  4126. "tray_info_idx": tray_info_idx,
  4127. "ams_id": ams_id,
  4128. "tray_id": tray_id,
  4129. "is_ht": is_ht,
  4130. "is_external": False,
  4131. "global_tray_id": global_tray_id,
  4132. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4133. "remain": tray.get("remain", -1),
  4134. }
  4135. )
  4136. # Check external spool(s) (vt_tray is a list)
  4137. for idx, vt in enumerate(vt_trays):
  4138. if vt.get("tray_type"):
  4139. color = self._normalize_color(vt.get("tray_color", ""))
  4140. tray_id = int(vt.get("id", 254))
  4141. filaments.append(
  4142. {
  4143. "type": vt["tray_type"],
  4144. "color": color,
  4145. "color_known": bool(vt.get("tray_color")),
  4146. "tray_info_idx": vt.get("tray_info_idx", ""),
  4147. "ams_id": -1,
  4148. "tray_id": idx,
  4149. "is_ht": False,
  4150. "is_external": True,
  4151. "global_tray_id": tray_id,
  4152. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4153. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4154. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4155. "remain": vt.get("remain", -1),
  4156. }
  4157. )
  4158. return filaments
  4159. def _normalize_color(self, color: str | None) -> str:
  4160. """Normalize color to #RRGGBB format."""
  4161. if not color:
  4162. return "#808080"
  4163. hex_color = color.replace("#", "")[:6]
  4164. return f"#{hex_color}"
  4165. def _normalize_color_for_compare(self, color: str | None) -> str:
  4166. """Normalize color for comparison (lowercase, no hash)."""
  4167. if not color:
  4168. return ""
  4169. return color.replace("#", "").lower()[:6]
  4170. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4171. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4172. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4173. stays the per-channel box that shipped — this only decides which of
  4174. several eligible spools is closest, so nothing becomes usable or
  4175. unusable because of it.
  4176. It ranks by how far apart the colours *look*, not how far apart their
  4177. numbers are. RGB distance overweights blue badly enough to invert the
  4178. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4179. the nearer of two eligible spools by RGB and the further by a factor of
  4180. four once measured perceptually.
  4181. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4182. transparent filament is not a colour the user chose, and counting it
  4183. would stop a transparent filament matching itself.
  4184. """
  4185. return perceptual_color_distance(color1, color2)
  4186. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4187. """Check if two colors are visually similar within a threshold."""
  4188. hex1 = self._normalize_color_for_compare(color1)
  4189. hex2 = self._normalize_color_for_compare(color2)
  4190. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4191. return False
  4192. try:
  4193. r1 = int(hex1[0:2], 16)
  4194. g1 = int(hex1[2:4], 16)
  4195. b1 = int(hex1[4:6], 16)
  4196. r2 = int(hex2[0:2], 16)
  4197. g2 = int(hex2[2:4], 16)
  4198. b2 = int(hex2[4:6], 16)
  4199. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4200. except ValueError:
  4201. return False
  4202. async def _build_inventory_remain_overrides(
  4203. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4204. ) -> dict[int, float]:
  4205. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4206. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4207. The MQTT ``remain`` field on a tray is the printer firmware's
  4208. RFID-decremented value, which has two limitations the "Prefer Lowest
  4209. Remaining Filament" feature has been ignoring (#1508):
  4210. - it's only meaningful for Bambu RFID spools; everything else reports
  4211. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4212. compare equal and the sort collapses to AMS-slot order — the user
  4213. who's curating inventory weights gets the lower-slot pick instead
  4214. of the lower-remaining pick;
  4215. - even when set, it's the *printer's* counter, not Bambuddy's
  4216. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4217. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4218. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4219. When the user has bound a spool to a slot, their own inventory
  4220. tracking is authoritative; this helper surfaces that value so the
  4221. sort can prefer it. Slots without a binding are absent from the
  4222. returned map — the caller then falls back to MQTT ``remain`` for
  4223. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4224. Returns an empty map on any failure (no inventory bindings, DB
  4225. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4226. is a preference, not a guarantee.
  4227. """
  4228. if not loaded:
  4229. return {}
  4230. # External / virtual-tray slots are tracked separately from AMS — skip
  4231. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4232. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4233. # match is fiddly and out of scope for this fix).
  4234. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4235. if not tracked_slots:
  4236. return {}
  4237. is_spoolman = await self._is_spoolman_mode(db)
  4238. overrides: dict[int, float] = {}
  4239. if is_spoolman:
  4240. result = await db.execute(
  4241. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4242. )
  4243. assignments = list(result.scalars().all())
  4244. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4245. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4246. for ams_id, tray_id, gtid in tracked_slots:
  4247. spoolman_id = by_slot.get((ams_id, tray_id))
  4248. if spoolman_id is None:
  4249. continue
  4250. grams = await _spoolman_remaining_grams(spoolman_id)
  4251. if grams is not None:
  4252. overrides[gtid] = grams
  4253. return overrides
  4254. # Internal inventory mode (default). selectinload matches the pattern
  4255. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4256. # plus an eager-loaded relationship rather than an explicit join, so
  4257. # the row-attribute shape is exactly what those routes already rely on.
  4258. result = await db.execute(
  4259. select(SpoolAssignment)
  4260. .options(selectinload(SpoolAssignment.spool))
  4261. .where(SpoolAssignment.printer_id == printer_id)
  4262. )
  4263. assignments = list(result.scalars().all())
  4264. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4265. for ams_id, tray_id, gtid in tracked_slots:
  4266. spool = by_slot.get((ams_id, tray_id))
  4267. if spool is None:
  4268. continue
  4269. label = float(spool.label_weight or 0)
  4270. used = float(spool.weight_used or 0)
  4271. overrides[gtid] = max(0.0, label - used)
  4272. return overrides
  4273. @staticmethod
  4274. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4275. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4276. here to avoid making this module import-dependent on that private
  4277. helper's signature."""
  4278. try:
  4279. from backend.app.api.routes.settings import get_setting
  4280. v = await get_setting(db, "spoolman_enabled")
  4281. return bool(v) and v.lower() == "true"
  4282. except Exception:
  4283. return False
  4284. @staticmethod
  4285. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4286. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4287. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4288. so a tied sort produces the same physical-position order the pre-#1508
  4289. stable sort did (preserves the regression-free baseline):
  4290. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4291. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4292. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4293. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4294. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4295. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4296. """
  4297. if ams_id is None or ams_id < 0:
  4298. return 10_000
  4299. if ams_id >= 128:
  4300. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4301. return ams_id * 4 + (tray_id or 0)
  4302. @staticmethod
  4303. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4304. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4305. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4306. non-tracked spools (the user has told us they care about these
  4307. specifically), then ascending by remaining within each tier, then
  4308. ascending by AMS slot position as the deterministic tie-breaker.
  4309. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4310. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4311. because the tier flag dominates — which is what lets us mix grams
  4312. (inventory) and percent (MQTT) without a unit conversion.
  4313. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4314. spools the printer DOES know something about sort ahead of those
  4315. it knows nothing about — preserves pre-#1508 behaviour for the
  4316. no-inventory-binding case.
  4317. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4318. external on ties, matching the legacy emission-order stable sort.
  4319. """
  4320. gtid = f.get("global_tray_id")
  4321. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4322. if overrides and gtid in overrides:
  4323. return (0, overrides[gtid], slot_order)
  4324. remain = f.get("remain", -1)
  4325. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4326. def _match_filaments_to_slots(
  4327. self,
  4328. required: list[dict],
  4329. loaded: list[dict],
  4330. prefer_lowest: bool = False,
  4331. inventory_remain_overrides: dict[int, float] | None = None,
  4332. fts_installed: bool = False,
  4333. ) -> list[int] | None:
  4334. """Match required filaments to loaded filaments and build AMS mapping.
  4335. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4336. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4337. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4338. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4339. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4340. matching among those trays.
  4341. Args:
  4342. required: List of required filaments with slot_id, type, color, tray_info_idx
  4343. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4344. Returns:
  4345. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4346. """
  4347. if not required:
  4348. return None
  4349. # Track used trays to avoid duplicate assignment
  4350. used_tray_ids: set[int] = set()
  4351. comparisons = []
  4352. # Forced slots first: a slot that would take any tray of its type must
  4353. # not take the one tray a forced slot can use (#3280). The mapping is
  4354. # built by slot_id below, so the order only decides who goes first.
  4355. # Among forced slots, those naming a variant first, as
  4356. # `_get_missing_force_color_slots` counts them.
  4357. for req in sorted(
  4358. required,
  4359. key=lambda r: (
  4360. not r.get("force_color_match"),
  4361. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4362. ),
  4363. ):
  4364. req_type = (req.get("type") or "").upper()
  4365. req_color = req.get("color", "")
  4366. req_tray_info_idx = req.get("tray_info_idx", "")
  4367. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4368. idx_match = None
  4369. exact_match = None
  4370. similar_match = None
  4371. similar_distance = float("inf")
  4372. type_only_match = None
  4373. # Get available trays (not already used)
  4374. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4375. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4376. # Hard filter — cross-nozzle assignment causes print failures
  4377. # ("position of left hotend is abnormal"), so never fall back.
  4378. # Skipped when an FTS is installed: it routes any AMS slot to either
  4379. # extruder, so restricting to one nozzle would wrongly exclude the
  4380. # correct spool sitting in the other nozzle's AMS (#2186).
  4381. req_nozzle_id = req.get("nozzle_id")
  4382. if req_nozzle_id is not None and not fts_installed:
  4383. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4384. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4385. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4386. # _prefer_lowest_sort_key for the full rationale.
  4387. if prefer_lowest:
  4388. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4389. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4390. # One line per filament req so a bug report can be diagnosed
  4391. # without enabling debug logging: shows what the matcher saw
  4392. # (req shape + sorted candidate trays with their remain values
  4393. # and any inventory override that was applied). Mirrored by
  4394. # the picked-match log at the bottom of the loop.
  4395. logger.info(
  4396. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4397. req.get("slot_id"),
  4398. req_type,
  4399. req_color,
  4400. req_tray_info_idx,
  4401. req_nozzle_id,
  4402. [
  4403. {
  4404. "gtid": f.get("global_tray_id"),
  4405. "type": f.get("type"),
  4406. "color": f.get("color"),
  4407. "tii": f.get("tray_info_idx"),
  4408. "remain": f.get("remain"),
  4409. "inv_g": (
  4410. inventory_remain_overrides.get(f.get("global_tray_id"))
  4411. if inventory_remain_overrides
  4412. else None
  4413. ),
  4414. }
  4415. for f in available
  4416. ],
  4417. )
  4418. # A forced slot takes only what `_get_missing_force_color_slots`
  4419. # accepts: same type, exact colour, and the same variant when both
  4420. # sides name one -- preferring the tray that does. Nothing looser:
  4421. # the model-based path holds a job the printer cannot satisfy this
  4422. # way, and a printer-pinned job fell through to type_only and
  4423. # printed in whatever colour came first (#3280).
  4424. forced = bool(req.get("force_color_match"))
  4425. if forced:
  4426. want_type = canonical_filament_type(req_type)
  4427. want_color = self._normalize_color_for_compare(req_color)
  4428. candidates = [
  4429. f
  4430. for f in available
  4431. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4432. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4433. and (
  4434. not req_tray_info_idx
  4435. or not f.get("tray_info_idx")
  4436. or f.get("tray_info_idx") == req_tray_info_idx
  4437. )
  4438. ]
  4439. exact_match = next(
  4440. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4441. candidates[0] if candidates else None,
  4442. )
  4443. # Check if tray_info_idx is unique among available trays
  4444. if req_tray_info_idx and not forced:
  4445. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4446. if len(idx_matches) == 1:
  4447. # Unique tray_info_idx - use it as definitive match
  4448. idx_match = idx_matches[0]
  4449. logger.debug(
  4450. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4451. f"-> tray {idx_match['global_tray_id']}"
  4452. )
  4453. elif len(idx_matches) > 1:
  4454. # Multiple trays with same tray_info_idx - use color matching among them
  4455. logger.debug(
  4456. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4457. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4458. )
  4459. if prefer_lowest:
  4460. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4461. # Use color matching within this subset
  4462. for f in idx_matches:
  4463. f_color = f.get("color", "")
  4464. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4465. if not exact_match:
  4466. exact_match = f
  4467. elif self._colors_are_similar(f_color, req_color):
  4468. distance = self._color_distance(f_color, req_color)
  4469. if distance is not None and distance < similar_distance:
  4470. similar_match = f
  4471. similar_distance = distance
  4472. elif not type_only_match:
  4473. type_only_match = f
  4474. # If no idx_match yet, do standard type/color matching on all available trays
  4475. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4476. for f in available:
  4477. f_type = (f.get("type") or "").upper()
  4478. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4479. continue
  4480. # Type matches - check color
  4481. f_color = f.get("color", "")
  4482. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4483. if not exact_match:
  4484. exact_match = f
  4485. elif self._colors_are_similar(f_color, req_color):
  4486. # Nearest wins, not first-in-tray-order. `available` is
  4487. # already in the caller's order (slot order, or the
  4488. # prefer-lowest sort), and `<` keeps the earliest of
  4489. # equally close spools — so that order survives as the
  4490. # tie-break (#2804).
  4491. distance = self._color_distance(f_color, req_color)
  4492. if distance is not None and distance < similar_distance:
  4493. similar_match = f
  4494. similar_distance = distance
  4495. elif not type_only_match:
  4496. type_only_match = f
  4497. match = idx_match or exact_match or similar_match or type_only_match
  4498. if match:
  4499. used_tray_ids.add(match["global_tray_id"])
  4500. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4501. else:
  4502. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4503. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4504. # "Why did it pick that spool" is the question every wrong-filament
  4505. # report starts with, and a `similar_color` win is now a ranked
  4506. # choice among several eligible spools rather than whichever tray
  4507. # came first, so it is worth being able to see after the fact.
  4508. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4509. # is on (#1766).
  4510. if match:
  4511. bucket = (
  4512. "idx"
  4513. if idx_match is not None
  4514. else "exact_color"
  4515. if exact_match is not None
  4516. else "similar_color"
  4517. if similar_match is not None
  4518. else "type_only"
  4519. )
  4520. logger.info(
  4521. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4522. match["global_tray_id"],
  4523. bucket,
  4524. req.get("slot_id"),
  4525. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4526. )
  4527. else:
  4528. logger.info(
  4529. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4530. req.get("slot_id"),
  4531. req_type,
  4532. req_color,
  4533. req_tray_info_idx,
  4534. ", force color match" if forced else "",
  4535. )
  4536. # Build mapping array
  4537. if not comparisons:
  4538. return None
  4539. max_slot_id = max(c["slot_id"] for c in comparisons)
  4540. if max_slot_id <= 0:
  4541. return None
  4542. mapping = [-1] * max_slot_id
  4543. for c in comparisons:
  4544. slot_id = c["slot_id"]
  4545. if slot_id and slot_id > 0:
  4546. mapping[slot_id - 1] = c["global_tray_id"]
  4547. return mapping
  4548. def _mark_printer_dispatched(
  4549. self,
  4550. printer_id: int,
  4551. pre_state: str | None,
  4552. pre_subtask_id: str | None,
  4553. ) -> None:
  4554. """Record that a print command was just sent to ``printer_id``.
  4555. Held until either the watchdog observes a state/subtask transition
  4556. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4557. """
  4558. if not pre_state:
  4559. # No pre_state means we can't detect a transition — fall back to a
  4560. # pure time-based hold using empty string as a sentinel that won't
  4561. # match any real printer state.
  4562. pre_state = ""
  4563. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4564. def _release_dispatch_hold(self, printer_id: int) -> None:
  4565. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4566. self._dispatch_holds.pop(printer_id, None)
  4567. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4568. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4569. Returns False (and clears the hold) once any of these are true:
  4570. - hard timeout (``_dispatch_max_hold``) has elapsed
  4571. - the printer has transitioned out of pre_state and we're past the
  4572. minimum cooldown
  4573. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4574. past the minimum cooldown
  4575. Otherwise the printer is held — caller should treat it as busy.
  4576. """
  4577. entry = self._dispatch_holds.get(printer_id)
  4578. if not entry:
  4579. return False
  4580. started_at, pre_state, pre_subtask_id = entry
  4581. elapsed = time.monotonic() - started_at
  4582. if elapsed >= self._dispatch_max_hold:
  4583. self._dispatch_holds.pop(printer_id, None)
  4584. return False
  4585. # Without a pre_state we can't detect a transition — fall back to the
  4586. # min cooldown alone, then drop the hold.
  4587. if not pre_state:
  4588. if elapsed >= self._dispatch_min_cooldown:
  4589. self._dispatch_holds.pop(printer_id, None)
  4590. return False
  4591. return True
  4592. status = printer_manager.get_status(printer_id)
  4593. current_state = getattr(status, "state", None) if status else None
  4594. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4595. transitioned = (current_state is not None and current_state != pre_state) or (
  4596. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4597. )
  4598. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4599. self._dispatch_holds.pop(printer_id, None)
  4600. return False
  4601. return True
  4602. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4603. """Check if a printer is connected and idle."""
  4604. if not printer_manager.is_connected(printer_id):
  4605. logger.debug("Printer %d: not connected", printer_id)
  4606. return False
  4607. state = printer_manager.get_status(printer_id)
  4608. if not state:
  4609. logger.debug("Printer %d: no status available", printer_id)
  4610. return False
  4611. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4612. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4613. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4614. # printer, it boots back into IDLE with no memory of the previous finish; without
  4615. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4616. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4617. logger.debug(
  4618. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4619. printer_id,
  4620. state.state,
  4621. )
  4622. return False
  4623. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4624. if not idle:
  4625. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4626. return False
  4627. # A print would run from the SD card the firmware is being written to.
  4628. from backend.app.services.firmware_update import upload_in_progress
  4629. if upload_in_progress(printer_id):
  4630. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4631. return False
  4632. return True
  4633. @staticmethod
  4634. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4635. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4636. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4637. and that the fixed-printer branch has already found connected, so the two
  4638. offline cases answer at their own exits and never arrive here.
  4639. The default is the model-based branch's ``Busy:`` wording, which
  4640. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4641. the right answer for the connected-but-no-telemetry second or two after a
  4642. reconnect: the model-based branch has always reported it that way, and it
  4643. is not something to wake anybody up for.
  4644. A plate nobody has confirmed is the one case here that does not resolve
  4645. itself — somebody has to walk over to the printer — so it is worded as
  4646. itself and allowed to notify.
  4647. """
  4648. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4649. return f"Waiting for plate confirmation: {printer_name}"
  4650. return f"Busy: {printer_name}"
  4651. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4652. """Read a setting value from the database."""
  4653. result = await db.execute(select(Settings).where(Settings.key == key))
  4654. setting = result.scalar_one_or_none()
  4655. return setting.value if setting else None
  4656. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4657. """Read a boolean setting from the database."""
  4658. result = await db.execute(select(Settings).where(Settings.key == key))
  4659. setting = result.scalar_one_or_none()
  4660. if setting:
  4661. return setting.value.lower() == "true"
  4662. return default
  4663. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4664. """Read an int setting; falls back to default on missing/unparseable rows."""
  4665. result = await db.execute(select(Settings).where(Settings.key == key))
  4666. setting = result.scalar_one_or_none()
  4667. if setting and setting.value:
  4668. try:
  4669. return int(setting.value)
  4670. except ValueError:
  4671. pass
  4672. return default
  4673. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4674. """Get drying presets (user-configured or built-in defaults)."""
  4675. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4676. setting = result.scalar_one_or_none()
  4677. if setting and setting.value:
  4678. try:
  4679. presets = json.loads(setting.value)
  4680. if isinstance(presets, dict) and presets:
  4681. return presets
  4682. except json.JSONDecodeError:
  4683. pass
  4684. return self.DEFAULT_DRYING_PRESETS
  4685. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4686. """Per-filament humidity thresholds (#1605).
  4687. Returns the user-configured overrides map keyed by normalized filament
  4688. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4689. unknown / unmapped types. Empty / unset → empty dict, in which case
  4690. callers fall back to ``ams_humidity_fair``.
  4691. """
  4692. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4693. setting = result.scalar_one_or_none()
  4694. if not setting or not setting.value:
  4695. return {}
  4696. try:
  4697. data = json.loads(setting.value)
  4698. except json.JSONDecodeError:
  4699. return {}
  4700. if not isinstance(data, dict):
  4701. return {}
  4702. out: dict[str, int] = {}
  4703. for key, value in data.items():
  4704. try:
  4705. out[str(key).upper() if key != "default" else "default"] = int(value)
  4706. except (TypeError, ValueError):
  4707. continue
  4708. return out
  4709. # Materials whose AMS spelling differs from the key the tables above use.
  4710. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4711. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4712. # good PA row (#3067).
  4713. #
  4714. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4715. # The drying popover has resolved these correctly since #2774 and the
  4716. # scheduler never did, which is exactly why #3067's reporter could dry a
  4717. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4718. #
  4719. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4720. # of nylon, so it is the one entry that is a judgement rather than a
  4721. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4722. # way, and PA's row is the hottest the table has. Drying it there is closer
  4723. # to right than not drying it at all, which is what it got before.
  4724. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4725. "NYLON": "PA",
  4726. "PA6": "PA",
  4727. "PA11": "PA",
  4728. "PA12": "PA",
  4729. "PAHT": "PA",
  4730. "PPA": "PA",
  4731. }
  4732. @classmethod
  4733. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4734. """The key in *table* that answers for this tray's material, or None.
  4735. The printer reports the material in ``tray_type``, and it spells filled
  4736. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4737. tables here are keyed by base material, so matching the raw string alone
  4738. found a row for 8 of the 41 types a printer can report and skipped the
  4739. rest -- silently, because every caller reads "no row" as "nothing to do
  4740. for this tray". Auto-drying therefore ignored every composite spool on
  4741. the install (#3067).
  4742. Exact match first, so a table the user has extended with a row of its
  4743. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4744. base material's. Then the suffix is dropped, then the alias map above
  4745. answers for the polyamide spellings.
  4746. Returns None rather than a default: what to do with an unrecognised
  4747. material differs per caller, and only the caller knows whether "no row"
  4748. means skip the tray or fall back to a catch-all. Nothing here invents a
  4749. temperature for a material the table does not list.
  4750. """
  4751. raw = cls._normalize_filament_type(tray_type or "")
  4752. if not raw:
  4753. return None
  4754. for candidate in (raw, raw.split("-")[0]):
  4755. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4756. if key in table:
  4757. return key
  4758. return None
  4759. @staticmethod
  4760. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4761. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4762. For mixed filament types loaded into one AMS, returns the most
  4763. restrictive (lowest) threshold across all loaded tray types — matches
  4764. the conservative-params strategy already used for drying temp/hours.
  4765. Empty / unloaded trays contribute no constraint. Unknown types use the
  4766. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4767. when no per-type map is configured at all.
  4768. """
  4769. default = thresholds.get("default", fallback)
  4770. if not thresholds:
  4771. return fallback
  4772. candidates: list[int] = []
  4773. for tray in trays:
  4774. tray_type = str(tray.get("tray_type") or "").strip()
  4775. if not tray_type:
  4776. continue
  4777. # A composite carries its base material's threshold when it has no
  4778. # row of its own, the same way it takes its drying preset (#3067).
  4779. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4780. candidates.append(thresholds[key] if key is not None else default)
  4781. if not candidates:
  4782. return default
  4783. return min(candidates)
  4784. def _get_conservative_drying_params(
  4785. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4786. ) -> tuple[int, int, str] | None:
  4787. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4788. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4789. """
  4790. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4791. hours_key = f"{temp_key}_hours"
  4792. min_temp = None
  4793. max_hours = None
  4794. filament_type = ""
  4795. for tray in trays:
  4796. tray_type = tray.get("tray_type", "")
  4797. if not tray_type:
  4798. continue
  4799. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4800. # which is what stopped auto-drying on every composite spool (#3067).
  4801. base_type = self._resolve_filament_key(tray_type, presets)
  4802. if base_type is None:
  4803. continue
  4804. # The table is user-editable JSON with no per-row validation, so a
  4805. # row can be present and empty. That has always meant "skip this
  4806. # material", and it has to keep meaning it: the reads below fall
  4807. # back to 55C/12h per missing field, which is a temperature nobody
  4808. # chose and would deform a PLA spool.
  4809. preset = presets[base_type]
  4810. if not preset:
  4811. continue
  4812. temp = preset.get(temp_key, 55)
  4813. hours = preset.get(hours_key, 12)
  4814. # Conservative: lowest temp, longest duration
  4815. if min_temp is None or temp < min_temp:
  4816. min_temp = temp
  4817. if max_hours is None or hours > max_hours:
  4818. max_hours = hours
  4819. if not filament_type:
  4820. filament_type = base_type
  4821. if min_temp is None:
  4822. return None
  4823. return (min_temp, max_hours or 12, filament_type)
  4824. async def _check_filament_low(self, db: AsyncSession) -> None:
  4825. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4826. ``on_filament_low`` has had a column, a schema field, a route, a template
  4827. and a UI toggle since the notification system was built, and no caller --
  4828. so the toggle could be switched on and could never fire. This is the
  4829. producer.
  4830. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4831. ``low_stock_threshold_pct`` override is already exactly this decision:
  4832. already configurable, already surfaced, already driving the Inventory
  4833. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4834. consulted -- it has been measured up to 56 points out against a scale,
  4835. which is not a number to page someone on.
  4836. Only slots with an assigned spool produce an event. A slot Bambuddy
  4837. cannot resolve to a spool has no remaining weight it can stand behind,
  4838. and guessing one is how the remain percentage would have got in.
  4839. """
  4840. from backend.app.models.spool import Spool
  4841. # Time-gated rather than run on every pass. run() sleeps
  4842. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4843. # early-return path counts as productive while an upload is in flight
  4844. # (#2602), so an unthrottled check would re-read the whole spool
  4845. # collection every 3 seconds for the length of a batch drain. In
  4846. # Spoolman mode that is a request storm against a third-party service,
  4847. # which is the thing this producer's design note argues against; and
  4848. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4849. # check_queue holding the scheduler's session, so the outage would
  4850. # throttle the print queue itself. A low spool is not a 3-second
  4851. # concern -- the idle interval is the natural resolution.
  4852. now = time.monotonic()
  4853. if now < self._filament_low_next_check:
  4854. return
  4855. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4856. try:
  4857. # on_filament_low defaults to off on every provider, so on most
  4858. # installs nobody wants this alert. Without this the check would
  4859. # still read every assigned spool each interval -- the whole
  4860. # collection over HTTP in Spoolman mode -- for an event that is
  4861. # switched off. One query against the provider table settles it
  4862. # before any spool work, the same guard the bed-cooled waiter uses.
  4863. # No printer_id: this asks whether any provider wants the event at
  4864. # all; per-printer scoping is applied when the event is sent.
  4865. #
  4866. # While nobody wants it, no pass sees a slot go back above its
  4867. # threshold, so nothing can re-arm; a spool refilled under the same
  4868. # id in that time would stay silenced until a restart. Forgetting
  4869. # what was sent is right anyway: whoever switches the event back on
  4870. # is told about the spools that are low now.
  4871. #
  4872. # The MQTT relay publishes the same event, so a connected relay is
  4873. # reason enough to run the check. Its record is forgotten when the
  4874. # relay is switched off, not when the broker drops: a reconnect must
  4875. # not re-send every low slot.
  4876. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4877. relay = mqtt_relay.enabled and mqtt_relay.connected
  4878. if not notify:
  4879. self._notified_filament_low.clear()
  4880. if not mqtt_relay.enabled:
  4881. self._relayed_filament_low.clear()
  4882. if not notify and not relay:
  4883. return
  4884. global_threshold = await self._get_low_stock_threshold(db)
  4885. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4886. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4887. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4888. if spoolman_on:
  4889. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4890. else:
  4891. rows = (
  4892. await db.execute(
  4893. select(SpoolAssignment, Spool)
  4894. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4895. # An archived spool is not stock. The Inventory page's
  4896. # Low Stock count skips them (InventoryPage.tsx:1089)
  4897. # and get_all_spools without allow_archived already
  4898. # excludes them in Spoolman mode, so without this the
  4899. # internal path is the only one that alerts on them.
  4900. .where(Spool.archived_at.is_(None))
  4901. )
  4902. ).all()
  4903. for assignment, spool in rows:
  4904. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4905. if pct is None:
  4906. continue
  4907. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4908. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4909. pct,
  4910. threshold,
  4911. spool.color_name,
  4912. )
  4913. if not slots:
  4914. # Nothing resolvable this pass. Deliberately not clearing the
  4915. # notified set: a Spoolman that is briefly unreachable would
  4916. # otherwise re-alert on every spool as soon as it came back.
  4917. return
  4918. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  4919. except Exception as e:
  4920. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4921. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4922. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4923. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4924. if raw is None or raw.value is None:
  4925. return 20.0
  4926. try:
  4927. value = float(raw.value)
  4928. except (TypeError, ValueError):
  4929. return 20.0
  4930. return value if 0 < value <= 100 else 20.0
  4931. async def _filament_low_slots_spoolman(
  4932. self, db: AsyncSession, global_threshold: float
  4933. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4934. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4935. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4936. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4937. so the global threshold is the only one that applies here. That matches
  4938. what the Inventory page already does in this mode.
  4939. One ``get_all_spools`` call covers every slot rather than a request per
  4940. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4941. without ``allow_archived`` -- which is the behaviour the internal path
  4942. has to ask for explicitly.
  4943. An unreachable Spoolman returns no slots rather than raising. It is an
  4944. ordinary state for a third-party service, not an error in this pass: the
  4945. caller's "nothing resolvable" branch already leaves the notified set
  4946. alone, which is exactly right here, whereas letting it reach the broad
  4947. ``except`` would write a full traceback every time the check runs.
  4948. """
  4949. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4950. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4951. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4952. if not assignments:
  4953. return {}
  4954. client = await get_spoolman_client()
  4955. if client is None:
  4956. return {}
  4957. try:
  4958. all_spools = await client.get_all_spools()
  4959. except SpoolmanUnavailableError as e:
  4960. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4961. return {}
  4962. by_id: dict[int, dict] = {}
  4963. for raw in all_spools:
  4964. raw_id = raw.get("id")
  4965. if isinstance(raw_id, int):
  4966. by_id[raw_id] = raw
  4967. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4968. for assignment in assignments:
  4969. raw = by_id.get(assignment.spoolman_spool_id)
  4970. if raw is None:
  4971. continue
  4972. try:
  4973. mapped = _map_spoolman_spool(raw)
  4974. except ValueError:
  4975. continue
  4976. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4977. if pct is None:
  4978. continue
  4979. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4980. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4981. return slots
  4982. async def _emit_filament_low(
  4983. self,
  4984. db: AsyncSession,
  4985. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  4986. *,
  4987. notify: bool = True,
  4988. relay: bool = False,
  4989. ) -> None:
  4990. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  4991. printers: dict[int, Printer] = {}
  4992. for key, (pct, threshold, color) in slots.items():
  4993. printer_id, ams_id, tray_id, spool_id = key
  4994. if pct >= threshold:
  4995. # Back above the line: re-arm rather than expire on a timer, so a
  4996. # refilled slot can alert again and a spool sitting just under the
  4997. # threshold stays quiet.
  4998. self._notified_filament_low.discard(key)
  4999. self._relayed_filament_low.discard(key)
  5000. continue
  5001. send_notification = notify and key not in self._notified_filament_low
  5002. # Only while connected, so a crossing the relay missed reaches it
  5003. # after the reconnect.
  5004. send_relay = relay and key not in self._relayed_filament_low
  5005. if not send_notification and not send_relay:
  5006. continue
  5007. # Marked before sending, which is a choice rather than the only
  5008. # option, and it is the opposite failure mode from the one the
  5009. # debounce argues against: one transient provider failure loses this
  5010. # alert until the spool goes back above the threshold and crosses it
  5011. # again. Marking after a successful send would trade that for
  5012. # re-alerting on every pass while a provider is down -- which is the
  5013. # repetition the whole debounce exists to prevent, and the louder of
  5014. # the two failures. A spool that is low stays low, so the next real
  5015. # signal is not far away; a provider stuck retrying is a signal that
  5016. # never stops.
  5017. if send_notification:
  5018. self._notified_filament_low.add(key)
  5019. if send_relay:
  5020. self._relayed_filament_low.add(key)
  5021. if printer_id not in printers:
  5022. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5023. if printer is None:
  5024. continue
  5025. printers[printer_id] = printer
  5026. printer = printers[printer_id]
  5027. slot = _ams_slot_label(ams_id, tray_id)
  5028. if send_notification:
  5029. try:
  5030. await notification_service.on_filament_low(
  5031. printer_id,
  5032. printer.name,
  5033. slot,
  5034. int(pct),
  5035. db,
  5036. color=color,
  5037. )
  5038. except Exception as e:
  5039. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5040. if send_relay:
  5041. try:
  5042. await mqtt_relay.on_filament_low(
  5043. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5044. )
  5045. except Exception as e:
  5046. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5047. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5048. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5049. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5050. a schema field, a template and a UI toggle, and nothing that computes the
  5051. condition -- the Forecast panel does it in the browser, so with no page
  5052. open nothing could ever alert. This runs the same arithmetic
  5053. (``stock_forecast``) from the scheduler loop.
  5054. An alert is sent when a SKU *moves into* a condition, once, and again
  5055. after the condition has cleared. A SKU that worsens from reorder to break
  5056. alerts again as a break, because the panel treats the two as exclusive; one
  5057. that eases from break back to reorder does not alert again.
  5058. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5059. while it is still low tells you.
  5060. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5061. loop runs every 3 s while an upload is in flight, and the whole spool
  5062. collection is read over HTTP in Spoolman mode. Both events default to off
  5063. on every provider, so nothing is read unless a provider wants one.
  5064. """
  5065. now = time.monotonic()
  5066. if now < self._stock_forecast_next_check:
  5067. return
  5068. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5069. try:
  5070. if self._stock_alerts_persisted is None:
  5071. await self._load_stock_alerts(db)
  5072. wanted = {
  5073. "reorder": bool(
  5074. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5075. ),
  5076. "break": bool(
  5077. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5078. ),
  5079. }
  5080. if not any(wanted.values()):
  5081. # Nobody wants either event. Forget what was sent, so whoever
  5082. # switches one on is told about the SKUs that are low now.
  5083. self._notified_stock_alerts.clear()
  5084. await self._save_stock_alerts(db)
  5085. return
  5086. forecasts = await self._stock_forecasts(db)
  5087. if forecasts is None:
  5088. # Spoolman unreachable. Deliberately not clearing the notified
  5089. # set: a brief outage would otherwise re-alert every SKU when it
  5090. # came back.
  5091. return
  5092. await self._emit_stock_alerts(db, forecasts, wanted)
  5093. await self._save_stock_alerts(db)
  5094. except Exception as e:
  5095. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5096. def _serialize_stock_alerts(self) -> str:
  5097. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5098. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5099. return json.dumps(rows)
  5100. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5101. """Read the notified set saved by the last run, once per process.
  5102. A missing or unreadable row is an empty set: the worst that does is one
  5103. repeat of what a restart used to cause every time.
  5104. """
  5105. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5106. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5107. if raw and raw.value:
  5108. try:
  5109. for key, kind, events in json.loads(raw.value):
  5110. if len(key) == 4 and kind in ("reorder", "break"):
  5111. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5112. except (ValueError, TypeError):
  5113. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5114. loaded = {}
  5115. self._notified_stock_alerts = loaded
  5116. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5117. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5118. """Write the notified set to its settings row if it changed since it was last read or written."""
  5119. serialized = self._serialize_stock_alerts()
  5120. if serialized == self._stock_alerts_persisted:
  5121. return
  5122. from backend.app.core.db_dialect import upsert_setting
  5123. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5124. await db.commit()
  5125. self._stock_alerts_persisted = serialized
  5126. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5127. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5128. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5129. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5130. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5131. sku_settings = {
  5132. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5133. lead_time_days=row.lead_time_days,
  5134. safety_margin_value=row.safety_margin_value,
  5135. safety_margin_unit=row.safety_margin_unit,
  5136. alerts_snoozed=bool(row.alerts_snoozed),
  5137. )
  5138. for row in sku_rows
  5139. }
  5140. if await self._get_bool_setting(db, "spoolman_enabled"):
  5141. spools = await self._stock_spools_spoolman()
  5142. if spools is None:
  5143. return None
  5144. # Spoolman owns the usage in this mode and Bambuddy's own history
  5145. # table holds nothing for those spools, so the rate is always the
  5146. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  5147. # are local spool ids, and a Spoolman id that happens to match one
  5148. # (left over from before Spoolman was switched on) would borrow an
  5149. # unrelated spool's history.
  5150. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5151. else:
  5152. spools = await self._stock_spools_internal(db)
  5153. history = await self._stock_usage_history(db)
  5154. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5155. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5156. from backend.app.models.spool import Spool
  5157. # Stock, and the spools archived recently enough to count towards the
  5158. # rate (stock_forecast.archived_counts decides; this only trims the read).
  5159. cutoff = utcnow_naive() - timedelta(days=stock_forecast.ARCHIVED_RATE_WINDOW_DAYS + 1)
  5160. rows = (
  5161. (await db.execute(select(Spool).where(or_(Spool.archived_at.is_(None), Spool.archived_at >= cutoff))))
  5162. .scalars()
  5163. .all()
  5164. )
  5165. return [
  5166. stock_forecast.StockSpool(
  5167. id=spool.id,
  5168. material=spool.material,
  5169. subtype=spool.subtype,
  5170. brand=spool.brand,
  5171. color_name=spool.color_name,
  5172. label_weight=float(spool.label_weight or 0),
  5173. weight_used=float(spool.weight_used or 0),
  5174. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5175. created_at=spool.created_at,
  5176. archived_at=spool.archived_at,
  5177. )
  5178. for spool in rows
  5179. ]
  5180. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  5181. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5182. rows = (
  5183. await db.execute(
  5184. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5185. .order_by(SpoolUsageHistory.created_at.desc())
  5186. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5187. )
  5188. ).all()
  5189. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5190. for spool_id, created_at, weight_used in rows:
  5191. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5192. # filtered before the limit, so the window matches the forecast panel's.
  5193. if created_at is None or spool_id is None:
  5194. continue
  5195. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5196. return history
  5197. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5198. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5199. Archived ones too: a recently used-up spool counts towards its SKU's
  5200. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5201. page (and so the panel) reads; it dates archiving by the spool's last
  5202. use, as Spoolman records no archive date.
  5203. """
  5204. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5205. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5206. client = await get_spoolman_client()
  5207. if client is None:
  5208. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5209. return None
  5210. try:
  5211. raw_spools = await client.get_all_spools(allow_archived=True)
  5212. except SpoolmanUnavailableError as e:
  5213. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5214. return None
  5215. spools: list[stock_forecast.StockSpool] = []
  5216. for raw in raw_spools:
  5217. try:
  5218. mapped = _map_spoolman_spool(raw)
  5219. except ValueError:
  5220. continue
  5221. created_at = _spoolman_time(mapped.get("created_at"))
  5222. archived_at = None
  5223. if raw.get("archived"):
  5224. # Archived without a date to tell when: not stock, and too old to
  5225. # count towards the rate.
  5226. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5227. spools.append(
  5228. stock_forecast.StockSpool(
  5229. id=mapped["id"],
  5230. material=mapped["material"],
  5231. subtype=mapped.get("subtype"),
  5232. brand=mapped.get("brand"),
  5233. color_name=mapped.get("color_name"),
  5234. label_weight=float(mapped.get("label_weight") or 0),
  5235. weight_used=float(mapped.get("weight_used") or 0),
  5236. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5237. created_at=created_at,
  5238. archived_at=archived_at,
  5239. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5240. )
  5241. )
  5242. return spools
  5243. async def _emit_stock_alerts(
  5244. self,
  5245. db: AsyncSession,
  5246. forecasts: stock_forecast.ForecastMap,
  5247. wanted: dict[str, bool],
  5248. ) -> None:
  5249. """Send the notifications for each SKU that has moved into a stock alert condition.
  5250. A SKU in break has also reached its reorder point, so both events apply to
  5251. it: the break event goes to providers that have it on, and the reorder event
  5252. to the providers that have only that one on. A provider with both on gets the
  5253. break and no second message.
  5254. What is remembered per SKU is the condition and which events had a
  5255. subscriber when it was sent. An event with no subscriber is forgotten, so
  5256. switching it on later reports the SKUs already in that condition.
  5257. """
  5258. active_events = {event for event, on in wanted.items() if on}
  5259. for key, (forecast, spool) in forecasts.items():
  5260. kind: str | None = None
  5261. if not forecast.snoozed:
  5262. if forecast.stock_break_alert:
  5263. kind = "break"
  5264. elif forecast.reorder_alert:
  5265. kind = "reorder"
  5266. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5267. events = applicable & active_events
  5268. if not events:
  5269. self._notified_stock_alerts.pop(key, None)
  5270. continue
  5271. previous = self._notified_stock_alerts.get(key)
  5272. told = (previous[1] & active_events) if previous else frozenset()
  5273. # Trimmed to the events this condition can send. That is what makes easing from
  5274. # break back to reorder silent (the reorder event was told with the break) and
  5275. # worsening again news again (the break event is no longer remembered).
  5276. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5277. # Recorded before sending, for the reason _emit_filament_low gives: a
  5278. # provider that is down should lose this alert, not repeat it every hour.
  5279. to_send = events - told
  5280. # Both flags imply a positive rate and so a day count.
  5281. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5282. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5283. color = None if spool.color_name_is_synthesized else spool.color_name
  5284. try:
  5285. if "break" in to_send:
  5286. await notification_service.on_stock_break_alert(
  5287. spool.material,
  5288. spool.brand,
  5289. forecast.remaining_g,
  5290. rate,
  5291. days_left,
  5292. forecast.effective_lead_time_days,
  5293. db,
  5294. subtype=spool.subtype,
  5295. color=color,
  5296. )
  5297. if "reorder" in to_send:
  5298. await notification_service.on_stock_reorder_alert(
  5299. spool.material,
  5300. spool.brand,
  5301. forecast.remaining_g,
  5302. rate,
  5303. days_left,
  5304. db,
  5305. subtype=spool.subtype,
  5306. color=color,
  5307. skip_break_subscribers=kind == "break",
  5308. )
  5309. except Exception as e:
  5310. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5311. # A SKU with no spools left is no longer alerting.
  5312. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5313. del self._notified_stock_alerts[key]
  5314. @staticmethod
  5315. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5316. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5317. from backend.app.core.auth import is_auth_enabled
  5318. if user_id is None or not await is_auth_enabled(db):
  5319. return ALL_PRINTERS
  5320. return await resolve_user_id_printer_scope(db, user_id)
  5321. async def _model_job_printer_ids(
  5322. self,
  5323. db: AsyncSession,
  5324. item: PrintQueueItem,
  5325. scope: PrinterScope,
  5326. cache: dict[tuple[str, str | None, int | None], set[int]],
  5327. ) -> set[int]:
  5328. """Every printer an "Any <model>" job could land on: the active printers
  5329. of each of its candidate models, in its location, that its creator may use.
  5330. ``cache`` holds one lookup per model, location and creator for the pass,
  5331. so a long queue of model jobs does not query once per job."""
  5332. printer_ids: set[int] = set()
  5333. for candidate in _candidates_for(item):
  5334. if not candidate.target_model:
  5335. continue
  5336. key = (candidate.target_model, item.target_location, item.created_by_id)
  5337. if key not in cache:
  5338. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5339. cache[key] = {printer.id for printer in printers}
  5340. printer_ids |= cache[key]
  5341. return printer_ids
  5342. async def _check_auto_drying(
  5343. self,
  5344. db: AsyncSession,
  5345. queue_items: list[PrintQueueItem],
  5346. dispatching_printers: set[int],
  5347. ):
  5348. """Start drying on idle printers based on humidity.
  5349. Three modes (can all be enabled independently):
  5350. - queue_drying_enabled: Dry between scheduled queue prints
  5351. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5352. - print_drying_enabled: Also evaluate printers that are currently printing,
  5353. when model+firmware supports "Print While Drying" (gated by
  5354. supports_drying_while_printing). Drying temperature is capped at
  5355. max(40, preset_temp - 5) to protect spools mid-print.
  5356. """
  5357. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5358. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5359. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5360. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5361. # The wait belongs to ambient drying: the settings UI only shows it while
  5362. # ambient drying is on, so a value left behind when ambient is turned off
  5363. # must not keep delaying the one path that still reaches the wait gate
  5364. # without it (a mid-print start under print_drying).
  5365. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5366. # Clear every streak as soon as the wait is inactive. An early return (or
  5367. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5368. # a quick toggle-on inherit an old streak.
  5369. if not sustained_wait_active:
  5370. self._auto_dry_above.clear()
  5371. if not queue_drying_enabled and not ambient_drying_enabled:
  5372. # Stop active drying on all printers if both features disabled
  5373. if self._drying_in_progress:
  5374. for pid in list(self._drying_in_progress):
  5375. if pid in self._scheduled_drying_printer_ids:
  5376. continue
  5377. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5378. await self._stop_drying(pid)
  5379. return
  5380. # Update drying state from printer status (handles backend restart)
  5381. self._sync_drying_state()
  5382. # Find printers with scheduled items (for queue drying mode)
  5383. # An "Any <model>" job counts for every printer it could land on.
  5384. printers_with_scheduled: set[int] = set()
  5385. # Printers with a job that could start now: the ones block mode keeps
  5386. # a new cycle off. A job waiting for its start time is what queue
  5387. # drying dries ahead of.
  5388. printers_with_ready_items: set[int] = set()
  5389. now_utc = datetime.now(timezone.utc)
  5390. creator_scopes: dict[int | None, PrinterScope] = {}
  5391. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5392. for item in queue_items:
  5393. if item.printer_id:
  5394. item_printers = {item.printer_id}
  5395. elif item.target_model or item.variants:
  5396. if item.created_by_id not in creator_scopes:
  5397. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5398. item_printers = await self._model_job_printer_ids(
  5399. db, item, creator_scopes[item.created_by_id], model_printers
  5400. )
  5401. else:
  5402. continue
  5403. if item.scheduled_time and not item.manual_start:
  5404. printers_with_scheduled |= item_printers
  5405. sched = item.scheduled_time
  5406. if sched is not None and sched.tzinfo is None:
  5407. sched = sched.replace(tzinfo=timezone.utc)
  5408. if sched is None or sched <= now_utc:
  5409. printers_with_ready_items |= item_printers
  5410. # If only queue mode is on and no printers have scheduled items, stop drying
  5411. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5412. # may still be eligible for mid-print drying regardless of queue state).
  5413. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5414. for pid in list(self._drying_in_progress):
  5415. if pid in self._scheduled_drying_printer_ids:
  5416. continue
  5417. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5418. await self._stop_drying(pid)
  5419. return
  5420. # Get humidity threshold (global fallback)
  5421. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5422. setting = result.scalar_one_or_none()
  5423. global_humidity_threshold = int(setting.value) if setting else 60
  5424. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5425. # to the global threshold for every AMS unit.
  5426. per_type_thresholds = await self._get_humidity_thresholds(db)
  5427. # Get drying presets
  5428. presets = await self._get_drying_presets(db)
  5429. # Determine if drying should be skipped for printers with pending items
  5430. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5431. # Get all active printers
  5432. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5433. for printer in all_printers.scalars():
  5434. pid = printer.id
  5435. # Resolve model+firmware up front — needed to decide whether this printer
  5436. # qualifies for mid-print drying (busy printer on capable hardware).
  5437. state = printer_manager.get_status(pid)
  5438. if not state:
  5439. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5440. continue
  5441. model = printer_manager.get_model(pid)
  5442. firmware = state.firmware_version
  5443. # "Mid-print" has to mean the printer is actually printing (#2801).
  5444. # It used to be inferred from the dispatch set, which also holds
  5445. # printers that merely could not be dispatched to -- so a printer
  5446. # sitting in FINISH behind an unacknowledged plate was treated as
  5447. # printing, had its drying temperature capped by the mid-print
  5448. # spool protection, and was logged as (mid-print) while idle.
  5449. is_printing = state.state in _ACTIVE_PRINT_STATES
  5450. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5451. # A printer whose print is running or imminent is left alone unless
  5452. # it can dry through it. `dispatching_printers` is deliberately the
  5453. # narrow set: running, held post-dispatch, or mid-upload.
  5454. if (is_printing or pid in dispatching_printers) and not mid_print:
  5455. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5456. continue
  5457. if not mid_print:
  5458. # In queue-only mode, only dry printers that have scheduled prints
  5459. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5460. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5461. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5462. await self._stop_drying(pid)
  5463. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5464. continue
  5465. # When block mode is on, don't START new drying on printers with
  5466. # a job that could start now: the cycle would hold it. One
  5467. # scheduled for later may pre-dry; if the cycle is still running
  5468. # at its time, the hold applies then. Already-drying printers go
  5469. # through so humidity auto-stop logic still runs.
  5470. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5471. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5472. continue
  5473. if not printer_manager.is_connected(pid):
  5474. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5475. continue
  5476. # Plate-clear is deliberately ignored here (#2801). It answers
  5477. # "is the bed ready for the next job", which says nothing about
  5478. # whether the AMS may heat -- and the gap between a finished print
  5479. # and the acknowledgment is exactly when drying is most useful,
  5480. # because the printer is free and nobody is waiting on it. Leaving
  5481. # the plate unacknowledged is also how people hold the queue by
  5482. # hand, and that hold should not cost them their drying.
  5483. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5484. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5485. continue
  5486. # Check drying capability. For mid-print path, supports_drying_while_printing
  5487. # was already verified when computing mid_print above.
  5488. if not mid_print and not supports_drying(model, firmware):
  5489. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5490. continue
  5491. # Check each AMS unit from raw_data
  5492. ams_list = state.raw_data.get("ams", [])
  5493. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5494. for ams_data in ams_list:
  5495. module_type = str(ams_data.get("module_type") or "")
  5496. ams_id = int(ams_data.get("id", 0))
  5497. # Only n3f/n3s support drying
  5498. if module_type not in ("n3f", "n3s"):
  5499. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5500. continue
  5501. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5502. # Most-restrictive of all loaded tray types; falls back to the
  5503. # global threshold when no overrides are configured.
  5504. trays = ams_data.get("tray", []) or []
  5505. humidity_threshold = self.resolve_humidity_threshold(
  5506. trays, per_type_thresholds, global_humidity_threshold
  5507. )
  5508. dry_time = int(ams_data.get("dry_time") or 0)
  5509. # Read humidity as a percentage. The 1-5 index is never
  5510. # substituted: it is inverted, and being unable to exceed any
  5511. # threshold it would read as "dry" forever (#3140). ``None``
  5512. # already means "skip this unit" everywhere below.
  5513. humidity_pct = ams_humidity_percent(ams_data)
  5514. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5515. unit_key = (pid, ams_id)
  5516. unit_state = self._auto_dry_units.get(unit_key)
  5517. # Already drying — let it run to its configured duration (#1892).
  5518. #
  5519. # We deliberately do NOT stop drying from a humidity re-check here.
  5520. # Relative humidity drops steeply in heated air, so the AMS sensor
  5521. # reads ~15-20% within minutes of the dryer starting even while the
  5522. # filament is still saturated. A humidity-based early-stop therefore
  5523. # always fires at the minimum-time floor, truncating both user-started
  5524. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5525. # The firmware stops when the configured duration elapses; scheduling
  5526. # stops (print takes priority, queue no longer needs drying) are
  5527. # handled separately via _stop_drying().
  5528. if dry_time > 0:
  5529. if pid not in self._drying_in_progress:
  5530. # Drying we didn't start (manual or from before restart) —
  5531. # track it so scheduling stops still apply; never auto-stop it.
  5532. self._drying_in_progress[pid] = time.monotonic()
  5533. if unit_state is not None:
  5534. unit_state["running"] = True
  5535. logger.debug(
  5536. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5537. pid,
  5538. ams_id,
  5539. dry_time,
  5540. humidity,
  5541. )
  5542. continue
  5543. # Nothing is drying. Close out a cycle we armed ourselves and
  5544. # judge whether it achieved anything (#2770).
  5545. #
  5546. # "Achieved anything" is measured against the LOWEST reading any
  5547. # cycle on this unit has ended at, not against the threshold and
  5548. # not against the previous cycle. A spool that is genuinely wet
  5549. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5550. # allowed to keep going for as long as it is still coming down,
  5551. # however far it still is from the threshold. What must not
  5552. # continue is a cycle that ends exactly where the last one did,
  5553. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5554. # Comparing against the running minimum rather than the previous
  5555. # end is what stops a sensor oscillating by one point between two
  5556. # values from reading as progress every other cycle.
  5557. if unit_state is not None and unit_state.pop("running", False):
  5558. unit_state["ended_at"] = time.monotonic()
  5559. # The streak that armed this cycle is spent; the next one
  5560. # starts fresh (and accumulates through the re-arm cooldown
  5561. # below, so the wait overlaps the cooldown, never stacks on
  5562. # top of it).
  5563. self._auto_dry_above.pop(unit_key, None)
  5564. if humidity is not None and humidity > humidity_threshold:
  5565. best = unit_state.get("best_end_humidity")
  5566. if isinstance(best, int) and humidity < best:
  5567. # Still coming down. Keep going, however far the
  5568. # threshold still is.
  5569. unproductive = 0
  5570. else:
  5571. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5572. if not isinstance(best, int) or humidity < best:
  5573. unit_state["best_end_humidity"] = humidity
  5574. unit_state["unproductive"] = unproductive
  5575. logger.info(
  5576. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5577. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5578. pid,
  5579. ams_id,
  5580. humidity,
  5581. humidity_threshold,
  5582. unit_state.get("best_end_humidity"),
  5583. unproductive,
  5584. )
  5585. # A cycle that ended at or below the threshold needs no
  5586. # counter reset here: the branch below drops the whole entry.
  5587. # Humidity below threshold — no need to start drying. This is
  5588. # also the only thing that lifts a suspension: the reading we
  5589. # gave up on has come down, so auto-drying works again and the
  5590. # unit goes back to having no history at all.
  5591. if humidity is None or humidity <= humidity_threshold:
  5592. if unit_state is not None and unit_state.get("suspended"):
  5593. logger.info(
  5594. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5595. "threshold, resuming automatic drying",
  5596. pid,
  5597. ams_id,
  5598. humidity,
  5599. humidity_threshold,
  5600. )
  5601. # Clear the judgement, keep the clock (#2801). Dropping the
  5602. # whole entry also dropped `ended_at`, and with it the
  5603. # 30-minute cooldown -- so a reading that dips to the
  5604. # threshold as the AMS cools and comes back above it once
  5605. # warm wiped its own history and re-armed immediately. That
  5606. # oscillation is the very thing #2770's cooldown exists to
  5607. # ride out, and it is worst at exactly the margin that makes
  5608. # a unit dry repeatedly: a point or two above the threshold.
  5609. if unit_state is not None:
  5610. unit_state.pop("suspended", None)
  5611. unit_state.pop("unproductive", None)
  5612. unit_state.pop("best_end_humidity", None)
  5613. # A real below-threshold reading ends any sustained-wait
  5614. # streak (#2518) -- "continuously above" means exactly that.
  5615. # An absent reading (humidity is None) is no-information and
  5616. # leaves the streak alone; the observation-gap guard handles
  5617. # a prolonged sensor silence.
  5618. if humidity is not None:
  5619. _above = self._auto_dry_above.pop(unit_key, None)
  5620. if _above is not None and sustained_wait_active:
  5621. logger.info(
  5622. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5623. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5624. pid,
  5625. ams_id,
  5626. humidity,
  5627. time.monotonic() - _above["since"],
  5628. sustained_minutes,
  5629. humidity_threshold,
  5630. )
  5631. logger.debug(
  5632. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5633. pid,
  5634. ams_id,
  5635. humidity,
  5636. humidity_threshold,
  5637. )
  5638. continue
  5639. # Sustained-humidity streak (#2518): updated on every pass that
  5640. # observes the reading above the threshold, BEFORE the
  5641. # suspension/cooldown gates below -- a suspended or cooling-down
  5642. # unit still accumulates streak time, so the wait overlaps those
  5643. # gates instead of stacking after them. Inert when the feature
  5644. # is off: no entries are written, and an entry left over from a
  5645. # toggle-off is dropped so it cannot seed a stale streak later.
  5646. if sustained_wait_active:
  5647. _now = time.monotonic()
  5648. # Four missed scheduler passes, floored: a single slow pass
  5649. # must not void a streak, but the ceiling has to scale with
  5650. # the cadence or a slow loop silently restarts every streak.
  5651. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5652. _above = self._auto_dry_above.get(unit_key)
  5653. if _above is None:
  5654. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5655. elif _now - _above["last"] > _gap_ceiling:
  5656. # Restart, and say so at the same level as the dip
  5657. # reset: a silent restart voids the streak invisibly,
  5658. # and a user who set a long wait and never gets a dry
  5659. # has no way to see why.
  5660. logger.info(
  5661. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5662. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5663. pid,
  5664. ams_id,
  5665. _now - _above["last"],
  5666. _gap_ceiling,
  5667. sustained_minutes,
  5668. )
  5669. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5670. else:
  5671. _above["last"] = _now
  5672. else:
  5673. self._auto_dry_above.pop(unit_key, None)
  5674. if unit_state is not None:
  5675. if unit_state.get("suspended"):
  5676. logger.debug(
  5677. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5678. "above the %d%% threshold",
  5679. pid,
  5680. ams_id,
  5681. int(unit_state.get("unproductive", 0)),
  5682. humidity_threshold,
  5683. )
  5684. continue
  5685. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5686. unit_state["suspended"] = True
  5687. logger.warning(
  5688. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5689. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5690. "higher while it is warm, so a threshold in that range can never be reached and "
  5691. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5692. pid,
  5693. ams_id,
  5694. int(unit_state.get("unproductive", 0)),
  5695. humidity,
  5696. humidity_threshold,
  5697. )
  5698. await self._notify_auto_drying_suspended(
  5699. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5700. )
  5701. continue
  5702. ended_at = unit_state.get("ended_at")
  5703. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5704. logger.debug(
  5705. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5706. "cycle before the humidity reading is worth acting on",
  5707. pid,
  5708. ams_id,
  5709. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5710. )
  5711. continue
  5712. # Check cannot-dry reasons (power constraints etc.). Sits
  5713. # ahead of the sustained wait so a unit the firmware refuses
  5714. # to dry never logs a wait it was never going to cash in.
  5715. sf_reasons = ams_data.get("dry_sf_reason", [])
  5716. if sf_reasons:
  5717. logger.debug(
  5718. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5719. pid,
  5720. ams_id,
  5721. sf_reasons,
  5722. )
  5723. continue
  5724. # Sustained-humidity wait (#2518): ambient-triggered starts
  5725. # wait; only a printer with a scheduled queue item pending
  5726. # keeps the instant behavior, because that drying has a real
  5727. # deadline. Mid-print is deliberately NOT exempt while ambient
  5728. # drying is on: a humidity start on a printer that happens to be
  5729. # printing is as vulnerable to a lid-open spike as one on an idle
  5730. # printer (proven live: a 2-point threshold crossing mid-print
  5731. # bought a parked 12h command). Inactive when ambient drying is
  5732. # off: print_drying then still starts mid-print cycles on its own
  5733. # (#1816, "regardless of queue state"), and those stay instant.
  5734. if sustained_wait_active and pid not in printers_with_scheduled:
  5735. _above = self._auto_dry_above.get(unit_key)
  5736. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5737. if _waited < sustained_minutes * 60:
  5738. logger.debug(
  5739. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5740. "threshold for %.0fs of the required %dm",
  5741. pid,
  5742. ams_id,
  5743. humidity,
  5744. humidity_threshold,
  5745. _waited,
  5746. sustained_minutes,
  5747. )
  5748. continue
  5749. # Get conservative drying params for mixed filaments
  5750. params = self._get_conservative_drying_params(trays, module_type, presets)
  5751. if not params:
  5752. logger.debug(
  5753. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5754. )
  5755. continue
  5756. temp, duration_hours, filament_type = params
  5757. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5758. # "drying temperature must not exceed the filament's softening temperature"
  5759. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5760. # ineffective and firmware will reject anyway.
  5761. if mid_print:
  5762. temp = max(40, temp - 5)
  5763. # Start drying
  5764. logger.info(
  5765. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5766. "starting %s drying at %d°C for %dh%s",
  5767. pid,
  5768. ams_id,
  5769. humidity,
  5770. humidity_threshold,
  5771. filament_type,
  5772. temp,
  5773. duration_hours,
  5774. " (mid-print)" if mid_print else "",
  5775. )
  5776. success = printer_manager.send_drying_command(
  5777. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5778. )
  5779. if success:
  5780. self._drying_in_progress[pid] = time.monotonic()
  5781. armed = self._auto_dry_units.setdefault(
  5782. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5783. )
  5784. armed["running"] = True
  5785. async def _notify_auto_drying_suspended(
  5786. self,
  5787. db: AsyncSession,
  5788. printer: Printer,
  5789. ams_id: int,
  5790. humidity: int,
  5791. threshold: int,
  5792. cycles: int,
  5793. ) -> None:
  5794. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5795. Fires once per suspension — the caller sets ``suspended`` before calling
  5796. and every later pass short-circuits on it — because the whole point is
  5797. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5798. building needs that to reach them, and the hourly humidity alarm they
  5799. are already getting says the opposite of what happened here.
  5800. Never raises: a notification provider being down must not stop the
  5801. suspension itself from taking effect.
  5802. """
  5803. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5804. try:
  5805. await notification_service.on_ams_drying_suspended(
  5806. printer.id,
  5807. printer.name,
  5808. ams_label,
  5809. float(humidity),
  5810. float(threshold),
  5811. cycles,
  5812. db,
  5813. )
  5814. except Exception as e:
  5815. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5816. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5817. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5818. The unproductive-cycle counter exists to notice that *drying* is not
  5819. moving the humidity reading. A cycle that ended because somebody sent a
  5820. stop says nothing about that — it was cut short before it had a chance —
  5821. so counting it would suspend auto-drying for a reason that has nothing to
  5822. do with the loop the counter is there to break.
  5823. Two callers, both of them a stop Bambuddy is responsible for: the
  5824. print-takes-priority stop below, and the manual Stop button. Left
  5825. uncalled, an install that dries between queue jobs would suspend its own
  5826. auto-drying after two prints interrupted a dry — exactly the install
  5827. queue-drying exists for.
  5828. The rest of the unit's history is kept: the cooldown before re-arming
  5829. still applies, and an earlier count still stands.
  5830. """
  5831. state = self._auto_dry_units.get((printer_id, ams_id))
  5832. if state is not None:
  5833. state.pop("running", None)
  5834. state["ended_at"] = time.monotonic()
  5835. # A stopped cycle spends the streak that armed it, same as a completed
  5836. # one (#2518).
  5837. self._auto_dry_above.pop((printer_id, ams_id), None)
  5838. def _sync_drying_state(self):
  5839. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5840. One direction only: it prunes, it never adds. A printer drying without an
  5841. entry here — because the user started the cycle from Studio, the printer's
  5842. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5843. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5844. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5845. That is deliberate for now rather than an oversight: populating this from
  5846. telemetry would hand the scheduler authority to stop drying a user started
  5847. by hand. It also means the backend-restart case this used to claim to
  5848. handle is not handled.
  5849. """
  5850. to_remove = []
  5851. for pid in self._drying_in_progress:
  5852. state = printer_manager.get_status(pid)
  5853. if not state:
  5854. to_remove.append(pid)
  5855. continue
  5856. # Check if any AMS unit is still drying
  5857. ams_list = state.raw_data.get("ams", [])
  5858. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5859. if not any_drying:
  5860. to_remove.append(pid)
  5861. for pid in to_remove:
  5862. self._drying_in_progress.pop(pid, None)
  5863. # A printer that has gone away entirely takes its per-AMS auto-drying
  5864. # history with it (#2770), so a printer deleted and re-added does not
  5865. # inherit a suspension it never earned.
  5866. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5867. self._auto_dry_units.pop(key, None)
  5868. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5869. # printer starts a fresh wait, and vanished printers do not leak
  5870. # entries.
  5871. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5872. self._auto_dry_above.pop(key, None)
  5873. @staticmethod
  5874. def _drying_is_only_parked(printer_id: int) -> bool:
  5875. """True when every AMS unit with a drying timer on this printer is parked.
  5876. A parked timer (#2896: the command was taken but the countdown never
  5877. runs) does not end on its own, so nothing may wait on it. False when no
  5878. unit reports a timer yet -- a command just sent that the firmware has not
  5879. reported back is real drying about to begin.
  5880. """
  5881. state = printer_manager.get_status(printer_id)
  5882. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5883. timed = []
  5884. for unit in units:
  5885. try:
  5886. if int(unit.get("dry_time") or 0) > 0:
  5887. timed.append(unit)
  5888. except (TypeError, ValueError):
  5889. continue
  5890. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5891. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5892. """True when a running cycle can be left alone while the next print runs.
  5893. Some hardware dries happily through a print and #2758 settled that we
  5894. should not tear those cycles down: the X2D there was refusing to
  5895. *start* a job, which is a different problem, and stopping drying before
  5896. every dispatch would throw away cycles the printer was content to run.
  5897. Where the model cannot do it, or the user has not enabled it, the print
  5898. takes priority and the cycle stops -- which is what the queue_drying_block
  5899. setting has always promised in its off position.
  5900. """
  5901. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5902. return False
  5903. status = printer_manager.get_status(printer_id)
  5904. return supports_drying_while_printing(
  5905. printer_manager.get_model(printer_id),
  5906. status.firmware_version if status else None,
  5907. )
  5908. async def _stop_drying(self, printer_id: int):
  5909. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5910. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5911. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5912. enough to kill a cycle the user had started by hand on a *different*
  5913. unit of the same printer (#2801). That contradicted the contract
  5914. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5915. only knows about cycles Bambuddy began, so the action must not reach
  5916. past them either.
  5917. """
  5918. state = printer_manager.get_status(printer_id)
  5919. if not state:
  5920. self._drying_in_progress.pop(printer_id, None)
  5921. return
  5922. ams_list = state.raw_data.get("ams", [])
  5923. for ams_data in ams_list:
  5924. dry_time = int(ams_data.get("dry_time") or 0)
  5925. if dry_time > 0:
  5926. ams_id = int(ams_data.get("id", 0))
  5927. if (printer_id, ams_id) not in self._auto_dry_units:
  5928. logger.debug(
  5929. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5930. printer_id,
  5931. ams_id,
  5932. )
  5933. continue
  5934. logger.info(
  5935. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5936. printer_id,
  5937. ams_id,
  5938. )
  5939. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5940. self.forget_auto_dry_cycle(printer_id, ams_id)
  5941. self._drying_in_progress.pop(printer_id, None)
  5942. # Scheduled manual drying (#2638) -----------------------------------
  5943. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5944. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5945. async def _check_scheduled_dryings(self, db: AsyncSession):
  5946. """Dispatch due scheduled drying runs and track running ones."""
  5947. now = utcnow_naive()
  5948. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5949. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5950. since_prune = time.monotonic()
  5951. if (
  5952. self._last_scheduled_drying_prune is None
  5953. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5954. ):
  5955. self._last_scheduled_drying_prune = since_prune
  5956. await db.execute(
  5957. delete(ScheduledDrying).where(
  5958. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5959. ScheduledDrying.completed_at.is_not(None),
  5960. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5961. )
  5962. )
  5963. # Same order as the list route: with two rows due on one printer the
  5964. # earliest scheduled wins rather than whatever the DB hands back first.
  5965. result = await db.execute(
  5966. select(ScheduledDrying)
  5967. .where(ScheduledDrying.status.in_(("pending", "running")))
  5968. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5969. )
  5970. rows = list(result.scalars().all())
  5971. # Rebuild from the DB every tick so route-side cancels and completions
  5972. # show up. Auto-drying's stop-all branches check this set before
  5973. # stopping anything (#2638).
  5974. # Kept from the previous pass so a run that ended between passes — a
  5975. # cancel through the route, say — can still be released below.
  5976. previously_running = self._scheduled_drying_printer_ids
  5977. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5978. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5979. # Model and firmware come from the printer row, not the live state.
  5980. printer_ids = {row.printer_id for row in rows}
  5981. printers_by_id: dict[int, Printer] = {}
  5982. if printer_ids:
  5983. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5984. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5985. for row in rows:
  5986. if row.status == "running":
  5987. self._update_running_scheduled_drying(row, now)
  5988. continue
  5989. if row.start_after is not None and row.start_after > now:
  5990. continue
  5991. state = printer_manager.get_status(row.printer_id)
  5992. if not state:
  5993. row.waiting_reason = "printer_offline"
  5994. continue
  5995. # Same preflight the immediate endpoint runs. Without it the publish
  5996. # succeeds, the row goes to running, the printer ignores the command
  5997. # and the run silently cancels itself after the grace window.
  5998. printer = printers_by_id.get(row.printer_id)
  5999. unsupported = drying_preflight.check_drying_supported(
  6000. printer.model if printer else None, state.firmware_version
  6001. )
  6002. if unsupported:
  6003. row.status = "failed"
  6004. row.error_message = unsupported
  6005. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6006. row.completed_at = now
  6007. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6008. continue
  6009. if (
  6010. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6011. ) or row.printer_id in running_printer_ids:
  6012. row.waiting_reason = "already_drying"
  6013. continue
  6014. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6015. row.waiting_reason = "printer_busy"
  6016. continue
  6017. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6018. if target is None:
  6019. row.waiting_reason = "ams_not_found"
  6020. continue
  6021. blocking = drying_preflight.blocking_reason_codes(target)
  6022. if blocking:
  6023. # Keep the power case distinct; it needs the user to act, so the
  6024. # card can say so instead of waiting silently.
  6025. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6026. continue
  6027. filament = drying_preflight.resolve_filament(target, row.filament)
  6028. logger.info(
  6029. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6030. row.id,
  6031. row.printer_id,
  6032. row.ams_id,
  6033. row.temp,
  6034. row.duration_hours,
  6035. )
  6036. success = printer_manager.send_drying_command(
  6037. row.printer_id,
  6038. row.ams_id,
  6039. row.temp,
  6040. row.duration_hours,
  6041. mode=1,
  6042. filament=filament,
  6043. rotate_tray=row.rotate_tray,
  6044. )
  6045. if success:
  6046. row.status = "running"
  6047. row.started_at = now
  6048. row.waiting_reason = None
  6049. row.filament = filament
  6050. self._drying_in_progress[row.printer_id] = time.monotonic()
  6051. self._scheduled_drying_printer_ids.add(row.printer_id)
  6052. running_printer_ids.add(row.printer_id)
  6053. else:
  6054. row.waiting_reason = "printer_offline"
  6055. # Release the printers whose run has ended. `_drying_in_progress` is
  6056. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6057. # but that call sits behind the auto-drying enabled check, and this
  6058. # method is the one writer that runs whether auto-drying is on or not.
  6059. # With it off, nothing would ever drop the entry short of a print being
  6060. # dispatched to the same printer, so the next scheduled run would wait
  6061. # on "already_drying" forever and `queue_drying_block` would hold the
  6062. # printer's prints too. Covers a run that ended during this pass and one
  6063. # cancelled through the route between passes.
  6064. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6065. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6066. self._drying_in_progress.pop(printer_id, None)
  6067. await db.commit()
  6068. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6069. """Detect completion or interruption of a running scheduled drying.
  6070. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6071. drying. Within the grace window after start we ignore dry_time==0
  6072. (the status lags the command). After that, dry_time==0 near the end
  6073. of the configured duration means completed. Much earlier means the
  6074. run was stopped: re-queue it if a print preempted the dryer, but a
  6075. stop while the printer is idle was deliberate, so cancel the row
  6076. rather than restart drying the user just stopped.
  6077. """
  6078. if row.started_at is None:
  6079. row.started_at = now
  6080. return
  6081. elapsed = (now - row.started_at).total_seconds()
  6082. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6083. return
  6084. state = printer_manager.get_status(row.printer_id)
  6085. if not state:
  6086. return # offline mid-dry; resolve when it reconnects
  6087. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6088. # throw on a malformed id would cost the whole pass including print
  6089. # dispatch, every tick.
  6090. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6091. try:
  6092. dry_time = int(target.get("dry_time") or 0) if target else 0
  6093. except (TypeError, ValueError):
  6094. dry_time = 0
  6095. if dry_time > 0 and is_countdown_parked(target):
  6096. # The printer took the command but the countdown is not running
  6097. # (#2896) and will never reach 0, so the run would stay "running"
  6098. # forever. A print in progress is the likely cause (the power budget
  6099. # is spent), so re-queue it like any interruption; the next start
  6100. # waits for the printer to be idle. Parked on an idle printer is a
  6101. # refusal, not something a retry fixes. The timer itself is left on
  6102. # the printer: it may yet start once power frees up.
  6103. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6104. logger.info(
  6105. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6106. row.id,
  6107. row.ams_id,
  6108. )
  6109. row.status = "pending"
  6110. row.started_at = None
  6111. row.waiting_reason = "interrupted"
  6112. else:
  6113. logger.warning(
  6114. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6115. row.id,
  6116. row.ams_id,
  6117. )
  6118. row.status = "failed"
  6119. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6120. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6121. row.completed_at = now
  6122. return
  6123. if dry_time > 0:
  6124. return
  6125. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6126. row.status = "completed"
  6127. row.completed_at = now
  6128. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6129. row.status = "pending"
  6130. row.started_at = None
  6131. row.waiting_reason = "interrupted"
  6132. else:
  6133. row.status = "cancelled"
  6134. row.completed_at = now
  6135. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6136. """Get all smart plugs associated with a printer."""
  6137. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6138. return list(result.scalars().all())
  6139. @staticmethod
  6140. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6141. """Pick the plug to power-cycle a printer back online with (#2629).
  6142. Only a plug flagged ``controls_printer_power`` can actually bring the
  6143. printer back; waiting for a boot on an accessory (filter fan, lights)
  6144. just burns the power-on timeout and fails the dispatch. Falls back to
  6145. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6146. Callers must pass a non-empty list.
  6147. """
  6148. for plug in auto_on_plugs:
  6149. if plug.controls_printer_power:
  6150. return plug
  6151. return auto_on_plugs[0]
  6152. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6153. # chamber-temperature recommendations BambuStudio ships for the matching
  6154. # filament profile; users can override via Settings → Workflow → Preheat
  6155. # card. "default" applies when a loaded tray's normalised type isn't in
  6156. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6157. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6158. "PLA": 0,
  6159. "PETG": 0,
  6160. "PETG-CF": 40,
  6161. "ABS": 45,
  6162. "ASA": 45,
  6163. "PA": 50,
  6164. "PA-CF": 55,
  6165. "PC": 50,
  6166. "PC-FR": 50,
  6167. "TPU": 0,
  6168. "PVA": 0,
  6169. "default": 0,
  6170. }
  6171. @classmethod
  6172. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6173. """The bundled map under the same key casing a parsed one gets.
  6174. The constant is declared with a lowercase ``default`` because that is
  6175. the key the Settings editor writes and displays. Every read of the map
  6176. happens after ``str(key).upper()``, so handing the constant back as
  6177. declared broke the contract the parser documents: an install that had
  6178. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6179. and the resolution loop's fallback silently found nothing. It read the
  6180. right number only because the bundled default happens to be 0 -- change
  6181. that constant and every unconfigured install would keep preheating to
  6182. zero with no way to tell why.
  6183. """
  6184. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6185. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6186. """Parse the user-configured filament→chamber-target map, falling back
  6187. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6188. are uppercased and the 'default' fallback is always present in the
  6189. returned dict so the resolution loop can index it unconditionally."""
  6190. raw = await self._get_setting(db, "preheat_filament_targets")
  6191. if not raw:
  6192. return self._bundled_preheat_targets()
  6193. try:
  6194. parsed = json.loads(raw)
  6195. if not isinstance(parsed, dict):
  6196. raise ValueError("not an object")
  6197. except (json.JSONDecodeError, ValueError) as exc:
  6198. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6199. return self._bundled_preheat_targets()
  6200. # Coerce values to int; drop unparseable rows so a stray string
  6201. # doesn't crash the loop.
  6202. out: dict[str, int] = {}
  6203. for key, value in parsed.items():
  6204. try:
  6205. out[str(key).upper()] = int(value)
  6206. except (TypeError, ValueError):
  6207. continue
  6208. if "DEFAULT" not in out:
  6209. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6210. return out
  6211. @staticmethod
  6212. def _normalize_filament_type(tray_type: str) -> str:
  6213. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6214. existing drying-preset normalisation (split-at-space, upper-case) so
  6215. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6216. "PA-CF" (no space to split on).
  6217. This is the first stage of ``_resolve_filament_key``, which goes on to
  6218. drop the suffix and consult the alias map; on its own it only decides
  6219. what the tray is called, not which row answers for it.
  6220. Indexing the split rather than testing the input: a tray_type of spaces
  6221. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6222. it through to an IndexError.
  6223. """
  6224. words = (tray_type or "").split()
  6225. return words[0].upper() if words else ""
  6226. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6227. """Per-filament chamber target for one tray's reported type, or 0 when
  6228. the tray is empty / RFID-less and reports no type at all.
  6229. A filled or foamed variant wants its base material's chamber when the
  6230. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6231. not the 0 an unknown type falls to. The specific type is still tried
  6232. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6233. (#2902).
  6234. That lookup is now the shared one, which adds the polyamide aliases on
  6235. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6236. too, rather than the catch-all it was landing on (#3067).
  6237. """
  6238. if not self._normalize_filament_type(tray_type or ""):
  6239. return 0
  6240. key = self._resolve_filament_key(tray_type, targets)
  6241. if key is not None:
  6242. return targets[key]
  6243. # A type the map does not list at all, which is not the same as a tray
  6244. # with nothing in it -- that already returned 0 above.
  6245. return targets.get("DEFAULT", 0)
  6246. def _derive_chamber_target(
  6247. self,
  6248. printer: Printer,
  6249. targets: dict[str, int],
  6250. item: PrintQueueItem | None = None,
  6251. ) -> int:
  6252. """Chamber target for the trays this print actually loads: the max of
  6253. their per-filament targets. Returns 0 when there is nothing to read (no
  6254. status, no AMS telemetry — e.g. external-spool prints) or when every
  6255. tray considered maps to 0, and the chamber phase then short-circuits in
  6256. the main loop.
  6257. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6258. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6259. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6260. plus soak burned ahead of each upload, on a printer whose chamber never
  6261. reaches the target anyway (#2886). An item with no usable mapping falls
  6262. back to scanning every loaded tray: that is the only signal left, and
  6263. narrowing to nothing would skip preheat on prints that genuinely need
  6264. it.
  6265. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6266. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6267. less slots have empty `tray_type` and contribute nothing. The external
  6268. spool is consulted only when the mapping names it (>= 254); it stays
  6269. out of the unnarrowed scan, so an item without a mapping derives from
  6270. the AMS alone exactly as before.
  6271. """
  6272. state = printer_manager.get_status(printer.id)
  6273. if state is None:
  6274. return 0
  6275. raw_data = state.raw_data or {}
  6276. used = _used_global_tray_ids(item)
  6277. ams_list = raw_data.get("ams")
  6278. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6279. if isinstance(ams_list, dict):
  6280. ams_list = ams_list.get("ams") or []
  6281. if not isinstance(ams_list, list):
  6282. ams_list = []
  6283. best = 0
  6284. for ams in ams_list:
  6285. if not isinstance(ams, dict):
  6286. continue
  6287. ams_id = _int_or(ams.get("id"), 0)
  6288. for tray in ams.get("tray") or []:
  6289. # A non-dict entry has never been seen from real firmware, but
  6290. # `.get` on one raises, and nothing between here and
  6291. # `_dispatch_one`'s try/finally catches it — the item would be
  6292. # left holding its dispatch claim. Preheat is best-effort by
  6293. # contract, so step over it instead.
  6294. if not isinstance(tray, dict):
  6295. continue
  6296. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6297. continue
  6298. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6299. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6300. for vt in raw_data.get("vt_tray") or []:
  6301. if not isinstance(vt, dict):
  6302. continue
  6303. # `_build_loaded_filaments` addresses external feeds by the id
  6304. # the firmware reports — 255 main, 254 deputy — defaulting to
  6305. # 254 when the field is absent. Same expression here so the two
  6306. # agree on which entry a mapping's 254/255 refers to.
  6307. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6308. continue
  6309. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6310. return best
  6311. def _release_keep_warm(self, pid: int) -> None:
  6312. """Release keep-warm on a printer that left the candidate set.
  6313. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6314. reports the target we set (``entry.held_target``), so a user or
  6315. subsequent print that changed the bed target since is not clobbered.
  6316. Best-effort, never raises.
  6317. The entry is kept, not dropped, when the printer cannot be reached
  6318. right now: a printer that is briefly offline still has a hot bed, and
  6319. holding the entry is what keeps the max-duration timeout applying and
  6320. lets a later tick retry the release. Only a printer that has left the
  6321. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6322. """
  6323. entry = self._keep_warm.get(pid)
  6324. if entry is None:
  6325. return
  6326. state = printer_manager.get_status(pid)
  6327. client = printer_manager.get_client(pid)
  6328. if state is None or client is None:
  6329. logger.debug(
  6330. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6331. pid,
  6332. )
  6333. return
  6334. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6335. if int(cur_bed_target) != entry.held_target:
  6336. # Someone else owns the bed now, so there is nothing of ours to
  6337. # undo and nothing left to track.
  6338. logger.info(
  6339. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6340. pid,
  6341. int(cur_bed_target),
  6342. entry.held_target,
  6343. )
  6344. self._keep_warm.pop(pid, None)
  6345. return
  6346. try:
  6347. client.set_bed_temperature(0)
  6348. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6349. self._keep_warm.pop(pid, None)
  6350. except Exception as exc:
  6351. # Keep the entry so the next tick tries again rather than leaving
  6352. # the bed hot with nothing tracking it.
  6353. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6354. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6355. """Release printers that dropped out of the keep-warm candidate set.
  6356. Called from ``_apply_keep_warm`` on every tick (with the current
  6357. candidate set), and from ``check_queue``'s no-pending-items early
  6358. return (with an empty candidate set) so orphaned holds still get
  6359. released when the queue empties. Also called with an empty candidate
  6360. set when any of the three gate settings toggles off, so a printer
  6361. whose feature was disabled mid-hold gets its bed released.
  6362. Printers being dispatched this tick are excluded from the bed-off
  6363. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6364. transient 0 in between would just churn against preheat. Ownership of
  6365. the hot bed transfers to the preheat rollback pin instead — if the
  6366. dispatch aborts before the print starts (failed upload, cancelled
  6367. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6368. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6369. is the ONLY thing standing between an aborted dispatch and a bed
  6370. left hot with no owner. A successful print start clears the pin and
  6371. the print's own gcode takes over, as usual.
  6372. """
  6373. for _pid in list(self._keep_warm):
  6374. if _pid in active_candidates:
  6375. continue
  6376. if _pid in dispatched:
  6377. handed_over = self._keep_warm.pop(_pid, None)
  6378. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6379. if handed_over is not None:
  6380. self._preheat_pin_bed[_pid] = handed_over.held_target
  6381. continue
  6382. self._release_keep_warm(_pid)
  6383. async def _apply_keep_warm(
  6384. self,
  6385. db: AsyncSession,
  6386. items: list[PrintQueueItem],
  6387. dispatch_ids: list[int] | set[int],
  6388. busy_printers: set[int],
  6389. require_plate_clear: bool,
  6390. ) -> None:
  6391. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6392. When a printer just finished a job (FINISH state) and the next queued
  6393. item needs chamber heating, hold the bed hot so the chamber stays warm
  6394. during the bed-clearing window. The bed is the chamber's heating
  6395. element here, not a print surface — nothing is printing during the
  6396. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6397. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6398. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6399. aftermarket chamber heaters), raised to the item's own parsed
  6400. bed_temperature when that is higher. Items whose archive metadata has
  6401. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6402. get a hold — chamber need is what gates the feature, not metadata.
  6403. Skips entirely for filaments that map to a 0°C chamber target
  6404. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6405. names, so a hot-chamber spool it never touches does not hold the bed of
  6406. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6407. whole unit, as every item was before. Printers being dispatched this
  6408. cycle are excluded:
  6409. ``_preheat_and_soak`` already handles their bed temperature.
  6410. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6411. released to 0 and the entry is latched ``expired=True`` so
  6412. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6413. MQTT: publish is skipped when firmware already has the target.
  6414. The release sweep runs BEFORE the engagement gate so a printer that
  6415. was owned by keep-warm still gets its bed released when any of the
  6416. three gate settings is toggled off mid-hold. The
  6417. ``check_queue`` early-return-when-no-items path also calls
  6418. ``_sweep_keep_warm`` directly to release orphaned holds.
  6419. """
  6420. dispatch_set = set(dispatch_ids)
  6421. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6422. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6423. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6424. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6425. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6426. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6427. # Release sweep first — must run even when gate_open is False so a
  6428. # printer owned by keep-warm when a gate toggles off gets released.
  6429. self._sweep_keep_warm(
  6430. active_candidates=warm_candidates if gate_open else set(),
  6431. dispatched=dispatched_printers,
  6432. )
  6433. if not gate_open:
  6434. return
  6435. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6436. max_hold_seconds = (
  6437. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6438. )
  6439. now_mono = time.monotonic()
  6440. filament_targets: dict[str, int] | None = None
  6441. for pid in warm_candidates:
  6442. entry = self._keep_warm.get(pid)
  6443. # Latched-expired: max-duration timeout already fired for this
  6444. # printer. Skip until the release sweep drops the entry (i.e.
  6445. # until the printer leaves the candidate set).
  6446. if entry is not None and entry.expired:
  6447. continue
  6448. # These two guards sit ahead of the max-duration check below, so an
  6449. # engaged hold only ages out while its printer is still reachable
  6450. # and still in FINISH. That is deliberate rather than a hole: with
  6451. # no status or no client there is no M140 to send anyway, and the
  6452. # elapsed check runs off `entry.started` so it fires on the first
  6453. # tick after the printer comes back. Leaving FINISH means the plate
  6454. # was cleared, which drops the printer out of `warm_candidates` and
  6455. # hands it to `_release_keep_warm` instead. The invariant worth
  6456. # preserving if this is ever reordered: every path out of an
  6457. # engaged hold ends in a bed-off, whether by timeout or release.
  6458. state = printer_manager.get_status(pid)
  6459. if state is None or state.state != "FINISH":
  6460. continue
  6461. client = printer_manager.get_client(pid)
  6462. if client is None:
  6463. continue
  6464. next_item = next((it for it in items if it.printer_id == pid), None)
  6465. if next_item is None:
  6466. continue
  6467. # Hold temperature: the configured keep-warm temp, raised to the
  6468. # item's own bed temp when the metadata reports a higher one. A
  6469. # missing bed_temperature (Orca gcode.3mf exports parse without
  6470. # one) does NOT skip the hold — chamber need gates the feature.
  6471. archive = next_item.archive
  6472. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6473. bed_target = max(item_bed, hold_temp)
  6474. if bed_target <= 0:
  6475. continue
  6476. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6477. if explicit is not None:
  6478. chamber_needed = int(explicit) > 0
  6479. else:
  6480. if filament_targets is None:
  6481. filament_targets = await self._get_preheat_filament_targets(db)
  6482. printer_obj = await self._get_printer(db, pid)
  6483. chamber_needed = (
  6484. printer_obj is not None
  6485. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6486. )
  6487. if not chamber_needed:
  6488. continue
  6489. # Seed the timer on first engagement; keep it on subsequent ticks
  6490. # (never re-seed — that would defeat the max-duration cap).
  6491. if entry is None:
  6492. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6493. self._keep_warm[pid] = entry
  6494. elapsed = now_mono - entry.started
  6495. if elapsed > max_hold_seconds:
  6496. # Timeout: publish bed → 0 once (if firmware still holds our
  6497. # target) and latch expired. The entry stays until the release
  6498. # sweep drops it, preventing the next tick from re-seeding.
  6499. logger.warning(
  6500. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6501. pid,
  6502. elapsed,
  6503. )
  6504. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6505. if int(cur_bed_target) == entry.held_target:
  6506. try:
  6507. client.set_bed_temperature(0)
  6508. except Exception as exc:
  6509. logger.warning(
  6510. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6511. pid,
  6512. exc,
  6513. )
  6514. else:
  6515. logger.info(
  6516. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6517. pid,
  6518. int(cur_bed_target),
  6519. entry.held_target,
  6520. )
  6521. entry.expired = True
  6522. continue
  6523. # Idempotence: skip publish when firmware already has our target.
  6524. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6525. if int(cur_bed_target) == bed_target:
  6526. entry.held_target = bed_target
  6527. continue
  6528. try:
  6529. client.set_bed_temperature(bed_target)
  6530. entry.held_target = bed_target
  6531. logger.info(
  6532. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6533. bed_target,
  6534. pid,
  6535. )
  6536. except Exception as exc:
  6537. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6538. def _sample_chamber_temps(self) -> None:
  6539. """Record a chamber temperature sample for every connected printer.
  6540. Called once per scheduler tick (every 3–30 s). Entries older than
  6541. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6542. Also evicts per-printer state whose printer_id is no longer registered
  6543. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6544. """
  6545. now = time.monotonic()
  6546. cutoff = now - self._chamber_history_ttl
  6547. statuses = printer_manager.get_all_statuses()
  6548. known_pids = set(statuses.keys())
  6549. for pid, status in statuses.items():
  6550. if status is None or not status.connected:
  6551. continue
  6552. temps = status.temperatures or {}
  6553. chamber = temps.get("chamber")
  6554. if chamber is None:
  6555. continue
  6556. hist = self._chamber_history.setdefault(pid, deque())
  6557. hist.append((now, float(chamber)))
  6558. while hist and hist[0][0] < cutoff:
  6559. hist.popleft()
  6560. # Evict state for printers that are no longer registered with the manager.
  6561. # This is the one place a keep-warm entry is dropped without releasing
  6562. # the bed: the printer is gone from the manager, so there is no client
  6563. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6564. # for printers that are merely unreachable, which is what makes this
  6565. # the terminal case rather than a silent leak.
  6566. for pid in list(self._chamber_history):
  6567. if pid not in known_pids:
  6568. self._chamber_history.pop(pid, None)
  6569. for pid in list(self._keep_warm):
  6570. if pid not in known_pids:
  6571. logger.info(
  6572. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6573. pid,
  6574. )
  6575. self._keep_warm.pop(pid, None)
  6576. for pid in list(self._preheat_pin):
  6577. if pid not in known_pids:
  6578. self._preheat_pin.pop(pid, None)
  6579. self._preheat_pin_bed.pop(pid, None)
  6580. def _chamber_soak_remaining(
  6581. self,
  6582. printer_id: int,
  6583. chamber_target: float,
  6584. soak_seconds: int,
  6585. tolerance: float = 2.0,
  6586. ) -> int:
  6587. """Return how many seconds of soak time are still needed.
  6588. Credits the time the chamber has already spent at temperature against
  6589. the configured soak. The credit may not start earlier than any of:
  6590. * **The newest sample.** Nothing recent means the printer stopped
  6591. reporting mid-observation and the chamber may have cooled unseen, so
  6592. the full soak is required. (A 2 h history whose last reading is half
  6593. an hour old is not evidence of anything — the measured cooling rate
  6594. is fast enough to cross the threshold in that time.)
  6595. * **The most recent contiguous run of samples.** A gap wider than
  6596. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6597. far side is not evidence of temperature.
  6598. * **The end of the most recent real dip below the threshold.**
  6599. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6600. — see that constant for the thermal reasoning. A stray low reading is
  6601. an artifact, and treating it as cooling would discard a soak that
  6602. actually happened.
  6603. Returns ``soak_seconds`` when nothing can be credited (no history,
  6604. stale history, or the chamber is below the threshold right now) and 0
  6605. once the credited time covers the whole soak.
  6606. """
  6607. hist = self._chamber_history.get(printer_id)
  6608. if not hist:
  6609. return soak_seconds
  6610. now = time.monotonic()
  6611. newest_ts, newest_temp = hist[-1]
  6612. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6613. return soak_seconds # stale — no fresh evidence to credit
  6614. threshold = chamber_target - tolerance
  6615. if newest_temp < threshold:
  6616. return soak_seconds # below target right now; nothing is soaked
  6617. samples = list(hist)
  6618. # Earliest point we have unbroken observations for.
  6619. credit_from = samples[-1][0]
  6620. for i in range(len(samples) - 1, 0, -1):
  6621. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6622. break
  6623. credit_from = samples[i - 1][0]
  6624. # Pull the credit forward to the end of the last significant dip. Each
  6625. # excursion is measured between the in-range readings that bracket it,
  6626. # so a lone stray sample is charged one sampling interval rather than
  6627. # zero, and the comparison errs towards calling a dip real.
  6628. i = 0
  6629. while i < len(samples):
  6630. if samples[i][1] >= threshold:
  6631. i += 1
  6632. continue
  6633. j = i
  6634. while j < len(samples) and samples[j][1] < threshold:
  6635. j += 1
  6636. # `newest_temp >= threshold` was checked above, so j is in range.
  6637. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6638. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6639. # Credit resumes at the last below-threshold sample rather than
  6640. # the first good one after it, so a recovered dip over-credits
  6641. # by up to one sampling interval — the opposite lean to the
  6642. # bracketing above. Both are bounded by the sample cadence and
  6643. # dwarfed by the grace period, so neither is worth the extra
  6644. # arithmetic to remove.
  6645. credit_from = max(credit_from, samples[j - 1][0])
  6646. i = j
  6647. return max(0, soak_seconds - int(now - credit_from))
  6648. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6649. """Tell an in-flight dispatch that its item no longer wants to print.
  6650. Called by the queue's cancel and delete routes. Those only write to the
  6651. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6652. observe — so preheat would keep heating for the rest of max_wait + soak
  6653. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6654. blocking every other queued item behind a print that is not happening.
  6655. Signalling in memory rather than re-reading the row keeps this off the
  6656. database entirely: no second session, no transaction held across a long
  6657. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6658. Bambuddy serves from a single uvicorn process with one scheduler task,
  6659. so the route and the dispatch always share this object. The flag is
  6660. advisory — dropping it (e.g. after a restart) only costs a wasted
  6661. preheat, never a wrongly-abandoned print.
  6662. Only ids with a dispatch actually in flight are recorded, so the set
  6663. stays bounded by the upload pool rather than growing once per cancelled
  6664. item for the life of the process. Skipping the rest loses nothing: an
  6665. item that is not in flight cannot start heating later either, because
  6666. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6667. the caller has already committed a terminal status (or deleted the row)
  6668. before calling this.
  6669. """
  6670. if item_id in self._inflight:
  6671. self._cancelled_dispatches.add(item_id)
  6672. # A print sent for it earlier that never started is not one any more.
  6673. self._forget_unstarted_print(item_id, unless_printing=False)
  6674. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6675. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6676. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6677. while it is parked, so the wait is chopped into
  6678. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6679. """
  6680. remaining = float(seconds)
  6681. while remaining > 0:
  6682. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6683. await asyncio.sleep(slice_secs)
  6684. remaining -= slice_secs
  6685. if item_id in self._cancelled_dispatches:
  6686. return False
  6687. return True
  6688. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6689. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6690. The full preheat stage does this as part of its own dispatch: an H2D
  6691. left in heating mode by the ABS job before it would otherwise cook the
  6692. PLA that follows. The skip path never reaches that code, so it calls
  6693. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6694. add to the rollback pin, because a flap set to cooling for a print that
  6695. needs no heat is where it should have been either way.
  6696. Best-effort like everything else in the stage: a refused command logs
  6697. and the dispatch carries on.
  6698. """
  6699. model = printer.model or ""
  6700. if not supports_airduct(model):
  6701. return
  6702. state = printer_manager.get_status(printer.id)
  6703. current = getattr(state, "airduct_mode", None) if state else None
  6704. if current == _AIRDUCT_MODE_COOLING:
  6705. return
  6706. client = printer_manager.get_client(printer.id)
  6707. if client is None:
  6708. return
  6709. try:
  6710. client.set_airduct_mode("cooling")
  6711. except Exception as exc:
  6712. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6713. async def _preheat_and_soak(
  6714. self,
  6715. db: AsyncSession,
  6716. item: PrintQueueItem,
  6717. printer: Printer,
  6718. archive: PrintArchive | None,
  6719. ) -> bool:
  6720. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6721. Returns True when the dispatch should carry on to the upload — including
  6722. every case where preheat is skipped, since a skipped preheat is not a
  6723. reason to abandon the print. Returns False only when the item stopped
  6724. wanting to be printed while the stage was waiting (cancelled or
  6725. deleted); the caller must then abandon the dispatch, and
  6726. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6727. Resolution order:
  6728. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6729. to the global `preheat_enabled` setting; 'on' forces the stage on
  6730. even if the global is off.
  6731. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6732. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6733. across the trays `item.ams_mapping` names (every loaded slot when
  6734. it names none).
  6735. 3. A target of 0 off the filament map skips the whole stage: the
  6736. materials this print loads want no chamber, so there is nothing to
  6737. soak for and the bed phase would only delay the upload (#3041).
  6738. An explicit 0 typed into the per-item override, or a per-item
  6739. 'on', still runs the bed phase and the soak — both are the user
  6740. asking for a warm bed in so many words.
  6741. 4. Three hardware tiers branch the wait loop:
  6742. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6743. send M141 to the resolved target, then wait for the chamber sensor
  6744. to reach it (or the max-wait timeout to elapse).
  6745. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6746. no M141; the bed is the only heat source, so we wait for the chamber
  6747. sensor to rise via bed radiation OR fall through on timeout.
  6748. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6749. temperature; the function just heats the bed and holds for the
  6750. configured soak duration.
  6751. The bed target comes from the archive's parsed metadata
  6752. (`bed_temperature`); if missing the preheat stage logs and returns
  6753. without dispatching anything, rather than guessing at a default that
  6754. might wreck filament setup.
  6755. Failures are logged but never re-raised — preheat is best-effort. A
  6756. printer that goes offline mid-soak, a refused gcode command, or a
  6757. missing temperature reading must not turn into a failed queue item; the
  6758. normal upload + start path runs immediately after this method returns.
  6759. """
  6760. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6761. if override == "off":
  6762. return True
  6763. if override == "inherit":
  6764. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6765. if not enabled:
  6766. return True
  6767. # override == "on" forces the stage on regardless of the global setting.
  6768. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6769. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6770. # Chamber target resolution:
  6771. # 1. Explicit per-item override beats everything (user knows best).
  6772. # 2. Otherwise derive from the filament types this print loads, via
  6773. # the per-filament target map. A PLA-only print derives 0 and the
  6774. # block below skips the stage without the user touching anything,
  6775. # even when an ASA spool is sitting in another slot of the same
  6776. # AMS (#2886).
  6777. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6778. if explicit_target is not None and explicit_target > 0:
  6779. chamber_target = int(explicit_target)
  6780. chamber_source = "item-override"
  6781. elif explicit_target == 0:
  6782. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6783. chamber_source = "item-override-zero"
  6784. else:
  6785. targets = await self._get_preheat_filament_targets(db)
  6786. chamber_target = self._derive_chamber_target(printer, targets, item)
  6787. chamber_source = "filament-map"
  6788. # Nothing to preheat *for*. A zero that came out of the filament map is
  6789. # the map saying this print's materials want no chamber conditioning --
  6790. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6791. # anyway heated the bed and then held it for the full soak, which
  6792. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6793. # own G-code sets the bed the moment it starts, so preheating it here
  6794. # only moves that heating ahead of the upload instead of overlapping
  6795. # with it, and the soak has no chamber to condition (#3041).
  6796. #
  6797. # An explicit statement from the user still runs the stage. Forcing the
  6798. # per-item override to 'on', or typing a chamber target of exactly 0,
  6799. # both mean "preheat the bed for this print" -- the second is
  6800. # documented as doing precisely that. Only the automatic path, the
  6801. # global toggle plus the filament map, short-circuits here.
  6802. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6803. logger.info(
  6804. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6805. "target, so there is nothing to soak for (override=%s model=%s)",
  6806. item.id,
  6807. override,
  6808. printer.model or "",
  6809. )
  6810. self._preheat_flap_to_cooling(item.id, printer)
  6811. return True
  6812. bed_target = await _queued_plate_bed_temperature(item, archive)
  6813. if bed_target <= 0:
  6814. # No bed temperature in the slicer metadata. When the print needs a
  6815. # hot chamber the bed is simply how we heat it, so fall back to the
  6816. # configured chamber-heating bed temperature rather than skipping
  6817. # the whole stage — otherwise the print starts with a cold chamber,
  6818. # which is exactly what preheat exists to prevent. Without a chamber
  6819. # requirement there is nothing to preheat *for*, so skip as before
  6820. # rather than guess a bed temperature for the print itself.
  6821. if chamber_target <= 0:
  6822. logger.info(
  6823. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6824. item.id,
  6825. )
  6826. return True
  6827. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6828. logger.info(
  6829. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6830. "%d°C to drive the chamber to %d°C",
  6831. item.id,
  6832. bed_target,
  6833. chamber_target,
  6834. )
  6835. client = printer_manager.get_client(printer.id)
  6836. if client is None:
  6837. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6838. return True
  6839. model = printer.model or ""
  6840. has_heater = supports_chamber_heater(model)
  6841. has_sensor = supports_chamber_temp(model)
  6842. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6843. # Fast path: if the chamber has been continuously above target for at
  6844. # least soak_seconds and the bed is already at temperature, skip the
  6845. # entire preheat stage. Typical case: keep-warm held the bed between
  6846. # consecutive same-material prints and the chamber never dropped.
  6847. if do_chamber and has_sensor and soak_seconds > 0:
  6848. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6849. if remaining == 0:
  6850. cur = printer_manager.get_status(printer.id)
  6851. if cur:
  6852. cur_temps = cur.temperatures or {}
  6853. if (
  6854. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6855. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6856. ):
  6857. logger.info(
  6858. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6859. "and bed is already at temperature (chamber history fast-path)",
  6860. item.id,
  6861. chamber_target,
  6862. soak_seconds,
  6863. )
  6864. # Still set targets to prevent cooling during the 3MF upload window.
  6865. # Register each successful set in the preheat pin so `_dispatch_one`
  6866. # unwinds them on any non-success exit.
  6867. pin = self._preheat_pin.setdefault(printer.id, set())
  6868. try:
  6869. client.set_bed_temperature(bed_target)
  6870. pin.add("bed")
  6871. self._preheat_pin_bed[printer.id] = bed_target
  6872. except Exception as exc:
  6873. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6874. if supports_airduct(model):
  6875. cur_airduct = getattr(cur, "airduct_mode", None)
  6876. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6877. try:
  6878. client.set_airduct_mode("heating")
  6879. # Only undo what we can see we replaced. `None`
  6880. # means no mode has been observed yet, and
  6881. # rolling that back to cooling would assert a
  6882. # state the printer never reported.
  6883. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6884. pin.add("airduct")
  6885. except Exception as exc:
  6886. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6887. if has_heater:
  6888. try:
  6889. client.set_chamber_temperature(chamber_target)
  6890. pin.add("chamber")
  6891. except Exception as exc:
  6892. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6893. return True
  6894. logger.info(
  6895. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6896. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6897. item.id,
  6898. bed_target,
  6899. chamber_target if do_chamber else 0,
  6900. chamber_source,
  6901. override,
  6902. model,
  6903. has_heater,
  6904. has_sensor,
  6905. max_wait,
  6906. soak_seconds,
  6907. )
  6908. # Preheat rollback registry: everything we set below is recorded here so
  6909. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6910. # (bed off, chamber off, airduct back to cooling) on any non-success
  6911. # exit. Populated as each command succeeds; consumed and cleared by
  6912. # `_dispatch_one`.
  6913. pin = self._preheat_pin.setdefault(printer.id, set())
  6914. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6915. # cache the target locally so the polling reads below see consistent
  6916. # state (firmware MQTT echoes lag by ~1s).
  6917. try:
  6918. client.set_bed_temperature(bed_target)
  6919. pin.add("bed")
  6920. self._preheat_pin_bed[printer.id] = bed_target
  6921. except Exception as exc:
  6922. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6923. return True
  6924. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6925. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6926. # left it on, regardless of M141. Default cooling actively vents the
  6927. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6928. # cooling never converges — the heater fights the open exhaust. We
  6929. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6930. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6931. # on an H2D that was previously running ABS would otherwise stay in
  6932. # heating mode and overheat PLA). The current-state read keeps the
  6933. # command idempotent — no MQTT chatter when the flap is already where
  6934. # we want it.
  6935. if supports_airduct(model):
  6936. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6937. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6938. current_state = printer_manager.get_status(printer.id)
  6939. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6940. if current_airduct != desired_id:
  6941. try:
  6942. client.set_airduct_mode(desired_airduct)
  6943. # As in the fast path: only pin a rollback for a flap we
  6944. # saw in cooling. `current_airduct` of None means no mode
  6945. # has been observed, so there is nothing to restore to.
  6946. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6947. pin.add("airduct")
  6948. except Exception as exc:
  6949. logger.warning(
  6950. "Queue item %s: preheat airduct %s mode failed: %s",
  6951. item.id,
  6952. desired_airduct,
  6953. exc,
  6954. )
  6955. if do_chamber and has_heater:
  6956. try:
  6957. client.set_chamber_temperature(chamber_target)
  6958. pin.add("chamber")
  6959. except Exception as exc:
  6960. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6961. # Release the pooled DB connection before the (potentially many-minute)
  6962. # heat-soak wait below (#2572). Every setting this method needs is read
  6963. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6964. # it never touches the DB. Without this the caller's transaction sat
  6965. # "idle in transaction" for the whole soak, pinning one pooled connection
  6966. # per preheating printer. expire_on_commit=False keeps item/printer
  6967. # readable afterwards; there are no pending writes to lose here.
  6968. await db.commit()
  6969. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6970. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6971. # Poll every 3s — frequent enough for responsive logging without
  6972. # spamming the MQTT state stream. The "converged" predicate is:
  6973. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6974. # AND
  6975. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6976. BED_TOLERANCE = 2.0
  6977. CHAMBER_TOLERANCE = 2.0
  6978. POLL_INTERVAL = 3.0
  6979. deadline = asyncio.get_event_loop().time() + max_wait
  6980. while True:
  6981. state = printer_manager.get_status(printer.id)
  6982. if state is None:
  6983. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6984. break
  6985. temps = state.temperatures or {}
  6986. bed_now = float(temps.get("bed", 0) or 0)
  6987. chamber_now = float(temps.get("chamber", 0) or 0)
  6988. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6989. if not do_chamber:
  6990. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6991. elif not has_sensor:
  6992. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6993. else:
  6994. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6995. if bed_ok and chamber_ok:
  6996. logger.info(
  6997. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6998. item.id,
  6999. bed_now,
  7000. chamber_now,
  7001. )
  7002. break
  7003. if asyncio.get_event_loop().time() >= deadline:
  7004. logger.info(
  7005. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7006. item.id,
  7007. bed_now,
  7008. bed_target,
  7009. chamber_now,
  7010. chamber_target if do_chamber else 0,
  7011. )
  7012. break
  7013. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7014. logger.info(
  7015. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7016. item.id,
  7017. )
  7018. return False
  7019. if soak_seconds > 0:
  7020. if do_chamber and has_sensor:
  7021. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7022. else:
  7023. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7024. if remaining > 0:
  7025. logger.info(
  7026. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7027. "has been above target for ~%ds already)",
  7028. item.id,
  7029. remaining,
  7030. soak_seconds,
  7031. soak_seconds - remaining,
  7032. )
  7033. if not await self._preheat_sleep(item.id, remaining):
  7034. logger.info(
  7035. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7036. item.id,
  7037. )
  7038. return False
  7039. else:
  7040. logger.info(
  7041. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7042. item.id,
  7043. chamber_target,
  7044. soak_seconds,
  7045. )
  7046. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7047. return True
  7048. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7049. """Turn on smart plug and wait for printer to connect.
  7050. Returns True if printer connected successfully within timeout.
  7051. """
  7052. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7053. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7054. # Check current plug state
  7055. status = await service.get_status(plug)
  7056. if not status.get("reachable"):
  7057. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7058. return False
  7059. # Turn on if not already on
  7060. if status.get("state") != "ON":
  7061. success = await service.turn_on(plug)
  7062. if not success:
  7063. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7064. return False
  7065. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7066. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7067. # Get printer from database for connection
  7068. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7069. printer = result.scalar_one_or_none()
  7070. if not printer:
  7071. logger.error("Printer %s not found in database", printer_id)
  7072. return False
  7073. # End the pass's transaction before waiting up to minutes for the boot:
  7074. # held open, it pins a pooled connection idle in transaction
  7075. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7076. # through it.
  7077. await db.commit()
  7078. # Wait for printer to boot (give it some time before trying to connect)
  7079. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7080. await asyncio.sleep(30)
  7081. # Try to connect to the printer periodically
  7082. elapsed = 30 # Already waited 30s
  7083. while elapsed < self._power_on_wait_time:
  7084. # Try to connect
  7085. logger.info("Attempting to connect to printer %s...", printer_id)
  7086. try:
  7087. connected = await printer_manager.connect_printer(printer)
  7088. if connected:
  7089. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7090. # Give it a moment to stabilize and get status
  7091. await asyncio.sleep(5)
  7092. return True
  7093. except Exception as e:
  7094. logger.debug("Connection attempt failed: %s", e)
  7095. await asyncio.sleep(self._power_on_check_interval)
  7096. elapsed += self._power_on_check_interval
  7097. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7098. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7099. return False
  7100. async def _check_previous_success(
  7101. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7102. ) -> bool:
  7103. """Check if the previous print on this printer succeeded.
  7104. ``printer_id`` names the printer to look at when the item has none yet
  7105. (a job for any printer of a model, checked against the one offered).
  7106. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7107. deliberate action, not a failure, so subsequent items should still
  7108. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7109. a skip isn't an actual print attempt, so it must not gate downstream
  7110. items — counting it as a failed predecessor was the cascade bug that
  7111. let a single cancellation block 18 items over 3 days for the reporter.
  7112. Only `failed` and `aborted` — real print-attempt failures — block.
  7113. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7114. action — #1818) are also excluded from the lookback so the user can
  7115. clear the gate after fixing the physical issue without having to
  7116. re-queue every downstream job.
  7117. """
  7118. result = await db.execute(
  7119. select(PrintQueueItem)
  7120. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7121. .where(PrintQueueItem.id != item.id)
  7122. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7123. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7124. # A row ended without a completion time must not count as the
  7125. # latest: PostgreSQL sorts NULL first in a descending order.
  7126. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7127. .limit(1)
  7128. )
  7129. prev_item = result.scalar_one_or_none()
  7130. # If no previous item, assume success (first in queue)
  7131. if not prev_item:
  7132. return True
  7133. return prev_item.status in ("completed", "cancelled")
  7134. async def _repoint_siblings_at_archive(
  7135. self,
  7136. db: AsyncSession,
  7137. *,
  7138. consumed_library_file_id: int,
  7139. archive_id: int,
  7140. dispatched_item_id: int,
  7141. ) -> int:
  7142. """Move the other queue items off a library row that is about to be deleted (#2819).
  7143. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7144. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7145. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7146. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7147. clones, so the first dispatch could pull the file out from under rows that
  7148. had not run yet. What those rows did next depended on the database, and
  7149. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7150. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7151. they were left pointing at a row that no longer existed, failing with
  7152. "Library file not found" whenever someone started them -- or sitting
  7153. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7154. constraint, so there the rows were deleted outright and the queued copies
  7155. simply vanished, with no error and no history.
  7156. The archive holds its own copy of the 3MF, so the remaining copies can print
  7157. from it instead. Two things happen here, and both must happen *before* the
  7158. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7159. * every row still naming the file has ``library_file_id`` cleared, which is
  7160. what takes it out of the cascade's reach. That covers rows this cannot
  7161. re-point as well -- a copy already printing from its own archive, and the
  7162. finished ones, which are not spare parts but the record a batch order
  7163. counts its progress from.
  7164. * the rows that still need something to print are pointed at the archive.
  7165. Returns how many items were re-pointed.
  7166. """
  7167. variant_item_ids = (
  7168. (
  7169. await db.execute(
  7170. select(PrintQueueVariant.queue_item_id).where(
  7171. PrintQueueVariant.library_file_id == consumed_library_file_id
  7172. )
  7173. )
  7174. )
  7175. .scalars()
  7176. .all()
  7177. )
  7178. # Candidate rows naming the consumed file have to go rather than be
  7179. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7180. # one out of the cascade. This is what PostgreSQL already does, and
  7181. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7182. # outcome changes -- the two backends simply stop disagreeing about
  7183. # whether the row is still there.
  7184. #
  7185. # It also has to happen before the re-point below: a cross-model item
  7186. # (#671) picks a variant every pass and folds it onto the row, and
  7187. # _resolve_variant clears archive_id as it does so, which would undo the
  7188. # re-point on the very next lap.
  7189. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7190. # An item left with other candidates still has somewhere to go, and those
  7191. # carry their own target model -- pointing it at this archive would print a
  7192. # file the matcher never chose. It is excluded from the re-point and simply
  7193. # re-resolves against what is left.
  7194. surviving_variant_item_ids = set(
  7195. (
  7196. await db.execute(
  7197. select(PrintQueueVariant.queue_item_id).where(
  7198. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7199. )
  7200. )
  7201. )
  7202. .scalars()
  7203. .all()
  7204. )
  7205. repoint_ids = set(
  7206. (
  7207. await db.execute(
  7208. select(PrintQueueItem.id)
  7209. .where(PrintQueueItem.id != dispatched_item_id)
  7210. .where(PrintQueueItem.archive_id.is_(None))
  7211. # "skipped" belongs here with the two live states: it is not
  7212. # terminal. Clearing a printer's previous-success gate puts
  7213. # every item skipped by it back to "pending"
  7214. # (resume_after_failure), and one restored onto a deleted
  7215. # file is the same orphan by a slower route. "failed",
  7216. # "cancelled", "aborted" and "completed" never return.
  7217. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7218. .where(
  7219. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7220. )
  7221. .where(
  7222. or_(
  7223. PrintQueueItem.library_file_id == consumed_library_file_id,
  7224. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7225. )
  7226. )
  7227. )
  7228. )
  7229. .scalars()
  7230. .all()
  7231. )
  7232. if repoint_ids:
  7233. await db.execute(
  7234. update(PrintQueueItem)
  7235. .where(PrintQueueItem.id.in_(repoint_ids))
  7236. .values(
  7237. archive_id=archive_id,
  7238. library_file_id=None,
  7239. # The file this flag named is already consumed. Leaving it set
  7240. # would arm every re-pointed copy to delete whatever library
  7241. # row it is next given.
  7242. cleanup_library_after_dispatch=False,
  7243. )
  7244. )
  7245. logger.info(
  7246. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7247. sorted(repoint_ids),
  7248. archive_id,
  7249. consumed_library_file_id,
  7250. dispatched_item_id,
  7251. )
  7252. # Everything else that still names the file: taken out of the cascade's
  7253. # reach without touching what it prints. The file is gone either way; what
  7254. # this preserves is the row.
  7255. await db.execute(
  7256. update(PrintQueueItem)
  7257. .where(PrintQueueItem.id != dispatched_item_id)
  7258. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7259. .values(library_file_id=None)
  7260. )
  7261. return len(repoint_ids)
  7262. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7263. """Schedule power-off if the queue item enabled auto_off_after.
  7264. Delegates to the smart-plug manager so the off honours each plug's
  7265. configured strategy (time delay or temperature threshold), is cancelled
  7266. if the printer starts printing again, and never cuts power on a loaded
  7267. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7268. powered off on the timeout regardless of print state.
  7269. """
  7270. if not item.auto_off_after:
  7271. return
  7272. try:
  7273. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7274. except Exception as e:
  7275. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7276. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7277. """Get a human-readable name for a queue item."""
  7278. if item.archive_id:
  7279. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7280. archive = result.scalar_one_or_none()
  7281. if archive:
  7282. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7283. if item.library_file_id:
  7284. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7285. library_file = result.scalar_one_or_none()
  7286. if library_file:
  7287. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7288. # A cross-model item (#671) holds no file of its own until a printer is
  7289. # picked, so name it after its first candidate — otherwise every waiting
  7290. # notification for one reads "Job #12". Queried rather than read off
  7291. # item.variants because callers outside the selection loop have not
  7292. # eager-loaded them, and a lazy load raises in async.
  7293. first_variant_name = (
  7294. await db.execute(
  7295. select(LibraryFile.filename)
  7296. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7297. .where(PrintQueueVariant.queue_item_id == item.id)
  7298. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7299. .limit(1)
  7300. )
  7301. ).scalar_one_or_none()
  7302. if first_variant_name:
  7303. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7304. return f"Job #{item.id}"
  7305. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7306. """Get printer by ID."""
  7307. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7308. return result.scalar_one_or_none()
  7309. async def _notify_dispatch_gave_up(
  7310. self,
  7311. queue_item_id: int,
  7312. printer_id: int,
  7313. created_by_id: int | None,
  7314. reason: str = "Printer accepted the file but never started printing",
  7315. ) -> None:
  7316. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7317. Called from the watchdog, which is a background task with no session of
  7318. its own — hence the fresh one here. Best-effort throughout: the row is
  7319. already marked failed and that is the load-bearing part; a notification
  7320. provider being down must not resurrect the retry loop we just stopped.
  7321. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7322. path passes its own, because "accepted the file but never started" is the
  7323. opposite of what happened there — the printer refused it outright (#2732).
  7324. """
  7325. try:
  7326. async with async_session() as db:
  7327. item = await db.get(PrintQueueItem, queue_item_id)
  7328. if not item:
  7329. return
  7330. job_name = await self._get_job_name(db, item)
  7331. printer = await self._get_printer(db, printer_id)
  7332. await notification_service.on_queue_job_failed(
  7333. job_name=job_name,
  7334. printer_id=printer_id,
  7335. printer_name=printer.name if printer else "Unknown",
  7336. reason=reason,
  7337. db=db,
  7338. )
  7339. except Exception as e:
  7340. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7341. try:
  7342. await ws_manager.send_queue_item_failed(
  7343. user_id=created_by_id,
  7344. queue_item_id=queue_item_id,
  7345. printer_id=printer_id,
  7346. reason="never_started",
  7347. )
  7348. except Exception:
  7349. pass # toast is best-effort
  7350. async def _filament_short_on(
  7351. self,
  7352. db: AsyncSession,
  7353. item: PrintQueueItem,
  7354. printer_id: int,
  7355. *,
  7356. require_known: bool = False,
  7357. ) -> bool:
  7358. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7359. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7360. assigned there, with the mapping the item would get there, but changes
  7361. nothing. The model-based matcher uses it to prefer a printer whose
  7362. spools can finish the job.
  7363. False whenever the gate would let the item through: "Print Anyway",
  7364. no mapping, or a check that fails. With ``require_known`` all three of
  7365. those, and any printed slot whose remaining amount is unknown, count
  7366. as short instead: releasing a held job starts it with nobody asked, so
  7367. it needs the amount on record, not merely nothing against it.
  7368. """
  7369. if item.skip_filament_check:
  7370. return False
  7371. try:
  7372. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7373. if not mapping:
  7374. return require_known
  7375. deficit = await compute_deficit_for_queue_item(
  7376. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7377. )
  7378. except Exception as e:
  7379. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7380. return require_known
  7381. return bool(deficit)
  7382. async def _release_short_model_hold(
  7383. self,
  7384. db: AsyncSession,
  7385. item: PrintQueueItem,
  7386. unavailable: set[int],
  7387. require_plate_clear: bool,
  7388. printer_scope: PrinterScope,
  7389. ) -> bool:
  7390. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7391. The deficit gate holds a model-based job on the printer the matcher
  7392. gave it, because "Print Anyway" needs a printer to print on. When
  7393. another idle printer of the job's model has the filament, the job is
  7394. moved to that printer and its hold lifted, and the fixed-printer
  7395. branch dispatches it in this same pass, through the same checks a
  7396. held job meets when the user presses Start. It is moved rather than
  7397. put back in the pool because the model-based branch would pick again
  7398. without requiring the amounts on record (below), and could pick a
  7399. different printer. Only the deficit gate sets ``filament_short``, so a
  7400. job held for any other reason stays held.
  7401. The printer it is held on is left out: a spool loaded there is started
  7402. with Start, as before, rather than while someone may still be loading
  7403. the next one. Each job is checked at most every
  7404. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7405. on each idle printer again.
  7406. Cross-model jobs (#671) stay held: checking a variant writes its file
  7407. onto the item, which would leave a job that is not moved holding
  7408. another variant's file for the printer it waits on.
  7409. A printer qualifies only on a positive finding: every slot the plate
  7410. prints mapped to a spool whose remaining amount is on record and
  7411. enough. A printer whose spools Bambuddy does not track is not one.
  7412. Returns True when the job was moved. A check that fails keeps the hold
  7413. rather than stopping the queue pass.
  7414. """
  7415. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7416. return False
  7417. if not item.target_model or item.variants:
  7418. return False
  7419. now = time.monotonic()
  7420. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7421. return False
  7422. self._short_hold_checked_at[item.id] = now
  7423. try:
  7424. candidates = _candidates_for(item)
  7425. if not candidates:
  7426. return False
  7427. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7428. async def is_short(pid: int) -> bool:
  7429. return await self._filament_short_on(db, item, pid, require_known=True)
  7430. async def unmatched_on(pid: int) -> list[str]:
  7431. return await self._unmatched_on(db, item, pid)
  7432. match_id, _ = await self._find_idle_printer_for_model(
  7433. db,
  7434. item.target_model,
  7435. unavailable | {item.printer_id},
  7436. effective_types,
  7437. item.target_location,
  7438. filament_overrides=filament_overrides,
  7439. require_plate_clear=require_plate_clear,
  7440. printer_scope=printer_scope,
  7441. is_short=is_short,
  7442. unmatched_on=unmatched_on,
  7443. )
  7444. # Every idle printer short comes back as the first of them.
  7445. if match_id is None or await is_short(match_id):
  7446. return False
  7447. except Exception as e:
  7448. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7449. return False
  7450. logger.info(
  7451. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7452. item.id,
  7453. match_id,
  7454. item.printer_id,
  7455. )
  7456. self._short_hold_checked_at.pop(item.id, None)
  7457. item.printer_id = match_id
  7458. # Resolved against the printer it leaves (#3239): the tray mapping and
  7459. # the nozzle positions.
  7460. drop_printer_resolved(item)
  7461. item.manual_start = False
  7462. item.filament_short = False
  7463. item.waiting_reason = None
  7464. await db.commit()
  7465. try:
  7466. printer = await self._get_printer(db, match_id)
  7467. await notification_service.on_queue_job_assigned(
  7468. job_name=await self._get_job_name(db, item),
  7469. printer_id=match_id,
  7470. printer_name=printer.name if printer else "Unknown",
  7471. target_model=item.target_model,
  7472. db=db,
  7473. )
  7474. except Exception as e:
  7475. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7476. return True
  7477. async def _block_on_filament_deficit(
  7478. self,
  7479. db: AsyncSession,
  7480. item: PrintQueueItem,
  7481. ) -> bool:
  7482. """Promote the item to manual_start when the assigned spool is short (#1496).
  7483. Returns True when this dispatch attempt was blocked, False when the
  7484. item is clear to start. A previously-flagged item whose spool has
  7485. since been swapped to one with enough material clears the flag here
  7486. so the next scheduler tick dispatches it.
  7487. """
  7488. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7489. # don't re-flag, don't even compute. Without this short-circuit the
  7490. # scheduler bounces between "user said anyway" (route clears
  7491. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7492. # on identical spool state) (#1698-followup).
  7493. if item.skip_filament_check:
  7494. # #1762 diagnostic: surface the short-circuit at INFO so a
  7495. # future "Print Anyway didn't work" report (e.g. issue #1762
  7496. # comment 3) has actionable evidence in the support bundle
  7497. # without needing DEBUG enabled.
  7498. logger.info(
  7499. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7500. item.id,
  7501. )
  7502. return False
  7503. try:
  7504. deficit = await compute_deficit_for_queue_item(db, item)
  7505. except Exception as e:
  7506. # Never let a flaky deficit check wedge the queue — log and let
  7507. # dispatch proceed. The PrintModal-side check still runs on the
  7508. # manual paths.
  7509. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7510. return False
  7511. if deficit:
  7512. item.filament_short = True
  7513. item.manual_start = True
  7514. await db.commit()
  7515. job_name = await self._get_job_name(db, item)
  7516. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7517. logger.info(
  7518. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7519. item.id,
  7520. len(deficit),
  7521. )
  7522. try:
  7523. await notification_service.on_queue_job_waiting(
  7524. job_name=job_name,
  7525. target_model=(printer.model if printer else "") or "",
  7526. waiting_reason="filament_short",
  7527. db=db,
  7528. printer_id=item.printer_id,
  7529. )
  7530. except Exception as e:
  7531. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7532. return True
  7533. # No deficit — clear any stale flag from a previous tick.
  7534. if item.filament_short:
  7535. item.filament_short = False
  7536. await db.commit()
  7537. return False
  7538. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7539. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7540. Compared the way the matcher compares, so the same hex or a similar one
  7541. is a match. Only slots the plate prints, mapped to a tray the printer
  7542. reports, with a colour on both sides: anything else is not a colour the
  7543. job printed in.
  7544. """
  7545. by_tray = {f["global_tray_id"]: f for f in loaded}
  7546. found = []
  7547. for req in required:
  7548. slot_id = req.get("slot_id") or 0
  7549. if slot_id <= 0 or slot_id > len(mapping):
  7550. continue
  7551. tray_id = mapping[slot_id - 1]
  7552. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7553. if tray is not None and tray.get("color_known") is False:
  7554. # A spool without a colour set is not a different colour.
  7555. continue
  7556. wanted = self._normalize_color_for_compare(req.get("color"))
  7557. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7558. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7559. continue
  7560. found.append(
  7561. {
  7562. "slot_id": slot_id,
  7563. "type": req.get("type") or "",
  7564. "wanted": f"#{wanted.upper()}",
  7565. "got": f"#{got.upper()}",
  7566. "tray": tray_id,
  7567. }
  7568. )
  7569. return found
  7570. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7571. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7572. Read from the mapping the job is about to be sent with, whoever made
  7573. it: the matcher's same-material fallback, a preset match in another
  7574. colour, or a slot picked by hand. The file's colour is the one after
  7575. overrides, so a colour swapped on purpose is not one. None whenever
  7576. there is nothing to compare, and on any failure: a missing note must
  7577. never stop a print.
  7578. """
  7579. try:
  7580. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7581. if not isinstance(mapping, list) or not item.printer_id:
  7582. return None
  7583. status = printer_manager.get_status(item.printer_id)
  7584. if status is None:
  7585. return None
  7586. required = await self._get_filament_requirements(db, item)
  7587. if not required:
  7588. return None
  7589. self._apply_filament_overrides(item, required)
  7590. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7591. except Exception as e:
  7592. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7593. return None
  7594. if found:
  7595. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7596. return json.dumps(found) if found else None
  7597. async def _unmatched_requirements(
  7598. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7599. ) -> list[dict]:
  7600. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7601. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7602. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7603. on why an empty list is not one.
  7604. """
  7605. if mapping is None:
  7606. status = printer_manager.get_status(printer_id)
  7607. if status is None or not self._build_loaded_filaments(status):
  7608. return []
  7609. # Every required slot reads unresolved against an empty mapping.
  7610. mapping = []
  7611. required = await self._get_filament_requirements(db, item)
  7612. if required:
  7613. self._apply_filament_overrides(item, required)
  7614. else:
  7615. # An unreadable 3MF still has its forced colours to go by: they are
  7616. # what the mapping was built from (#3280).
  7617. required = _forced_override_requirements(item)
  7618. return _unresolved_required(required, mapping) if required else []
  7619. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7620. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7621. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7622. Choosing a printer for an "any model" job only checked that each type
  7623. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7624. the spool on the other nozzle, or one spool asked for twice, passes. The
  7625. hold then gave the printer back, and the next pass chose it again.
  7626. Empty when the hold would let the item through, including "Print
  7627. Anyway" and a match that fails: the printer is then chosen as before.
  7628. """
  7629. if item.skip_filament_check:
  7630. return []
  7631. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7632. if key in self._unmatched_memo:
  7633. return list(self._unmatched_memo[key])
  7634. try:
  7635. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7636. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7637. except Exception as e:
  7638. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7639. return []
  7640. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7641. self._unmatched_memo[key] = described
  7642. return list(described)
  7643. async def _block_on_unmatched_filament(
  7644. self,
  7645. db: AsyncSession,
  7646. item: PrintQueueItem,
  7647. release_assignment: bool = False,
  7648. ) -> bool:
  7649. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7650. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7651. goes ahead, letting the printer choose — which is how a job prints in the
  7652. wrong material without anyone being asked. Holding is the same answer the
  7653. deficit gate already gives for "the spool is too light", so it reuses the
  7654. same promote-and-notify machinery.
  7655. Keyed off unresolved slots in the *computed* mapping intersected with the
  7656. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7657. read: on its own it also pads slots this plate does not print, so the
  7658. array alone would hold perfectly good jobs. Reading the mapping rather
  7659. than the printer's loaded filament types also inherits the matcher's
  7660. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7661. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7662. type-only scan would wave that through.
  7663. A mapping that resolved *nothing* is the same finding arriving as an
  7664. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7665. could not replace, and dispatch then goes out as ``use_ams`` with no
  7666. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7667. That is held too, but only once live status positively reports loaded
  7668. trays: #2589's mapping is bogus precisely because the AMS was not known
  7669. yet, and its empty loaded list is that ignorance rather than a miss.
  7670. ``release_assignment`` is for the model-based path, which commits its
  7671. printer choice before the gates run. Holding an "any P2S" job would
  7672. otherwise pin it to the one P2S that could not run it.
  7673. Returns True when this dispatch attempt was blocked.
  7674. """
  7675. if item.skip_filament_check or not item.printer_id:
  7676. return False
  7677. mapping: list | None = None
  7678. if item.ams_mapping:
  7679. try:
  7680. mapping = json.loads(item.ams_mapping)
  7681. except (json.JSONDecodeError, TypeError):
  7682. return False
  7683. if not isinstance(mapping, list):
  7684. return False
  7685. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7686. if not unmatched:
  7687. # No cleanup needed here: once start is pressed the item is no
  7688. # longer staged, and whichever exit runs next overwrites the reason
  7689. # (`hold_item` on the fixed-printer branch, the assignment on the
  7690. # model-based one), as does dispatch.
  7691. return False
  7692. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7693. held_by = item.printer_id
  7694. item.manual_start = True
  7695. # Human-readable: this renders on the queue row.
  7696. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7697. if release_assignment:
  7698. # "Any P2S" means any, so the job returns to the pool rather than
  7699. # waiting on the printer that could not take it. The mapping goes
  7700. # with the assignment: its tray IDs were resolved against the
  7701. # printer being released and mean nothing on the next one (#2799),
  7702. # and keeping them would hold the job again even on a printer that
  7703. # has the filament, since an unresolved slot is deliberately not a
  7704. # conflict worth recomputing over.
  7705. item.printer_id = None
  7706. drop_printer_resolved(item)
  7707. await db.commit()
  7708. job_name = await self._get_job_name(db, item)
  7709. printer = await self._get_printer(db, held_by)
  7710. logger.info(
  7711. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7712. item.id,
  7713. held_by,
  7714. wanted,
  7715. )
  7716. try:
  7717. await notification_service.on_queue_job_waiting(
  7718. job_name=job_name,
  7719. target_model=(printer.model if printer else "") or "",
  7720. waiting_reason=f"needs {wanted}",
  7721. db=db,
  7722. # Released to the pool: no printer holds it any more.
  7723. printer_id=None if release_assignment else held_by,
  7724. )
  7725. except Exception as e:
  7726. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7727. return True
  7728. @staticmethod
  7729. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7730. """The queue item's owner as the row has it now.
  7731. item.created_by_id was read before preheat and upload, which can take
  7732. minutes; deleting the user clears the row, not this session's copy.
  7733. """
  7734. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7735. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7736. """Hand the queue item's owner to printer_manager so the
  7737. print-complete callback can credit the user in PrintLogEntry (#1670).
  7738. No-ops when the item has no `created_by_id` or the referenced user
  7739. row is missing (e.g. user deleted between queue-add and dispatch —
  7740. in that case the print log row falls back to the existing un-credited
  7741. behaviour rather than crashing the dispatch).
  7742. """
  7743. from backend.app.models.user import User
  7744. # Read from the row, not item.created_by_id or db.get: both can still
  7745. # hold a user deleted during the upload, after delete_user forgot them
  7746. # (on SQLite the id may be someone new's by the time the print ends).
  7747. # Joined with the printer too: one deleted during the upload was
  7748. # forgotten as well, and this would write the owner back under its id.
  7749. owner = (
  7750. await db.execute(
  7751. select(User.id, User.username)
  7752. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7753. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7754. .where(PrintQueueItem.id == item.id)
  7755. )
  7756. ).first()
  7757. if owner:
  7758. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7759. if item.printer_id is not None:
  7760. self._unconfirmed_print_user[item.id] = item.printer_id
  7761. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7762. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7763. A cancel lands in another session while the upload runs (the edit route
  7764. even tells users to cancel a job that is being sent). An unconditional
  7765. write here would turn that cancellation into a failure, with a failure
  7766. notification, and block the next job that needs the previous print to
  7767. have succeeded. Returns whether the item was marked failed.
  7768. """
  7769. result = cast(
  7770. CursorResult,
  7771. await db.execute(
  7772. update(PrintQueueItem)
  7773. .where(PrintQueueItem.id == item.id)
  7774. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7775. # Failed before the print started: no slot printed in any colour (#3279).
  7776. .values(
  7777. status="failed",
  7778. error_message=message,
  7779. completed_at=datetime.now(timezone.utc),
  7780. color_substitutions=None,
  7781. )
  7782. .execution_options(synchronize_session=False)
  7783. ),
  7784. )
  7785. await db.commit()
  7786. if result.rowcount == 0:
  7787. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7788. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7789. return False
  7790. await db.refresh(item)
  7791. from backend.app.services.print_batch import refresh_batches_after
  7792. await refresh_batches_after([item.id])
  7793. return True
  7794. @staticmethod
  7795. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7796. """Put a job whose printer turned busy before the start back in the queue.
  7797. Only if it is still printing: a stop that landed meanwhile stands.
  7798. """
  7799. await db.execute(
  7800. update(PrintQueueItem)
  7801. .where(PrintQueueItem.id == item.id)
  7802. .where(PrintQueueItem.status == "printing")
  7803. .values(status="pending", started_at=None, color_substitutions=None)
  7804. .execution_options(synchronize_session=False)
  7805. )
  7806. await db.commit()
  7807. @staticmethod
  7808. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7809. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7810. try:
  7811. await ws_manager.send_queue_item_failed(
  7812. user_id=toast_uid,
  7813. queue_item_id=item.id,
  7814. printer_id=item.printer_id,
  7815. reason="cancelled_mid_dispatch",
  7816. )
  7817. except Exception:
  7818. pass # toast is best-effort
  7819. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7820. """Upload file and start print for a queue item.
  7821. Supports two sources:
  7822. - archive_id: Print from an existing archive
  7823. - library_file_id: Print from a library file (file manager)
  7824. """
  7825. logger.info("Starting queue item %s", item.id)
  7826. # Also covers a reservation left active by a process interruption
  7827. # during an earlier attempt. `_dispatch_one` releases this marker on
  7828. # every exit unless start_print() confirms that the command was sent.
  7829. self._unconfirmed_budget_reservations.add(item.id)
  7830. try:
  7831. from backend.app.models.user import User
  7832. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7833. # Recompute at the final authorization boundary as well as enqueue
  7834. # time. This covers rows created before the server-side estimate
  7835. # migration and prevents any alternate write path from weakening
  7836. # the budget reservation.
  7837. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7838. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7839. item.estimated_cost = await estimate_queue_source_cost(
  7840. db,
  7841. archive=archive,
  7842. library_file=library_file,
  7843. plate_id=item.plate_id,
  7844. ams_mapping=item.ams_mapping,
  7845. printer_id=item.printer_id,
  7846. )
  7847. await validate_print_budget(
  7848. db,
  7849. cost_center_id=item.cost_center_id,
  7850. estimated_cost=item.estimated_cost,
  7851. current_user=queue_user,
  7852. exclude_queue_item_id=item.id,
  7853. exclude_reservation_source_type="print_queue",
  7854. exclude_reservation_source_id=item.id,
  7855. )
  7856. budget_reservation = await create_budget_reservation(
  7857. db,
  7858. cost_center_id=item.cost_center_id,
  7859. estimated_cost=item.estimated_cost,
  7860. current_user=queue_user,
  7861. source_type="print_queue",
  7862. source_id=item.id,
  7863. print_archive_id=item.archive_id,
  7864. exclude_queue_item_id=item.id,
  7865. )
  7866. await db.commit()
  7867. except HTTPException as exc:
  7868. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7869. return
  7870. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7871. await self._power_off_if_needed(db, item)
  7872. return
  7873. # Get printer first (needed for both paths)
  7874. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7875. printer = result.scalar_one_or_none()
  7876. if not printer:
  7877. if not await self._fail_dispatch(db, item, "Printer not found"):
  7878. return
  7879. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7880. await self._power_off_if_needed(db, item)
  7881. return
  7882. # Check printer is connected
  7883. if not printer_manager.is_connected(item.printer_id):
  7884. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7885. return
  7886. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7887. await self._power_off_if_needed(db, item)
  7888. return
  7889. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7890. # `items` was taken at the top of check_queue, but the user can /cancel
  7891. # any pending row in the gap before we reach this point. Re-read the
  7892. # row and bail out cleanly instead of starting an FTP upload for a row
  7893. # that's already cancelled. The atomic CAS at the pending→printing
  7894. # transition (below, before start_print) is the load-bearing guard;
  7895. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7896. await db.refresh(item)
  7897. if item.status != "pending":
  7898. logger.info(
  7899. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7900. item.id,
  7901. item.status,
  7902. )
  7903. return
  7904. # Busy-printer guard (#2598). check_queue gates dispatch on
  7905. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  7906. # keep reporting FINISH for tens of seconds *after* it accepted a
  7907. # project_file (see the watchdog's phase-B note). A watchdog revert
  7908. # (#2555) also releases the dispatch hold, so a re-selected item can
  7909. # reach here while its printer has actually started printing. Uploading
  7910. # and dispatching then collides with the live job — the firmware answers
  7911. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  7912. # live state right before the expensive FTP upload: if the printer is
  7913. # busy, leave the item pending and let a later tick dispatch it once the
  7914. # printer is genuinely idle. No wasted upload, no collision.
  7915. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7916. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  7917. logger.info(
  7918. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  7919. "leaving item pending for a later tick (#2598)",
  7920. item.id,
  7921. item.printer_id,
  7922. pre_dispatch_state,
  7923. )
  7924. return
  7925. # Determine source: archive or library file
  7926. archive = None
  7927. library_file = None
  7928. file_path = None
  7929. filename = None
  7930. cleanup_disk_paths: list[Path] = []
  7931. # Set when a dispatch consumes its library file, so the photos can be
  7932. # carried over after the commit that removes the row (#3077).
  7933. consumed_library_file_id: int | None = None
  7934. consumed_photos: list[str] = []
  7935. if item.archive_id:
  7936. # Print from archive
  7937. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7938. archive = result.scalar_one_or_none()
  7939. if not archive:
  7940. if not await self._fail_dispatch(db, item, "Archive not found"):
  7941. return
  7942. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7943. await self._power_off_if_needed(db, item)
  7944. return
  7945. # Persist the queue item's selected plate onto the archive so Print
  7946. # History can show the actual plate after cancel/fail/complete (#2603).
  7947. # Only when the archive doesn't already carry one, so a reprint of a
  7948. # plate-specific archive isn't relabelled by a differently-plated
  7949. # queue row.
  7950. if archive.plate_id is None and item.plate_id is not None:
  7951. archive.plate_id = item.plate_id
  7952. # Ask-for-outcome opt-in rides from the queue item to the archive
  7953. # the same way (#1898); never cleared here so a reprint of an
  7954. # archive that already asked keeps asking.
  7955. if item.confirm_outcome:
  7956. archive.confirm_requested = True
  7957. file_path = settings.base_dir / archive.file_path
  7958. filename = archive.filename
  7959. elif item.library_file_id:
  7960. # Print from library file (file manager)
  7961. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7962. library_file = result.scalar_one_or_none()
  7963. if not library_file:
  7964. # "Not found" covers two different situations and only one of
  7965. # them is recoverable, so say which. A trashed file is still
  7966. # there and restoring it makes a re-queued job work; a file that
  7967. # is really gone needs a different one. Neither is knowable from
  7968. # the queue, which is the whole complaint about this message.
  7969. trashed = (
  7970. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7971. ).scalar_one_or_none()
  7972. if not await self._fail_dispatch(
  7973. db,
  7974. item,
  7975. (
  7976. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7977. if trashed
  7978. else "Library file not found — it was deleted after this job was queued"
  7979. ),
  7980. ):
  7981. return
  7982. logger.error(
  7983. "Queue item %s: library file %s is %s",
  7984. item.id,
  7985. item.library_file_id,
  7986. "in the trash" if trashed else "gone",
  7987. )
  7988. await self._power_off_if_needed(db, item)
  7989. return
  7990. # Library files store absolute paths
  7991. lib_path = Path(library_file.file_path)
  7992. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7993. filename = library_file.filename
  7994. # Create archive from library file so usage tracking has access to the 3MF
  7995. queue_item_id = item.id
  7996. # Held separately: a cleanup dispatch clears item.library_file_id
  7997. # below, and the log line at the end of this block reported that
  7998. # cleared field -- so every consumed print logged "from library
  7999. # file None", which is the one case worth being able to trace.
  8000. source_library_file_id = item.library_file_id
  8001. try:
  8002. from backend.app.services.archive import ArchiveService
  8003. archive_service = ArchiveService(db)
  8004. archive = await archive_service.archive_print(
  8005. printer_id=item.printer_id,
  8006. source_file=file_path,
  8007. original_filename=filename,
  8008. created_by_id=item.created_by_id,
  8009. project_id=item.project_id,
  8010. cost_center_id=item.cost_center_id,
  8011. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8012. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8013. )
  8014. if archive:
  8015. item.archive_id = archive.id
  8016. if item.confirm_outcome:
  8017. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8018. if budget_reservation is not None:
  8019. budget_reservation.print_archive_id = archive.id
  8020. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8021. consumed_library_file_id = library_file.id
  8022. item.library_file_id = None
  8023. cleanup_disk_paths.append(file_path)
  8024. if library_file.thumbnail_path:
  8025. thumb_path = Path(library_file.thumbnail_path)
  8026. if not thumb_path.is_absolute():
  8027. thumb_path = settings.base_dir / library_file.thumbnail_path
  8028. cleanup_disk_paths.append(thumb_path)
  8029. # Before the delete, not after: on PostgreSQL the FK
  8030. # cascade would already have taken these rows (#2819).
  8031. await self._repoint_siblings_at_archive(
  8032. db,
  8033. consumed_library_file_id=consumed_library_file_id,
  8034. archive_id=archive.id,
  8035. dispatched_item_id=item.id,
  8036. )
  8037. # Read while the row is still here; the photos move
  8038. # below, once the delete has actually committed.
  8039. consumed_photos = list(library_file.photos or [])
  8040. # The delete clears the link on the earlier archives of
  8041. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8042. # SQLite). This one is loaded, so set it here too, or it
  8043. # keeps the stale id in the session.
  8044. archive.library_file_id = None
  8045. await db.delete(library_file)
  8046. file_path = settings.base_dir / archive.file_path
  8047. filename = archive.filename
  8048. # Commit, not flush — flush opens the SQLite write
  8049. # transaction (item.archive_id update + library_file
  8050. # delete) and would hold the WAL writer lock through the
  8051. # FTP upload below, causing "database is locked" cascades
  8052. # for sensor history + concurrent cancels (#1853).
  8053. await db.commit()
  8054. logger.info(
  8055. "Queue item %s: Created archive %s from library file %s",
  8056. item.id,
  8057. archive.id,
  8058. source_library_file_id,
  8059. )
  8060. except Exception as e:
  8061. logger.warning(
  8062. "Queue item %s: Failed to create archive from library file: %s",
  8063. queue_item_id,
  8064. e,
  8065. exc_info=True,
  8066. )
  8067. await db.rollback()
  8068. item = await db.get(PrintQueueItem, queue_item_id)
  8069. if item:
  8070. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8071. return
  8072. await self._power_off_if_needed(db, item)
  8073. return
  8074. if not archive:
  8075. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8076. return
  8077. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8078. await self._power_off_if_needed(db, item)
  8079. return
  8080. # The photos follow the file into the archive that replaces it, for
  8081. # the same reason the siblings do (#3077). After the commit above,
  8082. # never before it: that commit can fail ("database is locked",
  8083. # #1853) and roll the library row back, and photos already moved
  8084. # would leave it naming a directory that no longer exists. The
  8085. # file and thumbnail unlinks are deferred for the same reason.
  8086. if consumed_library_file_id is not None and consumed_photos:
  8087. # Held as a plain int, read here while the session is still
  8088. # healthy, because the handler below may not touch an ORM
  8089. # instance at all. The commit it exists for fails inside the
  8090. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8091. # first DML statement, so a busy writer surfaces as "database
  8092. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8093. # internally through safe_reraise before re-raising, which
  8094. # expires every loaded instance and leaves the session in
  8095. # pending-rollback state -- so `archive.id` inside the except
  8096. # would itself raise PendingRollbackError and the rollback
  8097. # below would never be reached.
  8098. archive_id = archive.id
  8099. try:
  8100. carried_photos = move_library_photos(
  8101. consumed_library_file_id,
  8102. consumed_photos,
  8103. archive_photos_dir(archive),
  8104. )
  8105. if carried_photos:
  8106. archive.photos = list(archive.photos or []) + carried_photos
  8107. await db.commit()
  8108. except Exception as e:
  8109. # The archive and the delete are already committed; the
  8110. # print goes ahead either way. Worst case the pictures sit
  8111. # unnamed in the archive's own directory.
  8112. #
  8113. # Ints only until the rollback has run, per the note above,
  8114. # which is why this logs queue_item_id and not item.id --
  8115. # the sibling handler forty lines up does the same.
  8116. logger.warning(
  8117. "Queue item %s: failed to carry library photos into archive %s: %s",
  8118. queue_item_id,
  8119. archive_id,
  8120. e,
  8121. )
  8122. await db.rollback()
  8123. # rollback() expires every loaded instance, and in async
  8124. # SQLAlchemy the next plain attribute read is lazy IO
  8125. # outside the greenlet -- MissingGreenlet, which would turn
  8126. # this cosmetic failure into a dispatch crash in exactly the
  8127. # "database is locked" case the block exists for (#1853).
  8128. # The nozzle guard, the upload and the start all keep
  8129. # reading item, archive and printer, so all three go back
  8130. # into the session before falling through.
  8131. item = await db.get(PrintQueueItem, queue_item_id)
  8132. archive = await db.get(PrintArchive, archive_id)
  8133. printer = await db.get(Printer, item.printer_id) if item else None
  8134. if not item or not archive or not printer:
  8135. logger.error(
  8136. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8137. queue_item_id,
  8138. archive_id,
  8139. )
  8140. return
  8141. else:
  8142. # Neither archive nor library file specified
  8143. if not await self._fail_dispatch(db, item, "No source file specified"):
  8144. return
  8145. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8146. await self._power_off_if_needed(db, item)
  8147. return
  8148. # Check file exists on disk
  8149. if not file_path.exists():
  8150. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8151. return
  8152. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8153. await self._power_off_if_needed(db, item)
  8154. return
  8155. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8156. # size dispatched to a printer with a different nozzle installed is
  8157. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8158. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8159. # gives the user no idea what went wrong. Catch it here, before we spend
  8160. # time preheating and uploading, and fail with an actionable message.
  8161. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8162. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8163. # the printer hasn't reported its nozzles yet, we fall through and let the
  8164. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8165. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8166. # as one of the two hotends is a 0.6.
  8167. #
  8168. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8169. # (#2885): the printer fetches one as part of starting the print, so the
  8170. # set to test against is "reachable", not "currently mounted". This runs
  8171. # well before the rack picker at the bottom of this method, so without
  8172. # the rack in scope here that picker never got the chance to run.
  8173. sliced_nozzle = archive.nozzle_diameter if archive else None
  8174. if sliced_nozzle:
  8175. nozzle_status = printer_manager.get_status(item.printer_id)
  8176. installed = _installed_nozzle_diameters(nozzle_status)
  8177. rack = _rack_nozzle_diameters(nozzle_status)
  8178. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8179. if mismatch_msg:
  8180. if not await self._fail_dispatch(db, item, mismatch_msg):
  8181. return
  8182. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8183. await notification_service.on_queue_job_failed(
  8184. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8185. printer_id=printer.id,
  8186. printer_name=printer.name,
  8187. reason=mismatch_msg,
  8188. db=db,
  8189. )
  8190. try:
  8191. await ws_manager.send_queue_item_failed(
  8192. user_id=item.created_by_id,
  8193. queue_item_id=item.id,
  8194. printer_id=item.printer_id,
  8195. reason="nozzle_mismatch",
  8196. )
  8197. except Exception:
  8198. pass
  8199. await self._power_off_if_needed(db, item)
  8200. return
  8201. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8202. # bed (and chamber, if applicable) is at temperature when the firmware
  8203. # starts the actual print routine. Best-effort: any failure logs and
  8204. # falls through to the normal upload+start path rather than turning a
  8205. # configuration issue into a failed queue item.
  8206. # Returns False only when the item was cancelled or deleted while the
  8207. # stage was holding at temperature. Uploading and starting it anyway
  8208. # would print a job the user has already called off, so abandon the
  8209. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8210. if not await self._preheat_and_soak(db, item, printer, archive):
  8211. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8212. return
  8213. # See `_effective_plate_id` for why this is resolved once here rather
  8214. # than each site below repeating `item.plate_id or 1`.
  8215. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8216. # G-code injection for auto-print systems (#422)
  8217. injected_path = None
  8218. # #2547: tracked separately from `injected_path`, which is also set when
  8219. # only a START snippet was injected. Only an END snippet changes what the
  8220. # camera sees at print completion.
  8221. end_gcode_injected = False
  8222. if item.gcode_injection:
  8223. try:
  8224. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8225. if snippets_raw:
  8226. snippets = json.loads(snippets_raw)
  8227. model_snippets = snippets.get(printer.model, {})
  8228. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8229. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8230. if start_gc or end_gc:
  8231. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8232. injected_path = inject_gcode_into_3mf(
  8233. file_path, effective_plate_id, start_gc or None, end_gc or None
  8234. )
  8235. if injected_path:
  8236. file_path = injected_path
  8237. end_gcode_injected = bool(end_gc)
  8238. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8239. else:
  8240. logger.warning(
  8241. "Queue item %s: G-code injection returned no result, using original", item.id
  8242. )
  8243. except Exception as e:
  8244. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8245. # #2547: the finish-photo path can't learn from telemetry that this print
  8246. # ends with user End G-code — which means the plate may be gone by the
  8247. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8248. # the print once the printer confirms it running.
  8249. if end_gcode_injected:
  8250. print_dispatch_context.mark_pending(printer.id)
  8251. # Upload to root directory (not /cache/) - the start_print command references
  8252. # files by name only (ftp://{filename}), so they must be in the root
  8253. remote_filename = derive_remote_filename(filename)
  8254. remote_path = f"/{remote_filename}"
  8255. # Get FTP retry settings
  8256. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8257. logger.info(
  8258. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8259. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8260. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8261. )
  8262. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8263. # Every read this method needs (printer, archive/library, preheat) is
  8264. # done, and the library-file branch already committed its archive
  8265. # creation. Without this the transaction opened by the first SELECT above
  8266. # stays "idle in transaction" for the entire upload — multiple seconds
  8267. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8268. # a farm dispatching many jobs at once then exhausts the pool. This was
  8269. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8270. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8271. # readable; the status writes below (upload-failure path and the
  8272. # pending->printing CAS) transparently open a fresh transaction.
  8273. # The owner is read here, after preheat, so the commit releases this read too.
  8274. toast_uid = await self._queue_owner_id(db, item)
  8275. await db.commit()
  8276. # Delete existing file if present (avoids 553 error on overwrite)
  8277. try:
  8278. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8279. delete_result = await delete_file_async(
  8280. printer.ip_address,
  8281. printer.access_code,
  8282. remote_path,
  8283. socket_timeout=ftp_timeout,
  8284. printer_model=printer.model,
  8285. # This delete and the upload below are one bounded, user-initiated
  8286. # unit -- at most nine connections -- so neither skips on the
  8287. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8288. # trace this delete took the TLS failure and armed the cool-off,
  8289. # and the upload's four attempts were then spent against it
  8290. # without a socket being opened.
  8291. respect_handshake_cooloff=False,
  8292. )
  8293. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8294. except Exception as e:
  8295. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8296. # Dispatch toast — announce the upload start with the total byte
  8297. # count so the frontend can render an honest progress bar.
  8298. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8299. try:
  8300. total_bytes = file_path.stat().st_size
  8301. except OSError:
  8302. total_bytes = 0
  8303. try:
  8304. await ws_manager.send_queue_item_uploading(
  8305. user_id=toast_uid,
  8306. queue_item_id=item.id,
  8307. printer_id=item.printer_id,
  8308. printer_name=printer.name,
  8309. file_name=toast_file_name,
  8310. total_bytes=total_bytes,
  8311. )
  8312. except Exception:
  8313. pass # toast is best-effort
  8314. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8315. # A deadline expiry gets its own message: "check your SD card" is the
  8316. # wrong advice for a link that was simply too slow to finish (#2529).
  8317. upload_error: str | None = None
  8318. # Why the upload failed, straight from the client rather than inferred.
  8319. # Owned here, so a background fetch for another print cannot overwrite
  8320. # it between the failure and the sentence built from it (#2899).
  8321. upload_failure = FtpFailureReport()
  8322. try:
  8323. if ftp_retry_enabled:
  8324. uploaded = await with_ftp_retry(
  8325. upload_file_async,
  8326. printer.ip_address,
  8327. printer.access_code,
  8328. file_path,
  8329. remote_path,
  8330. socket_timeout=ftp_timeout,
  8331. printer_model=printer.model,
  8332. progress_callback=progress_bridge,
  8333. respect_handshake_cooloff=False,
  8334. failure=upload_failure,
  8335. max_retries=ftp_retry_count,
  8336. retry_delay=ftp_retry_delay,
  8337. operation_name=f"Upload print to {printer.name}",
  8338. )
  8339. else:
  8340. uploaded = await upload_file_async(
  8341. printer.ip_address,
  8342. printer.access_code,
  8343. file_path,
  8344. remote_path,
  8345. socket_timeout=ftp_timeout,
  8346. printer_model=printer.model,
  8347. progress_callback=progress_bridge,
  8348. respect_handshake_cooloff=False,
  8349. failure=upload_failure,
  8350. )
  8351. except UploadCancelled as e:
  8352. uploaded = False
  8353. upload_error = (
  8354. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8355. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8356. )
  8357. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8358. except Exception as e:
  8359. uploaded = False
  8360. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8361. # Clean up injected temp file after upload attempt
  8362. if injected_path and injected_path.exists():
  8363. injected_path.unlink(missing_ok=True)
  8364. # Again after the upload, which can take minutes: an owner deleted
  8365. # meanwhile gets no more toasts, and neither does whoever has their id.
  8366. toast_uid = await self._queue_owner_id(db, item)
  8367. # The printer's copy at this path was replaced (or deleted above): the
  8368. # file browser's previews must not show the old one.
  8369. from backend.app.services.printer_file_cache import printer_file_cache
  8370. printer_file_cache.forget(printer.id, remote_path)
  8371. if not uploaded:
  8372. # This used to be one string for every upload failure, telling
  8373. # everyone to check the SD card. The client knows which of seven
  8374. # things went wrong and logs each one differently; it just had no
  8375. # way to say so here, so the card got named even for a TLS
  8376. # handshake that never reached the printer's filesystem (#2899).
  8377. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8378. failure = upload_failure.failure
  8379. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8380. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  8381. return
  8382. if not await self._fail_dispatch(db, item, error_msg):
  8383. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8384. return
  8385. logger.error(
  8386. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8387. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8388. )
  8389. # Send failure notification
  8390. await notification_service.on_queue_job_failed(
  8391. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8392. printer_id=printer.id,
  8393. printer_name=printer.name,
  8394. # The same sentence the queue shows. A push notification saying
  8395. # something different from the UI is its own small bug (#2899).
  8396. reason=error_msg,
  8397. db=db,
  8398. )
  8399. try:
  8400. await ws_manager.send_queue_item_failed(
  8401. user_id=toast_uid,
  8402. queue_item_id=item.id,
  8403. printer_id=item.printer_id,
  8404. reason="upload_failed",
  8405. )
  8406. except Exception:
  8407. pass
  8408. await self._power_off_if_needed(db, item)
  8409. return
  8410. # The printer took a file, so any run of refused uploads is over: the
  8411. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8412. self._upload_refusals.pop(printer.id, None)
  8413. self._upload_refusal_notified.discard(printer.id)
  8414. # Parse AMS mapping if stored
  8415. ams_mapping = None
  8416. if item.ams_mapping:
  8417. try:
  8418. ams_mapping = json.loads(item.ams_mapping)
  8419. except json.JSONDecodeError:
  8420. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8421. # Register as expected print so we don't create a duplicate archive
  8422. # Only applicable for archive-based prints
  8423. if archive:
  8424. from backend.app.main import register_expected_print
  8425. register_expected_print(
  8426. item.printer_id,
  8427. remote_filename,
  8428. archive.id,
  8429. ams_mapping=ams_mapping,
  8430. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8431. # no print-start email, and neither does whoever has their id.
  8432. created_by_id=toast_uid,
  8433. cost_center_id=item.cost_center_id,
  8434. # The plate actually dispatched, not the queue item's raw
  8435. # column: on None, `register_expected_print` stores nothing,
  8436. # and `extract_filament_usage_from_3mf` then books every
  8437. # filament in the file rather than the one plate that printed.
  8438. plate_id=effective_plate_id,
  8439. )
  8440. # Registration happens before the print command by necessity (the
  8441. # printer can report the print before the send returns), so record
  8442. # what to undo if we never get as far as sending. `_dispatch_one`
  8443. # rolls back anything still pending here on every exit — exception,
  8444. # early return, or cancel winning the CAS below.
  8445. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8446. # Propagate the queue item's owner into printer_manager so the
  8447. # print-complete callback can credit the user in the PrintLogEntry
  8448. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8449. # items) or when the user clicks the manual-start button.
  8450. await self._propagate_owner_to_printer_manager(db, item)
  8451. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8452. # This prevents phantom reprints if the backend crashes/restarts after the
  8453. # print command is sent but before the status update is committed.
  8454. # If we crash after this commit but before start_print(), the item will be
  8455. # in "printing" status without actually printing - but that's safer than
  8456. # accidentally reprinting the same file hours later.
  8457. #
  8458. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8459. # initial pending read at the top of check_queue and this point) flips
  8460. # the row to "cancelled" in a separate session. Without the WHERE
  8461. # status='pending' clause, the unconditional update here would silently
  8462. # overwrite that cancellation and we'd ship the MQTT start_print below
  8463. # — printer obeys, user sees "I pressed cancel and the print started".
  8464. # rowcount==0 means the user won the race; bail out, best-effort delete
  8465. # the file we just uploaded, do NOT send start_print.
  8466. now_utc = datetime.now(timezone.utc)
  8467. billing_run_id = str(uuid.uuid4())
  8468. # Written with the move to printing, so a retried send replaces the
  8469. # last answer and a cancelled one leaves the row alone (#3279).
  8470. color_substitutions = await self._color_substitutions_for(db, item)
  8471. cas = await db.execute(
  8472. update(PrintQueueItem)
  8473. .where(PrintQueueItem.id == item.id)
  8474. .where(PrintQueueItem.status == "pending")
  8475. .values(
  8476. status="printing",
  8477. started_at=now_utc,
  8478. billing_run_id=billing_run_id,
  8479. color_substitutions=color_substitutions,
  8480. )
  8481. )
  8482. await db.commit()
  8483. if cas.rowcount == 0:
  8484. logger.info(
  8485. "Queue item %s no longer pending at print-command time "
  8486. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8487. item.id,
  8488. )
  8489. try:
  8490. await delete_file_async(
  8491. printer.ip_address,
  8492. printer.access_code,
  8493. remote_path,
  8494. socket_timeout=ftp_timeout,
  8495. printer_model=printer.model,
  8496. )
  8497. except Exception as cleanup_err:
  8498. logger.debug(
  8499. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8500. item.id,
  8501. cleanup_err,
  8502. )
  8503. try:
  8504. await ws_manager.send_queue_item_failed(
  8505. user_id=toast_uid,
  8506. queue_item_id=item.id,
  8507. printer_id=item.printer_id,
  8508. reason="cancelled_mid_dispatch",
  8509. )
  8510. except Exception:
  8511. pass
  8512. return
  8513. # Sync the in-memory item so subsequent code that reads item.status /
  8514. # item.started_at sees the values we just persisted.
  8515. item.status = "printing"
  8516. item.started_at = now_utc
  8517. item.billing_run_id = billing_run_id
  8518. if archive is not None:
  8519. archive.billing_run_id = billing_run_id
  8520. # Legacy transaction deletion used an archive-wide skip flag.
  8521. # A newly dispatched run has its own UUID/tombstone, so it must be
  8522. # billable independently of any older deleted run on this archive.
  8523. archive.wallet_charge_skipped = False
  8524. # Persist before MQTT send so completion and restart recovery can
  8525. # always recover the internal billing identity.
  8526. await db.commit()
  8527. for cleanup_path in cleanup_disk_paths:
  8528. try:
  8529. if cleanup_path.exists():
  8530. cleanup_path.unlink()
  8531. except OSError as cleanup_err:
  8532. logger.warning(
  8533. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8534. json.dumps(
  8535. {
  8536. "queue_item_id": item.id,
  8537. "path": str(cleanup_path),
  8538. "error": str(cleanup_err),
  8539. },
  8540. sort_keys=True,
  8541. ),
  8542. )
  8543. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8544. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8545. # #1898: with the opt-in default-good setting, moving on to the next
  8546. # print resolves the previous print's unanswered outcome prompt as
  8547. # "good" — this path also covers the camera-based plate detection,
  8548. # which releases the gate by allowing dispatch rather than by an
  8549. # explicit acknowledgment. Rides on the dispatch transaction.
  8550. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8551. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8552. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8553. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8554. # Capture state before dispatch so the watchdog can detect whether the
  8555. # printer actually transitioned (#967). Also capture subtask_id so the
  8556. # watchdog can recognise "command landed but state hasn't flipped yet"
  8557. # on slow H2D transitions (#1078).
  8558. pre_status = printer_manager.get_status(item.printer_id)
  8559. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8560. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8561. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8562. # #1721: respect the user's explicit timelapse choice. The #1397
  8563. # force-on at dispatch was removed because it caused per-layer nozzle
  8564. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8565. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8566. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8567. # FINISH-state fallback — no need to force a video.
  8568. effective_timelapse = bool(item.timelapse)
  8569. # Nozzle-rack fallback (#2800). A job that never passed through the
  8570. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8571. # dispatches with no nozzle field at all and chooses for itself — which
  8572. # is how a print levelled on one hotend and then printed on another,
  8573. # millimetres above the plate. Derive the per-slot extruder assignment
  8574. # from the file being dispatched.
  8575. #
  8576. # Done here rather than at queue time because this is the first point
  8577. # that knows both the actual printer and the actual file: an item can
  8578. # be created without a printer (model-based assignment), reassigned
  8579. # afterwards, or have its file swapped for a G-code-injected copy just
  8580. # above. Every queue-creation path — the print dialog, a bulk library
  8581. # add, the webhook, a pipeline run — is covered by the one call.
  8582. # Skipped when the item already carries a Bambu Studio capture: that
  8583. # one wins downstream anyway, so reading the 3MF again would be work
  8584. # thrown away on every dispatch.
  8585. # Rack position resolution (#1784), tried before the #2800 fallback
  8586. # below because it can express what that one cannot: a plate wanting a
  8587. # *different* hotend off the rack per filament group. The position per
  8588. # group is the operator's pick — the 3MF states it nowhere, proven by
  8589. # sending one plate twice with different picks and finding the two
  8590. # files identical bar float noise — so it is resolved here against the
  8591. # rack as it stands right now, after the upload, not at queue time.
  8592. resolved_nozzle_mapping = None
  8593. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8594. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8595. if rack_plan is not None:
  8596. try:
  8597. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8598. except (json.JSONDecodeError, TypeError):
  8599. stored_choice = {}
  8600. logger.warning(
  8601. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8602. item.id,
  8603. item.nozzle_rack_choice,
  8604. )
  8605. # JSON object keys are strings; the groups are ints.
  8606. choice: dict[int, int] = {}
  8607. for key, value in (stored_choice or {}).items():
  8608. try:
  8609. choice[int(key)] = int(value)
  8610. except (TypeError, ValueError):
  8611. continue
  8612. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8613. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8614. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8615. )
  8616. if resolved_nozzle_mapping is None and choice:
  8617. # An explicit pick that no longer holds stops the print. The
  8618. # operator named a hotend; printing from a different one is
  8619. # how a plate gets levelled on one nozzle and drawn with
  8620. # another, millimetres above the bed. Nothing has been sent
  8621. # to the printer yet, so failing here costs only the upload.
  8622. # The file is already on the SD card by this point, and a
  8623. # 3MF left there is a phantom print waiting to be started
  8624. # from the touchscreen. Same cleanup the start_print
  8625. # failure path below does, for the same reason.
  8626. try:
  8627. await delete_file_async(
  8628. printer.ip_address,
  8629. printer.access_code,
  8630. remote_path,
  8631. printer_model=printer.model,
  8632. )
  8633. except Exception:
  8634. pass # Best-effort — don't fail the error handler
  8635. if not await self._fail_dispatch(
  8636. db,
  8637. item,
  8638. (
  8639. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8640. "Edit the item to choose another position."
  8641. ),
  8642. ):
  8643. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8644. return
  8645. logger.warning(
  8646. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8647. item.id,
  8648. printer.name,
  8649. rack_error,
  8650. choice,
  8651. [slot.get("id") for slot in live_rack],
  8652. )
  8653. await notification_service.on_queue_job_failed(
  8654. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8655. printer_id=printer.id,
  8656. printer_name=printer.name,
  8657. reason=item.error_message,
  8658. db=db,
  8659. )
  8660. try:
  8661. await ws_manager.send_queue_item_failed(
  8662. user_id=toast_uid,
  8663. queue_item_id=item.id,
  8664. printer_id=item.printer_id,
  8665. reason="nozzle_rack_pick_stale",
  8666. )
  8667. except Exception:
  8668. pass # Best-effort — don't fail the error handler
  8669. return
  8670. if resolved_nozzle_mapping is None:
  8671. # Nothing was picked and nothing could be assigned. Falls
  8672. # through to the #2800 path, which is what ran before this
  8673. # existed — strictly not worse than today.
  8674. logger.info(
  8675. "Queue item %s: no rack positions assignable (%s); falling back",
  8676. item.id,
  8677. rack_error,
  8678. )
  8679. else:
  8680. logger.info(
  8681. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8682. item.id,
  8683. resolved_nozzle_mapping,
  8684. rack_plan.slot_groups,
  8685. choice or "auto",
  8686. )
  8687. nozzle_slot_extruders = None
  8688. if (
  8689. not item.nozzle_mapping
  8690. and resolved_nozzle_mapping is None
  8691. and file_path is not None
  8692. and is_nozzle_rack_model(printer.model)
  8693. ):
  8694. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8695. if slot_extruders:
  8696. nozzle_slot_extruders = json.dumps(slot_extruders)
  8697. # Every filament this plate prints is on the external spool -> the print
  8698. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8699. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8700. # table", which is what held the reporter's P1S at Heatbed preheating
  8701. # for ten minutes before it gave up (#3087). The MQTT command builder
  8702. # already downgrades a mapping that is *only* external ([254]), but a
  8703. # multi-filament project pads the slots this plate does not print with
  8704. # -1 — BambuStudio's own convention — and down there a -1 is
  8705. # indistinguishable from a slot that never resolved, which must never be
  8706. # sent to the spool holder (#2589). Here the plate's filament list says
  8707. # which is which, so the answer is exact rather than a guess.
  8708. #
  8709. # Deliberately narrow: this fires only when every consumed slot is an
  8710. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8711. # alone and the firmware still rejects the print, exactly as today. And
  8712. # only for single-nozzle printers, mirroring the builder's own reconcile
  8713. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8714. # whether to use the AMS, so it is not ours to rewrite.
  8715. effective_use_ams = item.use_ams
  8716. plate_uses_only_external = False
  8717. if (
  8718. ams_mapping
  8719. and file_path is not None
  8720. # Cheap gate before opening the file: with nothing on the spool
  8721. # holder anywhere in the mapping, no subset of it can be all
  8722. # external, so most dispatches never pay for the parse. The
  8723. # isinstance also keeps a malformed stored mapping (a bare number
  8724. # from a hand-edited row) failing where it always failed, in the
  8725. # command builder, rather than here.
  8726. and isinstance(ams_mapping, list)
  8727. and any(_is_external_tray(t) for t in ams_mapping)
  8728. and not _might_be_dual_nozzle(printer.model, pre_status)
  8729. ):
  8730. from backend.app.services.filament_requirements import extract_filament_requirements
  8731. consumed = _consumed_mapping_entries(
  8732. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8733. )
  8734. if consumed and all(_is_external_tray(t) for t in consumed):
  8735. # Exact for this plate: the command builder must not turn the
  8736. # AMS back on for a real tray another plate of the file uses,
  8737. # whether the job asked for the AMS or already had it off.
  8738. plate_uses_only_external = True
  8739. if plate_uses_only_external and effective_use_ams:
  8740. effective_use_ams = False
  8741. logger.info(
  8742. "Queue item %s: every filament plate %s prints is on the external spool "
  8743. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8744. item.id,
  8745. effective_plate_id,
  8746. ams_mapping,
  8747. )
  8748. # A slot that lost its K-profile selection (a power cycle resets every
  8749. # slot to the default K) would print on the default. The idle check in
  8750. # the status handler normally restores it first, but nothing guarantees
  8751. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8752. # Never allowed to stop the print it is protecting.
  8753. try:
  8754. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8755. except Exception:
  8756. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8757. # Start the print with AMS mapping, plate_id and print options.
  8758. # nozzle_mapping rides through verbatim — JSON string captured from
  8759. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8760. # parses + injects it only for dual-nozzle models so a null on every
  8761. # other model is a transparent pass-through. The rack fallback is
  8762. # resolved down there too, where the live rack position is known.
  8763. started = printer_manager.start_print(
  8764. item.printer_id,
  8765. remote_filename,
  8766. plate_id=effective_plate_id,
  8767. ams_mapping=ams_mapping,
  8768. bed_levelling=item.bed_levelling,
  8769. flow_cali=item.flow_cali,
  8770. vibration_cali=item.vibration_cali,
  8771. layer_inspect=item.layer_inspect,
  8772. timelapse=effective_timelapse,
  8773. use_ams=effective_use_ams,
  8774. plate_uses_only_external=plate_uses_only_external,
  8775. nozzle_offset_cali=item.nozzle_offset_cali,
  8776. nozzle_mapping=item.nozzle_mapping
  8777. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8778. nozzle_slot_extruders=nozzle_slot_extruders,
  8779. )
  8780. if started:
  8781. # The command is away, so the expectation is now legitimate and must
  8782. # survive. Anything still in this dict when _dispatch_one exits gets
  8783. # rolled back.
  8784. self._unconfirmed_expected_print.pop(item.id, None)
  8785. self._unconfirmed_budget_reservations.discard(item.id)
  8786. self._unconfirmed_print_user.pop(item.id, None)
  8787. if item.printer_id is not None:
  8788. self._sent_unstarted_print[item.id] = (
  8789. item.printer_id,
  8790. remote_filename if archive else None,
  8791. archive.id if archive else None,
  8792. )
  8793. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8794. # target, chamber target, airduct heating) — the gcode owns
  8795. # heater/flap control from here. Clearing the pin prevents
  8796. # `_dispatch_one`'s finally from unwinding a live print.
  8797. self._preheat_pin.pop(item.printer_id, None)
  8798. self._preheat_pin_bed.pop(item.printer_id, None)
  8799. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8800. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8801. # status='processing' from upload start until the printer acked
  8802. # (or timed out). The frontend derives "Awaiting printer…" purely
  8803. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8804. # event would push the status chip out of 'PROCESSING' prematurely
  8805. # — which is exactly what the screenshot at #1625-followup
  8806. # complained about.
  8807. # Register the local 3MF in the cover-cache so /cover skips FTP
  8808. # (#1166 follow-up). file_path was resolved earlier from either the
  8809. # archive or the library file row.
  8810. if file_path is not None:
  8811. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8812. # Hold the printer against further dispatches until the watchdog
  8813. # confirms the printer transitioned (or until the hard timeout).
  8814. # Prevents multi-plate batches from triple-dispatching onto the
  8815. # same H2D Pro while it digests the first project_file (#1157).
  8816. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8817. # Watchdog: if the printer never transitions out of pre_state AND
  8818. # never advances subtask_id, the MQTT publish was accepted locally but
  8819. # didn't reach the printer (half-broken session — same shape as
  8820. # #887/#936). Revert the queue item so the next dispatch can pick it
  8821. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8822. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8823. # that would otherwise cause the item to re-dispatch as a reprint
  8824. # of the just-finished job (#1078).
  8825. if pre_state:
  8826. spawn_background_task(
  8827. self._watchdog_print_start(
  8828. item.id,
  8829. item.printer_id,
  8830. pre_state,
  8831. pre_subtask_id,
  8832. pre_gcode_file,
  8833. created_by_id=toast_uid,
  8834. ),
  8835. name=f"watchdog-print-start-{item.id}",
  8836. )
  8837. # Get estimated time for notification.
  8838. #
  8839. # This used to fall back to `library_file.print_time_seconds`, a column
  8840. # LibraryFile does not have — the print time it knows about lives in
  8841. # `file_metadata`. So a library print whose archive carried no parseable
  8842. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8843. # AttributeError right here, *after* the printer had already been sent
  8844. # the job: the started-notification never fired, and the exception
  8845. # unwound the whole queue pass, so every other printer still waiting to
  8846. # be dispatched on that tick silently missed its turn.
  8847. #
  8848. # The queue item caches the print time at creation ("Cached from
  8849. # archive/library"), which is the value this was reaching for.
  8850. estimated_time = None
  8851. if archive and archive.print_time_seconds:
  8852. estimated_time = archive.print_time_seconds
  8853. elif item.print_time_seconds:
  8854. estimated_time = item.print_time_seconds
  8855. # Send job started notification
  8856. await notification_service.on_queue_job_started(
  8857. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8858. printer_id=printer.id,
  8859. printer_name=printer.name,
  8860. db=db,
  8861. estimated_time=estimated_time,
  8862. )
  8863. # MQTT relay - publish queue job started
  8864. try:
  8865. await mqtt_relay.on_queue_job_started(
  8866. job_id=item.id,
  8867. filename=filename,
  8868. printer_id=printer.id,
  8869. printer_name=printer.name,
  8870. printer_serial=printer.serial_number,
  8871. )
  8872. except Exception:
  8873. pass # Don't fail if MQTT fails
  8874. else:
  8875. # Clean up uploaded file from SD card to prevent phantom prints
  8876. try:
  8877. await delete_file_async(
  8878. printer.ip_address,
  8879. printer.access_code,
  8880. remote_path,
  8881. printer_model=printer.model,
  8882. )
  8883. except Exception:
  8884. pass # Best-effort — don't fail the error handler
  8885. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8886. # state can flip from idle to active in the window between the
  8887. # pre-dispatch check above and this publish (the FTP upload takes
  8888. # seconds); start_print() then refuses to send project_file to the
  8889. # now-busy printer and returns False. Failing the item here would be
  8890. # wrong — the printer is fine, it is simply busy — so revert to
  8891. # pending and let a later tick dispatch it once the printer is idle,
  8892. # exactly like the pre-dispatch guard. Only a start_print() False on
  8893. # an idle/unknown printer is a genuine command failure.
  8894. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8895. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  8896. logger.info(
  8897. "Queue item %s: printer %s became busy (state=%s) before the start "
  8898. "command was sent — deferring, reverting item to pending (#2598)",
  8899. item.id,
  8900. item.printer_id,
  8901. post_dispatch_state,
  8902. )
  8903. await self._defer_until_printer_idle(db, item)
  8904. return
  8905. # Print command failed - revert status
  8906. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  8907. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8908. return
  8909. logger.error(
  8910. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  8911. f"printer_manager.start_print() returned False. "
  8912. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  8913. f"Check printer status and backend logs for details."
  8914. )
  8915. # Send failure notification
  8916. await notification_service.on_queue_job_failed(
  8917. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8918. printer_id=printer.id,
  8919. printer_name=printer.name,
  8920. reason="Failed to send print command to printer - check printer connection and status",
  8921. db=db,
  8922. )
  8923. try:
  8924. await ws_manager.send_queue_item_failed(
  8925. user_id=toast_uid,
  8926. queue_item_id=item.id,
  8927. printer_id=item.printer_id,
  8928. reason="start_command_failed",
  8929. )
  8930. except Exception:
  8931. pass
  8932. await self._power_off_if_needed(db, item)
  8933. @staticmethod
  8934. async def _watchdog_print_start(
  8935. queue_item_id: int,
  8936. printer_id: int,
  8937. pre_state: str,
  8938. pre_subtask_id: str | None = None,
  8939. pre_gcode_file: str | None = None,
  8940. timeout: float = 90.0,
  8941. phase_b_timeout: float = 180.0,
  8942. poll_interval: float = 3.0,
  8943. created_by_id: int | None = None,
  8944. ) -> None:
  8945. """Revert a queue item if the printer never acknowledges the start command.
  8946. Bambuddy optimistically marks the queue item as "printing" right after the
  8947. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  8948. Phase A (up to ``timeout``): wait for either an active-state transition
  8949. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  8950. primary signal; subtask_id advance handles the H2D case where state can
  8951. sit at FINISH for ~50 s after the printer accepted ``project_file``
  8952. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  8953. was lost on a half-broken session (#887/#936) — revert and force
  8954. reconnect (the #967 recovery path).
  8955. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8956. alone): keep watching for the active-state transition. subtask_id alone
  8957. proves the file landed but not that the printer started — and a printer
  8958. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8959. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8960. used to leave the queue item stuck in 'printing' forever because the
  8961. old watchdog returned success as soon as subtask_id advanced. If Phase
  8962. B times out, revert the queue item so the user can retry without
  8963. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8964. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8965. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8966. transitions that also don't emit an early subtask_id tick.
  8967. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8968. refuses to verify our commands will never start this job or any other,
  8969. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8970. burns an upload slot the rest of the farm is queued behind — that path
  8971. is for a printer that might still come good, which this one cannot
  8972. (#2732). It fails the item on the spot with the actual reason instead.
  8973. """
  8974. last_status = None
  8975. landed_on_subtask = False
  8976. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8977. # every push carrying an `hms` key, so the fault can come and go between
  8978. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8979. command_rejected = False
  8980. # Latched for the same reason as command_rejected: drying can finish, or
  8981. # be stopped by the user, part-way through the dispatch window. Seeing it
  8982. # once is what matters — it is the state the printer was in when it
  8983. # declined to start (#2758).
  8984. drying_ams_ids: list[int] = []
  8985. # The printer answered the start with a refusal: nothing will start,
  8986. # and the command was not lost, so no reconnect either.
  8987. start_refusal: tuple[str, str | None] | None = None
  8988. deadline = time.monotonic() + timeout
  8989. while time.monotonic() < deadline:
  8990. await asyncio.sleep(poll_interval)
  8991. status = printer_manager.get_status(printer_id)
  8992. if not status:
  8993. # Printer disconnected — don't mess with the DB. Drop the
  8994. # in-memory dispatch hold too so a fresh dispatch can retry
  8995. # once the printer comes back; the hard timeout would
  8996. # otherwise hold the printer unnecessarily.
  8997. scheduler._release_dispatch_hold(printer_id)
  8998. return
  8999. last_status = status
  9000. if status.state in _ACTIVE_PRINT_STATES:
  9001. # Printer is actively processing the job — release the
  9002. # post-dispatch hold so the next pending item for this printer
  9003. # can be evaluated normally. We do NOT accept arbitrary state
  9004. # transitions: a printer going FINISH -> IDLE (user dismissed
  9005. # the post-print prompt without accepting our project_file)
  9006. # would otherwise look like "command landed" and leave the
  9007. # queue item stuck in 'printing' forever (#1370).
  9008. scheduler._release_dispatch_hold(printer_id)
  9009. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9010. try:
  9011. await ws_manager.send_queue_item_acked(
  9012. user_id=created_by_id,
  9013. queue_item_id=queue_item_id,
  9014. printer_id=printer_id,
  9015. )
  9016. except Exception:
  9017. pass
  9018. return
  9019. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9020. # Checked only after the active-state exit above: a stale HMS left
  9021. # over from an earlier job must never abort a print that is visibly
  9022. # running. An actually-refused command leaves the printer idle, so
  9023. # this ordering costs the detection nothing.
  9024. if _mqtt_commands_rejected(status):
  9025. command_rejected = True
  9026. break
  9027. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9028. if isinstance(refusal, tuple):
  9029. start_refusal = refusal
  9030. break
  9031. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9032. # Phase A exit — printer accepted the file (subtask_id flipped
  9033. # to our submission id). Don't return yet: the printer may
  9034. # have accepted the command but never actually start (e.g.
  9035. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9036. # B watches for the active-state transition.
  9037. landed_on_subtask = True
  9038. break
  9039. if landed_on_subtask and not command_rejected:
  9040. phase_b_deadline = time.monotonic() + phase_b_timeout
  9041. while time.monotonic() < phase_b_deadline:
  9042. await asyncio.sleep(poll_interval)
  9043. status = printer_manager.get_status(printer_id)
  9044. if not status:
  9045. scheduler._release_dispatch_hold(printer_id)
  9046. return
  9047. last_status = status
  9048. if status.state in _ACTIVE_PRINT_STATES:
  9049. scheduler._release_dispatch_hold(printer_id)
  9050. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9051. try:
  9052. await ws_manager.send_queue_item_acked(
  9053. user_id=created_by_id,
  9054. queue_item_id=queue_item_id,
  9055. printer_id=printer_id,
  9056. )
  9057. except Exception:
  9058. pass
  9059. return
  9060. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9061. # Same ordering rule as Phase A: a running print wins over a
  9062. # lingering HMS.
  9063. if _mqtt_commands_rejected(status):
  9064. command_rejected = True
  9065. break
  9066. # No active-state transition. Revert the item so the scheduler can retry.
  9067. # Drop the in-memory hold so the retry isn't blocked by it.
  9068. scheduler._release_dispatch_hold(printer_id)
  9069. # Logged on every failed dispatch window, not just the last one, so a
  9070. # support bundle shows the correlation from the first attempt rather than
  9071. # only after the retry budget is spent (#2758).
  9072. if drying_ams_ids:
  9073. logger.info(
  9074. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9075. queue_item_id,
  9076. printer_id,
  9077. ", ".join(str(i) for i in drying_ams_ids),
  9078. )
  9079. # Four outcomes from the revert attempt, each routed differently:
  9080. # "reverted": row flipped from printing -> pending, run recovery
  9081. # "gave_up": same, but the retry budget is spent — row failed
  9082. # rather than pending, so it stops going round again
  9083. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9084. # on_print_complete or user). Skip recovery entirely
  9085. # — the print clearly landed somewhere even if the
  9086. # watchdog didn't see the active-state transition.
  9087. # "revert_failed": SQLite contention exhausted retries. Still run
  9088. # recovery so the MQTT session gets a fresh client_id
  9089. # on the half-broken-session path.
  9090. #
  9091. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9092. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9093. # the watchdog again. For a printer that is genuinely wedged that loop never
  9094. # ends — the reporter had one printer "since this morning still not launch"
  9095. # — and each lap also consumes an upload slot that the other printers in the
  9096. # farm are waiting on. Retrying is right; retrying forever is not.
  9097. async def _do_revert(db):
  9098. item = await db.get(PrintQueueItem, queue_item_id)
  9099. if not item or item.status != "printing":
  9100. return "already_moved_on"
  9101. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9102. item.started_at = None
  9103. # The print never started: no slot printed in any colour (#3279).
  9104. item.color_substitutions = None
  9105. # Charge the attempt to the candidate that was actually dispatched, so
  9106. # a cross-model item (#671) reaches for its other file next lap instead
  9107. # of retrying the printer that just failed to start. Matched by file
  9108. # because that is what the resolver copied onto the row.
  9109. if item.library_file_id is not None:
  9110. await db.execute(
  9111. update(PrintQueueVariant)
  9112. .where(PrintQueueVariant.queue_item_id == item.id)
  9113. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9114. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9115. )
  9116. if command_rejected:
  9117. # No retry budget for this one: the printer refused to verify the
  9118. # command, and re-uploading the same 3MF to the same printer will
  9119. # be refused the same way. Fail now with the fix rather than after
  9120. # three laps of a message about SD cards (#2732).
  9121. item.status = "failed"
  9122. item.error_message = (
  9123. "The printer rejected the print command: MQTT command verification failed "
  9124. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9125. "then start the job again."
  9126. )
  9127. item.completed_at = datetime.now(timezone.utc)
  9128. await db.commit()
  9129. return "command_rejected"
  9130. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9131. item.status = "failed"
  9132. if drying_ams_ids:
  9133. # #2758: the generic message below sent the reporter looking
  9134. # at the SD card while the actual obstacle — AMS units in a
  9135. # drying cycle — was on screen the whole time. Name what we
  9136. # observed and let the user judge it; Bambuddy does not stop
  9137. # the cycle itself, because on this hardware drying can run
  9138. # alongside a print and stopping it may not be the fix.
  9139. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9140. item.error_message = (
  9141. f"The printer accepted the file but never started printing, after "
  9142. f"{item.dispatch_attempts} attempts. {units} "
  9143. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9144. f"some printers refuse to begin a print while an AMS is in a drying "
  9145. f"cycle, and an AMS drying without its external power supply can also "
  9146. f"leave too little power for the start-of-print calibration. Stop the "
  9147. f"drying, or connect the AMS power supply, and start the job again."
  9148. )
  9149. else:
  9150. item.error_message = (
  9151. f"The printer accepted the file but never started printing, after "
  9152. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9153. f"prompt or error, confirm its SD card is readable, and start the job again."
  9154. )
  9155. item.completed_at = datetime.now(timezone.utc)
  9156. await release_budget_reservation(
  9157. db,
  9158. source_type="print_queue",
  9159. source_id=item.id,
  9160. status="released",
  9161. )
  9162. await db.commit()
  9163. return "gave_up"
  9164. item.status = "pending"
  9165. await db.commit()
  9166. return "reverted"
  9167. try:
  9168. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9169. except Exception as e:
  9170. logger.warning(
  9171. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9172. "scheduler may keep treating this item as in-flight",
  9173. queue_item_id,
  9174. printer_id,
  9175. e,
  9176. )
  9177. revert_outcome = "revert_failed"
  9178. if revert_outcome in ("command_rejected", "gave_up"):
  9179. # The item is failed: its print user and expected print must not
  9180. # pass the printer's next print off as Bambuddy's.
  9181. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9182. from backend.app.services.print_batch import refresh_batches_after
  9183. await refresh_batches_after([queue_item_id])
  9184. elif revert_outcome == "reverted":
  9185. # Another try claims the printer again. Until then no print on it
  9186. # is vouched for as this item's, except a late start of its file.
  9187. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9188. elif revert_outcome == "already_moved_on":
  9189. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9190. if revert_outcome == "already_moved_on":
  9191. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9192. # other path) already moved the item past 'printing', don't run the
  9193. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9194. # session breaks ongoing prints on the same printer.
  9195. return
  9196. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9197. if revert_outcome == "command_rejected":
  9198. logger.error(
  9199. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9200. "failed) — the print command was rejected, not lost. Failing the item "
  9201. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9202. queue_item_id,
  9203. printer_id,
  9204. HMS_MQTT_VERIFY_FAILED,
  9205. )
  9206. await scheduler._notify_dispatch_gave_up(
  9207. queue_item_id,
  9208. printer_id,
  9209. created_by_id,
  9210. reason="Printer rejected the print command (MQTT command verification failed)",
  9211. )
  9212. # Same reasoning as the landed_on_subtask path below: the file is on
  9213. # the printer and a forced reconnect would only add 0500_4003 to a
  9214. # problem that has nothing to do with the MQTT session (#1150).
  9215. return
  9216. if revert_outcome == "gave_up":
  9217. logger.error(
  9218. "Queue item %s: printer %d never started the print after %d dispatch "
  9219. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9220. "re-uploading it again (#2555)",
  9221. queue_item_id,
  9222. printer_id,
  9223. DISPATCH_MAX_ATTEMPTS,
  9224. total_timeout,
  9225. )
  9226. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9227. elif revert_outcome == "reverted":
  9228. if start_refusal is not None:
  9229. logger.warning(
  9230. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9231. "reverted to 'pending' for retry",
  9232. queue_item_id,
  9233. printer_id,
  9234. start_refusal[0],
  9235. start_refusal[1],
  9236. )
  9237. elif landed_on_subtask:
  9238. logger.warning(
  9239. "Queue item %s: printer %d accepted project_file (subtask_id "
  9240. "advanced) but never transitioned to an active state within "
  9241. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9242. "for retry (#1678)",
  9243. queue_item_id,
  9244. printer_id,
  9245. total_timeout,
  9246. )
  9247. else:
  9248. logger.warning(
  9249. "Queue item %s: printer %d did not respond to print command within "
  9250. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9251. "for retry (#967)",
  9252. queue_item_id,
  9253. printer_id,
  9254. timeout,
  9255. pre_state,
  9256. pre_subtask_id,
  9257. )
  9258. # Phase B was entered iff subtask_id advanced, which means the
  9259. # project_file landed on the printer. A forced reconnect at this point
  9260. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9261. # skip the recovery entirely.
  9262. if landed_on_subtask or start_refusal is not None:
  9263. return
  9264. # Phase A timeout path: if the printer's gcode_file changed since
  9265. # pre-dispatch, the project_file command landed and the printer is
  9266. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9267. # If gcode_file is unchanged, the publish was silently swallowed
  9268. # (#887/#936) and force_reconnect recovery is what we want.
  9269. client = printer_manager.get_client(printer_id)
  9270. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9271. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9272. if publish_landed:
  9273. logger.warning(
  9274. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9275. "received the command and is parsing slowly. Skipping forced "
  9276. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9277. queue_item_id,
  9278. current_gcode_file,
  9279. pre_gcode_file,
  9280. )
  9281. elif client and hasattr(client, "force_reconnect_stale_session"):
  9282. client.force_reconnect_stale_session(
  9283. f"queue print command unacknowledged after {timeout:.0f}s "
  9284. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9285. )
  9286. # Global scheduler instance
  9287. scheduler = PrintScheduler()