print_scheduler.py 524 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364
  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 InvalidFilenameError, derive_remote_filename, validate_print_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. # STORAGE (a missing, full or unusable card or USB drive) and AUTH (a rejected
  337. # access code) were left out at first, because they need the user. But
  338. # failing the item leaves the printer just as idle, and #3409's H2D with an
  339. # unusable USB stick ate seven jobs within an hour. Every job sent to that
  340. # printer fails the same way, so they wait too; the retry finds the fix once
  341. # the user has made it.
  342. #
  343. # A 553 can also be this one file: a name the card's filesystem cannot hold.
  344. # That one fails the item, see `_start_print`.
  345. #
  346. # Not here: NOT_FOUND (a path problem, which can be this one file), UNKNOWN,
  347. # and an upload that overran its deadline -- each retry of that costs a whole
  348. # upload that would be just as slow.
  349. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  350. {
  351. FtpFailureKind.HANDSHAKE,
  352. FtpFailureKind.COOLOFF,
  353. FtpFailureKind.TIMEOUT,
  354. FtpFailureKind.NETWORK,
  355. FtpFailureKind.STORAGE,
  356. FtpFailureKind.AUTH,
  357. }
  358. )
  359. def _refused_upload_hold_reason(printer_label: str, kind: FtpFailureKind | None) -> str:
  360. """What a job waiting on a printer that refused its last upload shows.
  361. Storage and the access code need the user to do something, so they say
  362. what; the rest clear on their own.
  363. """
  364. if kind is FtpFailureKind.STORAGE:
  365. return f"{printer_label} refused to store the file — check its SD card or USB drive. {_REFUSED_UPLOAD_TAIL}"
  366. if kind is FtpFailureKind.AUTH:
  367. return (
  368. f"{printer_label} refused the file transfer — check its access code on the Printers page. "
  369. f"{_REFUSED_UPLOAD_TAIL}"
  370. )
  371. return f"{printer_label} is not accepting files — {_REFUSED_UPLOAD_TAIL}"
  372. _REFUSED_UPLOAD_TAIL = "Bambuddy will retry automatically"
  373. def _asks_nothing_new(waiting_reason: str) -> bool:
  374. """A model job's reason made only of busy printers and printers that refused an upload.
  375. The refusal sent its own notification (`_requeue_after_upload_refused`),
  376. so this one has nothing to add.
  377. """
  378. parts = [p.strip() for p in waiting_reason.split(" | ")]
  379. return all(p.startswith("Busy:") or p.endswith(_REFUSED_UPLOAD_TAIL) for p in parts)
  380. # How long a printer whose upload was put back stays out of dispatch (#3210).
  381. # The first window matches the FTP client's own handshake cool-off, so the
  382. # retry lands after the client would talk to the printer again anyway. Each
  383. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  384. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  385. # five connection attempts and a page of log. A successful upload resets it.
  386. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  387. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  388. def _upload_backoff_seconds(refusals: int) -> int:
  389. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  390. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  391. @dataclass(slots=True)
  392. class _ModelCandidate:
  393. """One (file, printer model) pair the model-based matcher may try.
  394. Model-based assignment used to have exactly one of these per item, held
  395. directly in the item's own columns. Cross-model queue items (#671) have
  396. several, held in ``print_queue_variants``. Both shapes are normalised into
  397. this so the matching, the cross-model gate and the waiting-reason handling
  398. are written once and an item without variants provably takes the same path
  399. it took before variants existed.
  400. ``variant`` is None for the item's own columns and set for a real variant
  401. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  402. item once that candidate wins.
  403. """
  404. target_model: str | None
  405. sliced_for: str | None
  406. required_filament_types: str | None
  407. filament_overrides: str | None
  408. variant: "PrintQueueVariant | None" = None
  409. def _sliced_for_model(archive, library_file) -> str | None:
  410. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  411. if archive is not None:
  412. return archive.sliced_for_model
  413. if library_file is not None and library_file.file_metadata:
  414. return library_file.file_metadata.get("sliced_for_model")
  415. return None
  416. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  417. """The filament a candidate needs, as ``(types, overrides)``.
  418. Both columns are JSON text written by the slicer step. Malformed content is
  419. treated as no constraint rather than as an error: a job whose overrides
  420. cannot be parsed still prints, it just gets no filament-based narrowing.
  421. Overrides carry their own types, so the returned type list is the union of
  422. the two — an override on one slot must not drop the requirements of the
  423. slots it says nothing about.
  424. Shared by the matcher and by the smart-plug wake step so both ask a printer
  425. for the same filament (#2876). Waking a printer the matcher would then
  426. reject on colour is the bug this exists to prevent.
  427. """
  428. required_types = None
  429. if candidate.required_filament_types:
  430. try:
  431. required_types = json.loads(candidate.required_filament_types)
  432. except json.JSONDecodeError:
  433. pass
  434. filament_overrides = None
  435. if candidate.filament_overrides:
  436. try:
  437. filament_overrides = json.loads(candidate.filament_overrides)
  438. except json.JSONDecodeError:
  439. pass
  440. effective_types = required_types
  441. if filament_overrides:
  442. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  443. if override_types:
  444. effective_types = sorted(set(required_types or []) | set(override_types))
  445. return effective_types, filament_overrides
  446. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  447. """Whether ``item`` was competing for the printer another item just took.
  448. The SJF starvation guard marks a job as jumped when a shorter one lower in
  449. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  450. compete for the same printer, so the guard has to look across both lanes
  451. (#3200); looking only inside the dispatched item's own lane let a stream of
  452. short model-based jobs hold a longer pinned job back indefinitely.
  453. Location filters are not checked: over-marking only lifts an item that was
  454. going to wait anyway, while under-marking is the starvation this prevents.
  455. """
  456. if item.printer_id is not None:
  457. return item.printer_id == printer_id
  458. if not printer_model:
  459. return False
  460. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  461. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  462. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  463. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  464. """Candidate files for ``item``, best first.
  465. An item with no variant rows yields exactly one candidate built from its own
  466. columns — the pre-#671 behaviour, unchanged.
  467. Variants come back least-attempted first, ties broken by the user's
  468. ``position``. On the first pass every count is zero, so this is purely the
  469. user's priority order. After a start-watchdog bounce the printer that failed
  470. drops behind, so the next lap tries the other machine rather than spending the
  471. item's whole retry budget on the one that is wedged. Once every candidate has
  472. been tried equally often they cycle again, which keeps the item-level
  473. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  474. still gives up, it just does not give up without trying them.
  475. """
  476. if not item.variants:
  477. if not item.archive_id and not item.library_file_id:
  478. # Nothing to print at all. Dispatching would fail deep in the upload
  479. # on "No archive_id or library_file_id"; the caller holds the item
  480. # with an explanation instead.
  481. return []
  482. return [
  483. _ModelCandidate(
  484. target_model=item.target_model,
  485. sliced_for=_sliced_for_model(item.archive, item.library_file),
  486. required_filament_types=item.required_filament_types,
  487. filament_overrides=item.filament_overrides,
  488. )
  489. ]
  490. # Drop candidates whose file is gone or in the trash. Both are reachable and
  491. # neither is covered by the schema: library deletes are soft (the row lives
  492. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  493. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  494. # fires there and a hard delete leaves the variant row pointing at nothing.
  495. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  496. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  497. return [
  498. _ModelCandidate(
  499. target_model=v.target_model,
  500. sliced_for=_sliced_for_model(None, v.library_file),
  501. required_filament_types=v.required_filament_types,
  502. filament_overrides=v.filament_overrides,
  503. variant=v,
  504. )
  505. for v in ordered
  506. ]
  507. # Why a job for any printer of a model waits when every free one's last print
  508. # failed. The queue page matches it to offer Resume for the model.
  509. MODEL_GATE_WAIT_REASON = "The last print failed on every free matching printer"
  510. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  511. """Fold one waiting reason per candidate into a single line for the item.
  512. A cross-model item produces a reason per candidate, and pasting them
  513. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  514. — on which machine?). Each reason is prefixed with its model, except in the
  515. single-candidate case where the item already displays its target model and
  516. the prefix would be noise.
  517. Identical reasons collapse rather than repeat, so three idle-less models
  518. read as one clause.
  519. When *every* candidate is merely busy the parts are joined with the ``" | "``
  520. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  521. unprefixed. That case must keep testing busy-only: a fleet that is simply
  522. printing needs no user action, and labelling the clauses would turn each pass
  523. over a two-model item into a "job waiting" notification.
  524. """
  525. reasons = [(model, reason) for model, reason in per_model if reason]
  526. if not reasons:
  527. return None
  528. if len(reasons) == 1:
  529. return reasons[0][1]
  530. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  531. if len(distinct) == 1:
  532. return distinct[0]
  533. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  534. return " | ".join(distinct)
  535. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  536. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  537. """Human label for the models an item is waiting on ("H2S or H2C").
  538. Notifications take a single target model. For a cross-model item the item's
  539. own ``target_model`` is whichever variant happens to be first, which reads as
  540. a lie once it is the H2C that actually runs — so name all of them.
  541. """
  542. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  543. if not models:
  544. return None
  545. return " or ".join(models)
  546. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  547. """True if ``mapping`` is a non-empty list whose every entry is the
  548. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  549. Such a mapping is a bug artifact: a frontend status-load race can serialize
  550. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  551. recomputed from live status at dispatch rather than trusted, otherwise it
  552. reaches the print command and is silently downgraded to external-spool mode.
  553. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  554. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  555. explicit external selection (``>= 254``) is NOT unresolved either — those
  556. keep their meaning.
  557. """
  558. if not isinstance(mapping, list) or not mapping:
  559. return False
  560. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  561. def _is_tray_id(value: object) -> bool:
  562. """True when ``value`` can be read as a global tray ID.
  563. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  564. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  565. against whatever happens to be loaded there.
  566. """
  567. return isinstance(value, int) and not isinstance(value, bool)
  568. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  569. # stages an item (#2799). The manual_start branch clears every other reason on
  570. # a staged item (#3074); this one is the reason it was staged, so it stays.
  571. _UNMATCHED_HOLD_PREFIX = "Needs "
  572. # How often an "any model" job held for low filament looks for another printer
  573. # of its model that has enough (#3137). Each look matches its filament on every
  574. # idle printer again, which a 30 s queue pass would otherwise repeat each time.
  575. _SHORT_HOLD_RECHECK_SECONDS = 120
  576. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  577. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  578. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  579. def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
  580. """The item's force_color_match overrides as filament requirements (#3280).
  581. What ``_build_override_direct_mapping`` matches when the 3MF cannot be
  582. read, so the checks after it judge the same list.
  583. """
  584. try:
  585. overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
  586. except (json.JSONDecodeError, TypeError):
  587. return []
  588. if not isinstance(overrides, list):
  589. return []
  590. return [
  591. {
  592. "slot_id": o.get("slot_id"),
  593. "type": o.get("type", ""),
  594. "color": o.get("color", ""),
  595. "tray_info_idx": o.get("tray_info_idx", ""),
  596. "force_color_match": True,
  597. }
  598. for o in overrides
  599. if isinstance(o, dict) and o.get("force_color_match") and isinstance(o.get("slot_id"), int)
  600. ]
  601. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  602. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  603. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  604. for a filament this plate does not use. A slot past the end of the mapping
  605. is unresolved too.
  606. """
  607. unresolved = []
  608. for req in required:
  609. slot_id = req.get("slot_id") or 0
  610. if slot_id <= 0:
  611. continue
  612. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  613. if not _is_tray_id(tray) or tray < 0:
  614. unresolved.append(req)
  615. return unresolved
  616. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  617. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  618. # on `_mapping_is_all_unresolved`.
  619. _EXTERNAL_TRAY_ID_MIN = 254
  620. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  621. """The ``mapping`` entries for the slots this plate actually prints.
  622. ``required`` comes from ``extract_filament_requirements``, which drops any
  623. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  624. consumes, and one absent from it is padding. That distinction is why this
  625. decision lives here and not in the MQTT command builder: a ``-1`` in the
  626. mapping means either "this plate does not print filament N" or "we never
  627. worked out which tray", and only the plate's own filament list separates
  628. them. The builder sees both as the same byte, which is how a plate whose one
  629. printed filament sat on the external spool went out as `use_ams=true` with a
  630. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  631. with 07FF_8012 (#3087).
  632. Returns None whenever the two cannot be lined up — no mapping, no parsed
  633. requirements, or a requirement the mapping is too short to cover — so every
  634. caller falls back to existing behaviour rather than acting on a guess.
  635. """
  636. if not isinstance(mapping, list) or not mapping or not required:
  637. return None
  638. entries = []
  639. for filament in required:
  640. slot_id = filament.get("slot_id")
  641. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  642. # The mapping and the requirements disagree about how many filaments
  643. # the file has. They came from different reads, so judge nothing.
  644. return None
  645. entries.append(mapping[slot_id - 1])
  646. return entries or None
  647. def _is_external_tray(tray_id) -> bool:
  648. """True for an explicit external-spool selection (254/255), not for an
  649. unresolved slot and not for an AMS tray."""
  650. if tray_id is None:
  651. return False
  652. try:
  653. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  654. except (TypeError, ValueError):
  655. return False
  656. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  657. """Whether this printer could have two extruders, judged generously.
  658. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  659. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  660. why the MQTT command builder skips its own use_ams reconcile there. Anything
  661. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  662. with, external spools or not.
  663. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  664. behaviour it has always had, while a wrong "no" would rewrite a field that
  665. steers which nozzle prints. The model name is the first answer (it is what
  666. the command builder falls back to as well), then the same live evidence the
  667. dispatcher's extruder annotation uses — a second nozzle reporting a
  668. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  669. since a single-nozzle printer has exactly one.
  670. """
  671. if is_dual_nozzle_model(printer_model):
  672. return True
  673. nozzles = getattr(status, "nozzles", None) or []
  674. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  675. return True
  676. raw = getattr(status, "raw_data", None) or {}
  677. if raw.get("ams_extruder_map"):
  678. return True
  679. vt_trays = raw.get("vt_tray") or []
  680. return isinstance(vt_trays, list) and len(vt_trays) > 1
  681. def _int_or(value, default: int) -> int:
  682. """``int(value)``, or ``default`` when the field is missing or junk.
  683. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  684. the next — and a tray id that fails to parse must not take the whole
  685. derivation down with it.
  686. """
  687. try:
  688. return int(value)
  689. except (TypeError, ValueError):
  690. return default
  691. # What a queue job's dispatch is worked out from, and an edit can change.
  692. _DISPATCH_INPUTS = (
  693. "printer_id",
  694. "status",
  695. "ams_mapping",
  696. "plate_id",
  697. "filament_overrides",
  698. "skip_filament_check",
  699. "target_model",
  700. "target_location",
  701. )
  702. async def _edited_since_loaded(db: AsyncSession, item: PrintQueueItem) -> bool:
  703. """Whether ``item`` was changed or removed since ``check_queue`` loaded it.
  704. The pass works on the jobs as loaded at its start, and it may have waited
  705. since: a plug powering a printer on takes minutes. A job edited meanwhile
  706. (moved to another printer, given a mapping or another plate, cancelled)
  707. is left to the next pass, which reads it fresh: deciding from the stale
  708. copy would overwrite the edit, or send the job where it no longer goes.
  709. The query flushes the pass's own pending changes first, so those don't
  710. count as edits.
  711. """
  712. row = (
  713. await db.execute(
  714. select(*(getattr(PrintQueueItem, name) for name in _DISPATCH_INPUTS)).where(PrintQueueItem.id == item.id)
  715. )
  716. ).one_or_none()
  717. if row is not None and all(getattr(item, name) == value for name, value in zip(_DISPATCH_INPUTS, row, strict=True)):
  718. return False
  719. logger.info("Queue item %s changed during this pass; leaving it to the next", item.id)
  720. return True
  721. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  722. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  723. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  724. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  725. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  726. agree or a mapping cannot be read back against live tray telemetry.
  727. """
  728. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  729. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  730. """The global tray ids ``item`` actually prints from, or None if unknown.
  731. ``ams_mapping`` is the array the print command carries: position = filament
  732. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  733. not use. None means "no usable statement" — no mapping, unparseable JSON,
  734. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  735. documents), or one that resolves to no tray at all. Callers must treat None
  736. as "consider every loaded tray" rather than "consider none": narrowing on
  737. an absent mapping would silently drop requirements the print really has.
  738. """
  739. raw = getattr(item, "ams_mapping", None)
  740. if not raw:
  741. return None
  742. if isinstance(raw, str):
  743. try:
  744. mapping = json.loads(raw)
  745. except (json.JSONDecodeError, TypeError):
  746. return None
  747. else:
  748. mapping = raw
  749. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  750. return None
  751. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  752. return used or None
  753. def _mqtt_commands_rejected(status) -> bool:
  754. """True when the printer is currently reporting that it refused a command.
  755. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  756. a control command it could not verify. Queries still answer, so the printer
  757. looks connected and idle while project_file, gcode_line and
  758. ams_change_filament are all dropped — no amount of waiting or re-uploading
  759. changes that (#2732).
  760. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  761. ``print_error`` path builds HMSError differently), so this is safe to call on
  762. every watchdog poll.
  763. """
  764. for err in getattr(status, "hms_errors", None) or []:
  765. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  766. return True
  767. return False
  768. def _drying_ams_ids(status) -> list[int]:
  769. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  770. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  771. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  772. started (#2758) — it is a diagnostic, not a gate.
  773. Deliberately not used to block or stop drying before dispatch. This printer
  774. class supports drying concurrently with an active print
  775. (``supports_drying_while_printing``), so drying is not incompatible with
  776. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  777. while two AMS units were drying, one of them without its external PSU. Until
  778. it is known whether the blocker is drying itself or the power budget
  779. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  780. hardware is perfectly happy to continue.
  781. """
  782. ids: list[int] = []
  783. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  784. if not isinstance(unit, dict):
  785. continue
  786. try:
  787. if int(unit.get("dry_time") or 0) > 0:
  788. ids.append(int(unit.get("id", 0)))
  789. except (TypeError, ValueError):
  790. continue
  791. return ids
  792. def _parse_diameter(raw) -> float | None:
  793. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  794. try:
  795. value = float(raw)
  796. except (TypeError, ValueError):
  797. return None
  798. return value if value > 0 else None
  799. def _nozzle_info_by_id(status) -> dict[int, dict]:
  800. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  801. The field name is historical: on the H2 series ``nozzle_info`` carries an
  802. entry for *every* nozzle the printer knows about — the L/R hotends under
  803. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  804. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  805. :func:`_installed_nozzle_diameters` each take the half they need.
  806. """
  807. by_id: dict[int, dict] = {}
  808. for entry in getattr(status, "nozzle_rack", None) or []:
  809. if not isinstance(entry, dict):
  810. continue
  811. try:
  812. by_id[int(entry.get("id"))] = entry
  813. except (TypeError, ValueError):
  814. continue
  815. return by_id
  816. # What the firmware puts in a nozzle's serial number when the carriage or dock
  817. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  818. # its nozzle back in the rack (#2885).
  819. _EMPTY_NOZZLE_SERIAL = "N/A"
  820. def _nozzle_is_mounted(entry: dict | None) -> bool:
  821. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  822. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  823. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  824. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  825. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  826. the dock. So the diameter is not a presence signal (#2885).
  827. Emptiness has to be stated, not merely unstated. The serial must be the
  828. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  829. absent — an empty serial only means the printer didn't say, and a firmware
  830. that reports neither field normalises to exactly that. Treating "didn't
  831. say" as "empty" would silently switch the #1899 guard off on any such
  832. machine, so everything we cannot positively call empty counts as mounted.
  833. """
  834. if entry is None:
  835. return True
  836. serial = str(entry.get("serial_number") or "").strip().upper()
  837. if serial != _EMPTY_NOZZLE_SERIAL:
  838. return True
  839. try:
  840. max_temp = float(entry.get("max_temp") or 0)
  841. except (TypeError, ValueError):
  842. return True
  843. return max_temp > 0
  844. def _installed_nozzle_diameters(status) -> list[float]:
  845. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  846. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  847. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  848. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  849. told us its nozzle hardware" — callers must treat that as unknown, not as a
  850. mismatch, so we never block a print on missing data.
  851. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  852. though ``nozzles`` still carries a diameter for it: that value is stale, and
  853. counting it would let a slice match a nozzle the machine does not have
  854. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  855. """
  856. info = _nozzle_info_by_id(status)
  857. diameters: list[float] = []
  858. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  859. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  860. try:
  861. value = float(raw)
  862. except (TypeError, ValueError):
  863. continue
  864. if value > 0 and _nozzle_is_mounted(info.get(index)):
  865. diameters.append(value)
  866. return diameters
  867. def _rack_nozzle_diameters(status) -> list[float]:
  868. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  869. Keyed off the nozzle ids themselves rather than the printer model: only a
  870. rack machine ever reports ids 16-21, so there is no model registry to keep
  871. in sync. An empty dock is simply absent from the payload — measured on an
  872. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  873. present — so appearing here already means "a nozzle is in that dock".
  874. ``stat`` is deliberately not interpreted: its values aren't known, and
  875. reading it wrongly could hide a nozzle the printer would happily fetch.
  876. """
  877. diameters: list[float] = []
  878. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  879. if nozzle_id not in _RACK_NOZZLE_IDS:
  880. continue
  881. # PrinterState spells it "diameter"; the REST schema renames it to
  882. # "nozzle_diameter". Accept either so a caller holding the serialised
  883. # shape gets the same answer.
  884. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  885. if value is not None:
  886. diameters.append(value)
  887. return diameters
  888. def _format_diameters(diameters: list[float]) -> str:
  889. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  890. Deduplicated because a loaded rack holds several nozzles of the same size,
  891. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  892. short form doesn't. Matching still runs over the full list.
  893. """
  894. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  895. def _nozzle_mismatch_message(
  896. sliced_nozzle: float | None,
  897. installed: list[float],
  898. rack: list[float] | None = None,
  899. ) -> str | None:
  900. """Return an actionable error message when the sliced nozzle can't be
  901. printed on any nozzle the machine can reach, else None (#1899).
  902. Fail-safe: returns None whenever we lack the data to judge — no sliced
  903. diameter, or the printer reported no nozzles — so a print is only ever
  904. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  905. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  906. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  907. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  908. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  909. as reachable: the printer fetches one as part of starting the print, so a
  910. slice that matches a docked nozzle is not a mismatch. Without this the
  911. guard blocked every job whose nozzle happened not to be on a hotend at
  912. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  913. diameter already mounted could ever print, and the user had to fetch the
  914. nozzle by hand on the printer's own UI first (#2885).
  915. """
  916. reachable = [*installed, *(rack or [])]
  917. if not sliced_nozzle or not reachable:
  918. return None
  919. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  920. return None
  921. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  922. if rack:
  923. where += f" and {_format_diameters(rack)} in the nozzle rack"
  924. return (
  925. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  926. f"{where}. Re-slice for an available nozzle, or fit the matching "
  927. f"nozzle before printing."
  928. )
  929. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  930. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  931. Shared by the required and loaded sides, which name their extruder
  932. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  933. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  934. 1 the left/deputy — and both are absent on single-nozzle printers, where
  935. naming a nozzle would be noise.
  936. """
  937. parts = [(entry.get("type") or "filament").upper()]
  938. if entry.get("color"):
  939. parts.append(str(entry["color"]))
  940. nozzle = entry.get(nozzle_key)
  941. if nozzle == 0:
  942. parts.append("(right nozzle)")
  943. elif nozzle == 1:
  944. parts.append("(left nozzle)")
  945. return " ".join(parts)
  946. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  947. """Explain that nothing loaded matches what the file needs (#2771).
  948. Only ever built for a printer with no AMS, where the loaded list is short
  949. enough to quote in full and there is no "load another spool and hit Resume"
  950. recovery — the external spool holder is all there is, so the user needs to
  951. be told which filament to put on it.
  952. """
  953. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  954. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  955. return (
  956. f"No filament loaded on this printer matches the file. It needs {want}; "
  957. f"the printer has {have} and no AMS. Load the required filament on the "
  958. f"external spool holder, or send this job to a printer that has it."
  959. )
  960. async def _queued_plate_bed_temperature(item: PrintQueueItem, archive: PrintArchive | None) -> int:
  961. """Bed temperature for the plate a queued job prints, 0 when unknown.
  962. The archive stores the highest bed temperature of any filament in the
  963. project, while the job may print another plate than the one archived: a
  964. PLA plate of a project that also holds PETG is heated for PLA. Read from
  965. the archive's file for the job's own plate, falling back to the stored
  966. value when the file can't be read.
  967. """
  968. stored = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  969. if archive is None or not archive.file_path:
  970. return stored
  971. temperature = await asyncio.to_thread(plate_bed_temperature, settings.base_dir / archive.file_path, item.plate_id)
  972. return temperature or stored
  973. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  974. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  975. every call site below it: G-code injection, usage registration, rack-plan
  976. lookup, slot-extruder lookup, the external-spool check, and the actual
  977. print command.
  978. A positive explicit ``plate_id`` on the queue item always wins. A
  979. non-positive one is treated as "not set" and resolved from the archive,
  980. the way the rest of the queue code already reads it (``if item.plate_id:``
  981. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  982. field, and passing a 0 straight through would build a print command for
  983. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  984. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  985. Falling back to a bare ``1`` instead of reading the archive assumes a
  986. single-plate file's one G-code is numbered 1, which only holds for a
  987. plate exported on its own: one cut out of a larger project keeps its
  988. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  989. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  990. the file, throws an HMS error, and sits wedged in IDLE until
  991. power-cycled (#2947).
  992. The call sites agreed on a fallback only by accident before this:
  993. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  994. the archive's own default plate internally whenever the plate id it's
  995. handed isn't in the file, so it could silently inject into a different
  996. plate than the one the print command itself asked for.
  997. Falls back to 1 when the archive can't be read, holds no G-code member at
  998. all, or its default member doesn't follow the ``plate_N`` naming
  999. convention (a slicer that doesn't use it has no number to dispatch).
  1000. An explicit plate the archive doesn't hold is logged and then sent
  1001. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  1002. to a plate that is in the file would print a model nobody asked for,
  1003. which is the worse of the two.
  1004. """
  1005. try:
  1006. with zipfile.ZipFile(file_path, "r") as zf:
  1007. names = zf.namelist()
  1008. except (OSError, zipfile.BadZipFile) as exc:
  1009. logger.warning(
  1010. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  1011. "is unavailable; dispatching plate %s",
  1012. file_path,
  1013. exc,
  1014. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  1015. )
  1016. names = None
  1017. if explicit_plate_id is not None and explicit_plate_id > 0:
  1018. if (
  1019. names is not None
  1020. and default_plate_number(names) is not None
  1021. and select_plate_gcode_name(names, explicit_plate_id) is None
  1022. ):
  1023. logger.warning(
  1024. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  1025. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  1026. "file, since printing a different plate would print the wrong model (#2947)",
  1027. file_path,
  1028. explicit_plate_id,
  1029. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  1030. explicit_plate_id,
  1031. )
  1032. return explicit_plate_id
  1033. resolved = default_plate_number(names) if names is not None else None
  1034. return resolved if resolved is not None else 1
  1035. class PrintScheduler:
  1036. """Background scheduler that processes the print queue."""
  1037. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  1038. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  1039. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  1040. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  1041. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  1042. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  1043. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1044. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1045. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  1046. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  1047. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  1048. }
  1049. def __init__(self):
  1050. self._running = False
  1051. self._check_interval = 30 # seconds
  1052. # After a pass that actually dispatched something, loop again almost
  1053. # immediately instead of sleeping the full interval (#2555). A dispatch
  1054. # changes printer state — a batch launch fans out over several passes as
  1055. # printers free up, a wedged head-of-line job reverts to pending, an
  1056. # upload slot opens — and the next batch of ready work should not have to
  1057. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  1058. # pending items are behind printers that are genuinely busy printing),
  1059. # there is nothing to react to, so we fall back to the normal interval;
  1060. # that also means this can never tight-loop, since fast ticks only
  1061. # continue while dispatches keep happening and the queue is draining.
  1062. self._fast_check_interval = 3 # seconds
  1063. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  1064. self._power_on_check_interval = 10 # seconds between connection checks
  1065. # Printers whose class-target power-on failed, mapped to the monotonic
  1066. # time their cool-off expires (#2786).
  1067. #
  1068. # Without this, one printer with an unreachable plug starves every
  1069. # sibling of its model forever: the wake step walks candidates in id
  1070. # order, spends the pass's single attempt on the same broken printer
  1071. # every time, and the healthy one two slots down is never reached. It
  1072. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  1073. # which delays the whole queue, not just this job.
  1074. #
  1075. # Entries expire on read rather than being cleared on success: a printer
  1076. # inside its cool-off is skipped before the power-on is reached, so a
  1077. # live entry can never be overwritten by a success anyway. A printer
  1078. # that comes back by any other route stops being a wake candidate the
  1079. # moment it connects.
  1080. self._wake_failures: dict[int, float] = {}
  1081. self._wake_failure_cooloff = 600 # seconds
  1082. # Printers whose last upload never reached them, mapped to the monotonic
  1083. # time they may be dispatched to again (#3210). Same expire-on-read shape
  1084. # as `_wake_failures`. Without it, a printer that cannot take files is
  1085. # idle on every pass, so it is picked on every pass.
  1086. self._upload_backoff: dict[int, float] = {}
  1087. # Refused uploads in a row per printer, which sets the next backoff
  1088. # window. Cleared by a successful upload to that printer.
  1089. self._upload_refusals: dict[int, int] = {}
  1090. # Why each printer in `_upload_backoff` refused its last upload, for
  1091. # the reason its jobs show. Cleared with `_upload_refusals`.
  1092. self._upload_refusal_kind: dict[int, FtpFailureKind] = {}
  1093. # The "job waiting" text last sent for each printer's current run of
  1094. # refusals. A refusal notifies only when its text differs, so a run
  1095. # notifies once, and again only if it turns into something the user
  1096. # has to fix. Cleared with `_upload_refusals`.
  1097. self._upload_refusal_notified: dict[int, str] = {}
  1098. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  1099. self._drying_in_progress: dict[int, float] = {}
  1100. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  1101. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  1102. # cycle and the humidity finally coming down, so the normal steady
  1103. # state is an empty dict. Fields:
  1104. # running — a cycle we armed is (or should be) on the firmware
  1105. # ended_at — monotonic when we observed that cycle end
  1106. # unproductive — consecutive armed cycles that ended with the reading
  1107. # still above the threshold
  1108. # suspended — we have stopped arming this unit and said so
  1109. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  1110. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  1111. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  1112. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  1113. # print-takes-priority stop, the manual-cycle adoption guard, and the
  1114. # arming setdefault all act on that meaning -- a unit that is merely
  1115. # waiting out its streak must not become stoppable or judgeable.
  1116. # since -- monotonic stamp when the current continuous above-threshold
  1117. # streak began
  1118. # last -- monotonic stamp of the last pass that observed the streak
  1119. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  1120. # Slots already notified as low on filament:
  1121. # {(printer_id, ams_id, tray_id, spool_id)}.
  1122. # Cleared when the slot goes back above its threshold rather than on a
  1123. # timer, mirroring _notified_hms_errors — a spool hovering at the
  1124. # boundary must not produce an alert on every pass, and a slot that has
  1125. # been refilled has to be able to alert again. See #2913.
  1126. #
  1127. # The spool id is part of the key because the slot alone cannot clear
  1128. # itself. Pull a low spool and put a different part-used one in the same
  1129. # slot: the key survives the pass where the slot resolves to nothing --
  1130. # deliberately, so a brief Spoolman outage does not re-alert everything
  1131. # when it returns -- and the replacement never goes above the threshold,
  1132. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1133. # different key and the stale one is inert.
  1134. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1135. # The same, for the MQTT relay's filament/low event: its own record, so
  1136. # one channel having been told never silences the other.
  1137. self._relayed_filament_low: set[tuple[int, int, int, int]] = set()
  1138. # Earliest monotonic time the next low-filament check may run (#2913).
  1139. self._filament_low_next_check: float = 0.0
  1140. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1141. # condition is "reorder" or "break", the events are those that had a
  1142. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1143. # condition clears, so it can alert again, and when nobody wants either
  1144. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1145. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1146. # re-send one message per SKU that is still low.
  1147. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1148. # The JSON last read from or written to that row; None until it has been read.
  1149. self._stock_alerts_persisted: str | None = None
  1150. # Earliest monotonic time the next stock forecast check may run (#2955).
  1151. self._stock_forecast_next_check: float = 0.0
  1152. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1153. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1154. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1155. # both features share _drying_in_progress.
  1156. self._scheduled_drying_printer_ids: set[int] = set()
  1157. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1158. # the first pass after a restart reaps anything left behind.
  1159. self._last_scheduled_drying_prune: float | None = None
  1160. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1161. # a project_file command must not get a second dispatch until either it
  1162. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1163. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1164. # during that window the DB busy_printers seed is empirically unreliable
  1165. # (multi-plate batches double-/triple-dispatched onto the same printer
  1166. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1167. # or revert.
  1168. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1169. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1170. # Minimum cooldown between dispatches to the same printer (covers the
  1171. # H2D's project_file digestion window).
  1172. self._dispatch_min_cooldown = 60.0
  1173. # Hard timeout — drop the hold even if we never observed a transition,
  1174. # so a lost MQTT session can't lock a printer out of the queue forever.
  1175. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1176. # watchdog runs first on the unhappy path.
  1177. self._dispatch_max_hold = 180.0
  1178. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1179. # an earlier pass and is still running. `_start_print` flips the row
  1180. # pending -> printing only *after* the upload completes, so until then
  1181. # the row stays `pending`: each tick, check_queue excludes these
  1182. # item_ids from re-selection and their printers from new dispatch /
  1183. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1184. # freed slots refill on the next fast tick. check_queue is the sole,
  1185. # sequential caller and the prune done-callbacks run in the same
  1186. # event-loop thread, so this dict needs no lock.
  1187. # item_id -> (task, printer_id)
  1188. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1189. # Expected prints registered by `_start_print` that have not yet had a
  1190. # print command sent. Populated at registration, dropped once
  1191. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1192. # other exit. Same threading argument as `_inflight` above: one
  1193. # sequential caller, callbacks on the same loop, so no lock.
  1194. # item_id -> (printer_id, remote_filename, archive_id)
  1195. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1196. # Budget reservations created for a dispatch whose print command has
  1197. # not been confirmed yet. `_dispatch_one` releases these on every
  1198. # unsuccessful exit; a successful start removes the item id and leaves
  1199. # the reservation for finance_billing to consume with the archive.
  1200. self._unconfirmed_budget_reservations: set[int] = set()
  1201. # The print user `_start_print` handed to printer_manager for an item
  1202. # whose print command has not been sent yet (item_id -> printer_id).
  1203. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1204. # expected print above: it marks the printer's next print as Bambuddy's.
  1205. self._unconfirmed_print_user: dict[int, int] = {}
  1206. # Prints whose command went out but which the printer has not been
  1207. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1208. # the file and archive None for a library print. The watchdog drops the
  1209. # entry once the print runs, and withdraws what it stands for when the
  1210. # print never starts (see `_forget_unstarted_print`).
  1211. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1212. # Chamber temperature history for smart soak-time reduction.
  1213. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1214. # Entries older than _chamber_history_ttl are pruned on write.
  1215. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1216. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1217. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1218. # Populated on engagement in `_apply_keep_warm`, cleared by
  1219. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1220. # when a gate setting toggles off mid-hold — the release publishes
  1221. # bed → 0 first).
  1222. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1223. # Preheat rollback registry: printer_id -> subset of
  1224. # {"bed", "chamber", "airduct"} listing which preheat commands
  1225. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1226. # every entry still present at exit unless the print successfully
  1227. # started, so a failed upload / cancel / exception never leaves the
  1228. # printer heating for a job that isn't happening.
  1229. self._preheat_pin: dict[int, set[str]] = {}
  1230. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1231. # rollback can tell its own target from one someone else has since
  1232. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1233. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1234. self._preheat_pin_bed: dict[int, int] = {}
  1235. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1236. # its preheat was still holding at temperature. Set by
  1237. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1238. # `_preheat_sleep`, and cleared when the dispatch exits.
  1239. self._cancelled_dispatches: set[int] = set()
  1240. # printer_id -> monotonic time it was first seen terminal while one of
  1241. # its queue rows was still 'printing'. Reset by any non-terminal
  1242. # observation, so it measures an unbroken run rather than a total.
  1243. # In-memory on purpose: a restart re-arms the grace period, which only
  1244. # delays a recovery that is already the exceptional path (#2829).
  1245. self._terminal_since: dict[int, float] = {}
  1246. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1247. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1248. # across idle printers repeats that for every one of them in a single
  1249. # pass. Cleared at the top of each pass so a re-sliced file is never
  1250. # served from a previous tick.
  1251. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1252. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1253. # matcher about every idle candidate, and a pass can ask again for the
  1254. # same job and printer (another variant, a previous-print retry, the
  1255. # low-filament move). Cleared with the requirement memo.
  1256. self._unmatched_memo: dict[tuple, list[str]] = {}
  1257. # When each "any model" job held for low filament last looked for
  1258. # another printer (#3137), by queue item id.
  1259. self._short_hold_checked_at: dict[int, float] = {}
  1260. async def run(self):
  1261. """Main loop - check queue every interval."""
  1262. self._running = True
  1263. logger.info("Print scheduler started")
  1264. await self._clear_stale_dispatch_claims(at_startup=True)
  1265. while self._running:
  1266. dispatched = False
  1267. try:
  1268. self._sample_chamber_temps()
  1269. # No-op while any upload is in flight; on a quiet tick it releases
  1270. # a claim whose best-effort clear failed (e.g. the database was
  1271. # briefly unreachable), instead of leaving the row wedged until
  1272. # the next restart.
  1273. await self._clear_stale_dispatch_claims()
  1274. await self._close_stranded_printing_items()
  1275. dispatched = await self.check_queue()
  1276. except Exception as e:
  1277. logger.error("Scheduler error: %s", e)
  1278. # Re-check quickly after a productive pass so a draining batch does
  1279. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1280. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1281. async def _close_stranded_printing_items(self) -> None:
  1282. """Close a ``printing`` row the completion event never closed (#2829).
  1283. ``on_print_complete`` refuses to close a row when the completion's
  1284. subtask name disagrees with the file the row was dispatched with, so a
  1285. completion meant for something else (the printer's own
  1286. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1287. The refusal has no way back, though: nothing else ever closes the row,
  1288. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1289. one bad comparison wedges that printer's queue until a human presses
  1290. cancel. That is what #2829's reporters hit, and the guard's own
  1291. docstring already called stranding the worse of the two failures.
  1292. This is the way back. When a row has been ``printing`` while its
  1293. printer sat in a terminal state for the whole grace period, the print
  1294. is over however the event was read, and the row is closed with the
  1295. status the printer's own state implies.
  1296. Deliberately conservative:
  1297. * Only a connected printer counts. A disconnected one has a stale
  1298. ``state`` and proves nothing.
  1299. * The clock is reset by any non-terminal observation, so this cannot
  1300. fire on a printer that is merely between stages.
  1301. * The grace period is far longer than the gap between a printer
  1302. finishing and its completion arriving, so the normal path always
  1303. wins the race and this only ever sees genuine strandings.
  1304. What it does *not* do is replay the completion's side effects --
  1305. notifications, billing, auto-off. It restores the queue, which is the
  1306. harm being undone; the archive was updated by the normal path
  1307. regardless, since only the queue block refuses. A recovery that
  1308. silently re-fired notifications minutes late would be its own bug.
  1309. """
  1310. try:
  1311. async with async_session() as db:
  1312. result = await db.execute(
  1313. select(PrintQueueItem)
  1314. .where(PrintQueueItem.status == "printing")
  1315. .where(PrintQueueItem.printer_id.is_not(None))
  1316. )
  1317. items = list(result.scalars().all())
  1318. if not items:
  1319. self._terminal_since.clear()
  1320. return
  1321. now = time.monotonic()
  1322. seen_printers: set[int] = set()
  1323. closed = False
  1324. for item in items:
  1325. printer_id = item.printer_id
  1326. seen_printers.add(printer_id)
  1327. state = printer_manager.get_status(printer_id)
  1328. status = _terminal_queue_status(state)
  1329. if status is None:
  1330. self._terminal_since.pop(printer_id, None)
  1331. continue
  1332. since = self._terminal_since.setdefault(printer_id, now)
  1333. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1334. continue
  1335. item.status = status
  1336. item.completed_at = datetime.now(timezone.utc)
  1337. closed = True
  1338. # The printer is idle: nothing it prints next is this item's.
  1339. self._forget_unstarted_print(item.id, unless_printing=True)
  1340. logger.warning(
  1341. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1342. "closing it as %s. Its completion event was never matched to it, which blocks "
  1343. "every later job for this printer (#2829).",
  1344. item.id,
  1345. printer_id,
  1346. getattr(state, "state", None),
  1347. now - since,
  1348. status,
  1349. )
  1350. if closed:
  1351. await db.commit()
  1352. from backend.app.services.print_batch import refresh_batches_after
  1353. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1354. for printer_id in list(self._terminal_since):
  1355. if printer_id not in seen_printers:
  1356. del self._terminal_since[printer_id]
  1357. except Exception as e:
  1358. # Best-effort, same as the claim sweep beside it: a recovery path
  1359. # that can itself break the scheduler loop is worse than the strand.
  1360. logger.error("Stranded-item sweep failed: %s", e)
  1361. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1362. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1363. A claim is only ever held by a live dispatch coroutine, so when this
  1364. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1365. is stale. At startup that is trivially true — no coroutine survives a
  1366. restart. It is equally true on any later tick where no upload is running,
  1367. which is what makes this safe to repeat rather than only run once.
  1368. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1369. the database is briefly unreachable at exactly the moment dispatch ends,
  1370. the claim survives and the row is wedged out of the selection query. That
  1371. used to last until the next restart (#2702 follow-up, seen when
  1372. PostgreSQL refused a connection mid-dispatch).
  1373. ``_inflight`` is populated when the task is spawned, before the coroutine
  1374. claims its row, and pruned by a done-callback that cannot run before the
  1375. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1376. race window and needs no age threshold. A size-derived upload deadline
  1377. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1378. """
  1379. if self._inflight:
  1380. return
  1381. try:
  1382. async with async_session() as db:
  1383. res = await db.execute(
  1384. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1385. )
  1386. await db.commit()
  1387. if res.rowcount:
  1388. logger.info(
  1389. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1390. res.rowcount,
  1391. " at startup" if at_startup else "",
  1392. )
  1393. except Exception as exc:
  1394. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1395. def stop(self):
  1396. """Stop the scheduler."""
  1397. self._running = False
  1398. logger.info("Print scheduler stopped")
  1399. def forget_printer(self, printer_id: int) -> None:
  1400. """Drop what is kept for a deleted printer, so the next printer given its
  1401. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1402. would keep it out of dispatch for up to an hour.
  1403. A dispatch already in flight keeps its own state (_inflight, the preheat
  1404. pins, unconfirmed prints): it unwinds that when it ends.
  1405. """
  1406. for keyed in (
  1407. self._upload_backoff,
  1408. self._upload_refusals,
  1409. self._upload_refusal_kind,
  1410. self._upload_refusal_notified,
  1411. self._wake_failures,
  1412. self._drying_in_progress,
  1413. self._dispatch_holds,
  1414. self._chamber_history,
  1415. self._keep_warm,
  1416. self._terminal_since,
  1417. ):
  1418. keyed.pop(printer_id, None)
  1419. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1420. for key in [key for key in keyed if key[0] == printer_id]:
  1421. del keyed[key]
  1422. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1423. del self._sent_unstarted_print[item_id]
  1424. async def check_queue(self) -> bool:
  1425. """Check for prints ready to start.
  1426. Returns True if this pass dispatched at least one item, so the caller
  1427. can loop again quickly instead of sleeping the full interval (#2555).
  1428. """
  1429. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1430. self._filament_req_memo.clear()
  1431. self._unmatched_memo.clear()
  1432. async with async_session() as db:
  1433. # Check if shortest-job-first scheduling is enabled
  1434. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1435. # Get all pending items in the one order the queue page shows them
  1436. # in (#3200). The first eligible item takes a printer, so this order
  1437. # decides who wins a printer that a pinned job and an "Any <model>"
  1438. # job both want. It used to start with ``printer_id``, which made the
  1439. # lane outrank the position: SQLite sorts NULL first, so model-based
  1440. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1441. # Neither is what the user dragged into place.
  1442. if sjf_enabled:
  1443. # SJF: items already jumped get top priority (starvation guard),
  1444. # then sort by print_time ascending. Items with no print time go
  1445. # last, and position breaks ties.
  1446. result = await db.execute(
  1447. select(PrintQueueItem)
  1448. .where(PrintQueueItem.status == "pending")
  1449. # Never re-select a row a dispatch worker has already claimed
  1450. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1451. # below, and the guard that lets an orphaned claim be ignored
  1452. # until startup reconciliation clears it.
  1453. .where(PrintQueueItem.dispatching_at.is_(None))
  1454. # archive/library_file are read by the cross-model gate
  1455. # (#2578); eager-load once per pass instead of a lazy-load
  1456. # (which would raise in async) per item.
  1457. .options(
  1458. selectinload(PrintQueueItem.archive),
  1459. selectinload(PrintQueueItem.library_file),
  1460. # Cross-model candidates (#671), plus each candidate's file
  1461. # for the same cross-model gate. Lazy-loading either would
  1462. # raise in async.
  1463. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1464. )
  1465. .order_by(
  1466. PrintQueueItem.been_jumped.desc(),
  1467. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1468. PrintQueueItem.position,
  1469. PrintQueueItem.id,
  1470. )
  1471. )
  1472. else:
  1473. result = await db.execute(
  1474. select(PrintQueueItem)
  1475. .where(PrintQueueItem.status == "pending")
  1476. # Skip rows already claimed by a dispatch worker (#2615).
  1477. .where(PrintQueueItem.dispatching_at.is_(None))
  1478. .options(
  1479. selectinload(PrintQueueItem.archive),
  1480. selectinload(PrintQueueItem.library_file),
  1481. # Cross-model candidates (#671), plus each candidate's file
  1482. # for the same cross-model gate. Lazy-loading either would
  1483. # raise in async.
  1484. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1485. )
  1486. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1487. )
  1488. items = list(result.scalars().all())
  1489. # Drop rows whose upload is still in flight from an earlier pass
  1490. # (#2602). They stay `pending` until the upload finishes, so without
  1491. # this a fast tick would re-select and re-dispatch the same row.
  1492. # Belt-and-suspenders with the printer exclusion below.
  1493. if self._inflight:
  1494. inflight_ids = set(self._inflight)
  1495. items = [it for it in items if it.id not in inflight_ids]
  1496. # Read plate-clear setting once per queue check. Default MUST be
  1497. # False to match the schema (SettingsSchema.require_plate_clear
  1498. # defaults False) and the frontend (toggle + card badge both treat a
  1499. # missing value as off). When no settings row exists, a True default
  1500. # here re-enabled the plate-clear gate the UI showed as disabled,
  1501. # blocking dispatch to FINISH-state printers forever with no UI path
  1502. # to clear it (#1865).
  1503. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1504. # Dispatch and track scheduled drying runs (#2638)
  1505. await self._check_scheduled_dryings(db)
  1506. if not items:
  1507. # No dispatchable pending items — still check auto-drying on idle
  1508. # printers, but keep any printer with an upload still in flight
  1509. # from an earlier pass out of it (#2602): its print is imminent,
  1510. # so it must not be auto-dried in the gap before the row flips to
  1511. # printing. Report the pass as productive while uploads run so the
  1512. # loop stays on the fast interval.
  1513. #
  1514. # Also release any keep-warm holds that got orphaned by the queue
  1515. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1516. # this early return, so call it directly with an empty candidate
  1517. # set. Without this, a printer whose queued item was cancelled or
  1518. # deleted would keep its bed at target until the max-duration
  1519. # timeout expired.
  1520. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1521. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1522. await self._check_auto_drying(db, [], inflight_printers)
  1523. await self._check_filament_low(db)
  1524. await self._check_stock_forecast(db)
  1525. return bool(self._inflight)
  1526. logger.info(
  1527. "Queue check: found %d pending items: %s",
  1528. len(items),
  1529. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1530. )
  1531. # Forget jobs that left the queue since they were last checked.
  1532. pending_ids = {i.id for i in items}
  1533. self._short_hold_checked_at = {
  1534. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1535. }
  1536. # Seed busy_printers with printers that already have an item in 'printing'
  1537. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1538. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1539. # lag several seconds behind the print command, so the next check_queue
  1540. # tick still sees IDLE and would double-dispatch onto the same printer.
  1541. # Without this guard, two pending items targeting the same printer
  1542. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1543. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1544. busy_result = await db.execute(
  1545. select(PrintQueueItem.printer_id)
  1546. .where(PrintQueueItem.status == "printing")
  1547. .where(PrintQueueItem.printer_id.is_not(None))
  1548. )
  1549. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1550. # Why each printer left this pass, recorded where the decision is
  1551. # made rather than re-derived when the summary is logged. #3018's
  1552. # bundle shows what the old summary produced: "printer 1 not
  1553. # available -- connected=True, state=IDLE" immediately followed by a
  1554. # dispatch to printer 1. Two things went wrong at once. The line read
  1555. # live state at log time, which by then no longer matched the state
  1556. # the decision was made on; and `busy_printers` holds both printers
  1557. # that cannot take work and printers this pass has claimed for it,
  1558. # which are opposite facts. It is the first line anyone greps for
  1559. # "why did my item not go out", so it has to say which.
  1560. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1561. # Printers this pass is dispatching to. They are in busy_printers so
  1562. # nothing else in the pass targets them -- that is a reservation, not
  1563. # an obstruction, and the summary says so.
  1564. claimed_printers: set[int] = set()
  1565. def mark_busy(printer_id: int, reason: str) -> None:
  1566. """Take ``printer_id`` out of this pass, recording why.
  1567. First reason wins: a printer already excluded by a stronger fact
  1568. -- a print running on it -- must not be relabelled by a weaker
  1569. check that ran later and would have excluded it anyway.
  1570. """
  1571. busy_printers.add(printer_id)
  1572. busy_reasons.setdefault(printer_id, reason)
  1573. def claim_printer(printer_id: int) -> None:
  1574. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1575. claimed_printers.add(printer_id)
  1576. mark_busy(printer_id, "selected for dispatch in this pass")
  1577. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1578. # worded for a different audience: the log wants "still inside its
  1579. # post-dispatch hold window", the queue row wants to know the printer
  1580. # is taken and nothing is broken. Only the cases that would read wrong
  1581. # as a plain "Busy" are recorded here; the rest fall back to it.
  1582. item_hold_reasons: dict[int, str] = {}
  1583. # Names and models for the printers this pass may have to write a
  1584. # waiting reason about, read once rather than per skip per tick. The
  1585. # model-based branch already has its names from `_printers_for_model`.
  1586. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1587. pinned_printers: dict[int, tuple[str, str]] = {}
  1588. if pinned_printer_ids:
  1589. pinned_rows = await db.execute(
  1590. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1591. )
  1592. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1593. def printer_label(printer_id: int) -> str:
  1594. """What to call this printer in a queue row."""
  1595. entry = pinned_printers.get(printer_id)
  1596. return (entry[0] if entry else "") or f"printer {printer_id}"
  1597. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1598. """Record why *item* is not going out, in the words the queue row shows.
  1599. The fixed-printer branch's single writer for ``waiting_reason``
  1600. (#3074). Before this, the sensor interlock was the only thing that
  1601. wrote the field there, so an item pinned to a printer that was
  1602. merely printing sat at `pending` with nothing to show for it —
  1603. indistinguishable from a queue that had stopped working — while
  1604. the same job queued as "Any <model>" explained itself.
  1605. Every exit from that branch now calls this, which is also what
  1606. replaced the interlock's old habit of clearing the field up front:
  1607. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1608. because whichever exit runs next overwrites it and the dispatch
  1609. path clears it.
  1610. A notification goes out when this item starts asking for
  1611. something, and only then: the new reason needs the user, and what
  1612. it replaced did not. "What it replaced did not" has to include a
  1613. busy-only reason, not just an empty one. The sequence this branch
  1614. actually produces is a print running (``Busy: X1C-01``) and then
  1615. the plate it left behind (``Waiting for plate confirmation``), and
  1616. testing "was the field empty" would call that no transition at all
  1617. and stay quiet through the one case worth saying out loud.
  1618. The cost is that a printer dropping offline, coming back busy and
  1619. dropping again asks twice rather than once. That is the honest
  1620. reading — it went wrong twice — and the alternative was a rule
  1621. that never fired for the case this was built for.
  1622. *notify* is how a caller opts out. The sensor interlock does: it
  1623. has never sent this notification, and a change about what the
  1624. queue *displays* is not the place to start (#1148).
  1625. """
  1626. if item.waiting_reason == reason:
  1627. return
  1628. # Busy-only and empty are the same thing here: neither is the
  1629. # queue asking the user for anything.
  1630. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1631. item.waiting_reason = reason
  1632. await db.commit()
  1633. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1634. return
  1635. try:
  1636. job_name = await self._get_job_name(db, item)
  1637. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1638. await notification_service.on_queue_job_waiting(
  1639. job_name=job_name,
  1640. target_model=(entry[1] if entry else "") or "",
  1641. waiting_reason=reason,
  1642. db=db,
  1643. printer_id=item.printer_id,
  1644. )
  1645. except Exception as e:
  1646. # A queue that cannot say why it is waiting is the bug being
  1647. # fixed here; a queue that stops dispatching because a
  1648. # notification provider is down would be a worse one.
  1649. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1650. async def hold_for_printer(
  1651. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1652. ) -> None:
  1653. """Take *printer_id* out of this pass and tell the item's owner why."""
  1654. mark_busy(printer_id, log_reason)
  1655. item_hold_reasons.setdefault(printer_id, item_reason)
  1656. await hold_item(item, item_reason)
  1657. # Defense-in-depth (#1157): augment busy_printers with any printer
  1658. # still in its post-dispatch hold window. Empirically, the DB seed
  1659. # above can miss in-flight items in a multi-plate batch — same-file
  1660. # plates were being dispatched 30 s apart while the H2D was still
  1661. # digesting the first project_file. The hold is keyed in-memory and
  1662. # released by the watchdog on the success path, so it adds a layer
  1663. # that doesn't depend on DB row visibility or completion-callback
  1664. # timing.
  1665. for held_printer_id in list(self._dispatch_holds.keys()):
  1666. if self._printer_in_dispatch_hold(held_printer_id):
  1667. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1668. # Exclude printers whose upload is still in flight from an earlier
  1669. # pass (#2602). The row is `pending` until the upload finishes and
  1670. # the printing-state seed / dispatch hold above only arm once the
  1671. # upload completes, so this is what holds the printer (and, via
  1672. # busy_printers, its auto-drying) out of the pass during the upload.
  1673. for _task, inflight_pid in self._inflight.values():
  1674. if inflight_pid is not None:
  1675. mark_busy(inflight_pid, "an upload to it is still in flight")
  1676. # Snapshot taken here, before the item loop adds anything (#2801).
  1677. #
  1678. # The three sources above all mean the same thing: a print on this
  1679. # printer is running or imminent. Everything the loop adds below
  1680. # means only "the queue could not dispatch to it this pass", which
  1681. # is a different statement -- a printer waiting on a plate-clear
  1682. # acknowledgment, an offline printer, one with no matching file.
  1683. #
  1684. # Auto-drying must only see the first kind. Reading the whole set
  1685. # as "is currently printing" is what put a plate-held printer down
  1686. # the mid-print path: it capped the drying temperature, logged the
  1687. # cycle as (mid-print), and skipped the very gate that was supposed
  1688. # to hold it. The interlock block below already documents the same
  1689. # hazard and works around it by staying out of busy_printers; this
  1690. # generalises that workaround instead of repeating it per case.
  1691. dispatching_printers: set[int] = set(busy_printers)
  1692. # Printers whose last upload never reached them (#3210). After the
  1693. # snapshot above on purpose: such a printer is idle, not about to
  1694. # print, and auto-drying must keep treating it as idle.
  1695. now_mono = time.monotonic()
  1696. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1697. # can leave them out: there is no print to keep a bed warm for.
  1698. # Their holds are written silently: the refusal that put a printer
  1699. # here sent the "job waiting" notification for its run (#3409).
  1700. backoff_printers: set[int] = set()
  1701. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1702. if now_mono >= retry_at:
  1703. del self._upload_backoff[backoff_pid]
  1704. continue
  1705. backoff_printers.add(backoff_pid)
  1706. mark_busy(
  1707. backoff_pid,
  1708. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1709. )
  1710. item_hold_reasons.setdefault(
  1711. backoff_pid,
  1712. _refused_upload_hold_reason(printer_label(backoff_pid), self._upload_refusal_kind.get(backoff_pid)),
  1713. )
  1714. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1715. # enclosure door left open, say. The fixed-printer branch turns
  1716. # this into a waiting_reason the user can act on; the model-based
  1717. # branch hides these printers from the matcher so an "Any <model>"
  1718. # job runs on a sibling instead of queueing behind the held one.
  1719. #
  1720. # Deliberately NOT merged into busy_printers, even though that set
  1721. # already means "unavailable this pass". _check_auto_drying reads
  1722. # it as "is currently printing" and would put an idle-but-held
  1723. # printer down the mid-print drying path, which caps the drying
  1724. # temperature and skips the queue-only gating. A held printer is
  1725. # idle; it should dry exactly as it did before.
  1726. #
  1727. # Only sensors we actually read and found alerting appear here; see
  1728. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1729. # holds nothing.
  1730. interlocked: dict[int, str] = {}
  1731. try:
  1732. interlocked = await ha_sensor_manager.blocked_printers(db)
  1733. except Exception as e:
  1734. # Never let the interlock stop the queue running. A broken
  1735. # lookup means no holds, not no dispatches.
  1736. logger.warning("Home Assistant interlock check failed: %s", e)
  1737. interlocked = {}
  1738. # Printers a smart plug can bring back, read once for the whole pass
  1739. # (#2786). Used by the model-based branch both to word "Offline" in
  1740. # the waiting reason and to decide what the wake step may switch on.
  1741. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1742. # At most one power-on per queue check. Each one blocks this loop
  1743. # for the boot wait, so a queue of ten class-targeted jobs must not
  1744. # switch on ten printers inside a single pass — the next pass wakes
  1745. # the next one (#2786).
  1746. power_on_attempted = False
  1747. # Log skip reasons once per queue check (not per item)
  1748. skip_reasons: dict[str, int] = {}
  1749. # Items selected for dispatch in this pass, one per printer. The
  1750. # loop below only *decides* — the uploads happen afterwards, in
  1751. # parallel (#2555). See _dispatch_selected().
  1752. dispatch_ids: list[int] = []
  1753. # Library rows queued with `cleanup_library_after_dispatch` (the
  1754. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1755. # that prints them: the row is deleted and the 3MF is unlinked from
  1756. # disk. That was safe only because dispatch was serial. Run two of
  1757. # them against the same row at once and the second DELETE matches no
  1758. # row (StaleDataError), and the winner's unlink can pull the file out
  1759. # from under the loser's in-flight upload.
  1760. #
  1761. # Only the cleanup flag mutates the row. An ordinary library print
  1762. # just reads it, so the common fan-out — one file, many printers,
  1763. # which is exactly the reporter's workload — still goes out fully in
  1764. # parallel. Narrow the guard to the mutating case; do not serialise
  1765. # the case the whole fix exists for.
  1766. dispatch_libs: set[int] = set()
  1767. consumed_libs: set[int] = set()
  1768. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1769. """True if dispatching `candidate` now would race another item's cleanup."""
  1770. lib_id = candidate.library_file_id
  1771. if lib_id is None:
  1772. return False
  1773. if candidate.cleanup_library_after_dispatch:
  1774. # We would delete a row someone else in this pass is reading.
  1775. return lib_id in dispatch_libs
  1776. # Someone else in this pass will delete the row out from under us.
  1777. return lib_id in consumed_libs
  1778. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1779. lib_id = candidate.library_file_id
  1780. if lib_id is None:
  1781. return
  1782. dispatch_libs.add(lib_id)
  1783. if candidate.cleanup_library_after_dispatch:
  1784. consumed_libs.add(lib_id)
  1785. # Printer scope of each job's creator (#1727), so an "any <model>"
  1786. # job only lands on a printer its creator may use. Loaded lazily,
  1787. # once per creator per pass.
  1788. from backend.app.core.auth import is_auth_enabled
  1789. scope_auth_enabled = await is_auth_enabled(db)
  1790. creator_scopes: dict[int, PrinterScope] = {}
  1791. # Printers a model job passes over while drying blocks the queue,
  1792. # as a pinned job waits for its own. A parked timer never ends,
  1793. # so it does not hold (#2896).
  1794. drying_held: set[int] = (
  1795. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1796. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1797. else set()
  1798. )
  1799. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1800. if not scope_auth_enabled or user_id is None:
  1801. return ALL_PRINTERS
  1802. if user_id not in creator_scopes:
  1803. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1804. return creator_scopes[user_id]
  1805. for item in items:
  1806. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1807. if item.scheduled_time:
  1808. sched = item.scheduled_time
  1809. if sched.tzinfo is None:
  1810. sched = sched.replace(tzinfo=timezone.utc)
  1811. if sched > datetime.now(timezone.utc):
  1812. # Waiting on the clock, not on a printer.
  1813. await hold_item(item, None)
  1814. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1815. continue
  1816. # Skip items that require manual start, except an "any model"
  1817. # job held for low filament that another idle printer can now
  1818. # run: that one is moved there and carries on below (#3137).
  1819. if item.manual_start and not (
  1820. item.filament_short
  1821. and await self._release_short_model_hold(
  1822. db,
  1823. item,
  1824. busy_printers | interlocked.keys() | drying_held,
  1825. require_plate_clear,
  1826. await _creator_scope(item.created_by_id),
  1827. )
  1828. ):
  1829. # Waiting on the user, not on a printer. Cleared here because
  1830. # this is the last pass that will look at the row: a staged
  1831. # item never reaches the branches below again, so a reason
  1832. # left from before it was staged would stand forever (#3074).
  1833. # The one exception is the unmatched-filament hold, whose
  1834. # reason was written at staging and is why the item waits:
  1835. # it names the filament to load (#2799). Pressing start
  1836. # clears manual_start, and the branches below overwrite it.
  1837. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1838. await hold_item(item, keep)
  1839. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1840. continue
  1841. if item.printer_id and item.printer_id not in pinned_printers:
  1842. # Moved by the release above to a printer no row named when
  1843. # the labels were read.
  1844. moved_to = await self._get_printer(db, item.printer_id)
  1845. if moved_to is not None:
  1846. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1847. if item.printer_id:
  1848. # Its creator may no longer use this printer (#1727): an
  1849. # admin took it away from their group after the job was
  1850. # queued, say to keep it free for a training session. Held,
  1851. # not failed, so it starts if access comes back or the user
  1852. # moves it to a printer they still have.
  1853. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1854. await hold_item(
  1855. item,
  1856. "Its owner no longer has access to this printer — move it to another printer",
  1857. notify=False,
  1858. )
  1859. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1860. continue
  1861. # Held by a sensor interlock (#1148). Checked before the
  1862. # busy_printers test that would otherwise swallow it
  1863. # silently — "waiting for a printer" and "waiting for you
  1864. # to shut the enclosure" need to read differently, and only
  1865. # one of them is something the user can fix.
  1866. #
  1867. # It used to be the only thing that wrote a waiting_reason on
  1868. # this branch, and it cleared the field up front so a lifted
  1869. # hold could not leave a shut door reading "Waiting on
  1870. # Enclosure Door". `hold_item` carries that guarantee now —
  1871. # every exit below writes — so the clear is gone and the
  1872. # interlock is an ordinary hold like the rest (#3074).
  1873. interlock_reason = interlocked.get(item.printer_id)
  1874. if interlock_reason:
  1875. # Silent, exactly as it has always been. #1148 built this
  1876. # as a hold that shows on the row, never as an alert, and
  1877. # routing it through the shared writer must not quietly
  1878. # turn every open door into a notification.
  1879. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1880. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1881. continue
  1882. # Specific printer assignment (existing behavior)
  1883. if item.printer_id in busy_printers:
  1884. # Whatever took the printer out of this pass — a print
  1885. # already running on it, a post-dispatch hold, an upload
  1886. # still in flight, an item ahead of this one in the same
  1887. # pass — reads the same way from the queue: the printer is
  1888. # taken and this item is in line for it. The exceptions
  1889. # that do not (an offline printer, say) recorded their own
  1890. # wording in `item_hold_reasons` when they held it.
  1891. await hold_item(
  1892. item,
  1893. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1894. notify=item.printer_id not in backoff_printers,
  1895. )
  1896. continue
  1897. # Check if printer is idle
  1898. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1899. printer_connected = printer_manager.is_connected(item.printer_id)
  1900. # If printer not connected, try to power on via smart plug
  1901. if not printer_connected:
  1902. plugs = await self._get_smart_plugs(db, item.printer_id)
  1903. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1904. if auto_on_plugs:
  1905. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1906. # Power on using the plug that actually feeds the printer, and
  1907. # wait for it to boot on that one only (#2629).
  1908. primary_plug = self._pick_power_plug(auto_on_plugs)
  1909. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1910. if powered_on:
  1911. # Also turn on any remaining auto_on plugs (e.g., filter)
  1912. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1913. try:
  1914. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1915. if await service.turn_on(extra_plug):
  1916. await publish_plug_state(
  1917. extra_plug.id,
  1918. extra_plug.name,
  1919. extra_plug.printer_id,
  1920. on=True,
  1921. ha_entity_id=extra_plug.ha_entity_id,
  1922. )
  1923. logger.info(
  1924. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1925. )
  1926. except Exception as e:
  1927. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1928. printer_connected = True
  1929. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1930. else:
  1931. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1932. await hold_for_printer(
  1933. item,
  1934. item.printer_id,
  1935. "smart-plug power-on failed",
  1936. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1937. )
  1938. continue
  1939. else:
  1940. # No plug or auto_on disabled. Worded exactly as the
  1941. # model-based branch words it (#2786): this is the one
  1942. # entry on that list the user has to act on, because
  1943. # Bambuddy will never switch this printer on itself.
  1944. await hold_for_printer(
  1945. item,
  1946. item.printer_id,
  1947. "offline, with no smart plug to power it on",
  1948. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1949. )
  1950. continue
  1951. # Check if printer is idle (busy with another print)
  1952. if not printer_idle:
  1953. await hold_for_printer(
  1954. item,
  1955. item.printer_id,
  1956. "not idle",
  1957. self._pinned_hold_reason(
  1958. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1959. ),
  1960. )
  1961. continue
  1962. # Drying blocks the queue, if the user asked it to. A hold
  1963. # is a skip like any other, so it belongs here with the
  1964. # rest of the availability checks.
  1965. # A parked timer (#2896) never ends, so it must not hold the
  1966. # queue; it stays tracked so the stop paths still reach it.
  1967. if (
  1968. self._drying_in_progress.get(item.printer_id)
  1969. and not self._drying_is_only_parked(item.printer_id)
  1970. and await self._get_bool_setting(db, "queue_drying_block")
  1971. ):
  1972. # Busy-shaped on purpose: the cycle ends on its own and
  1973. # the job goes out, so there is nothing to alert about.
  1974. await hold_for_printer(
  1975. item,
  1976. item.printer_id,
  1977. "drying, and drying is set to block the queue",
  1978. f"Busy: {printer_label(item.printer_id)} (drying)",
  1979. )
  1980. continue
  1981. # Check condition (previous print success)
  1982. if item.require_previous_success:
  1983. if not await self._check_previous_success(db, item):
  1984. item.status = "skipped"
  1985. item.error_message = "Previous print failed or was aborted"
  1986. item.completed_at = datetime.now(timezone.utc)
  1987. # Not pending any more, so not waiting for anything.
  1988. item.waiting_reason = None
  1989. await db.commit()
  1990. logger.info("Skipped queue item %s - previous print failed", item.id)
  1991. # Send notification
  1992. job_name = await self._get_job_name(db, item)
  1993. printer = await self._get_printer(db, item.printer_id)
  1994. await notification_service.on_queue_job_skipped(
  1995. job_name=job_name,
  1996. printer_id=item.printer_id,
  1997. printer_name=printer.name if printer else "Unknown",
  1998. reason="Previous print failed or was aborted",
  1999. db=db,
  2000. )
  2001. continue
  2002. # Resolve the AMS mapping when it's missing OR unresolved
  2003. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  2004. # frontend status-load race can persist [-1] (#2589) — and
  2005. # must be recomputed from live trays rather than trusted.
  2006. if await _edited_since_loaded(db, item):
  2007. continue
  2008. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  2009. if unmappable:
  2010. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  2011. continue
  2012. # Filament-deficit pre-dispatch check (#1496). If the
  2013. # assigned spool can't satisfy any required slot grams,
  2014. # promote the item to manual_start so the user must
  2015. # acknowledge via the ▶ button (which re-checks live).
  2016. if await self._block_on_filament_deficit(db, item):
  2017. # Now staged for the user to start by hand, and the row
  2018. # shows the filament-short badge instead. Cleared because
  2019. # a staged item never reaches this branch again.
  2020. await hold_item(item, None)
  2021. continue
  2022. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  2023. # than let the printer pick a substitute for a slot the
  2024. # matcher could not resolve on this printer.
  2025. if await self._block_on_unmatched_filament(db, item):
  2026. continue
  2027. # Hold this item back for the next pass rather than racing
  2028. # another dispatch over the same transient library row. The
  2029. # printer is still marked busy so a later item does not jump
  2030. # its place in this printer's queue.
  2031. if _library_row_conflict(item):
  2032. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2033. await hold_for_printer(
  2034. item,
  2035. item.printer_id,
  2036. "holding its place while another item releases a library row",
  2037. f"Busy: {printer_label(item.printer_id)}",
  2038. )
  2039. continue
  2040. # Print takes priority: stop a cycle Bambuddy armed, now
  2041. # that this item is definitely going out.
  2042. #
  2043. # Placement is the whole point (#2801). This used to sit up
  2044. # with the availability checks, inside the not-idle branch
  2045. # -- so it fired only on the passes where the print was NOT
  2046. # going to start, and never on the ones where it was.
  2047. # Drying is not one of the things `_is_printer_idle` looks
  2048. # at, so a stop could never have unblocked that printer
  2049. # anyway; the cycle was spent for nothing, auto-drying
  2050. # re-armed on the next tick, and a plate left
  2051. # unacknowledged turned that into a loop on the scheduler
  2052. # interval. Every skip between there and here -- a failed
  2053. # previous print, an unmappable item, a filament deficit, a
  2054. # contested library row -- is another way to lose a cycle
  2055. # for a print that never happens, which is why this waits
  2056. # until the decision is actually made.
  2057. if self._drying_in_progress.get(
  2058. item.printer_id
  2059. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2060. await self._stop_drying(item.printer_id)
  2061. # Queue the dispatch instead of running it here — see
  2062. # _dispatch_selected(). busy_printers still gets the printer
  2063. # immediately, so nothing else in this pass can target it.
  2064. #
  2065. # The reason goes first: this item is not waiting for anything
  2066. # any more, and the model-based branch clears its own at the
  2067. # equivalent moment (#3074).
  2068. await hold_item(item, None)
  2069. _claim_library_row(item)
  2070. dispatch_ids.append(item.id)
  2071. claim_printer(item.printer_id)
  2072. # SJF starvation guard: mark items that were jumped
  2073. if sjf_enabled and item.print_time_seconds is not None:
  2074. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2075. for other in items:
  2076. if (
  2077. other.id != item.id
  2078. and other.id not in dispatch_ids
  2079. and other.status == "pending"
  2080. and _could_take_printer(other, item.printer_id, pinned_model)
  2081. and not other.been_jumped
  2082. and other.position < item.position
  2083. and (
  2084. other.print_time_seconds is None
  2085. or other.print_time_seconds > item.print_time_seconds
  2086. )
  2087. ):
  2088. other.been_jumped = True
  2089. await db.commit()
  2090. elif item.target_model or item.variants:
  2091. # Model-based assignment - find any idle printer of matching model.
  2092. # A plain model-based item has exactly one candidate, built from
  2093. # its own columns. A cross-model item (#671) has one per sliced
  2094. # variant and takes the first that matches, walking them in the
  2095. # user's priority order so the pick is reproducible when more
  2096. # than one printer is free in the same pass.
  2097. candidates = _candidates_for(item)
  2098. item_scope = await _creator_scope(item.created_by_id)
  2099. printer_id = None
  2100. chosen: _ModelCandidate | None = None
  2101. per_model_reasons: list[tuple[str | None, str]] = []
  2102. # Candidates that cleared the cross-model gate below. The
  2103. # smart-plug wake step may only consider these — waking a
  2104. # printer for a file that can never legally run on it is
  2105. # worse than not waking at all (#2786).
  2106. wakeable_candidates: list[_ModelCandidate] = []
  2107. # Printers passed over because their last print failed.
  2108. gate_blocked: set[int] = set()
  2109. if not candidates:
  2110. # Every candidate file has been deleted or trashed out from
  2111. # under this item. Hold it with something the user can act
  2112. # on rather than letting it look dispatchable forever.
  2113. per_model_reasons.append(
  2114. (
  2115. item.target_model,
  2116. "Every file for this job has been deleted — add a file back or remove the item",
  2117. )
  2118. )
  2119. for candidate in candidates:
  2120. effective_types, filament_overrides = _filament_constraints(candidate)
  2121. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2122. # for an incompatible model to a printer, no matter how the
  2123. # row got into the DB (old rows, direct API writes). Held
  2124. # as pending with an actionable waiting_reason — the user
  2125. # fixes it by editing the item's target model.
  2126. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2127. per_model_reasons.append(
  2128. (
  2129. candidate.target_model,
  2130. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2131. f"{candidate.target_model} — edit the item and fix its target model",
  2132. )
  2133. )
  2134. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2135. continue
  2136. wakeable_candidates.append(candidate)
  2137. async def is_short(
  2138. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2139. ) -> bool:
  2140. # The check reads the file and plate off the item,
  2141. # so it must hold this candidate's. Resolving is
  2142. # safe to repeat, and the winner is resolved again
  2143. # below.
  2144. self._resolve_variant(item, candidate)
  2145. return await self._filament_short_on(db, item, pid)
  2146. async def unmatched_on(
  2147. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2148. ) -> list[str]:
  2149. self._resolve_variant(item, candidate)
  2150. return await self._unmatched_on(db, item, pid)
  2151. while True:
  2152. match_id, match_reason = await self._find_idle_printer_for_model(
  2153. db,
  2154. candidate.target_model,
  2155. # Sensor-held printers are unavailable to the
  2156. # matcher but stay out of busy_printers itself
  2157. # (#1148) — see where `interlocked` is built.
  2158. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2159. effective_types,
  2160. item.target_location,
  2161. filament_overrides=filament_overrides,
  2162. require_plate_clear=require_plate_clear,
  2163. wakeable_ids=wakeable_printer_ids,
  2164. printer_scope=item_scope,
  2165. is_short=is_short,
  2166. drying_ids=drying_held,
  2167. unmatched_on=unmatched_on,
  2168. refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
  2169. )
  2170. # "Only if the previous print succeeded" is about the
  2171. # printer the job lands on: one whose last print failed
  2172. # is passed over for another of the model.
  2173. if (
  2174. match_id
  2175. and item.require_previous_success
  2176. and not await self._check_previous_success(db, item, printer_id=match_id)
  2177. ):
  2178. gate_blocked.add(match_id)
  2179. continue
  2180. break
  2181. if match_id:
  2182. printer_id = match_id
  2183. chosen = candidate
  2184. break
  2185. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2186. # Nothing is available and nothing has been woken this pass:
  2187. # switch one matching printer on. Assignment is left to the
  2188. # next pass, which sees the booted printer's live state
  2189. # instead of guessing at it seconds after connect (#2786).
  2190. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2191. woken_id, attempted_id = await self._wake_printer_for_model(
  2192. db,
  2193. wakeable_candidates,
  2194. item.target_location,
  2195. busy_printers | interlocked.keys(),
  2196. wakeable_printer_ids,
  2197. require_plate_clear,
  2198. printer_scope=item_scope,
  2199. )
  2200. # An attempt spends the pass's one wake whether or not
  2201. # it worked: it has already blocked the queue loop for
  2202. # the boot wait. A failed printer is held out of later
  2203. # passes by its own cool-off, deliberately NOT by
  2204. # busy_printers — it is off, not busy, and labelling it
  2205. # busy would both misdescribe it in every later item's
  2206. # waiting reason and suppress the notification, since
  2207. # an all-busy reason is treated as needing no action.
  2208. power_on_attempted = attempted_id is not None
  2209. if woken_id is not None:
  2210. # Hold this item back rather than dispatching onto a
  2211. # printer whose AMS has not reported yet.
  2212. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2213. continue
  2214. if printer_id is None and gate_blocked:
  2215. # The matcher reports the printers passed over as busy;
  2216. # what holds the job is their failed last print.
  2217. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2218. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2219. # Fold the winning variant's file and settings onto the item
  2220. # before anything else looks at them — the guards below and
  2221. # every step of the dispatch read the item's own columns.
  2222. if chosen is not None:
  2223. self._resolve_variant(item, chosen)
  2224. # Update waiting_reason if changed and send notification when first waiting
  2225. if item.waiting_reason != waiting_reason:
  2226. was_waiting = item.waiting_reason is not None
  2227. previous_reason = item.waiting_reason
  2228. item.waiting_reason = waiting_reason
  2229. await db.commit()
  2230. # Send waiting notification only when transitioning to waiting state
  2231. # and the reason requires user action (not just "all printers busy")
  2232. # Also when a job that only waited for a busy printer
  2233. # now waits on something the user has to do.
  2234. if (
  2235. waiting_reason
  2236. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2237. and not _asks_nothing_new(waiting_reason)
  2238. ):
  2239. job_name = await self._get_job_name(db, item)
  2240. await notification_service.on_queue_job_waiting(
  2241. job_name=job_name,
  2242. target_model=_candidate_model_label(candidates) or item.target_model,
  2243. waiting_reason=waiting_reason,
  2244. db=db,
  2245. )
  2246. if printer_id:
  2247. # Before claiming the printer: hold back rather than race
  2248. # another dispatch over the same transient library row.
  2249. # Checked here so a held item does not get a printer
  2250. # assigned and then sit on it. See _library_row_conflict().
  2251. #
  2252. # No busy_printers.add() here, unlike the fixed-printer
  2253. # branch above: that one protects its printer's own queue
  2254. # ordering, but this item was never assigned to `printer_id`
  2255. # — the matcher merely offered it. Marking it busy would
  2256. # strand an idle printer for the rest of the pass.
  2257. if _library_row_conflict(item):
  2258. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2259. continue
  2260. if await _edited_since_loaded(db, item):
  2261. continue
  2262. # Assign printer and start - clear waiting reason
  2263. item.printer_id = printer_id
  2264. item.waiting_reason = None
  2265. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2266. # Send assignment notification
  2267. job_name = await self._get_job_name(db, item)
  2268. printer = await self._get_printer(db, printer_id)
  2269. await notification_service.on_queue_job_assigned(
  2270. job_name=job_name,
  2271. printer_id=printer_id,
  2272. printer_name=printer.name if printer else "Unknown",
  2273. target_model=item.target_model,
  2274. db=db,
  2275. )
  2276. # A mapping on this item was not made for the printer just
  2277. # picked: it came with a job moved here from a fixed
  2278. # printer, or from a variant. Its tray IDs can name a
  2279. # tray of the right type in another colour here, which
  2280. # the fit check lets through (#3239). Match afresh, by
  2281. # type and colour.
  2282. if item.ams_mapping:
  2283. logger.info(
  2284. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2285. item.id,
  2286. item.ams_mapping,
  2287. printer_id,
  2288. )
  2289. item.ams_mapping = None
  2290. # On a nozzle-rack printer its own nozzle mapping likewise
  2291. # (set through the API or an order's plate spec): it names
  2292. # rack positions, and the dispatch sends a stored one as-is
  2293. # instead of resolving this printer's rack. Elsewhere it
  2294. # holds extruder indices, the same on every printer of the
  2295. # model (an H2D VP keeps the slicer's for that reason), and
  2296. # one that came with the chosen variant belongs to that
  2297. # variant's file: both stay.
  2298. if (
  2299. (chosen is None or chosen.variant is None)
  2300. and printer is not None
  2301. and is_nozzle_rack_model(printer.model)
  2302. ):
  2303. item.nozzle_mapping = None
  2304. # Resolve the AMS mapping for the assigned printer. It is
  2305. # always missing here, so this computes it, and it also
  2306. # self-heals a bogus stored [-1] (#2589).
  2307. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2308. if unmappable:
  2309. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2310. continue
  2311. # Filament-deficit pre-dispatch check (#1496).
  2312. if await self._block_on_filament_deficit(db, item):
  2313. continue
  2314. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2315. # selection already filters on filament type, so this is a
  2316. # backstop for an AMS that changed between assignment and
  2317. # dispatch, and for a type loaded on the wrong nozzle.
  2318. # The assignment made above is released with the hold —
  2319. # this item asked for a model, not this printer.
  2320. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2321. continue
  2322. # As for a pinned job: drying stops once the print is
  2323. # decided, unless it may run through it.
  2324. if self._drying_in_progress.get(
  2325. printer_id
  2326. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2327. await self._stop_drying(printer_id)
  2328. _claim_library_row(item)
  2329. dispatch_ids.append(item.id)
  2330. claim_printer(printer_id)
  2331. # SJF starvation guard: mark items that were jumped
  2332. if sjf_enabled and item.print_time_seconds is not None:
  2333. for other in items:
  2334. if (
  2335. other.id != item.id
  2336. and other.id not in dispatch_ids
  2337. and other.status == "pending"
  2338. and _could_take_printer(other, printer_id, item.target_model)
  2339. and not other.been_jumped
  2340. and other.position < item.position
  2341. and (
  2342. other.print_time_seconds is None
  2343. or other.print_time_seconds > item.print_time_seconds
  2344. )
  2345. ):
  2346. other.been_jumped = True
  2347. await db.commit()
  2348. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2349. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2350. # skip summary that only lands after the transfers have finished is
  2351. # useless for working out why an item did not go out.
  2352. if skip_reasons:
  2353. logger.info("Queue skip summary: %s", skip_reasons)
  2354. for pid in sorted(busy_printers):
  2355. reason = busy_reasons.get(pid, "no reason recorded")
  2356. if pid in claimed_printers:
  2357. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2358. continue
  2359. # The three live fields stay, because they are what someone
  2360. # reading a bundle wants next -- but they are labelled as read
  2361. # now, not as the state the decision was made on, which is what
  2362. # made the old line contradict itself.
  2363. state = printer_manager.get_status(pid)
  2364. logger.info(
  2365. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2366. pid,
  2367. reason,
  2368. printer_manager.is_connected(pid),
  2369. state.state if state else "NO_STATUS",
  2370. printer_manager.is_awaiting_plate_clear(pid),
  2371. )
  2372. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2373. # selection and `_launch_uploads`, so anything raising here would
  2374. # discard this tick's selections — computed AMS mappings and all —
  2375. # and, on a persistent fault, stop the queue dispatching entirely.
  2376. # Same reasoning as the deficit check's guard below: never let an
  2377. # auxiliary check wedge the queue. The bed simply stays wherever it
  2378. # was, and the next tick tries again.
  2379. try:
  2380. await self._apply_keep_warm(
  2381. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2382. )
  2383. except Exception as e:
  2384. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2385. # Read the concurrency limit BEFORE the commit below, not inside
  2386. # _dispatch_selected(). A SELECT on this session after the commit
  2387. # implicitly opens a fresh transaction that nothing then closes, and
  2388. # it would stay open for the whole dispatch — minutes of "idle in
  2389. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2390. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2391. # checkpointed while every dispatch is writing to it.
  2392. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2393. # Selection is done; every decision above is recorded on `db`
  2394. # (model-based printer assignment, computed ams_mapping). Flush it
  2395. # before the dispatch tasks open their own sessions, or they will
  2396. # read a row that still says printer_id=None. This also releases the
  2397. # connection back to the pool for the duration of the dispatch.
  2398. await db.commit()
  2399. if dispatch_ids:
  2400. item_printers = {it.id: it.printer_id for it in items}
  2401. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2402. # Auto-drying: start drying on idle printers that have no pending queue items
  2403. await self._check_auto_drying(db, items, dispatching_printers)
  2404. # Low filament: alert on assigned spools that have crossed their
  2405. # low-stock threshold (#2913). Runs on both paths out of this method
  2406. # for the same reason auto-drying does — an empty queue does not mean
  2407. # the spools in the printers stopped mattering.
  2408. await self._check_filament_low(db)
  2409. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2410. # is about to run out before a replenishment could arrive (#2955).
  2411. await self._check_stock_forecast(db)
  2412. # Keep the loop on the fast interval while any upload is in flight so
  2413. # a slot freed mid-tick refills within seconds rather than after the
  2414. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2415. # deferred because the pool was full) also counts as productive.
  2416. return bool(dispatch_ids) or bool(self._inflight)
  2417. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2418. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2419. Dispatch used to happen inline in the selection loop: ``await
  2420. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2421. performs the FTP upload, that serialized every printer behind every
  2422. other printer's transfer even though the printers are independent
  2423. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2424. gather was awaited before ``check_queue`` returned, so the run loop
  2425. stayed blocked until the *slowest* upload in the batch finished — a
  2426. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2427. 93-printer farm even as other printers came free (#2602).
  2428. Each upload now runs as an independent background task tracked in
  2429. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2430. `pending` until their upload completes) and their printers from the
  2431. next pass's selection, and this method launches at most
  2432. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2433. the next fast tick instead of waiting out the whole batch. The bound
  2434. exists because the printers are independent but the host is not: each
  2435. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2436. file handle.
  2437. The no-overlapping-dispatch invariant the batch-await used to provide
  2438. is now carried by the in-flight exclusion in check_queue. Everything
  2439. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2440. per-printer hold, and each item's independent failure handling — still
  2441. lives in ``_start_print`` and runs per task exactly as before.
  2442. Synchronous on purpose: it registers every launched task into
  2443. ``self._inflight`` before returning, so the next (sequential) tick sees
  2444. an accurate in-flight count with no interleaving await.
  2445. """
  2446. free = limit - len(self._inflight)
  2447. if free <= 0:
  2448. logger.info(
  2449. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2450. len(self._inflight),
  2451. limit,
  2452. len(item_ids),
  2453. item_ids,
  2454. )
  2455. return
  2456. to_launch = item_ids[:free]
  2457. deferred = item_ids[free:]
  2458. logger.info(
  2459. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2460. len(to_launch),
  2461. len(self._inflight),
  2462. limit,
  2463. f" — deferring {deferred} to a later tick" if deferred else "",
  2464. )
  2465. for item_id in to_launch:
  2466. task = spawn_background_task(
  2467. self._dispatch_one(item_id, item_printers.get(item_id)),
  2468. name=f"queue-upload-{item_id}",
  2469. )
  2470. self._inflight[item_id] = (task, item_printers.get(item_id))
  2471. # Prune on completion so the freed slot is refillable next tick.
  2472. # spawn_background_task already logs any uncaught exception; this
  2473. # only reclaims the pool slot (fires on success, failure, or cancel).
  2474. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2475. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2476. """Upload + start one queue item in its own session (pool worker, #2602).
  2477. Its own session: pool workers run concurrently and an AsyncSession is
  2478. not safe to share across tasks; it also keeps a slow upload from pinning
  2479. the scheduler's session (and, on SQLite, its transaction) open for the
  2480. transfer's duration.
  2481. ``selected_printer_id`` is the printer this item was selected for, taken
  2482. from the same snapshot the caller used. It exists so the preheat pin can
  2483. be unwound on the paths that never reach the ``finally`` below — see the
  2484. claim failure a few lines down. Optional so the direct-call tests keep
  2485. working; when it is absent those paths simply behave as they did before.
  2486. """
  2487. async with async_session() as item_db:
  2488. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2489. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2490. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2491. # routes reject reassignment (409), so printer_id can't change out from
  2492. # under the in-flight upload and split the queue row from the
  2493. # archive/expected-print/physical command.
  2494. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2495. logger.info(
  2496. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2497. item_id,
  2498. )
  2499. # This return is outside the try/finally below, so the rollback
  2500. # has to happen here. Selecting this item already handed any
  2501. # keep-warm hold on its printer over to the preheat pin
  2502. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2503. # unwind it. Bailing without doing so leaves the bed hot with
  2504. # nothing tracking it: the keep-warm entry is gone, so the
  2505. # max-duration cap no longer applies, and if this was the
  2506. # printer's last pending item nothing else will ever turn it
  2507. # off. Reachable whenever a cancel or delete lands between
  2508. # selection and the claim.
  2509. if selected_printer_id is not None:
  2510. self._rollback_preheat_pin(item_id, selected_printer_id)
  2511. return
  2512. # Seeded from the caller's snapshot so the `item vanished` return
  2513. # below still unwinds the pin; overwritten with the row's own
  2514. # printer_id as soon as we have it.
  2515. item_printer_id: int | None = selected_printer_id
  2516. try:
  2517. item = await item_db.get(PrintQueueItem, item_id)
  2518. if not item:
  2519. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2520. return
  2521. item_printer_id = item.printer_id
  2522. await self._start_print(item_db, item)
  2523. finally:
  2524. # Undo an expected-print registration whose print command never
  2525. # went out. One choke point covers every way `_start_print` can
  2526. # end without sending: a raised exception (a DB failure mid-
  2527. # dispatch is the reported case), an early return, a cancel
  2528. # winning the #1853 CAS, or `start_print()` returning False.
  2529. # A confirmed send removes the entry itself, so this is a no-op
  2530. # on the happy path.
  2531. self._rollback_unconfirmed_expected_print(item_id)
  2532. # Likewise the print user it set: the printer's next print is
  2533. # not this item's.
  2534. self._rollback_unconfirmed_print_user(item_id)
  2535. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2536. # reservation survives only after start_print() accepted the
  2537. # command. Failure, cancellation, deferral, and exceptions all
  2538. # release it here.
  2539. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2540. # Unwind preheat state (bed/chamber/airduct) if the
  2541. # dispatch aborted before the print's own gcode took over.
  2542. # `_start_print` clears the pin on successful `start_print()`;
  2543. # anything still present here is by definition an aborted
  2544. # dispatch and gets rolled back so the printer isn't left
  2545. # heating for a job that isn't happening.
  2546. if item_printer_id is not None:
  2547. self._rollback_preheat_pin(item_id, item_printer_id)
  2548. # The cancellation flag only has meaning while this dispatch is
  2549. # running; drop it so the set cannot grow without bound and a
  2550. # re-queued item never inherits a stale cancellation.
  2551. self._cancelled_dispatches.discard(item_id)
  2552. # Release the claim on every exit. Once dispatch has finished the
  2553. # row's status carries the lock (printing/failed/cancelled are all
  2554. # != pending), so the token is only needed for the duration of the
  2555. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2556. # dispatchable again on the next tick.
  2557. await self._clear_dispatch_claim(item_db, item_id)
  2558. async def _requeue_after_upload_refused(
  2559. self,
  2560. db: AsyncSession,
  2561. item: PrintQueueItem,
  2562. printer: Printer,
  2563. error_msg: str,
  2564. toast_uid: int | None,
  2565. kind: FtpFailureKind,
  2566. ) -> None:
  2567. """Put an item back in the queue after its file never reached the printer (#3210).
  2568. The printer goes into `_upload_backoff`, which keeps every item away
  2569. from it until the window ends. The window grows with each refusal in a
  2570. row; see ``_upload_backoff_seconds``.
  2571. An item pinned to this printer keeps it, waits there, and is the one
  2572. that knocks again. An item for "Any <model>" goes back to the pool
  2573. instead, so another printer of the model can take it (#3409). Only the
  2574. assignment goes: the next model assignment drops whatever on the row
  2575. was worked out for one printer, as it does for every model job.
  2576. The first refusal in a run sends the one "Job waiting" notification,
  2577. and a later one only if it asks for something else (a card after a
  2578. dropped connection). It cannot wait for the hold the way it used to: a
  2579. released item is not held on this printer, so nothing would say why
  2580. it stopped. A job cancelled or moved during the upload sends none.
  2581. `dispatch_attempts` is not charged: that budget bounds a printer that
  2582. takes the file and then never starts, which this is not.
  2583. """
  2584. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2585. self._upload_refusals[printer.id] = refusals
  2586. self._upload_refusal_kind[printer.id] = kind
  2587. backoff = _upload_backoff_seconds(refusals)
  2588. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2589. released = False
  2590. if item.target_model:
  2591. # Only while it is still pending on this printer: a cancel, or a
  2592. # move the user made during the upload, stands.
  2593. result = cast(
  2594. CursorResult,
  2595. await db.execute(
  2596. update(PrintQueueItem)
  2597. .where(PrintQueueItem.id == item.id)
  2598. .where(PrintQueueItem.status == "pending")
  2599. .where(PrintQueueItem.printer_id == printer.id)
  2600. .values(printer_id=None, error_message=None)
  2601. .execution_options(synchronize_session=False)
  2602. ),
  2603. )
  2604. await db.commit()
  2605. released = result.rowcount > 0
  2606. elif item.error_message:
  2607. # The row is still `pending` -- it only moves to `printing` after a
  2608. # successful upload -- so there is no status to write back. Writing
  2609. # one anyway would undo a cancel that landed during the upload.
  2610. item.error_message = None
  2611. await db.commit()
  2612. logger.warning(
  2613. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue%s; "
  2614. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2615. item.id,
  2616. printer.id,
  2617. printer.name,
  2618. error_msg,
  2619. " and returned to the pool" if released else "",
  2620. refusals,
  2621. backoff,
  2622. )
  2623. reason = _refused_upload_hold_reason(printer.name or f"printer {printer.id}", kind)
  2624. if self._upload_refusal_notified.get(printer.id) != reason and await self._still_waiting_on(
  2625. db, item.id, None if released else printer.id
  2626. ):
  2627. self._upload_refusal_notified[printer.id] = reason
  2628. try:
  2629. await notification_service.on_queue_job_waiting(
  2630. job_name=await self._get_job_name(db, item),
  2631. target_model=item.target_model or printer.model or "",
  2632. waiting_reason=reason,
  2633. db=db,
  2634. printer_id=printer.id,
  2635. )
  2636. except Exception as e:
  2637. # The job is safe in the queue either way.
  2638. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  2639. try:
  2640. # Closes the dispatch toast for this attempt. Without it the toast
  2641. # keeps spinning on an upload that has ended.
  2642. await ws_manager.send_queue_item_failed(
  2643. user_id=toast_uid,
  2644. queue_item_id=item.id,
  2645. printer_id=printer.id,
  2646. reason="upload_failed",
  2647. )
  2648. except Exception:
  2649. pass # toast is best-effort
  2650. @staticmethod
  2651. async def _still_waiting_on(db: AsyncSession, item_id: int, printer_id: int | None) -> bool:
  2652. """Whether the item is still pending, on *printer_id* (None: unassigned)."""
  2653. row = (
  2654. await db.execute(
  2655. select(PrintQueueItem.status, PrintQueueItem.printer_id).where(PrintQueueItem.id == item_id)
  2656. )
  2657. ).one_or_none()
  2658. return row is not None and row.status == "pending" and row.printer_id == printer_id
  2659. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2660. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2661. if printer_id is not None:
  2662. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2663. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2664. """Withdraw the expected print and print user of a sent print that never started.
  2665. Both tell the rest of Bambuddy that the printer's next print is this
  2666. item's: left behind, a print started by hand later is taken for it.
  2667. With ``unless_printing``, a printer that is printing after all keeps
  2668. them, as that print is most likely this one starting late.
  2669. ``keep_expected`` withdraws only the print user, which vouches for any
  2670. print on the printer. The expected print names this item's file, so a
  2671. late start of it is still matched to its archive.
  2672. """
  2673. sent = self._sent_unstarted_print.get(item_id)
  2674. if sent is None:
  2675. return
  2676. printer_id, remote_filename, archive_id = sent
  2677. if unless_printing:
  2678. status = printer_manager.get_status(printer_id)
  2679. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2680. return
  2681. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2682. if keep_expected:
  2683. return
  2684. del self._sent_unstarted_print[item_id]
  2685. if remote_filename is not None and archive_id is not None:
  2686. try:
  2687. from backend.app.main import unregister_expected_print
  2688. unregister_expected_print(printer_id, remote_filename, archive_id)
  2689. except Exception:
  2690. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2691. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2692. """Drop an expectation for a print command that was never sent.
  2693. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2694. where the interesting exception is usually the one already propagating.
  2695. """
  2696. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2697. if pending is None:
  2698. return
  2699. printer_id, remote_filename, archive_id = pending
  2700. try:
  2701. from backend.app.main import unregister_expected_print
  2702. unregister_expected_print(printer_id, remote_filename, archive_id)
  2703. except Exception:
  2704. logger.warning(
  2705. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2706. item_id,
  2707. printer_id,
  2708. remote_filename,
  2709. archive_id,
  2710. exc_info=True,
  2711. )
  2712. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2713. """Release a queue reservation without touching the dispatch session."""
  2714. if item_id not in self._unconfirmed_budget_reservations:
  2715. return
  2716. for attempt in range(1, 4):
  2717. async with async_session() as cleanup_db:
  2718. try:
  2719. await release_budget_reservation(
  2720. cleanup_db,
  2721. source_type="print_queue",
  2722. source_id=item_id,
  2723. status="released",
  2724. )
  2725. await cleanup_db.commit()
  2726. self._unconfirmed_budget_reservations.discard(item_id)
  2727. return
  2728. except Exception as exc:
  2729. try:
  2730. await cleanup_db.rollback()
  2731. except Exception:
  2732. pass
  2733. if attempt == 3:
  2734. logger.error(
  2735. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2736. item_id,
  2737. attempt,
  2738. exc,
  2739. )
  2740. return
  2741. await asyncio.sleep(0.5 * attempt)
  2742. @staticmethod
  2743. def _reported_bed_target(printer_id: int) -> int | None:
  2744. """The bed target firmware currently reports, or None if it can't be read.
  2745. None means "no evidence", not "zero" — callers must not treat it as a
  2746. temperature. Deliberately total: this feeds cleanup paths that run in a
  2747. ``finally``, where a malformed status must not become the exception the
  2748. caller sees.
  2749. """
  2750. try:
  2751. state = printer_manager.get_status(printer_id)
  2752. if state is None:
  2753. return None
  2754. temps = state.temperatures
  2755. if not isinstance(temps, dict):
  2756. return None
  2757. return int(float(temps.get("bed_target", 0) or 0))
  2758. except (TypeError, ValueError, AttributeError):
  2759. return None
  2760. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2761. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2762. Turns the bed heater off, the chamber heater off, and opens the
  2763. airduct flap back to cooling — for whichever of those preheat
  2764. actually applied. `_start_print` clears the pin on successful
  2765. `start_print()`; anything still present when `_dispatch_one` exits
  2766. is by definition an aborted dispatch and gets rolled back here.
  2767. The bed is the one action that can be declined: if firmware has since
  2768. been given a target other than the one we pinned, it belongs to someone
  2769. else and is left alone. See the comment at that branch.
  2770. Also called directly from `_dispatch_one`'s claim-failure return, which
  2771. never reaches the ``finally``.
  2772. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2773. """
  2774. pin = self._preheat_pin.pop(printer_id, set())
  2775. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2776. if not pin:
  2777. return
  2778. client = printer_manager.get_client(printer_id)
  2779. if client is None:
  2780. logger.info(
  2781. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2782. item_id,
  2783. printer_id,
  2784. )
  2785. return
  2786. if "bed" in pin:
  2787. # Only undo our own target. If firmware reports something else, the
  2788. # user or another writer owns the bed now and zeroing it would
  2789. # clobber their choice -- the same guard `_release_keep_warm`
  2790. # applies to a keep-warm hold.
  2791. #
  2792. # Every uncertain case switches the bed off rather than leaving it:
  2793. # no recorded target (a pin written before this bookkeeping, or a
  2794. # setter that raised after pinning) and an unreadable status both
  2795. # fall through. A bed left hot with no owner is the worse failure,
  2796. # and this runs in a `finally` where raising would mask the real
  2797. # exception.
  2798. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2799. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2800. logger.info(
  2801. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2802. item_id,
  2803. printer_id,
  2804. cur_bed_target,
  2805. pinned_bed,
  2806. )
  2807. else:
  2808. try:
  2809. client.set_bed_temperature(0)
  2810. except Exception as exc:
  2811. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2812. if "chamber" in pin:
  2813. try:
  2814. client.set_chamber_temperature(0)
  2815. except Exception as exc:
  2816. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2817. if "airduct" in pin:
  2818. try:
  2819. client.set_airduct_mode("cooling")
  2820. except Exception as exc:
  2821. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2822. logger.info(
  2823. "Dispatch item %s (printer %d): preheat rollback → %s",
  2824. item_id,
  2825. printer_id,
  2826. sorted(pin),
  2827. )
  2828. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2829. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2830. Returns True if this call won the claim, False if the row was already
  2831. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2832. the load-bearing guard against reassign-during-dispatch (#2615).
  2833. ``printer_id`` is the printer the item was selected for: a row moved to
  2834. another printer since is not claimed, and the next pass selects it for
  2835. that one."""
  2836. query = (
  2837. update(PrintQueueItem)
  2838. .where(PrintQueueItem.id == item_id)
  2839. .where(PrintQueueItem.status == "pending")
  2840. .where(PrintQueueItem.dispatching_at.is_(None))
  2841. )
  2842. if printer_id is not None:
  2843. query = query.where(PrintQueueItem.printer_id == printer_id)
  2844. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2845. await db.commit()
  2846. return res.rowcount > 0
  2847. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2848. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2849. mask the dispatch outcome.
  2850. Retried, because the failure mode in practice is transient and narrow: a
  2851. database that is momentarily unreachable — PostgreSQL out of connection
  2852. slots is the observed case — refuses this write for a second or two while
  2853. the dispatch that just ended is still holding the row out of the selection
  2854. query. One attempt was enough to wedge the item; a couple of spaced
  2855. attempts clear it. Each attempt rolls back first, since a failed write
  2856. leaves the session needing it before it can be reused.
  2857. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2858. on the next quiet tick.
  2859. """
  2860. for attempt in range(1, 4):
  2861. try:
  2862. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2863. await db.commit()
  2864. return
  2865. except Exception as exc:
  2866. try:
  2867. await db.rollback()
  2868. except Exception:
  2869. pass
  2870. if attempt == 3:
  2871. logger.warning(
  2872. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2873. "— a later quiet tick will release it",
  2874. item_id,
  2875. attempt,
  2876. exc,
  2877. )
  2878. return
  2879. await asyncio.sleep(0.5 * attempt)
  2880. async def _printers_for_model(
  2881. self,
  2882. db: AsyncSession,
  2883. model: str,
  2884. target_location: str | None = None,
  2885. printer_scope: PrinterScope = ALL_PRINTERS,
  2886. ) -> list[Printer]:
  2887. """Active printers of *model*, optionally narrowed to one location.
  2888. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2889. answer "which printers can this job run on" from one query — a job can
  2890. only be woken onto a printer the matcher would also have considered.
  2891. ``printer_scope`` is the job creator's (#1727).
  2892. """
  2893. normalized_model = normalize_printer_model(model) or model
  2894. query = (
  2895. select(Printer)
  2896. .where(func.lower(Printer.model) == normalized_model.lower())
  2897. .where(Printer.is_active == True) # noqa: E712
  2898. )
  2899. if target_location:
  2900. query = query.where(Printer.location == target_location)
  2901. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2902. query = query.where(clause)
  2903. result = await db.execute(query)
  2904. return list(result.scalars().all())
  2905. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2906. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2907. Read once per queue check rather than per printer: it decides both
  2908. whether the wake step has anything to do and how an offline printer is
  2909. worded in the waiting reason — "Offline" and "offline with no Auto On
  2910. plug" are different problems, and the second is the one the user has to
  2911. fix themselves (#2786).
  2912. """
  2913. result = await db.execute(
  2914. select(SmartPlug.printer_id)
  2915. .where(SmartPlug.printer_id.is_not(None))
  2916. .where(SmartPlug.enabled == True) # noqa: E712
  2917. .where(SmartPlug.auto_on == True) # noqa: E712
  2918. )
  2919. return {pid for (pid,) in result.all() if pid is not None}
  2920. def _wake_recently_failed(self, printer_id: int) -> bool:
  2921. """True while this printer's failed power-on is still cooling off (#2786)."""
  2922. deadline = self._wake_failures.get(printer_id)
  2923. if deadline is None:
  2924. return False
  2925. if time.monotonic() >= deadline:
  2926. del self._wake_failures[printer_id]
  2927. return False
  2928. return True
  2929. async def _wake_printer_for_model(
  2930. self,
  2931. db: AsyncSession,
  2932. candidates: list[_ModelCandidate],
  2933. target_location: str | None,
  2934. exclude_ids: set[int],
  2935. wakeable_ids: set[int],
  2936. require_plate_clear: bool,
  2937. printer_scope: PrinterScope = ALL_PRINTERS,
  2938. ) -> tuple[int | None, int | None]:
  2939. """Power on one offline printer a model-based item could run on (#2786).
  2940. The fixed-printer branch has powered a printer on since smart plugs
  2941. existed. The model-based branch never could: its matcher drops an
  2942. offline printer into the "Offline:" waiting reason and nothing looks at
  2943. its plugs, so a class-targeted job with every matching printer switched
  2944. off sat pending forever. The reporter's log is the controlled
  2945. experiment — the same item, same plug, same Auto On setting, dispatched
  2946. the moment they edited it onto a specific printer.
  2947. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2948. power-on was actually tried, so the caller can tell "nothing here was
  2949. wakeable" (both None — cheap, other items may still find something)
  2950. from "we tried and it did not come up" (only ``attempted_id`` — the
  2951. boot timeout has already been spent).
  2952. A printer whose last known trays cannot satisfy the job is passed over
  2953. rather than woken (#2876): the colours are readable while it is off, so
  2954. switching a farm on one machine at a time to discover them wakes
  2955. printers that could never have taken the job.
  2956. Deliberately does NOT go on to match the job once a printer is up: AMS
  2957. trays arrive with the first status push after connect, so a filament
  2958. check against a printer that booted seconds ago can reject the printer
  2959. we just woke. The next queue pass matches it with live state.
  2960. At most one printer per pass. Each wake blocks the queue loop for the
  2961. boot wait, and a queue of ten class-targeted jobs must not switch on
  2962. ten printers inside one check.
  2963. """
  2964. for candidate in candidates:
  2965. if not candidate.target_model:
  2966. continue
  2967. required_types, filament_overrides = _filament_constraints(candidate)
  2968. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2969. for printer in sorted(printers, key=lambda p: p.id):
  2970. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2971. continue
  2972. if printer_manager.is_connected(printer.id):
  2973. continue
  2974. if self._wake_recently_failed(printer.id):
  2975. # Its plug did not bring it back a moment ago. Move on to a
  2976. # sibling instead of spending this pass — and every pass —
  2977. # on the same printer.
  2978. continue
  2979. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2980. # Waking this one buys nothing: it would boot into IDLE and
  2981. # then be held by the plate-clear gate, which is exactly
  2982. # what the reporter's log shows happening for 80 minutes
  2983. # after a fixed-printer wake. The flag is Bambuddy-side and
  2984. # persisted, so it is readable while the printer is off.
  2985. logger.info(
  2986. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2987. printer.id,
  2988. candidate.target_model,
  2989. )
  2990. continue
  2991. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2992. if shortfall:
  2993. logger.info(
  2994. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2995. printer.id,
  2996. candidate.target_model,
  2997. ", ".join(shortfall),
  2998. )
  2999. continue
  3000. plugs = await self._get_smart_plugs(db, printer.id)
  3001. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  3002. if not auto_on_plugs:
  3003. # wakeable_ids said otherwise — the plug changed under us
  3004. # mid-pass. Nothing to do but move on.
  3005. continue
  3006. logger.info(
  3007. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  3008. candidate.target_model,
  3009. printer.id,
  3010. )
  3011. primary_plug = self._pick_power_plug(auto_on_plugs)
  3012. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  3013. logger.warning(
  3014. "Could not power on printer %s via smart plug; not trying it again for %ss",
  3015. printer.id,
  3016. self._wake_failure_cooloff,
  3017. )
  3018. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  3019. return None, printer.id
  3020. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  3021. try:
  3022. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  3023. if await service.turn_on(extra_plug):
  3024. await publish_plug_state(
  3025. extra_plug.id,
  3026. extra_plug.name,
  3027. extra_plug.printer_id,
  3028. on=True,
  3029. ha_entity_id=extra_plug.ha_entity_id,
  3030. )
  3031. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  3032. except Exception as e:
  3033. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  3034. return printer.id, printer.id
  3035. return None, None
  3036. async def _find_idle_printer_for_model(
  3037. self,
  3038. db: AsyncSession,
  3039. model: str,
  3040. exclude_ids: set[int],
  3041. required_filament_types: list[str] | None = None,
  3042. target_location: str | None = None,
  3043. filament_overrides: list[dict] | None = None,
  3044. require_plate_clear: bool = True,
  3045. wakeable_ids: set[int] | None = None,
  3046. printer_scope: PrinterScope = ALL_PRINTERS,
  3047. is_short: Callable[[int], Awaitable[bool]] | None = None,
  3048. drying_ids: set[int] | None = None,
  3049. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  3050. refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
  3051. ) -> tuple[int | None, str | None]:
  3052. """Find an idle, connected printer matching the model with compatible filaments.
  3053. Args:
  3054. db: Database session
  3055. model: Printer model to match (e.g., "X1C", "P1S")
  3056. exclude_ids: Printer IDs to exclude (already busy)
  3057. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  3058. If provided, only printers with all required types loaded will match.
  3059. target_location: Optional location filter. If provided, only printers in this location are considered.
  3060. filament_overrides: Optional list of override dicts. Each entry may include
  3061. ``force_color_match: true`` to require an exact type+color match
  3062. on the printer for that slot. Without the flag the existing
  3063. colour-preference logic applies.
  3064. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  3065. offline printer is worded: one Bambuddy will switch on reads
  3066. differently from one the user has to go and switch on themselves.
  3067. is_short: Says whether a printer's spools are too light for the job (#3137).
  3068. A printer it flags is passed over while another eligible one
  3069. is not. When every eligible printer is short, the first is
  3070. returned all the same, so the deficit gate holds the job there
  3071. and "Print Anyway" still has a printer to print on.
  3072. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  3073. in the reason, as a pinned job's wait is.
  3074. unmatched_on: Names the filaments the slot matcher would leave without a
  3075. tray on a printer (#3280). A printer it names any for is
  3076. passed over like one missing a filament type: the checks
  3077. above only ask whether each type and forced colour is
  3078. loaded somewhere, not on the right nozzle or once per slot.
  3079. refused_uploads: Excluded printers out of dispatch after a refused upload,
  3080. with why (#3409). Each is named with the reason its own
  3081. queue rows show, not as "Busy".
  3082. Returns:
  3083. Tuple of (printer_id, waiting_reason):
  3084. - (printer_id, None) if a matching printer was found
  3085. - (None, reason) if no printer is available, with explanation
  3086. """
  3087. normalized_model = normalize_printer_model(model) or model
  3088. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  3089. location_suffix = f" in {target_location}" if target_location else ""
  3090. if not printers:
  3091. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3092. # Separate force-matched overrides from preference-only overrides
  3093. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3094. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3095. # Track reasons for skipping printers
  3096. printers_busy = []
  3097. # Printers out of dispatch after a refused upload, worded as the
  3098. # printer's own queue rows word it: "Busy" would read as printing (#3409).
  3099. printers_refused: list[str] = []
  3100. printers_offline = []
  3101. printers_offline_no_plug = []
  3102. printers_missing_filament: list[tuple[str, list[str]]] = []
  3103. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3104. # The first eligible printer that is short on filament, kept in case
  3105. # every eligible printer is (#3137).
  3106. short_fallback: int | None = None
  3107. for printer in printers:
  3108. if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
  3109. printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
  3110. continue
  3111. if printer.id in exclude_ids:
  3112. # Printer is already claimed by another job in this scheduling run.
  3113. # For force-color jobs, still check if the color would match — if not,
  3114. # report it as a color mismatch rather than plain "Busy" so the user
  3115. # knows the job needs a filament change, not just to wait for availability.
  3116. if force_overrides and not pref_overrides:
  3117. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3118. if missing_colors:
  3119. printers_missing_filament.append((printer.name, missing_colors))
  3120. continue
  3121. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3122. continue
  3123. is_connected = printer_manager.is_connected(printer.id)
  3124. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3125. if not is_connected:
  3126. # An offline printer whose last known filament cannot run this
  3127. # job is reported as needing filament rather than as offline
  3128. # (#2876). It is also the printer the smart-plug step will now
  3129. # decline to switch on, and "Offline:" on its own would leave
  3130. # that decision looking like nothing happening at all.
  3131. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3132. if shortfall:
  3133. printers_missing_filament.append((printer.name, shortfall))
  3134. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3135. printers_offline_no_plug.append(printer.name)
  3136. else:
  3137. printers_offline.append(printer.name)
  3138. continue
  3139. if not is_idle:
  3140. # Printer is currently printing. For force-color jobs, check whether the
  3141. # loaded color would satisfy the requirement — if not, surface it as a
  3142. # color-mismatch reason rather than plain "Busy" so the user understands
  3143. # that the job is waiting for a filament change, not just printer availability.
  3144. if force_overrides and not pref_overrides:
  3145. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3146. if missing_colors:
  3147. printers_missing_filament.append((printer.name, missing_colors))
  3148. logger.debug(
  3149. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3150. printer.id,
  3151. printer.name,
  3152. missing_colors,
  3153. )
  3154. continue
  3155. printers_busy.append(printer.name)
  3156. continue
  3157. # Validate filament compatibility if required types are specified
  3158. if required_filament_types:
  3159. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3160. if missing:
  3161. # When force_overrides are present, enrich missing entries with color info
  3162. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3163. if force_overrides:
  3164. force_color_map = {
  3165. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3166. for o in force_overrides
  3167. }
  3168. missing_enriched = [
  3169. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3170. for t in missing
  3171. ]
  3172. printers_missing_filament.append((printer.name, missing_enriched))
  3173. else:
  3174. printers_missing_filament.append((printer.name, missing))
  3175. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3176. continue
  3177. # Force color match: ALL flagged slots must have an exact type+color match
  3178. if force_overrides:
  3179. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3180. if missing_colors:
  3181. printers_missing_filament.append((printer.name, missing_colors))
  3182. logger.debug(
  3183. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3184. printer.id,
  3185. printer.name,
  3186. missing_colors,
  3187. )
  3188. continue
  3189. # The matcher has the last word: a printer it cannot map would be
  3190. # held and given back, then chosen again on the next pass (#3280).
  3191. if unmatched_on is not None:
  3192. unmatched = await unmatched_on(printer.id)
  3193. if unmatched:
  3194. printers_missing_filament.append((printer.name, unmatched))
  3195. logger.debug(
  3196. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3197. printer.id,
  3198. printer.name,
  3199. unmatched,
  3200. )
  3201. continue
  3202. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3203. if pref_overrides:
  3204. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3205. if color_matches > 0:
  3206. candidates.append((printer.id, color_matches))
  3207. else:
  3208. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3209. printers_missing_filament.append((printer.name, override_colors))
  3210. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3211. continue
  3212. else:
  3213. # No preference ordering needed: the first eligible printer
  3214. # wins, unless its spools are too light for the job (#3137).
  3215. if is_short is not None and await is_short(printer.id):
  3216. if short_fallback is None:
  3217. short_fallback = printer.id
  3218. logger.info(
  3219. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3220. printer.id,
  3221. printer.name,
  3222. )
  3223. continue
  3224. return printer.id, None
  3225. # If we have candidates from preference override matching, pick the one with most color matches
  3226. if candidates:
  3227. candidates.sort(key=lambda c: c[1], reverse=True)
  3228. if is_short is not None:
  3229. for candidate_id, _ in candidates:
  3230. if not await is_short(candidate_id):
  3231. return candidate_id, None
  3232. logger.info(
  3233. "Model-based assignment: passing over printer %s, not enough filament",
  3234. candidate_id,
  3235. )
  3236. return candidates[0][0], None
  3237. if short_fallback is not None:
  3238. return short_fallback, None
  3239. # Build waiting reason from what we found
  3240. reasons = []
  3241. if printers_missing_filament:
  3242. # Filament/color mismatch is most actionable - show first
  3243. if force_overrides and not pref_overrides:
  3244. # All mismatches are force-color failures — use descriptive message only;
  3245. # but only if there are no busy printers that DO have the matching color.
  3246. # If a printer has the right color but is busy, surface "Busy" instead so
  3247. # the user knows the job will start automatically once that printer is free.
  3248. # Same for a printer that is merely offline: Bambuddy switches that one on
  3249. # by itself, so the job is not actually waiting on anybody to change a
  3250. # spool (#2876 — offline printers reach this list now that a switched-off
  3251. # printer's own filament is read).
  3252. if not printers_busy and not printers_offline and not printers_refused:
  3253. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3254. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3255. # else: fall through — the self-resolving entries are appended below
  3256. else:
  3257. names_and_missing = [
  3258. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3259. ]
  3260. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3261. reasons.extend(printers_refused)
  3262. if printers_busy:
  3263. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3264. if printers_offline:
  3265. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3266. if printers_offline_no_plug:
  3267. # Named separately because it is the one entry on this list the
  3268. # user has to act on: no enabled Auto On plug means Bambuddy will
  3269. # never power this printer on for the queue (#2786).
  3270. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3271. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3272. @staticmethod
  3273. def _is_busy_only(waiting_reason: str) -> bool:
  3274. """Check if the waiting reason only contains 'Busy' entries.
  3275. When all matching printers are simply busy printing, the queued job
  3276. will start automatically once a printer finishes — no user action
  3277. is required, so we skip the notification.
  3278. """
  3279. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3280. return all(p.startswith("Busy:") for p in parts)
  3281. def _get_missing_force_color_slots(
  3282. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3283. ) -> list[str]:
  3284. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3285. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3286. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3287. with an exact type+color match.
  3288. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3289. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3290. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3291. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3292. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3293. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3294. setups are unaffected.
  3295. Returns:
  3296. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3297. """
  3298. if raw_data is None:
  3299. status = printer_manager.get_status(printer_id)
  3300. if not status:
  3301. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3302. raw_data = status.raw_data
  3303. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3304. loaded: list[tuple[str, str, str]] = []
  3305. for ams_unit in raw_data.get("ams", []):
  3306. for tray in ams_unit.get("tray", []):
  3307. tray_type = tray.get("tray_type")
  3308. if tray_type:
  3309. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3310. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3311. for vt in raw_data.get("vt_tray") or []:
  3312. vt_type = vt.get("tray_type")
  3313. if vt_type:
  3314. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3315. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3316. # One spool per slot, the way the matcher assigns them: two slots asking
  3317. # for the same filament need two spools of it (#3280). Slots naming a
  3318. # variant go first and take that variant before a spool naming none, so
  3319. # a slot open to any variant cannot use up the one a later slot needs.
  3320. missing = []
  3321. taken: set[int] = set()
  3322. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3323. o_type = canonical_filament_type(o.get("type") or "")
  3324. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3325. o_idx = o.get("tray_info_idx") or ""
  3326. fits = [
  3327. i
  3328. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3329. if i not in taken
  3330. and t_type == o_type
  3331. and t_color == o_color
  3332. and (not o_idx or not t_idx or o_idx == t_idx)
  3333. ]
  3334. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3335. if pick is not None:
  3336. taken.add(pick)
  3337. else:
  3338. color_label = o.get("color_name") or o.get("color", "?")
  3339. missing.append(f"{o_type} ({color_label})")
  3340. return missing
  3341. def _get_missing_filament_types(
  3342. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3343. ) -> list[str]:
  3344. """Get the list of required filament types that are not loaded on the printer.
  3345. Args:
  3346. printer_id: The printer ID
  3347. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3348. Returns:
  3349. List of missing filament types (empty if all are loaded)
  3350. """
  3351. if raw_data is None:
  3352. status = printer_manager.get_status(printer_id)
  3353. if not status:
  3354. return required_types # Can't determine, assume all missing
  3355. raw_data = status.raw_data
  3356. # Collect all filament types loaded on this printer (AMS units + external spool)
  3357. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3358. loaded_types: set[str] = set()
  3359. # Check AMS units (stored in raw_data["ams"])
  3360. ams_data = raw_data.get("ams", [])
  3361. if ams_data:
  3362. for ams_unit in ams_data:
  3363. for tray in ams_unit.get("tray", []):
  3364. tray_type = tray.get("tray_type")
  3365. if tray_type:
  3366. loaded_types.add(canonical_filament_type(tray_type))
  3367. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3368. for vt in raw_data.get("vt_tray") or []:
  3369. vt_type = vt.get("tray_type")
  3370. if vt_type:
  3371. loaded_types.add(canonical_filament_type(vt_type))
  3372. # Find which required types are missing (using canonical type for equivalence)
  3373. missing = []
  3374. for req_type in required_types:
  3375. if canonical_filament_type(req_type) not in loaded_types:
  3376. missing.append(req_type)
  3377. return missing
  3378. def _count_override_color_matches(
  3379. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3380. ) -> int:
  3381. """Count how many filament overrides have an exact color match on the printer.
  3382. Used to prefer printers that already have the desired override colors loaded.
  3383. """
  3384. if raw_data is None:
  3385. status = printer_manager.get_status(printer_id)
  3386. if not status:
  3387. return 0
  3388. raw_data = status.raw_data
  3389. # Collect loaded filaments' type+color pairs
  3390. loaded: set[tuple[str, str]] = set()
  3391. for ams_unit in raw_data.get("ams", []):
  3392. for tray in ams_unit.get("tray", []):
  3393. tray_type = tray.get("tray_type")
  3394. # `or ""`, not a dict default: a slot can carry the key with a
  3395. # null value, and this now runs against switched-off printers
  3396. # too, where nobody is watching for the AttributeError.
  3397. tray_color = tray.get("tray_color") or ""
  3398. if tray_type:
  3399. color_norm = tray_color.replace("#", "").lower()[:6]
  3400. loaded.add((canonical_filament_type(tray_type), color_norm))
  3401. for vt in raw_data.get("vt_tray") or []:
  3402. vt_type = vt.get("tray_type")
  3403. if vt_type:
  3404. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3405. loaded.add((canonical_filament_type(vt_type), color_norm))
  3406. # Types compared as the type check compares them: a PA12-CF override
  3407. # is met by PA-CF in its colour.
  3408. matches = 0
  3409. for o in overrides:
  3410. o_type = canonical_filament_type(o.get("type") or "")
  3411. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3412. if (o_type, o_color) in loaded:
  3413. matches += 1
  3414. return matches
  3415. @staticmethod
  3416. def _tray_reading(printer_id: int) -> dict:
  3417. """The best tray reading available for a printer that is not printing.
  3418. Live status first: a printer keeps its last status after the power
  3419. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3420. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3421. for when the client itself has been dropped and taken its status with
  3422. it — which is what every power-on attempt does.
  3423. An empty result means "we have never heard", not "nothing is loaded":
  3424. the two are indistinguishable from here, and only the second would be
  3425. safe to act on.
  3426. """
  3427. status = printer_manager.get_status(printer_id)
  3428. raw = (status.raw_data if status else None) or {}
  3429. for ams_unit in raw.get("ams") or []:
  3430. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3431. return raw
  3432. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3433. return raw
  3434. return printer_manager.last_known_trays(printer_id)
  3435. def _cached_filament_shortfall(
  3436. self,
  3437. printer_id: int,
  3438. required_types: list[str] | None,
  3439. filament_overrides: list[dict] | None,
  3440. ) -> list[str]:
  3441. """What a switched-off printer's last known filament cannot provide (#2876).
  3442. The smart-plug wake step used to consider only the model, so a job for a
  3443. colour loaded on the last printer in ID order switched on every earlier
  3444. one in turn, evaluated it, rejected it on colour and left it running.
  3445. Bambuddy knew those colours the whole time. This asks the same three
  3446. questions the matcher asks a live printer — required types, forced
  3447. colours, preferred colours — of the trays it last reported, and returns
  3448. the answers in the same shape the "Waiting for filament" reason uses.
  3449. Empty means the printer may still be able to take the job.
  3450. Fails open, and deliberately: with no tray reading (never connected
  3451. since Bambuddy started, or the cache dropped by a reconnect) this
  3452. returns nothing to report and the printer is treated as it was before.
  3453. A farm restarted while its printers were off must not conclude that
  3454. none of them can print.
  3455. """
  3456. if not required_types and not filament_overrides:
  3457. return []
  3458. raw_data = self._tray_reading(printer_id)
  3459. if not raw_data:
  3460. return []
  3461. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3462. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3463. if required_types:
  3464. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3465. if missing:
  3466. # Same enrichment the live path applies: a bare "PLA" is not
  3467. # much help when what is missing is a particular PLA.
  3468. force_color_map = {
  3469. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3470. }
  3471. return [
  3472. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3473. for t in missing
  3474. ]
  3475. if force_overrides:
  3476. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3477. if missing_colors:
  3478. return missing_colors
  3479. # Preference overrides read as a preference but the matcher treats zero
  3480. # matches as a skip, so a printer with none of the wanted colours is
  3481. # rejected there too. Waking it would only produce that same rejection.
  3482. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3483. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3484. return []
  3485. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3486. """Fold the winning candidate's file and settings onto the queue row (#671).
  3487. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3488. never escapes the selection loop. By the time the pass commits, the row
  3489. looks exactly like an ordinary single-file model-based item, so the upload,
  3490. archive creation, expected-print registration, print history and reprint
  3491. paths need no knowledge that variants exist.
  3492. No-ops for a non-variant candidate, which is already the item's own columns.
  3493. Safe to run and re-run: the item's file columns are only ever *read* when it
  3494. has no variants, so an item that gets resolved and then skipped (library-row
  3495. conflict, previous-print gate) is simply resolved again on the next pass.
  3496. """
  3497. variant = candidate.variant
  3498. if variant is None:
  3499. return
  3500. item.library_file_id = variant.library_file_id
  3501. item.library_file = variant.library_file
  3502. # The dispatcher checks archive_id first and would print that instead of
  3503. # the file we just picked. Creation refuses to combine the two, so this
  3504. # only ever fires on a hand-written row — clear it rather than silently
  3505. # dispatch something the matcher never considered.
  3506. item.archive_id = None
  3507. item.archive = None
  3508. item.target_model = variant.target_model
  3509. item.plate_id = variant.plate_id
  3510. item.ams_mapping = variant.ams_mapping
  3511. item.nozzle_mapping = variant.nozzle_mapping
  3512. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3513. item.filament_overrides = variant.filament_overrides
  3514. item.required_filament_types = variant.required_filament_types
  3515. if variant.print_time_seconds is not None:
  3516. # The row carried the shortest candidate's estimate so SJF could order
  3517. # it before a printer was known; now that one is chosen, record what is
  3518. # actually going to run so history and the ETA agree with reality.
  3519. item.print_time_seconds = variant.print_time_seconds
  3520. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3521. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3522. Recomputes from live printer status when the stored mapping is missing OR
  3523. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3524. frontend status-load race can serialize [-1] before the printer's AMS
  3525. trays are known (#2589) — and must not be trusted: downstream it would be
  3526. silently downgraded to external-spool mode and print against an empty
  3527. feed. A resolved mapping is re-checked against the target printer's
  3528. live trays before it is trusted (#2799) and recomputed when it does not
  3529. fit. When it does fit, its resolved slots are kept as they are and only
  3530. the slots the plate prints that are still unresolved are matched again;
  3531. all of it is left alone when the user has acknowledged it with "Print
  3532. Anyway".
  3533. When recompute cannot resolve it either (no compatible tray loaded), the
  3534. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3535. external selection. On a printer that reported loaded trays,
  3536. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3537. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3538. and the firmware surfaces a clear AMS-mapping error instead of silently
  3539. printing to the empty external feed.
  3540. Returns an actionable message when that firmware error is the only
  3541. possible outcome — the matcher ran, matched nothing, and the printer has
  3542. no AMS to load a different spool into (#2771). The caller fails the item
  3543. on it instead of spending an upload on a print that cannot start.
  3544. Returns None everywhere else, including every case where we simply lack
  3545. the data to judge, so dispatch is only ever blocked on a positive
  3546. finding.
  3547. """
  3548. stored_mapping: list | None = None
  3549. if item.ams_mapping:
  3550. try:
  3551. stored_mapping = json.loads(item.ams_mapping)
  3552. except (json.JSONDecodeError, TypeError):
  3553. stored_mapping = None
  3554. # Present and resolved. Global tray IDs only mean something relative to
  3555. # the printer they were resolved against, so "resolved" is not the same
  3556. # as "resolved *here*" — check the mapping still fits the printer that
  3557. # is about to run this item before trusting it (#2799). "Print anyway"
  3558. # is the user overriding exactly this judgement, so it short-circuits.
  3559. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3560. if item.skip_filament_check:
  3561. return None
  3562. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3563. if conflict is None:
  3564. # It fits, but a slot the plate prints may still be empty: the
  3565. # spool was missing when it was mapped, and has perhaps been
  3566. # loaded since. Nothing else would ever look at that slot again,
  3567. # so a job held for it would be held again on every Start.
  3568. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3569. if filled is not None:
  3570. item.ams_mapping = json.dumps(filled)
  3571. logger.info(
  3572. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3573. item.id,
  3574. stored_mapping,
  3575. printer_id,
  3576. filled,
  3577. )
  3578. await db.commit()
  3579. return None
  3580. logger.warning(
  3581. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3582. item.id,
  3583. stored_mapping,
  3584. printer_id,
  3585. conflict,
  3586. )
  3587. # Drop it before recomputing so a failed recompute cannot fall back
  3588. # to the mapping we just rejected.
  3589. item.ams_mapping = None
  3590. stored_mapping = None
  3591. await db.commit()
  3592. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3593. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3594. item.ams_mapping = json.dumps(computed_mapping)
  3595. logger.info(
  3596. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3597. item.id,
  3598. printer_id,
  3599. computed_mapping,
  3600. )
  3601. await db.commit()
  3602. return None
  3603. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3604. if external_only is not None:
  3605. item.ams_mapping = json.dumps(external_only)
  3606. logger.info(
  3607. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3608. "mapping every filament to it: %s",
  3609. item.id,
  3610. printer_id,
  3611. external_only,
  3612. )
  3613. await db.commit()
  3614. return None
  3615. if _mapping_is_all_unresolved(stored_mapping):
  3616. logger.warning(
  3617. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3618. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3619. item.id,
  3620. stored_mapping,
  3621. printer_id,
  3622. )
  3623. item.ams_mapping = None
  3624. await db.commit()
  3625. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3626. async def _external_spool_only_mapping(
  3627. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3628. ) -> list[int] | None:
  3629. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3630. A printer without an AMS prints from its external spool, and an external
  3631. spool whose filament was never set reports no type, so the matcher has
  3632. nothing to match. Sent without a mapping, the print goes out with the AMS
  3633. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3634. to carry such a job through; a job placed by model or location no longer
  3635. keeps one, and one queued that way never had one.
  3636. Only on a positive report: the printer has said it has no AMS, it has a
  3637. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3638. is not ours to pick), and no feed has a filament set — with one set, the
  3639. matcher has already given its answer. Not for a job that asked for its
  3640. colours to be matched strictly: a spool without a filament set has no
  3641. colour to check. Returns None otherwise.
  3642. """
  3643. if item.filament_overrides:
  3644. try:
  3645. overrides = json.loads(item.filament_overrides)
  3646. except (json.JSONDecodeError, TypeError):
  3647. return None
  3648. if not isinstance(overrides, list) or any(
  3649. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3650. ):
  3651. return None
  3652. status = printer_manager.get_status(printer_id)
  3653. if status is None or not isinstance(status.raw_data, dict):
  3654. return None
  3655. ams_units = status.raw_data.get("ams")
  3656. if not isinstance(ams_units, list) or ams_units:
  3657. return None
  3658. vt_trays = status.raw_data.get("vt_tray")
  3659. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3660. return None
  3661. if self._build_loaded_filaments(status):
  3662. return None
  3663. printer = await self._get_printer(db, printer_id)
  3664. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3665. return None
  3666. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3667. if external < _EXTERNAL_TRAY_ID_MIN:
  3668. return None
  3669. required = await self._get_filament_requirements(db, item)
  3670. slot_ids = [r.get("slot_id") for r in required or []]
  3671. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3672. if not slot_ids:
  3673. return None
  3674. mapping = [-1] * max(slot_ids)
  3675. for slot_id in slot_ids:
  3676. mapping[slot_id - 1] = external
  3677. return mapping
  3678. async def _fill_unresolved_slots(
  3679. self,
  3680. db: AsyncSession,
  3681. printer_id: int,
  3682. item: PrintQueueItem,
  3683. stored_mapping: list | None,
  3684. ) -> list | None:
  3685. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3686. Every resolved entry is kept, so a tray the user picked by hand stays
  3687. picked. Only the plate's unresolved slots are matched, and only against
  3688. trays the mapping does not already use: the matcher never gives two
  3689. slots one tray, and filling a gap with a tray the user assigned to
  3690. another slot would print that slot's filament twice.
  3691. Returns None when there is nothing to fill or nothing could be filled.
  3692. """
  3693. if not isinstance(stored_mapping, list) or not stored_mapping:
  3694. return None
  3695. required = await self._get_filament_requirements(db, item)
  3696. if not required:
  3697. return None
  3698. self._apply_filament_overrides(item, required)
  3699. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3700. if not gaps:
  3701. return None
  3702. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3703. computed = await self._compute_ams_mapping_for_printer(
  3704. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3705. )
  3706. if not computed:
  3707. return None
  3708. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3709. filled = False
  3710. for slot_id in gaps:
  3711. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3712. if _is_tray_id(tray) and tray >= 0:
  3713. merged[slot_id - 1] = tray
  3714. filled = True
  3715. return merged if filled else None
  3716. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3717. """What a staged item would be held for if it were started now (#2799).
  3718. The Start button asks this before releasing an item, so that a job whose
  3719. filament is still not loaded offers "Print Anyway" instead of being
  3720. released, held again by the scheduler and leaving no way past the hold.
  3721. It reaches the same answer the dispatch path would: a stored mapping
  3722. that fits is kept and only its gaps are matched again, and one that
  3723. does not fit (or is missing) is replaced by a fresh match.
  3724. Returns the missing filaments, described the way the queue row
  3725. describes them, or None when nothing is missing or there is not enough
  3726. evidence to say: no printer yet (a model-based item picks one at
  3727. dispatch), no status, no trays reported, or no readable 3MF.
  3728. """
  3729. if item.skip_filament_check or not item.printer_id:
  3730. return None
  3731. status = printer_manager.get_status(item.printer_id)
  3732. if status is None or not self._build_loaded_filaments(status):
  3733. return None
  3734. # Called from a request, not from a pass: drop whatever the last pass
  3735. # memoised so this reads the file as it is now. A pass running at the
  3736. # same time only loses its cache.
  3737. self._filament_req_memo.clear()
  3738. mapping: list | None = None
  3739. if item.ams_mapping:
  3740. try:
  3741. mapping = json.loads(item.ams_mapping)
  3742. except (json.JSONDecodeError, TypeError):
  3743. mapping = None
  3744. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3745. mapping = None
  3746. if mapping is not None:
  3747. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3748. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3749. else:
  3750. mapping = None
  3751. if mapping is None:
  3752. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3753. required = await self._get_filament_requirements(db, item)
  3754. if required:
  3755. self._apply_filament_overrides(item, required)
  3756. else:
  3757. # The same fallback the hold uses, or Start would release a job the
  3758. # next pass holds again (#3280).
  3759. required = _forced_override_requirements(item)
  3760. if not required:
  3761. return None
  3762. missing = _unresolved_required(required, mapping)
  3763. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3764. async def _stored_mapping_conflict(
  3765. self,
  3766. db: AsyncSession,
  3767. printer_id: int,
  3768. item: PrintQueueItem,
  3769. stored_mapping: list | None,
  3770. ) -> str | None:
  3771. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3772. A mapping is a list of global tray IDs, and those are only meaningful
  3773. relative to the printer they were resolved against — the same rule
  3774. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3775. arrives at a printer it was not resolved for:
  3776. * the print dialog stamps one mapping onto every selected printer, so a
  3777. mapping computed against the first printer is dispatched verbatim to
  3778. the rest, whose AMS slot order differs;
  3779. * a spool is moved between queueing and dispatch.
  3780. Both end the same way: the slot index still resolves, so nothing looks
  3781. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3782. the firmware's own type check, so a PETG slot happily prints in ASA.
  3783. Returns a short reason when the mapping names a tray this printer does
  3784. not have loaded, points a slot at a tray holding a different filament
  3785. type, or points it at an external spool this printer reports empty while
  3786. its AMS holds that slot's filament (#3239). Returns None when the
  3787. mapping fits, and — deliberately — whenever we lack the evidence to
  3788. judge, so a recompute only ever follows a positive finding.
  3789. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3790. matcher had nothing, not that the mapping belongs to another printer,
  3791. and destroying a partially hand-resolved mapping over it would lose the
  3792. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3793. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3794. item when that finds nothing.
  3795. """
  3796. if not isinstance(stored_mapping, list) or not stored_mapping:
  3797. return None
  3798. status = printer_manager.get_status(printer_id)
  3799. if status is None:
  3800. return None
  3801. loaded = self._build_loaded_filaments(status)
  3802. if not loaded:
  3803. # Nothing reported yet (reconnect, first push pending). Saying
  3804. # "tray not loaded" here would recompute against an AMS we cannot
  3805. # see, which is how #2589 produced a bogus all-[-1] in the first
  3806. # place.
  3807. return None
  3808. by_tray = {f["global_tray_id"]: f for f in loaded}
  3809. # Cheap pass first, on live status alone: every tray the mapping names
  3810. # has to exist here. This catches a foreign mapping without opening the
  3811. # 3MF, which is worth doing because the parse below is neither cached
  3812. # nor free.
  3813. for index, tray in enumerate(stored_mapping):
  3814. if not _is_tray_id(tray) or tray < 0:
  3815. continue
  3816. if tray in by_tray:
  3817. continue
  3818. if tray >= 254:
  3819. # An external feed we have not heard about is absence of
  3820. # evidence about *that slot* — the rest of the mapping is still
  3821. # worth judging, so skip it rather than abandoning the pass.
  3822. continue
  3823. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3824. # Only now is the 3MF worth opening: the type check needs to know what
  3825. # each slot actually asked for. The external spool is checked the same
  3826. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3827. # two printers with different filament in the external feed is the same
  3828. # failure this method exists to catch.
  3829. required = await self._get_filament_requirements(db, item)
  3830. if not required:
  3831. return None
  3832. self._apply_filament_overrides(item, required)
  3833. # External feeds the printer reports and reports as empty. That is
  3834. # evidence, unlike an external feed it says nothing about (#3239).
  3835. empty_external: set[int] = set()
  3836. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3837. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3838. if isinstance(vt, dict) and not vt.get("tray_type"):
  3839. try:
  3840. empty_external.add(int(vt.get("id", 254)))
  3841. except (TypeError, ValueError):
  3842. continue
  3843. for req in required:
  3844. slot_id = req.get("slot_id") or 0
  3845. if slot_id <= 0:
  3846. continue
  3847. if slot_id > len(stored_mapping):
  3848. return f"slot {slot_id} is not covered by the mapping"
  3849. tray = stored_mapping[slot_id - 1]
  3850. if not _is_tray_id(tray) or tray < 0:
  3851. continue
  3852. loaded_tray = by_tray.get(tray)
  3853. if loaded_tray is None:
  3854. # A mapping made for a printer that feeds this slot from its
  3855. # external spool, sent to one whose external spool is empty and
  3856. # whose AMS holds the filament (#3239). Only then: an external
  3857. # spool can be loaded without its filament set, and on a printer
  3858. # with nothing else to offer that job printed before. The colour
  3859. # has to match too: with only another colour in the AMS, the
  3860. # printer asking for the spool beats printing in that colour.
  3861. want = canonical_filament_type(req.get("type"))
  3862. if tray >= 254 and tray in empty_external and want:
  3863. ams_tray = next(
  3864. (
  3865. f
  3866. for f in loaded
  3867. if not f.get("is_external")
  3868. and canonical_filament_type(f.get("type")) == want
  3869. and self._colors_are_similar(f.get("color"), req.get("color"))
  3870. ),
  3871. None,
  3872. )
  3873. if ams_tray is not None:
  3874. return (
  3875. f"slot {slot_id} points at the external spool, which is empty, "
  3876. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3877. )
  3878. continue
  3879. want = canonical_filament_type(req.get("type"))
  3880. have = canonical_filament_type(loaded_tray.get("type"))
  3881. if want and have and want != have:
  3882. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3883. # A forced slot fits only a tray the matcher would give it (#3280).
  3884. if req.get("force_color_match"):
  3885. want_idx = req.get("tray_info_idx") or ""
  3886. have_idx = loaded_tray.get("tray_info_idx") or ""
  3887. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3888. loaded_tray.get("color")
  3889. ) or (want_idx and have_idx and want_idx != have_idx):
  3890. return (
  3891. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3892. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3893. )
  3894. return None
  3895. async def _unmappable_without_ams_message(
  3896. self,
  3897. db: AsyncSession,
  3898. printer_id: int,
  3899. item: PrintQueueItem,
  3900. computed_mapping: list[int] | None,
  3901. ) -> str | None:
  3902. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3903. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3904. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3905. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3906. uploaded several megabytes and burned its dispatch retries. This method
  3907. speaks only for the AMS-less case: there is nothing to resume into — the
  3908. external spool holder is the whole inventory — so the useful answer is to
  3909. say which filament is missing and stop. With an AMS attached it returns
  3910. None: where live status reported loaded trays,
  3911. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3912. reported none the print goes out and the firmware error is the answer —
  3913. the user can load the right spool and press Resume.
  3914. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3915. every branch that lacks the evidence to be sure returns None.
  3916. """
  3917. # None means the matcher never ran (no requirements parsed from the 3MF,
  3918. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3919. # dispatch as they always have.
  3920. if not _mapping_is_all_unresolved(computed_mapping):
  3921. return None
  3922. status = printer_manager.get_status(printer_id)
  3923. if status is None:
  3924. return None
  3925. # "No AMS" has to be a fact the printer stated, not the absence of a
  3926. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3927. # handled and is preserved across partial pushes thereafter, so a missing
  3928. # key means we have not heard yet — most likely a reconnect, where the
  3929. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3930. # empty list is the positive report of a printer with no AMS.
  3931. ams_units = status.raw_data.get("ams")
  3932. if not isinstance(ams_units, list) or ams_units:
  3933. return None
  3934. required = await self._get_filament_requirements(db, item)
  3935. loaded = self._build_loaded_filaments(status)
  3936. if not required or not loaded:
  3937. # Both were non-empty moments ago or the matcher could not have run.
  3938. # If the picture changed under us, say nothing rather than fail an
  3939. # item on stale evidence.
  3940. return None
  3941. self._apply_filament_overrides(item, required)
  3942. if any(r.get("force_color_match") for r in required):
  3943. # A forced colour is a spool the user can load on the external
  3944. # holder, so the unmatched hold stages the job instead (#3280).
  3945. return None
  3946. return _unmatched_filament_message(required, loaded)
  3947. async def _fail_unmappable_item(
  3948. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3949. ) -> None:
  3950. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3951. This replaces a failure, not a success: without it the item is uploaded,
  3952. rejected by the firmware with 0700_8012, retried twice more and failed
  3953. anyway with "never started the print after N dispatch attempts". So this
  3954. applies on the model-based path too. There it is rarely reached: choosing
  3955. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  3956. over one it cannot map, so an "Any <model>" job tries its siblings and
  3957. otherwise waits; this remains for a match that failed at selection time.
  3958. """
  3959. item.status = "failed"
  3960. item.error_message = message
  3961. item.completed_at = datetime.now(timezone.utc)
  3962. item.waiting_reason = None
  3963. await db.commit()
  3964. from backend.app.services.print_batch import refresh_batches_after
  3965. await refresh_batches_after([item.id])
  3966. logger.warning(
  3967. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3968. item.id,
  3969. printer_id,
  3970. message,
  3971. )
  3972. job_name = await self._get_job_name(db, item)
  3973. printer = await self._get_printer(db, printer_id)
  3974. await notification_service.on_queue_job_failed(
  3975. job_name=job_name,
  3976. printer_id=printer_id,
  3977. printer_name=printer.name if printer else "Unknown",
  3978. reason=message,
  3979. db=db,
  3980. )
  3981. try:
  3982. await ws_manager.send_queue_item_failed(
  3983. user_id=item.created_by_id,
  3984. queue_item_id=item.id,
  3985. printer_id=printer_id,
  3986. reason="filament_unmappable",
  3987. )
  3988. except Exception:
  3989. pass
  3990. async def _compute_ams_mapping_for_printer(
  3991. self,
  3992. db: AsyncSession,
  3993. printer_id: int,
  3994. item: PrintQueueItem,
  3995. *,
  3996. only_slots: set[int] | None = None,
  3997. reserved_trays: set[int] | None = None,
  3998. ) -> list[int] | None:
  3999. """Compute AMS mapping for a printer based on filament requirements.
  4000. Called when a queue item has no ams_mapping set — either for model-based
  4001. items after printer assignment, or printer-specific items (e.g. from VP).
  4002. Args:
  4003. db: Database session
  4004. printer_id: The assigned printer ID
  4005. item: The queue item (contains archive_id or library_file_id)
  4006. only_slots: Match only these filament slots; every other slot comes
  4007. back unresolved (-1). Used to fill the gaps of a stored mapping.
  4008. reserved_trays: Global tray IDs to leave out of the match, because
  4009. the stored mapping already gives them to another slot.
  4010. Returns:
  4011. AMS mapping array or None if no mapping needed/possible
  4012. """
  4013. # Get printer status
  4014. status = printer_manager.get_status(printer_id)
  4015. if not status:
  4016. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  4017. return None
  4018. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  4019. # either extruder, so the per-nozzle hard filter below must NOT apply.
  4020. # Otherwise a print on one nozzle can't use a spool physically loaded in
  4021. # an AMS on the *other* nozzle, and the matcher falls through to a
  4022. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  4023. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  4024. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  4025. # Get filament requirements from source file
  4026. filament_reqs = await self._get_filament_requirements(db, item)
  4027. if not filament_reqs:
  4028. # When the 3MF can't be read but force-color overrides are present, build a
  4029. # direct mapping from the overrides so the printer uses the correct AMS slot.
  4030. if item.filament_overrides:
  4031. try:
  4032. overrides = json.loads(item.filament_overrides)
  4033. force_overrides = [o for o in overrides if o.get("force_color_match")]
  4034. if force_overrides:
  4035. logger.info(
  4036. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  4037. "force-color override(s)",
  4038. item.id,
  4039. len(force_overrides),
  4040. )
  4041. return self._build_override_direct_mapping(force_overrides, status)
  4042. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4043. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  4044. logger.debug("No filament requirements found for queue item %s", item.id)
  4045. return None
  4046. self._apply_filament_overrides(item, filament_reqs)
  4047. if only_slots is not None:
  4048. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  4049. if not filament_reqs:
  4050. return None
  4051. # Build loaded filaments from printer status
  4052. loaded_filaments = self._build_loaded_filaments(status)
  4053. if reserved_trays:
  4054. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  4055. if not loaded_filaments:
  4056. logger.debug("No filaments loaded on printer %s", printer_id)
  4057. return None
  4058. # Check if user prefers lowest remaining filament when multiple spools match
  4059. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  4060. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  4061. # Without backup, the printer will not switch to a second spool when the
  4062. # picked one runs out — so sorting toward the lowest leaves the print
  4063. # at risk of running dry mid-job. None (unknown: no status report with
  4064. # cfg or home_flag yet) preserves today's behaviour intentionally.
  4065. if prefer_lowest and status.ams_filament_backup is False:
  4066. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  4067. prefer_lowest = False
  4068. # When the preference is on, surface Bambuddy's inventory-side
  4069. # remaining for each slot that's bound to a tracked spool, so the
  4070. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  4071. # entirely when the preference is off — no behaviour change for
  4072. # users who haven't opted in.
  4073. inventory_remain_overrides: dict[int, float] | None = None
  4074. if prefer_lowest:
  4075. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  4076. # Compute mapping: match required filaments to available slots
  4077. return self._match_filaments_to_slots(
  4078. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  4079. )
  4080. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  4081. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  4082. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  4083. diagnosis (#2771) describes the filament the matcher actually looked
  4084. for, not the one the 3MF was sliced with — naming the pre-override
  4085. filament in a user-facing error would send the user to load the wrong
  4086. spool.
  4087. """
  4088. if not item.filament_overrides:
  4089. return
  4090. try:
  4091. overrides = json.loads(item.filament_overrides)
  4092. override_map = {o["slot_id"]: o for o in overrides}
  4093. for req in filament_reqs:
  4094. if req["slot_id"] in override_map:
  4095. override = override_map[req["slot_id"]]
  4096. req["type"] = override["type"]
  4097. req["color"] = override["color"]
  4098. # A manual/preference override SWAPS the slot's filament, so the
  4099. # 3MF's original tray_info_idx now points at the old spool and must
  4100. # be cleared — matching then falls back to type+colour. A
  4101. # force_color_match override is not a swap: it carries the 3MF's
  4102. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4103. # it here too, letting the matcher pin the correct variant slot on a
  4104. # printer holding two same-colour spools of different variants (#2650).
  4105. # A spool that names no variant still counts; one naming another
  4106. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4107. req["tray_info_idx"] = (
  4108. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4109. )
  4110. # The matcher satisfies a forced slot only the way
  4111. # `_get_missing_force_color_slots` does, never by a similar
  4112. # colour or the type alone (#3280).
  4113. req["force_color_match"] = bool(override.get("force_color_match"))
  4114. logger.debug(
  4115. "Queue item %s: Override slot %d -> %s %s",
  4116. item.id,
  4117. req["slot_id"],
  4118. override["type"],
  4119. override["color"],
  4120. )
  4121. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4122. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4123. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4124. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4125. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4126. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4127. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4128. treated as the filament requirement for that slot and matched against the
  4129. current AMS state of the printer.
  4130. Returns the same format as ``_match_filaments_to_slots``, or None when
  4131. the AMS has no loaded filaments.
  4132. """
  4133. loaded = self._build_loaded_filaments(status)
  4134. if not loaded:
  4135. return None
  4136. reqs = [
  4137. {
  4138. "slot_id": o["slot_id"],
  4139. "type": o.get("type", ""),
  4140. "color": o.get("color", ""),
  4141. # These are all force_color_match overrides, so the idx (when the
  4142. # 3MF carried one) is the intended variant, not a stale swap —
  4143. # keep it so the matcher pins the right variant slot (#2650); a
  4144. # spool naming another variant does not satisfy it (#3280).
  4145. "tray_info_idx": o.get("tray_info_idx", ""),
  4146. "force_color_match": True,
  4147. }
  4148. for o in force_overrides
  4149. ]
  4150. return self._match_filaments_to_slots(reqs, loaded)
  4151. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4152. """Resolve the queue item's source 3MF and parse the per-slot
  4153. filament requirements out of it. Thin DB-resolver wrapper around
  4154. ``filament_requirements.extract_filament_requirements`` so the VP
  4155. queue-mode write path (#1188) can reuse the same parser at upload
  4156. time.
  4157. """
  4158. from backend.app.services.filament_requirements import extract_filament_requirements
  4159. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4160. # so every caller gets its own copy — a shared list would leak one
  4161. # item's overrides into the next item that happens to print the same
  4162. # plate.
  4163. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4164. if memo_key in self._filament_req_memo:
  4165. cached = self._filament_req_memo[memo_key]
  4166. return [dict(r) for r in cached] if cached else None
  4167. file_path: Path | None = None
  4168. if item.archive_id:
  4169. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4170. archive = result.scalar_one_or_none()
  4171. if archive:
  4172. file_path = settings.base_dir / archive.file_path
  4173. elif item.library_file_id:
  4174. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4175. library_file = result.scalar_one_or_none()
  4176. if library_file:
  4177. lib_path = Path(library_file.file_path)
  4178. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4179. if not file_path or not file_path.exists():
  4180. self._filament_req_memo[memo_key] = None
  4181. return None
  4182. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4183. self._filament_req_memo[memo_key] = filaments or None
  4184. return [dict(r) for r in filaments] if filaments else None
  4185. def _build_loaded_filaments(self, status) -> list[dict]:
  4186. """Build list of loaded filaments from printer status.
  4187. Args:
  4188. status: PrinterState from printer_manager
  4189. Returns:
  4190. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4191. """
  4192. filaments = []
  4193. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4194. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4195. # Routes external spools to an extruder (#2771). Mirrors
  4196. # `buildLoadedFilaments` in the frontend.
  4197. vt_trays = status.raw_data.get("vt_tray") or []
  4198. is_dual_nozzle = reports_two_nozzles(status)
  4199. # Parse AMS units from raw_data
  4200. ams_data = status.raw_data.get("ams", [])
  4201. for ams_unit in ams_data:
  4202. ams_id = int(ams_unit.get("id", 0))
  4203. trays = ams_unit.get("tray", [])
  4204. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4205. for tray in trays:
  4206. tray_type = tray.get("tray_type")
  4207. if tray_type:
  4208. tray_id = int(tray.get("id", 0))
  4209. tray_color = tray.get("tray_color", "")
  4210. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4211. tray_info_idx = tray.get("tray_info_idx", "")
  4212. # Normalize color: remove alpha, add hash
  4213. color = self._normalize_color(tray_color)
  4214. # Calculate global tray ID
  4215. # AMS-HT units have IDs starting at 128 with a single tray
  4216. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4217. filaments.append(
  4218. {
  4219. "type": tray_type,
  4220. "color": color,
  4221. # `color` reads a missing colour as #808080; this
  4222. # says whether the printer reported one at all.
  4223. "color_known": bool(tray_color),
  4224. "tray_info_idx": tray_info_idx,
  4225. "ams_id": ams_id,
  4226. "tray_id": tray_id,
  4227. "is_ht": is_ht,
  4228. "is_external": False,
  4229. "global_tray_id": global_tray_id,
  4230. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4231. "remain": tray.get("remain", -1),
  4232. }
  4233. )
  4234. # Check external spool(s) (vt_tray is a list)
  4235. for idx, vt in enumerate(vt_trays):
  4236. if vt.get("tray_type"):
  4237. color = self._normalize_color(vt.get("tray_color", ""))
  4238. tray_id = int(vt.get("id", 254))
  4239. filaments.append(
  4240. {
  4241. "type": vt["tray_type"],
  4242. "color": color,
  4243. "color_known": bool(vt.get("tray_color")),
  4244. "tray_info_idx": vt.get("tray_info_idx", ""),
  4245. "ams_id": -1,
  4246. "tray_id": idx,
  4247. "is_ht": False,
  4248. "is_external": True,
  4249. "global_tray_id": tray_id,
  4250. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4251. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4252. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4253. "remain": vt.get("remain", -1),
  4254. }
  4255. )
  4256. return filaments
  4257. def _normalize_color(self, color: str | None) -> str:
  4258. """Normalize color to #RRGGBB format."""
  4259. if not color:
  4260. return "#808080"
  4261. hex_color = color.replace("#", "")[:6]
  4262. return f"#{hex_color}"
  4263. def _normalize_color_for_compare(self, color: str | None) -> str:
  4264. """Normalize color for comparison (lowercase, no hash)."""
  4265. if not color:
  4266. return ""
  4267. return color.replace("#", "").lower()[:6]
  4268. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4269. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4270. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4271. stays the per-channel box that shipped — this only decides which of
  4272. several eligible spools is closest, so nothing becomes usable or
  4273. unusable because of it.
  4274. It ranks by how far apart the colours *look*, not how far apart their
  4275. numbers are. RGB distance overweights blue badly enough to invert the
  4276. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4277. the nearer of two eligible spools by RGB and the further by a factor of
  4278. four once measured perceptually.
  4279. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4280. transparent filament is not a colour the user chose, and counting it
  4281. would stop a transparent filament matching itself.
  4282. """
  4283. return perceptual_color_distance(color1, color2)
  4284. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4285. """Check if two colors are visually similar within a threshold."""
  4286. hex1 = self._normalize_color_for_compare(color1)
  4287. hex2 = self._normalize_color_for_compare(color2)
  4288. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4289. return False
  4290. try:
  4291. r1 = int(hex1[0:2], 16)
  4292. g1 = int(hex1[2:4], 16)
  4293. b1 = int(hex1[4:6], 16)
  4294. r2 = int(hex2[0:2], 16)
  4295. g2 = int(hex2[2:4], 16)
  4296. b2 = int(hex2[4:6], 16)
  4297. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4298. except ValueError:
  4299. return False
  4300. async def _build_inventory_remain_overrides(
  4301. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4302. ) -> dict[int, float]:
  4303. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4304. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4305. The MQTT ``remain`` field on a tray is the printer firmware's
  4306. RFID-decremented value, which has two limitations the "Prefer Lowest
  4307. Remaining Filament" feature has been ignoring (#1508):
  4308. - it's only meaningful for Bambu RFID spools; everything else reports
  4309. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4310. compare equal and the sort collapses to AMS-slot order — the user
  4311. who's curating inventory weights gets the lower-slot pick instead
  4312. of the lower-remaining pick;
  4313. - even when set, it's the *printer's* counter, not Bambuddy's
  4314. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4315. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4316. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4317. When the user has bound a spool to a slot, their own inventory
  4318. tracking is authoritative; this helper surfaces that value so the
  4319. sort can prefer it. Slots without a binding are absent from the
  4320. returned map — the caller then falls back to MQTT ``remain`` for
  4321. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4322. Returns an empty map on any failure (no inventory bindings, DB
  4323. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4324. is a preference, not a guarantee.
  4325. """
  4326. if not loaded:
  4327. return {}
  4328. # External / virtual-tray slots are tracked separately from AMS — skip
  4329. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4330. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4331. # match is fiddly and out of scope for this fix).
  4332. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4333. if not tracked_slots:
  4334. return {}
  4335. is_spoolman = await self._is_spoolman_mode(db)
  4336. overrides: dict[int, float] = {}
  4337. if is_spoolman:
  4338. result = await db.execute(
  4339. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4340. )
  4341. assignments = list(result.scalars().all())
  4342. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4343. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4344. for ams_id, tray_id, gtid in tracked_slots:
  4345. spoolman_id = by_slot.get((ams_id, tray_id))
  4346. if spoolman_id is None:
  4347. continue
  4348. grams = await _spoolman_remaining_grams(spoolman_id)
  4349. if grams is not None:
  4350. overrides[gtid] = grams
  4351. return overrides
  4352. # Internal inventory mode (default). selectinload matches the pattern
  4353. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4354. # plus an eager-loaded relationship rather than an explicit join, so
  4355. # the row-attribute shape is exactly what those routes already rely on.
  4356. result = await db.execute(
  4357. select(SpoolAssignment)
  4358. .options(selectinload(SpoolAssignment.spool))
  4359. .where(SpoolAssignment.printer_id == printer_id)
  4360. )
  4361. assignments = list(result.scalars().all())
  4362. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4363. for ams_id, tray_id, gtid in tracked_slots:
  4364. spool = by_slot.get((ams_id, tray_id))
  4365. if spool is None:
  4366. continue
  4367. label = float(spool.label_weight or 0)
  4368. used = float(spool.weight_used or 0)
  4369. overrides[gtid] = max(0.0, label - used)
  4370. return overrides
  4371. @staticmethod
  4372. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4373. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4374. here to avoid making this module import-dependent on that private
  4375. helper's signature."""
  4376. try:
  4377. from backend.app.api.routes.settings import get_setting
  4378. v = await get_setting(db, "spoolman_enabled")
  4379. return bool(v) and v.lower() == "true"
  4380. except Exception:
  4381. return False
  4382. @staticmethod
  4383. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4384. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4385. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4386. so a tied sort produces the same physical-position order the pre-#1508
  4387. stable sort did (preserves the regression-free baseline):
  4388. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4389. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4390. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4391. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4392. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4393. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4394. """
  4395. if ams_id is None or ams_id < 0:
  4396. return 10_000
  4397. if ams_id >= 128:
  4398. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4399. return ams_id * 4 + (tray_id or 0)
  4400. @staticmethod
  4401. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4402. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4403. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4404. non-tracked spools (the user has told us they care about these
  4405. specifically), then ascending by remaining within each tier, then
  4406. ascending by AMS slot position as the deterministic tie-breaker.
  4407. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4408. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4409. because the tier flag dominates — which is what lets us mix grams
  4410. (inventory) and percent (MQTT) without a unit conversion.
  4411. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4412. spools the printer DOES know something about sort ahead of those
  4413. it knows nothing about — preserves pre-#1508 behaviour for the
  4414. no-inventory-binding case.
  4415. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4416. external on ties, matching the legacy emission-order stable sort.
  4417. """
  4418. gtid = f.get("global_tray_id")
  4419. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4420. if overrides and gtid in overrides:
  4421. return (0, overrides[gtid], slot_order)
  4422. remain = f.get("remain", -1)
  4423. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4424. def _match_filaments_to_slots(
  4425. self,
  4426. required: list[dict],
  4427. loaded: list[dict],
  4428. prefer_lowest: bool = False,
  4429. inventory_remain_overrides: dict[int, float] | None = None,
  4430. fts_installed: bool = False,
  4431. ) -> list[int] | None:
  4432. """Match required filaments to loaded filaments and build AMS mapping.
  4433. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4434. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4435. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4436. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4437. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4438. matching among those trays.
  4439. Args:
  4440. required: List of required filaments with slot_id, type, color, tray_info_idx
  4441. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4442. Returns:
  4443. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4444. """
  4445. if not required:
  4446. return None
  4447. # Track used trays to avoid duplicate assignment
  4448. used_tray_ids: set[int] = set()
  4449. comparisons = []
  4450. # Forced slots first: a slot that would take any tray of its type must
  4451. # not take the one tray a forced slot can use (#3280). The mapping is
  4452. # built by slot_id below, so the order only decides who goes first.
  4453. # Among forced slots, those naming a variant first, as
  4454. # `_get_missing_force_color_slots` counts them.
  4455. for req in sorted(
  4456. required,
  4457. key=lambda r: (
  4458. not r.get("force_color_match"),
  4459. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4460. ),
  4461. ):
  4462. req_type = (req.get("type") or "").upper()
  4463. req_color = req.get("color", "")
  4464. req_tray_info_idx = req.get("tray_info_idx", "")
  4465. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4466. idx_match = None
  4467. exact_match = None
  4468. similar_match = None
  4469. similar_distance = float("inf")
  4470. type_only_match = None
  4471. # Get available trays (not already used)
  4472. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4473. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4474. # Hard filter — cross-nozzle assignment causes print failures
  4475. # ("position of left hotend is abnormal"), so never fall back.
  4476. # Skipped when an FTS is installed: it routes any AMS slot to either
  4477. # extruder, so restricting to one nozzle would wrongly exclude the
  4478. # correct spool sitting in the other nozzle's AMS (#2186).
  4479. req_nozzle_id = req.get("nozzle_id")
  4480. if req_nozzle_id is not None and not fts_installed:
  4481. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4482. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4483. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4484. # _prefer_lowest_sort_key for the full rationale.
  4485. if prefer_lowest:
  4486. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4487. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4488. # One line per filament req so a bug report can be diagnosed
  4489. # without enabling debug logging: shows what the matcher saw
  4490. # (req shape + sorted candidate trays with their remain values
  4491. # and any inventory override that was applied). Mirrored by
  4492. # the picked-match log at the bottom of the loop.
  4493. logger.info(
  4494. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4495. req.get("slot_id"),
  4496. req_type,
  4497. req_color,
  4498. req_tray_info_idx,
  4499. req_nozzle_id,
  4500. [
  4501. {
  4502. "gtid": f.get("global_tray_id"),
  4503. "type": f.get("type"),
  4504. "color": f.get("color"),
  4505. "tii": f.get("tray_info_idx"),
  4506. "remain": f.get("remain"),
  4507. "inv_g": (
  4508. inventory_remain_overrides.get(f.get("global_tray_id"))
  4509. if inventory_remain_overrides
  4510. else None
  4511. ),
  4512. }
  4513. for f in available
  4514. ],
  4515. )
  4516. # A forced slot takes only what `_get_missing_force_color_slots`
  4517. # accepts: same type, exact colour, and the same variant when both
  4518. # sides name one -- preferring the tray that does. Nothing looser:
  4519. # the model-based path holds a job the printer cannot satisfy this
  4520. # way, and a printer-pinned job fell through to type_only and
  4521. # printed in whatever colour came first (#3280).
  4522. forced = bool(req.get("force_color_match"))
  4523. if forced:
  4524. want_type = canonical_filament_type(req_type)
  4525. want_color = self._normalize_color_for_compare(req_color)
  4526. candidates = [
  4527. f
  4528. for f in available
  4529. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4530. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4531. and (
  4532. not req_tray_info_idx
  4533. or not f.get("tray_info_idx")
  4534. or f.get("tray_info_idx") == req_tray_info_idx
  4535. )
  4536. ]
  4537. exact_match = next(
  4538. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4539. candidates[0] if candidates else None,
  4540. )
  4541. # Check if tray_info_idx is unique among available trays
  4542. if req_tray_info_idx and not forced:
  4543. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4544. if len(idx_matches) == 1:
  4545. # Unique tray_info_idx - use it as definitive match
  4546. idx_match = idx_matches[0]
  4547. logger.debug(
  4548. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4549. f"-> tray {idx_match['global_tray_id']}"
  4550. )
  4551. elif len(idx_matches) > 1:
  4552. # Multiple trays with same tray_info_idx - use color matching among them
  4553. logger.debug(
  4554. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4555. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4556. )
  4557. if prefer_lowest:
  4558. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4559. # Use color matching within this subset
  4560. for f in idx_matches:
  4561. f_color = f.get("color", "")
  4562. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4563. if not exact_match:
  4564. exact_match = f
  4565. elif self._colors_are_similar(f_color, req_color):
  4566. distance = self._color_distance(f_color, req_color)
  4567. if distance is not None and distance < similar_distance:
  4568. similar_match = f
  4569. similar_distance = distance
  4570. elif not type_only_match:
  4571. type_only_match = f
  4572. # If no idx_match yet, do standard type/color matching on all available trays
  4573. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4574. for f in available:
  4575. f_type = (f.get("type") or "").upper()
  4576. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4577. continue
  4578. # Type matches - check color
  4579. f_color = f.get("color", "")
  4580. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4581. if not exact_match:
  4582. exact_match = f
  4583. elif self._colors_are_similar(f_color, req_color):
  4584. # Nearest wins, not first-in-tray-order. `available` is
  4585. # already in the caller's order (slot order, or the
  4586. # prefer-lowest sort), and `<` keeps the earliest of
  4587. # equally close spools — so that order survives as the
  4588. # tie-break (#2804).
  4589. distance = self._color_distance(f_color, req_color)
  4590. if distance is not None and distance < similar_distance:
  4591. similar_match = f
  4592. similar_distance = distance
  4593. elif not type_only_match:
  4594. type_only_match = f
  4595. match = idx_match or exact_match or similar_match or type_only_match
  4596. if match:
  4597. used_tray_ids.add(match["global_tray_id"])
  4598. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4599. else:
  4600. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4601. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4602. # "Why did it pick that spool" is the question every wrong-filament
  4603. # report starts with, and a `similar_color` win is now a ranked
  4604. # choice among several eligible spools rather than whichever tray
  4605. # came first, so it is worth being able to see after the fact.
  4606. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4607. # is on (#1766).
  4608. if match:
  4609. bucket = (
  4610. "idx"
  4611. if idx_match is not None
  4612. else "exact_color"
  4613. if exact_match is not None
  4614. else "similar_color"
  4615. if similar_match is not None
  4616. else "type_only"
  4617. )
  4618. logger.info(
  4619. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4620. match["global_tray_id"],
  4621. bucket,
  4622. req.get("slot_id"),
  4623. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4624. )
  4625. else:
  4626. logger.info(
  4627. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4628. req.get("slot_id"),
  4629. req_type,
  4630. req_color,
  4631. req_tray_info_idx,
  4632. ", force color match" if forced else "",
  4633. )
  4634. # Build mapping array
  4635. if not comparisons:
  4636. return None
  4637. max_slot_id = max(c["slot_id"] for c in comparisons)
  4638. if max_slot_id <= 0:
  4639. return None
  4640. mapping = [-1] * max_slot_id
  4641. for c in comparisons:
  4642. slot_id = c["slot_id"]
  4643. if slot_id and slot_id > 0:
  4644. mapping[slot_id - 1] = c["global_tray_id"]
  4645. return mapping
  4646. def _mark_printer_dispatched(
  4647. self,
  4648. printer_id: int,
  4649. pre_state: str | None,
  4650. pre_subtask_id: str | None,
  4651. ) -> None:
  4652. """Record that a print command was just sent to ``printer_id``.
  4653. Held until either the watchdog observes a state/subtask transition
  4654. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4655. """
  4656. if not pre_state:
  4657. # No pre_state means we can't detect a transition — fall back to a
  4658. # pure time-based hold using empty string as a sentinel that won't
  4659. # match any real printer state.
  4660. pre_state = ""
  4661. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4662. def _release_dispatch_hold(self, printer_id: int) -> None:
  4663. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4664. self._dispatch_holds.pop(printer_id, None)
  4665. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4666. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4667. Returns False (and clears the hold) once any of these are true:
  4668. - hard timeout (``_dispatch_max_hold``) has elapsed
  4669. - the printer has transitioned out of pre_state and we're past the
  4670. minimum cooldown
  4671. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4672. past the minimum cooldown
  4673. Otherwise the printer is held — caller should treat it as busy.
  4674. """
  4675. entry = self._dispatch_holds.get(printer_id)
  4676. if not entry:
  4677. return False
  4678. started_at, pre_state, pre_subtask_id = entry
  4679. elapsed = time.monotonic() - started_at
  4680. if elapsed >= self._dispatch_max_hold:
  4681. self._dispatch_holds.pop(printer_id, None)
  4682. return False
  4683. # Without a pre_state we can't detect a transition — fall back to the
  4684. # min cooldown alone, then drop the hold.
  4685. if not pre_state:
  4686. if elapsed >= self._dispatch_min_cooldown:
  4687. self._dispatch_holds.pop(printer_id, None)
  4688. return False
  4689. return True
  4690. status = printer_manager.get_status(printer_id)
  4691. current_state = getattr(status, "state", None) if status else None
  4692. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4693. transitioned = (current_state is not None and current_state != pre_state) or (
  4694. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4695. )
  4696. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4697. self._dispatch_holds.pop(printer_id, None)
  4698. return False
  4699. return True
  4700. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4701. """Check if a printer is connected and idle."""
  4702. if not printer_manager.is_connected(printer_id):
  4703. logger.debug("Printer %d: not connected", printer_id)
  4704. return False
  4705. state = printer_manager.get_status(printer_id)
  4706. if not state:
  4707. logger.debug("Printer %d: no status available", printer_id)
  4708. return False
  4709. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4710. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4711. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4712. # printer, it boots back into IDLE with no memory of the previous finish; without
  4713. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4714. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4715. logger.debug(
  4716. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4717. printer_id,
  4718. state.state,
  4719. )
  4720. return False
  4721. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4722. if not idle:
  4723. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4724. return False
  4725. # A print would run from the SD card the firmware is being written to.
  4726. from backend.app.services.firmware_update import upload_in_progress
  4727. if upload_in_progress(printer_id):
  4728. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4729. return False
  4730. return True
  4731. @staticmethod
  4732. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4733. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4734. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4735. and that the fixed-printer branch has already found connected, so the two
  4736. offline cases answer at their own exits and never arrive here.
  4737. The default is the model-based branch's ``Busy:`` wording, which
  4738. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4739. the right answer for the connected-but-no-telemetry second or two after a
  4740. reconnect: the model-based branch has always reported it that way, and it
  4741. is not something to wake anybody up for.
  4742. A plate nobody has confirmed is the one case here that does not resolve
  4743. itself — somebody has to walk over to the printer — so it is worded as
  4744. itself and allowed to notify.
  4745. """
  4746. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4747. return f"Waiting for plate confirmation: {printer_name}"
  4748. return f"Busy: {printer_name}"
  4749. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4750. """Read a setting value from the database."""
  4751. result = await db.execute(select(Settings).where(Settings.key == key))
  4752. setting = result.scalar_one_or_none()
  4753. return setting.value if setting else None
  4754. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4755. """Read a boolean setting from the database."""
  4756. result = await db.execute(select(Settings).where(Settings.key == key))
  4757. setting = result.scalar_one_or_none()
  4758. if setting:
  4759. return setting.value.lower() == "true"
  4760. return default
  4761. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4762. """Read an int setting; falls back to default on missing/unparseable rows."""
  4763. result = await db.execute(select(Settings).where(Settings.key == key))
  4764. setting = result.scalar_one_or_none()
  4765. if setting and setting.value:
  4766. try:
  4767. return int(setting.value)
  4768. except ValueError:
  4769. pass
  4770. return default
  4771. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4772. """Get drying presets (user-configured or built-in defaults)."""
  4773. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4774. setting = result.scalar_one_or_none()
  4775. if setting and setting.value:
  4776. try:
  4777. presets = json.loads(setting.value)
  4778. if isinstance(presets, dict) and presets:
  4779. return presets
  4780. except json.JSONDecodeError:
  4781. pass
  4782. return self.DEFAULT_DRYING_PRESETS
  4783. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4784. """Per-filament humidity thresholds (#1605).
  4785. Returns the user-configured overrides map keyed by normalized filament
  4786. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4787. unknown / unmapped types. Empty / unset → empty dict, in which case
  4788. callers fall back to ``ams_humidity_fair``.
  4789. """
  4790. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4791. setting = result.scalar_one_or_none()
  4792. if not setting or not setting.value:
  4793. return {}
  4794. try:
  4795. data = json.loads(setting.value)
  4796. except json.JSONDecodeError:
  4797. return {}
  4798. if not isinstance(data, dict):
  4799. return {}
  4800. out: dict[str, int] = {}
  4801. for key, value in data.items():
  4802. try:
  4803. out[str(key).upper() if key != "default" else "default"] = int(value)
  4804. except (TypeError, ValueError):
  4805. continue
  4806. return out
  4807. # Materials whose AMS spelling differs from the key the tables above use.
  4808. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4809. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4810. # good PA row (#3067).
  4811. #
  4812. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4813. # The drying popover has resolved these correctly since #2774 and the
  4814. # scheduler never did, which is exactly why #3067's reporter could dry a
  4815. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4816. #
  4817. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4818. # of nylon, so it is the one entry that is a judgement rather than a
  4819. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4820. # way, and PA's row is the hottest the table has. Drying it there is closer
  4821. # to right than not drying it at all, which is what it got before.
  4822. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4823. "NYLON": "PA",
  4824. "PA6": "PA",
  4825. "PA11": "PA",
  4826. "PA12": "PA",
  4827. "PAHT": "PA",
  4828. "PPA": "PA",
  4829. }
  4830. @classmethod
  4831. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4832. """The key in *table* that answers for this tray's material, or None.
  4833. The printer reports the material in ``tray_type``, and it spells filled
  4834. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4835. tables here are keyed by base material, so matching the raw string alone
  4836. found a row for 8 of the 41 types a printer can report and skipped the
  4837. rest -- silently, because every caller reads "no row" as "nothing to do
  4838. for this tray". Auto-drying therefore ignored every composite spool on
  4839. the install (#3067).
  4840. Exact match first, so a table the user has extended with a row of its
  4841. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4842. base material's. Then the suffix is dropped, then the alias map above
  4843. answers for the polyamide spellings.
  4844. Returns None rather than a default: what to do with an unrecognised
  4845. material differs per caller, and only the caller knows whether "no row"
  4846. means skip the tray or fall back to a catch-all. Nothing here invents a
  4847. temperature for a material the table does not list.
  4848. """
  4849. raw = cls._normalize_filament_type(tray_type or "")
  4850. if not raw:
  4851. return None
  4852. for candidate in (raw, raw.split("-")[0]):
  4853. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4854. if key in table:
  4855. return key
  4856. return None
  4857. @staticmethod
  4858. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4859. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4860. For mixed filament types loaded into one AMS, returns the most
  4861. restrictive (lowest) threshold across all loaded tray types — matches
  4862. the conservative-params strategy already used for drying temp/hours.
  4863. Empty / unloaded trays contribute no constraint. Unknown types use the
  4864. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4865. when no per-type map is configured at all.
  4866. """
  4867. default = thresholds.get("default", fallback)
  4868. if not thresholds:
  4869. return fallback
  4870. candidates: list[int] = []
  4871. for tray in trays:
  4872. tray_type = str(tray.get("tray_type") or "").strip()
  4873. if not tray_type:
  4874. continue
  4875. # A composite carries its base material's threshold when it has no
  4876. # row of its own, the same way it takes its drying preset (#3067).
  4877. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4878. candidates.append(thresholds[key] if key is not None else default)
  4879. if not candidates:
  4880. return default
  4881. return min(candidates)
  4882. def _get_conservative_drying_params(
  4883. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4884. ) -> tuple[int, int, str] | None:
  4885. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4886. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4887. """
  4888. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4889. hours_key = f"{temp_key}_hours"
  4890. min_temp = None
  4891. max_hours = None
  4892. filament_type = ""
  4893. for tray in trays:
  4894. tray_type = tray.get("tray_type", "")
  4895. if not tray_type:
  4896. continue
  4897. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4898. # which is what stopped auto-drying on every composite spool (#3067).
  4899. base_type = self._resolve_filament_key(tray_type, presets)
  4900. if base_type is None:
  4901. continue
  4902. # The table is user-editable JSON with no per-row validation, so a
  4903. # row can be present and empty. That has always meant "skip this
  4904. # material", and it has to keep meaning it: the reads below fall
  4905. # back to 55C/12h per missing field, which is a temperature nobody
  4906. # chose and would deform a PLA spool.
  4907. preset = presets[base_type]
  4908. if not preset:
  4909. continue
  4910. temp = preset.get(temp_key, 55)
  4911. hours = preset.get(hours_key, 12)
  4912. # Conservative: lowest temp, longest duration
  4913. if min_temp is None or temp < min_temp:
  4914. min_temp = temp
  4915. if max_hours is None or hours > max_hours:
  4916. max_hours = hours
  4917. if not filament_type:
  4918. filament_type = base_type
  4919. if min_temp is None:
  4920. return None
  4921. return (min_temp, max_hours or 12, filament_type)
  4922. async def _check_filament_low(self, db: AsyncSession) -> None:
  4923. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4924. ``on_filament_low`` has had a column, a schema field, a route, a template
  4925. and a UI toggle since the notification system was built, and no caller --
  4926. so the toggle could be switched on and could never fire. This is the
  4927. producer.
  4928. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4929. ``low_stock_threshold_pct`` override is already exactly this decision:
  4930. already configurable, already surfaced, already driving the Inventory
  4931. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4932. consulted -- it has been measured up to 56 points out against a scale,
  4933. which is not a number to page someone on.
  4934. Only slots with an assigned spool produce an event. A slot Bambuddy
  4935. cannot resolve to a spool has no remaining weight it can stand behind,
  4936. and guessing one is how the remain percentage would have got in.
  4937. """
  4938. from backend.app.models.spool import Spool
  4939. # Time-gated rather than run on every pass. run() sleeps
  4940. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4941. # early-return path counts as productive while an upload is in flight
  4942. # (#2602), so an unthrottled check would re-read the whole spool
  4943. # collection every 3 seconds for the length of a batch drain. In
  4944. # Spoolman mode that is a request storm against a third-party service,
  4945. # which is the thing this producer's design note argues against; and
  4946. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4947. # check_queue holding the scheduler's session, so the outage would
  4948. # throttle the print queue itself. A low spool is not a 3-second
  4949. # concern -- the idle interval is the natural resolution.
  4950. now = time.monotonic()
  4951. if now < self._filament_low_next_check:
  4952. return
  4953. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4954. try:
  4955. # on_filament_low defaults to off on every provider, so on most
  4956. # installs nobody wants this alert. Without this the check would
  4957. # still read every assigned spool each interval -- the whole
  4958. # collection over HTTP in Spoolman mode -- for an event that is
  4959. # switched off. One query against the provider table settles it
  4960. # before any spool work, the same guard the bed-cooled waiter uses.
  4961. # No printer_id: this asks whether any provider wants the event at
  4962. # all; per-printer scoping is applied when the event is sent.
  4963. #
  4964. # While nobody wants it, no pass sees a slot go back above its
  4965. # threshold, so nothing can re-arm; a spool refilled under the same
  4966. # id in that time would stay silenced until a restart. Forgetting
  4967. # what was sent is right anyway: whoever switches the event back on
  4968. # is told about the spools that are low now.
  4969. #
  4970. # The MQTT relay publishes the same event, so a connected relay is
  4971. # reason enough to run the check. Its record is forgotten when the
  4972. # relay is switched off, not when the broker drops: a reconnect must
  4973. # not re-send every low slot.
  4974. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4975. relay = mqtt_relay.enabled and mqtt_relay.connected
  4976. if not notify:
  4977. self._notified_filament_low.clear()
  4978. if not mqtt_relay.enabled:
  4979. self._relayed_filament_low.clear()
  4980. if not notify and not relay:
  4981. return
  4982. global_threshold = await self._get_low_stock_threshold(db)
  4983. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4984. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4985. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4986. if spoolman_on:
  4987. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4988. else:
  4989. rows = (
  4990. await db.execute(
  4991. select(SpoolAssignment, Spool)
  4992. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4993. # An archived spool is not stock. The Inventory page's
  4994. # Low Stock count skips them (InventoryPage.tsx:1089)
  4995. # and get_all_spools without allow_archived already
  4996. # excludes them in Spoolman mode, so without this the
  4997. # internal path is the only one that alerts on them.
  4998. .where(Spool.archived_at.is_(None))
  4999. )
  5000. ).all()
  5001. for assignment, spool in rows:
  5002. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  5003. if pct is None:
  5004. continue
  5005. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  5006. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  5007. pct,
  5008. threshold,
  5009. spool.color_name,
  5010. )
  5011. if not slots:
  5012. # Nothing resolvable this pass. Deliberately not clearing the
  5013. # notified set: a Spoolman that is briefly unreachable would
  5014. # otherwise re-alert on every spool as soon as it came back.
  5015. return
  5016. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  5017. except Exception as e:
  5018. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  5019. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  5020. """The global low-stock percentage, defaulting to the schema's 20.0."""
  5021. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  5022. if raw is None or raw.value is None:
  5023. return 20.0
  5024. try:
  5025. value = float(raw.value)
  5026. except (TypeError, ValueError):
  5027. return 20.0
  5028. return value if 0 < value <= 100 else 20.0
  5029. async def _filament_low_slots_spoolman(
  5030. self, db: AsyncSession, global_threshold: float
  5031. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  5032. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  5033. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  5034. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  5035. so the global threshold is the only one that applies here. That matches
  5036. what the Inventory page already does in this mode.
  5037. One ``get_all_spools`` call covers every slot rather than a request per
  5038. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  5039. without ``allow_archived`` -- which is the behaviour the internal path
  5040. has to ask for explicitly.
  5041. An unreachable Spoolman returns no slots rather than raising. It is an
  5042. ordinary state for a third-party service, not an error in this pass: the
  5043. caller's "nothing resolvable" branch already leaves the notified set
  5044. alone, which is exactly right here, whereas letting it reach the broad
  5045. ``except`` would write a full traceback every time the check runs.
  5046. """
  5047. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5048. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5049. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  5050. if not assignments:
  5051. return {}
  5052. client = await get_spoolman_client()
  5053. if client is None:
  5054. return {}
  5055. try:
  5056. all_spools = await client.get_all_spools()
  5057. except SpoolmanUnavailableError as e:
  5058. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  5059. return {}
  5060. by_id: dict[int, dict] = {}
  5061. for raw in all_spools:
  5062. raw_id = raw.get("id")
  5063. if isinstance(raw_id, int):
  5064. by_id[raw_id] = raw
  5065. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5066. for assignment in assignments:
  5067. raw = by_id.get(assignment.spoolman_spool_id)
  5068. if raw is None:
  5069. continue
  5070. try:
  5071. mapped = _map_spoolman_spool(raw)
  5072. except ValueError:
  5073. continue
  5074. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  5075. if pct is None:
  5076. continue
  5077. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  5078. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  5079. return slots
  5080. async def _emit_filament_low(
  5081. self,
  5082. db: AsyncSession,
  5083. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  5084. *,
  5085. notify: bool = True,
  5086. relay: bool = False,
  5087. ) -> None:
  5088. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  5089. printers: dict[int, Printer] = {}
  5090. for key, (pct, threshold, color) in slots.items():
  5091. printer_id, ams_id, tray_id, spool_id = key
  5092. if pct >= threshold:
  5093. # Back above the line: re-arm rather than expire on a timer, so a
  5094. # refilled slot can alert again and a spool sitting just under the
  5095. # threshold stays quiet.
  5096. self._notified_filament_low.discard(key)
  5097. self._relayed_filament_low.discard(key)
  5098. continue
  5099. send_notification = notify and key not in self._notified_filament_low
  5100. # Only while connected, so a crossing the relay missed reaches it
  5101. # after the reconnect.
  5102. send_relay = relay and key not in self._relayed_filament_low
  5103. if not send_notification and not send_relay:
  5104. continue
  5105. # Marked before sending, which is a choice rather than the only
  5106. # option, and it is the opposite failure mode from the one the
  5107. # debounce argues against: one transient provider failure loses this
  5108. # alert until the spool goes back above the threshold and crosses it
  5109. # again. Marking after a successful send would trade that for
  5110. # re-alerting on every pass while a provider is down -- which is the
  5111. # repetition the whole debounce exists to prevent, and the louder of
  5112. # the two failures. A spool that is low stays low, so the next real
  5113. # signal is not far away; a provider stuck retrying is a signal that
  5114. # never stops.
  5115. if send_notification:
  5116. self._notified_filament_low.add(key)
  5117. if send_relay:
  5118. self._relayed_filament_low.add(key)
  5119. if printer_id not in printers:
  5120. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5121. if printer is None:
  5122. continue
  5123. printers[printer_id] = printer
  5124. printer = printers[printer_id]
  5125. slot = _ams_slot_label(ams_id, tray_id)
  5126. if send_notification:
  5127. try:
  5128. await notification_service.on_filament_low(
  5129. printer_id,
  5130. printer.name,
  5131. slot,
  5132. int(pct),
  5133. db,
  5134. color=color,
  5135. )
  5136. except Exception as e:
  5137. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5138. if send_relay:
  5139. try:
  5140. await mqtt_relay.on_filament_low(
  5141. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5142. )
  5143. except Exception as e:
  5144. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5145. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5146. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5147. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5148. a schema field, a template and a UI toggle, and nothing that computes the
  5149. condition -- the Forecast panel does it in the browser, so with no page
  5150. open nothing could ever alert. This runs the same arithmetic
  5151. (``stock_forecast``) from the scheduler loop.
  5152. An alert is sent when a SKU *moves into* a condition, once, and again
  5153. after the condition has cleared. A SKU that worsens from reorder to break
  5154. alerts again as a break, because the panel treats the two as exclusive; one
  5155. that eases from break back to reorder does not alert again.
  5156. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5157. while it is still low tells you.
  5158. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5159. loop runs every 3 s while an upload is in flight, and the whole spool
  5160. collection is read over HTTP in Spoolman mode. Both events default to off
  5161. on every provider, so nothing is read unless a provider wants one.
  5162. """
  5163. now = time.monotonic()
  5164. if now < self._stock_forecast_next_check:
  5165. return
  5166. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5167. try:
  5168. if self._stock_alerts_persisted is None:
  5169. await self._load_stock_alerts(db)
  5170. wanted = {
  5171. "reorder": bool(
  5172. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5173. ),
  5174. "break": bool(
  5175. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5176. ),
  5177. }
  5178. if not any(wanted.values()):
  5179. # Nobody wants either event. Forget what was sent, so whoever
  5180. # switches one on is told about the SKUs that are low now.
  5181. self._notified_stock_alerts.clear()
  5182. await self._save_stock_alerts(db)
  5183. return
  5184. forecasts = await self._stock_forecasts(db)
  5185. if forecasts is None:
  5186. # Spoolman unreachable. Deliberately not clearing the notified
  5187. # set: a brief outage would otherwise re-alert every SKU when it
  5188. # came back.
  5189. return
  5190. await self._emit_stock_alerts(db, forecasts, wanted)
  5191. await self._save_stock_alerts(db)
  5192. except Exception as e:
  5193. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5194. def _serialize_stock_alerts(self) -> str:
  5195. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5196. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5197. return json.dumps(rows)
  5198. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5199. """Read the notified set saved by the last run, once per process.
  5200. A missing or unreadable row is an empty set: the worst that does is one
  5201. repeat of what a restart used to cause every time.
  5202. """
  5203. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5204. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5205. if raw and raw.value:
  5206. try:
  5207. for key, kind, events in json.loads(raw.value):
  5208. if len(key) == 4 and kind in ("reorder", "break"):
  5209. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5210. except (ValueError, TypeError):
  5211. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5212. loaded = {}
  5213. self._notified_stock_alerts = loaded
  5214. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5215. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5216. """Write the notified set to its settings row if it changed since it was last read or written."""
  5217. serialized = self._serialize_stock_alerts()
  5218. if serialized == self._stock_alerts_persisted:
  5219. return
  5220. from backend.app.core.db_dialect import upsert_setting
  5221. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5222. await db.commit()
  5223. self._stock_alerts_persisted = serialized
  5224. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5225. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5226. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5227. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5228. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5229. sku_settings = {
  5230. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5231. lead_time_days=row.lead_time_days,
  5232. safety_margin_value=row.safety_margin_value,
  5233. safety_margin_unit=row.safety_margin_unit,
  5234. alerts_snoozed=bool(row.alerts_snoozed),
  5235. )
  5236. for row in sku_rows
  5237. }
  5238. if await self._get_bool_setting(db, "spoolman_enabled"):
  5239. spools = await self._stock_spools_spoolman()
  5240. if spools is None:
  5241. return None
  5242. # Spoolman owns the usage in this mode and Bambuddy's own history
  5243. # table holds nothing for those spools, so the rate is always the
  5244. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  5245. # are local spool ids, and a Spoolman id that happens to match one
  5246. # (left over from before Spoolman was switched on) would borrow an
  5247. # unrelated spool's history.
  5248. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5249. else:
  5250. spools = await self._stock_spools_internal(db)
  5251. history = await self._stock_usage_history(db)
  5252. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5253. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5254. from backend.app.models.spool import Spool
  5255. # Stock, and the spools archived recently enough to count towards the
  5256. # rate (stock_forecast.archived_counts decides; this only trims the read).
  5257. cutoff = utcnow_naive() - timedelta(days=stock_forecast.ARCHIVED_RATE_WINDOW_DAYS + 1)
  5258. rows = (
  5259. (await db.execute(select(Spool).where(or_(Spool.archived_at.is_(None), Spool.archived_at >= cutoff))))
  5260. .scalars()
  5261. .all()
  5262. )
  5263. return [
  5264. stock_forecast.StockSpool(
  5265. id=spool.id,
  5266. material=spool.material,
  5267. subtype=spool.subtype,
  5268. brand=spool.brand,
  5269. color_name=spool.color_name,
  5270. label_weight=float(spool.label_weight or 0),
  5271. weight_used=float(spool.weight_used or 0),
  5272. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5273. created_at=spool.created_at,
  5274. archived_at=spool.archived_at,
  5275. )
  5276. for spool in rows
  5277. ]
  5278. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  5279. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5280. rows = (
  5281. await db.execute(
  5282. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5283. .order_by(SpoolUsageHistory.created_at.desc())
  5284. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5285. )
  5286. ).all()
  5287. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5288. for spool_id, created_at, weight_used in rows:
  5289. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5290. # filtered before the limit, so the window matches the forecast panel's.
  5291. if created_at is None or spool_id is None:
  5292. continue
  5293. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5294. return history
  5295. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5296. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5297. Archived ones too: a recently used-up spool counts towards its SKU's
  5298. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5299. page (and so the panel) reads; it dates archiving by the spool's last
  5300. use, as Spoolman records no archive date.
  5301. """
  5302. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5303. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5304. client = await get_spoolman_client()
  5305. if client is None:
  5306. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5307. return None
  5308. try:
  5309. raw_spools = await client.get_all_spools(allow_archived=True)
  5310. except SpoolmanUnavailableError as e:
  5311. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5312. return None
  5313. spools: list[stock_forecast.StockSpool] = []
  5314. for raw in raw_spools:
  5315. try:
  5316. mapped = _map_spoolman_spool(raw)
  5317. except ValueError:
  5318. continue
  5319. created_at = _spoolman_time(mapped.get("created_at"))
  5320. archived_at = None
  5321. if raw.get("archived"):
  5322. # Archived without a date to tell when: not stock, and too old to
  5323. # count towards the rate.
  5324. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5325. spools.append(
  5326. stock_forecast.StockSpool(
  5327. id=mapped["id"],
  5328. material=mapped["material"],
  5329. subtype=mapped.get("subtype"),
  5330. brand=mapped.get("brand"),
  5331. color_name=mapped.get("color_name"),
  5332. label_weight=float(mapped.get("label_weight") or 0),
  5333. weight_used=float(mapped.get("weight_used") or 0),
  5334. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5335. created_at=created_at,
  5336. archived_at=archived_at,
  5337. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5338. )
  5339. )
  5340. return spools
  5341. async def _emit_stock_alerts(
  5342. self,
  5343. db: AsyncSession,
  5344. forecasts: stock_forecast.ForecastMap,
  5345. wanted: dict[str, bool],
  5346. ) -> None:
  5347. """Send the notifications for each SKU that has moved into a stock alert condition.
  5348. A SKU in break has also reached its reorder point, so both events apply to
  5349. it: the break event goes to providers that have it on, and the reorder event
  5350. to the providers that have only that one on. A provider with both on gets the
  5351. break and no second message.
  5352. What is remembered per SKU is the condition and which events had a
  5353. subscriber when it was sent. An event with no subscriber is forgotten, so
  5354. switching it on later reports the SKUs already in that condition.
  5355. """
  5356. active_events = {event for event, on in wanted.items() if on}
  5357. for key, (forecast, spool) in forecasts.items():
  5358. kind: str | None = None
  5359. if not forecast.snoozed:
  5360. if forecast.stock_break_alert:
  5361. kind = "break"
  5362. elif forecast.reorder_alert:
  5363. kind = "reorder"
  5364. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5365. events = applicable & active_events
  5366. if not events:
  5367. self._notified_stock_alerts.pop(key, None)
  5368. continue
  5369. previous = self._notified_stock_alerts.get(key)
  5370. told = (previous[1] & active_events) if previous else frozenset()
  5371. # Trimmed to the events this condition can send. That is what makes easing from
  5372. # break back to reorder silent (the reorder event was told with the break) and
  5373. # worsening again news again (the break event is no longer remembered).
  5374. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5375. # Recorded before sending, for the reason _emit_filament_low gives: a
  5376. # provider that is down should lose this alert, not repeat it every hour.
  5377. to_send = events - told
  5378. # Both flags imply a positive rate and so a day count.
  5379. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5380. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5381. color = None if spool.color_name_is_synthesized else spool.color_name
  5382. try:
  5383. if "break" in to_send:
  5384. await notification_service.on_stock_break_alert(
  5385. spool.material,
  5386. spool.brand,
  5387. forecast.remaining_g,
  5388. rate,
  5389. days_left,
  5390. forecast.effective_lead_time_days,
  5391. db,
  5392. subtype=spool.subtype,
  5393. color=color,
  5394. )
  5395. if "reorder" in to_send:
  5396. await notification_service.on_stock_reorder_alert(
  5397. spool.material,
  5398. spool.brand,
  5399. forecast.remaining_g,
  5400. rate,
  5401. days_left,
  5402. db,
  5403. subtype=spool.subtype,
  5404. color=color,
  5405. skip_break_subscribers=kind == "break",
  5406. )
  5407. except Exception as e:
  5408. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5409. # A SKU with no spools left is no longer alerting.
  5410. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5411. del self._notified_stock_alerts[key]
  5412. @staticmethod
  5413. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5414. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5415. from backend.app.core.auth import is_auth_enabled
  5416. if user_id is None or not await is_auth_enabled(db):
  5417. return ALL_PRINTERS
  5418. return await resolve_user_id_printer_scope(db, user_id)
  5419. async def _model_job_printer_ids(
  5420. self,
  5421. db: AsyncSession,
  5422. item: PrintQueueItem,
  5423. scope: PrinterScope,
  5424. cache: dict[tuple[str, str | None, int | None], set[int]],
  5425. ) -> set[int]:
  5426. """Every printer an "Any <model>" job could land on: the active printers
  5427. of each of its candidate models, in its location, that its creator may use.
  5428. ``cache`` holds one lookup per model, location and creator for the pass,
  5429. so a long queue of model jobs does not query once per job."""
  5430. printer_ids: set[int] = set()
  5431. for candidate in _candidates_for(item):
  5432. if not candidate.target_model:
  5433. continue
  5434. key = (candidate.target_model, item.target_location, item.created_by_id)
  5435. if key not in cache:
  5436. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5437. cache[key] = {printer.id for printer in printers}
  5438. printer_ids |= cache[key]
  5439. return printer_ids
  5440. async def _check_auto_drying(
  5441. self,
  5442. db: AsyncSession,
  5443. queue_items: list[PrintQueueItem],
  5444. dispatching_printers: set[int],
  5445. ):
  5446. """Start drying on idle printers based on humidity.
  5447. Three modes (can all be enabled independently):
  5448. - queue_drying_enabled: Dry between scheduled queue prints
  5449. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5450. - print_drying_enabled: Also evaluate printers that are currently printing,
  5451. when model+firmware supports "Print While Drying" (gated by
  5452. supports_drying_while_printing). Drying temperature is capped at
  5453. max(40, preset_temp - 5) to protect spools mid-print.
  5454. """
  5455. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5456. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5457. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5458. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5459. # The wait belongs to ambient drying: the settings UI only shows it while
  5460. # ambient drying is on, so a value left behind when ambient is turned off
  5461. # must not keep delaying the one path that still reaches the wait gate
  5462. # without it (a mid-print start under print_drying).
  5463. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5464. # Clear every streak as soon as the wait is inactive. An early return (or
  5465. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5466. # a quick toggle-on inherit an old streak.
  5467. if not sustained_wait_active:
  5468. self._auto_dry_above.clear()
  5469. if not queue_drying_enabled and not ambient_drying_enabled:
  5470. # Stop active drying on all printers if both features disabled
  5471. if self._drying_in_progress:
  5472. for pid in list(self._drying_in_progress):
  5473. if pid in self._scheduled_drying_printer_ids:
  5474. continue
  5475. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5476. await self._stop_drying(pid)
  5477. return
  5478. # Update drying state from printer status (handles backend restart)
  5479. self._sync_drying_state()
  5480. # Find printers with scheduled items (for queue drying mode)
  5481. # An "Any <model>" job counts for every printer it could land on.
  5482. printers_with_scheduled: set[int] = set()
  5483. # Printers with a job that could start now: the ones block mode keeps
  5484. # a new cycle off. A job waiting for its start time is what queue
  5485. # drying dries ahead of.
  5486. printers_with_ready_items: set[int] = set()
  5487. now_utc = datetime.now(timezone.utc)
  5488. creator_scopes: dict[int | None, PrinterScope] = {}
  5489. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5490. for item in queue_items:
  5491. if item.printer_id:
  5492. item_printers = {item.printer_id}
  5493. elif item.target_model or item.variants:
  5494. if item.created_by_id not in creator_scopes:
  5495. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5496. item_printers = await self._model_job_printer_ids(
  5497. db, item, creator_scopes[item.created_by_id], model_printers
  5498. )
  5499. else:
  5500. continue
  5501. if item.scheduled_time and not item.manual_start:
  5502. printers_with_scheduled |= item_printers
  5503. sched = item.scheduled_time
  5504. if sched is not None and sched.tzinfo is None:
  5505. sched = sched.replace(tzinfo=timezone.utc)
  5506. if sched is None or sched <= now_utc:
  5507. printers_with_ready_items |= item_printers
  5508. # If only queue mode is on and no printers have scheduled items, stop drying
  5509. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5510. # may still be eligible for mid-print drying regardless of queue state).
  5511. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5512. for pid in list(self._drying_in_progress):
  5513. if pid in self._scheduled_drying_printer_ids:
  5514. continue
  5515. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5516. await self._stop_drying(pid)
  5517. return
  5518. # Get humidity threshold (global fallback)
  5519. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5520. setting = result.scalar_one_or_none()
  5521. global_humidity_threshold = int(setting.value) if setting else 60
  5522. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5523. # to the global threshold for every AMS unit.
  5524. per_type_thresholds = await self._get_humidity_thresholds(db)
  5525. # Get drying presets
  5526. presets = await self._get_drying_presets(db)
  5527. # Determine if drying should be skipped for printers with pending items
  5528. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5529. # Get all active printers
  5530. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5531. for printer in all_printers.scalars():
  5532. pid = printer.id
  5533. # Resolve model+firmware up front — needed to decide whether this printer
  5534. # qualifies for mid-print drying (busy printer on capable hardware).
  5535. state = printer_manager.get_status(pid)
  5536. if not state:
  5537. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5538. continue
  5539. model = printer_manager.get_model(pid)
  5540. firmware = state.firmware_version
  5541. # "Mid-print" has to mean the printer is actually printing (#2801).
  5542. # It used to be inferred from the dispatch set, which also holds
  5543. # printers that merely could not be dispatched to -- so a printer
  5544. # sitting in FINISH behind an unacknowledged plate was treated as
  5545. # printing, had its drying temperature capped by the mid-print
  5546. # spool protection, and was logged as (mid-print) while idle.
  5547. is_printing = state.state in _ACTIVE_PRINT_STATES
  5548. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5549. # A printer whose print is running or imminent is left alone unless
  5550. # it can dry through it. `dispatching_printers` is deliberately the
  5551. # narrow set: running, held post-dispatch, or mid-upload.
  5552. if (is_printing or pid in dispatching_printers) and not mid_print:
  5553. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5554. continue
  5555. if not mid_print:
  5556. # In queue-only mode, only dry printers that have scheduled prints
  5557. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5558. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5559. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5560. await self._stop_drying(pid)
  5561. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5562. continue
  5563. # When block mode is on, don't START new drying on printers with
  5564. # a job that could start now: the cycle would hold it. One
  5565. # scheduled for later may pre-dry; if the cycle is still running
  5566. # at its time, the hold applies then. Already-drying printers go
  5567. # through so humidity auto-stop logic still runs.
  5568. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5569. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5570. continue
  5571. if not printer_manager.is_connected(pid):
  5572. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5573. continue
  5574. # Plate-clear is deliberately ignored here (#2801). It answers
  5575. # "is the bed ready for the next job", which says nothing about
  5576. # whether the AMS may heat -- and the gap between a finished print
  5577. # and the acknowledgment is exactly when drying is most useful,
  5578. # because the printer is free and nobody is waiting on it. Leaving
  5579. # the plate unacknowledged is also how people hold the queue by
  5580. # hand, and that hold should not cost them their drying.
  5581. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5582. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5583. continue
  5584. # Check drying capability. For mid-print path, supports_drying_while_printing
  5585. # was already verified when computing mid_print above.
  5586. if not mid_print and not supports_drying(model, firmware):
  5587. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5588. continue
  5589. # Check each AMS unit from raw_data
  5590. ams_list = state.raw_data.get("ams", [])
  5591. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5592. for ams_data in ams_list:
  5593. module_type = str(ams_data.get("module_type") or "")
  5594. ams_id = int(ams_data.get("id", 0))
  5595. # Only n3f/n3s support drying
  5596. if module_type not in ("n3f", "n3s"):
  5597. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5598. continue
  5599. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5600. # Most-restrictive of all loaded tray types; falls back to the
  5601. # global threshold when no overrides are configured.
  5602. trays = ams_data.get("tray", []) or []
  5603. humidity_threshold = self.resolve_humidity_threshold(
  5604. trays, per_type_thresholds, global_humidity_threshold
  5605. )
  5606. dry_time = int(ams_data.get("dry_time") or 0)
  5607. # Read humidity as a percentage. The 1-5 index is never
  5608. # substituted: it is inverted, and being unable to exceed any
  5609. # threshold it would read as "dry" forever (#3140). ``None``
  5610. # already means "skip this unit" everywhere below.
  5611. humidity_pct = ams_humidity_percent(ams_data)
  5612. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5613. unit_key = (pid, ams_id)
  5614. unit_state = self._auto_dry_units.get(unit_key)
  5615. # Already drying — let it run to its configured duration (#1892).
  5616. #
  5617. # We deliberately do NOT stop drying from a humidity re-check here.
  5618. # Relative humidity drops steeply in heated air, so the AMS sensor
  5619. # reads ~15-20% within minutes of the dryer starting even while the
  5620. # filament is still saturated. A humidity-based early-stop therefore
  5621. # always fires at the minimum-time floor, truncating both user-started
  5622. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5623. # The firmware stops when the configured duration elapses; scheduling
  5624. # stops (print takes priority, queue no longer needs drying) are
  5625. # handled separately via _stop_drying().
  5626. if dry_time > 0:
  5627. if pid not in self._drying_in_progress:
  5628. # Drying we didn't start (manual or from before restart) —
  5629. # track it so scheduling stops still apply; never auto-stop it.
  5630. self._drying_in_progress[pid] = time.monotonic()
  5631. if unit_state is not None:
  5632. unit_state["running"] = True
  5633. logger.debug(
  5634. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5635. pid,
  5636. ams_id,
  5637. dry_time,
  5638. humidity,
  5639. )
  5640. continue
  5641. # Nothing is drying. Close out a cycle we armed ourselves and
  5642. # judge whether it achieved anything (#2770).
  5643. #
  5644. # "Achieved anything" is measured against the LOWEST reading any
  5645. # cycle on this unit has ended at, not against the threshold and
  5646. # not against the previous cycle. A spool that is genuinely wet
  5647. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5648. # allowed to keep going for as long as it is still coming down,
  5649. # however far it still is from the threshold. What must not
  5650. # continue is a cycle that ends exactly where the last one did,
  5651. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5652. # Comparing against the running minimum rather than the previous
  5653. # end is what stops a sensor oscillating by one point between two
  5654. # values from reading as progress every other cycle.
  5655. if unit_state is not None and unit_state.pop("running", False):
  5656. unit_state["ended_at"] = time.monotonic()
  5657. # The streak that armed this cycle is spent; the next one
  5658. # starts fresh (and accumulates through the re-arm cooldown
  5659. # below, so the wait overlaps the cooldown, never stacks on
  5660. # top of it).
  5661. self._auto_dry_above.pop(unit_key, None)
  5662. if humidity is not None and humidity > humidity_threshold:
  5663. best = unit_state.get("best_end_humidity")
  5664. if isinstance(best, int) and humidity < best:
  5665. # Still coming down. Keep going, however far the
  5666. # threshold still is.
  5667. unproductive = 0
  5668. else:
  5669. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5670. if not isinstance(best, int) or humidity < best:
  5671. unit_state["best_end_humidity"] = humidity
  5672. unit_state["unproductive"] = unproductive
  5673. logger.info(
  5674. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5675. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5676. pid,
  5677. ams_id,
  5678. humidity,
  5679. humidity_threshold,
  5680. unit_state.get("best_end_humidity"),
  5681. unproductive,
  5682. )
  5683. # A cycle that ended at or below the threshold needs no
  5684. # counter reset here: the branch below drops the whole entry.
  5685. # Humidity below threshold — no need to start drying. This is
  5686. # also the only thing that lifts a suspension: the reading we
  5687. # gave up on has come down, so auto-drying works again and the
  5688. # unit goes back to having no history at all.
  5689. if humidity is None or humidity <= humidity_threshold:
  5690. if unit_state is not None and unit_state.get("suspended"):
  5691. logger.info(
  5692. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5693. "threshold, resuming automatic drying",
  5694. pid,
  5695. ams_id,
  5696. humidity,
  5697. humidity_threshold,
  5698. )
  5699. # Clear the judgement, keep the clock (#2801). Dropping the
  5700. # whole entry also dropped `ended_at`, and with it the
  5701. # 30-minute cooldown -- so a reading that dips to the
  5702. # threshold as the AMS cools and comes back above it once
  5703. # warm wiped its own history and re-armed immediately. That
  5704. # oscillation is the very thing #2770's cooldown exists to
  5705. # ride out, and it is worst at exactly the margin that makes
  5706. # a unit dry repeatedly: a point or two above the threshold.
  5707. if unit_state is not None:
  5708. unit_state.pop("suspended", None)
  5709. unit_state.pop("unproductive", None)
  5710. unit_state.pop("best_end_humidity", None)
  5711. # A real below-threshold reading ends any sustained-wait
  5712. # streak (#2518) -- "continuously above" means exactly that.
  5713. # An absent reading (humidity is None) is no-information and
  5714. # leaves the streak alone; the observation-gap guard handles
  5715. # a prolonged sensor silence.
  5716. if humidity is not None:
  5717. _above = self._auto_dry_above.pop(unit_key, None)
  5718. if _above is not None and sustained_wait_active:
  5719. logger.info(
  5720. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5721. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5722. pid,
  5723. ams_id,
  5724. humidity,
  5725. time.monotonic() - _above["since"],
  5726. sustained_minutes,
  5727. humidity_threshold,
  5728. )
  5729. logger.debug(
  5730. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5731. pid,
  5732. ams_id,
  5733. humidity,
  5734. humidity_threshold,
  5735. )
  5736. continue
  5737. # Sustained-humidity streak (#2518): updated on every pass that
  5738. # observes the reading above the threshold, BEFORE the
  5739. # suspension/cooldown gates below -- a suspended or cooling-down
  5740. # unit still accumulates streak time, so the wait overlaps those
  5741. # gates instead of stacking after them. Inert when the feature
  5742. # is off: no entries are written, and an entry left over from a
  5743. # toggle-off is dropped so it cannot seed a stale streak later.
  5744. if sustained_wait_active:
  5745. _now = time.monotonic()
  5746. # Four missed scheduler passes, floored: a single slow pass
  5747. # must not void a streak, but the ceiling has to scale with
  5748. # the cadence or a slow loop silently restarts every streak.
  5749. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5750. _above = self._auto_dry_above.get(unit_key)
  5751. if _above is None:
  5752. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5753. elif _now - _above["last"] > _gap_ceiling:
  5754. # Restart, and say so at the same level as the dip
  5755. # reset: a silent restart voids the streak invisibly,
  5756. # and a user who set a long wait and never gets a dry
  5757. # has no way to see why.
  5758. logger.info(
  5759. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5760. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5761. pid,
  5762. ams_id,
  5763. _now - _above["last"],
  5764. _gap_ceiling,
  5765. sustained_minutes,
  5766. )
  5767. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5768. else:
  5769. _above["last"] = _now
  5770. else:
  5771. self._auto_dry_above.pop(unit_key, None)
  5772. if unit_state is not None:
  5773. if unit_state.get("suspended"):
  5774. logger.debug(
  5775. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5776. "above the %d%% threshold",
  5777. pid,
  5778. ams_id,
  5779. int(unit_state.get("unproductive", 0)),
  5780. humidity_threshold,
  5781. )
  5782. continue
  5783. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5784. unit_state["suspended"] = True
  5785. logger.warning(
  5786. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5787. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5788. "higher while it is warm, so a threshold in that range can never be reached and "
  5789. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5790. pid,
  5791. ams_id,
  5792. int(unit_state.get("unproductive", 0)),
  5793. humidity,
  5794. humidity_threshold,
  5795. )
  5796. await self._notify_auto_drying_suspended(
  5797. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5798. )
  5799. continue
  5800. ended_at = unit_state.get("ended_at")
  5801. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5802. logger.debug(
  5803. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5804. "cycle before the humidity reading is worth acting on",
  5805. pid,
  5806. ams_id,
  5807. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5808. )
  5809. continue
  5810. # Check cannot-dry reasons (power constraints etc.). Sits
  5811. # ahead of the sustained wait so a unit the firmware refuses
  5812. # to dry never logs a wait it was never going to cash in.
  5813. sf_reasons = ams_data.get("dry_sf_reason", [])
  5814. if sf_reasons:
  5815. logger.debug(
  5816. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5817. pid,
  5818. ams_id,
  5819. sf_reasons,
  5820. )
  5821. continue
  5822. # Sustained-humidity wait (#2518): ambient-triggered starts
  5823. # wait; only a printer with a scheduled queue item pending
  5824. # keeps the instant behavior, because that drying has a real
  5825. # deadline. Mid-print is deliberately NOT exempt while ambient
  5826. # drying is on: a humidity start on a printer that happens to be
  5827. # printing is as vulnerable to a lid-open spike as one on an idle
  5828. # printer (proven live: a 2-point threshold crossing mid-print
  5829. # bought a parked 12h command). Inactive when ambient drying is
  5830. # off: print_drying then still starts mid-print cycles on its own
  5831. # (#1816, "regardless of queue state"), and those stay instant.
  5832. if sustained_wait_active and pid not in printers_with_scheduled:
  5833. _above = self._auto_dry_above.get(unit_key)
  5834. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5835. if _waited < sustained_minutes * 60:
  5836. logger.debug(
  5837. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5838. "threshold for %.0fs of the required %dm",
  5839. pid,
  5840. ams_id,
  5841. humidity,
  5842. humidity_threshold,
  5843. _waited,
  5844. sustained_minutes,
  5845. )
  5846. continue
  5847. # Get conservative drying params for mixed filaments
  5848. params = self._get_conservative_drying_params(trays, module_type, presets)
  5849. if not params:
  5850. logger.debug(
  5851. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5852. )
  5853. continue
  5854. temp, duration_hours, filament_type = params
  5855. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5856. # "drying temperature must not exceed the filament's softening temperature"
  5857. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5858. # ineffective and firmware will reject anyway.
  5859. if mid_print:
  5860. temp = max(40, temp - 5)
  5861. # Start drying
  5862. logger.info(
  5863. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5864. "starting %s drying at %d°C for %dh%s",
  5865. pid,
  5866. ams_id,
  5867. humidity,
  5868. humidity_threshold,
  5869. filament_type,
  5870. temp,
  5871. duration_hours,
  5872. " (mid-print)" if mid_print else "",
  5873. )
  5874. success = printer_manager.send_drying_command(
  5875. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5876. )
  5877. if success:
  5878. self._drying_in_progress[pid] = time.monotonic()
  5879. armed = self._auto_dry_units.setdefault(
  5880. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5881. )
  5882. armed["running"] = True
  5883. async def _notify_auto_drying_suspended(
  5884. self,
  5885. db: AsyncSession,
  5886. printer: Printer,
  5887. ams_id: int,
  5888. humidity: int,
  5889. threshold: int,
  5890. cycles: int,
  5891. ) -> None:
  5892. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5893. Fires once per suspension — the caller sets ``suspended`` before calling
  5894. and every later pass short-circuits on it — because the whole point is
  5895. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5896. building needs that to reach them, and the hourly humidity alarm they
  5897. are already getting says the opposite of what happened here.
  5898. Never raises: a notification provider being down must not stop the
  5899. suspension itself from taking effect.
  5900. """
  5901. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5902. try:
  5903. await notification_service.on_ams_drying_suspended(
  5904. printer.id,
  5905. printer.name,
  5906. ams_label,
  5907. float(humidity),
  5908. float(threshold),
  5909. cycles,
  5910. db,
  5911. )
  5912. except Exception as e:
  5913. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5914. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5915. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5916. The unproductive-cycle counter exists to notice that *drying* is not
  5917. moving the humidity reading. A cycle that ended because somebody sent a
  5918. stop says nothing about that — it was cut short before it had a chance —
  5919. so counting it would suspend auto-drying for a reason that has nothing to
  5920. do with the loop the counter is there to break.
  5921. Two callers, both of them a stop Bambuddy is responsible for: the
  5922. print-takes-priority stop below, and the manual Stop button. Left
  5923. uncalled, an install that dries between queue jobs would suspend its own
  5924. auto-drying after two prints interrupted a dry — exactly the install
  5925. queue-drying exists for.
  5926. The rest of the unit's history is kept: the cooldown before re-arming
  5927. still applies, and an earlier count still stands.
  5928. """
  5929. state = self._auto_dry_units.get((printer_id, ams_id))
  5930. if state is not None:
  5931. state.pop("running", None)
  5932. state["ended_at"] = time.monotonic()
  5933. # A stopped cycle spends the streak that armed it, same as a completed
  5934. # one (#2518).
  5935. self._auto_dry_above.pop((printer_id, ams_id), None)
  5936. def _sync_drying_state(self):
  5937. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5938. One direction only: it prunes, it never adds. A printer drying without an
  5939. entry here — because the user started the cycle from Studio, the printer's
  5940. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5941. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5942. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5943. That is deliberate for now rather than an oversight: populating this from
  5944. telemetry would hand the scheduler authority to stop drying a user started
  5945. by hand. It also means the backend-restart case this used to claim to
  5946. handle is not handled.
  5947. """
  5948. to_remove = []
  5949. for pid in self._drying_in_progress:
  5950. state = printer_manager.get_status(pid)
  5951. if not state:
  5952. to_remove.append(pid)
  5953. continue
  5954. # Check if any AMS unit is still drying
  5955. ams_list = state.raw_data.get("ams", [])
  5956. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5957. if not any_drying:
  5958. to_remove.append(pid)
  5959. for pid in to_remove:
  5960. self._drying_in_progress.pop(pid, None)
  5961. # A printer that has gone away entirely takes its per-AMS auto-drying
  5962. # history with it (#2770), so a printer deleted and re-added does not
  5963. # inherit a suspension it never earned.
  5964. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5965. self._auto_dry_units.pop(key, None)
  5966. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5967. # printer starts a fresh wait, and vanished printers do not leak
  5968. # entries.
  5969. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5970. self._auto_dry_above.pop(key, None)
  5971. @staticmethod
  5972. def _drying_is_only_parked(printer_id: int) -> bool:
  5973. """True when every AMS unit with a drying timer on this printer is parked.
  5974. A parked timer (#2896: the command was taken but the countdown never
  5975. runs) does not end on its own, so nothing may wait on it. False when no
  5976. unit reports a timer yet -- a command just sent that the firmware has not
  5977. reported back is real drying about to begin.
  5978. """
  5979. state = printer_manager.get_status(printer_id)
  5980. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5981. timed = []
  5982. for unit in units:
  5983. try:
  5984. if int(unit.get("dry_time") or 0) > 0:
  5985. timed.append(unit)
  5986. except (TypeError, ValueError):
  5987. continue
  5988. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5989. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5990. """True when a running cycle can be left alone while the next print runs.
  5991. Some hardware dries happily through a print and #2758 settled that we
  5992. should not tear those cycles down: the X2D there was refusing to
  5993. *start* a job, which is a different problem, and stopping drying before
  5994. every dispatch would throw away cycles the printer was content to run.
  5995. Where the model cannot do it, or the user has not enabled it, the print
  5996. takes priority and the cycle stops -- which is what the queue_drying_block
  5997. setting has always promised in its off position.
  5998. """
  5999. if not await self._get_bool_setting(db, "print_drying_enabled"):
  6000. return False
  6001. status = printer_manager.get_status(printer_id)
  6002. return supports_drying_while_printing(
  6003. printer_manager.get_model(printer_id),
  6004. status.firmware_version if status else None,
  6005. )
  6006. async def _stop_drying(self, printer_id: int):
  6007. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  6008. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  6009. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  6010. enough to kill a cycle the user had started by hand on a *different*
  6011. unit of the same printer (#2801). That contradicted the contract
  6012. ``_sync_drying_state`` already documents -- the entry gate deliberately
  6013. only knows about cycles Bambuddy began, so the action must not reach
  6014. past them either.
  6015. """
  6016. state = printer_manager.get_status(printer_id)
  6017. if not state:
  6018. self._drying_in_progress.pop(printer_id, None)
  6019. return
  6020. ams_list = state.raw_data.get("ams", [])
  6021. for ams_data in ams_list:
  6022. dry_time = int(ams_data.get("dry_time") or 0)
  6023. if dry_time > 0:
  6024. ams_id = int(ams_data.get("id", 0))
  6025. if (printer_id, ams_id) not in self._auto_dry_units:
  6026. logger.debug(
  6027. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  6028. printer_id,
  6029. ams_id,
  6030. )
  6031. continue
  6032. logger.info(
  6033. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  6034. printer_id,
  6035. ams_id,
  6036. )
  6037. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  6038. self.forget_auto_dry_cycle(printer_id, ams_id)
  6039. self._drying_in_progress.pop(printer_id, None)
  6040. # Scheduled manual drying (#2638) -----------------------------------
  6041. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  6042. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  6043. async def _check_scheduled_dryings(self, db: AsyncSession):
  6044. """Dispatch due scheduled drying runs and track running ones."""
  6045. now = utcnow_naive()
  6046. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  6047. # Monotonic, so a clock adjustment cannot park the prune for hours.
  6048. since_prune = time.monotonic()
  6049. if (
  6050. self._last_scheduled_drying_prune is None
  6051. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  6052. ):
  6053. self._last_scheduled_drying_prune = since_prune
  6054. await db.execute(
  6055. delete(ScheduledDrying).where(
  6056. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  6057. ScheduledDrying.completed_at.is_not(None),
  6058. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  6059. )
  6060. )
  6061. # Same order as the list route: with two rows due on one printer the
  6062. # earliest scheduled wins rather than whatever the DB hands back first.
  6063. result = await db.execute(
  6064. select(ScheduledDrying)
  6065. .where(ScheduledDrying.status.in_(("pending", "running")))
  6066. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  6067. )
  6068. rows = list(result.scalars().all())
  6069. # Rebuild from the DB every tick so route-side cancels and completions
  6070. # show up. Auto-drying's stop-all branches check this set before
  6071. # stopping anything (#2638).
  6072. # Kept from the previous pass so a run that ended between passes — a
  6073. # cancel through the route, say — can still be released below.
  6074. previously_running = self._scheduled_drying_printer_ids
  6075. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6076. running_printer_ids = set(self._scheduled_drying_printer_ids)
  6077. # Model and firmware come from the printer row, not the live state.
  6078. printer_ids = {row.printer_id for row in rows}
  6079. printers_by_id: dict[int, Printer] = {}
  6080. if printer_ids:
  6081. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  6082. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  6083. for row in rows:
  6084. if row.status == "running":
  6085. self._update_running_scheduled_drying(row, now)
  6086. continue
  6087. if row.start_after is not None and row.start_after > now:
  6088. continue
  6089. state = printer_manager.get_status(row.printer_id)
  6090. if not state:
  6091. row.waiting_reason = "printer_offline"
  6092. continue
  6093. # Same preflight the immediate endpoint runs. Without it the publish
  6094. # succeeds, the row goes to running, the printer ignores the command
  6095. # and the run silently cancels itself after the grace window.
  6096. printer = printers_by_id.get(row.printer_id)
  6097. unsupported = drying_preflight.check_drying_supported(
  6098. printer.model if printer else None, state.firmware_version
  6099. )
  6100. if unsupported:
  6101. row.status = "failed"
  6102. row.error_message = unsupported
  6103. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6104. row.completed_at = now
  6105. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6106. continue
  6107. if (
  6108. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6109. ) or row.printer_id in running_printer_ids:
  6110. row.waiting_reason = "already_drying"
  6111. continue
  6112. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6113. row.waiting_reason = "printer_busy"
  6114. continue
  6115. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6116. if target is None:
  6117. row.waiting_reason = "ams_not_found"
  6118. continue
  6119. blocking = drying_preflight.blocking_reason_codes(target)
  6120. if blocking:
  6121. # Keep the power case distinct; it needs the user to act, so the
  6122. # card can say so instead of waiting silently.
  6123. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6124. continue
  6125. filament = drying_preflight.resolve_filament(target, row.filament)
  6126. logger.info(
  6127. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6128. row.id,
  6129. row.printer_id,
  6130. row.ams_id,
  6131. row.temp,
  6132. row.duration_hours,
  6133. )
  6134. success = printer_manager.send_drying_command(
  6135. row.printer_id,
  6136. row.ams_id,
  6137. row.temp,
  6138. row.duration_hours,
  6139. mode=1,
  6140. filament=filament,
  6141. rotate_tray=row.rotate_tray,
  6142. )
  6143. if success:
  6144. row.status = "running"
  6145. row.started_at = now
  6146. row.waiting_reason = None
  6147. row.filament = filament
  6148. self._drying_in_progress[row.printer_id] = time.monotonic()
  6149. self._scheduled_drying_printer_ids.add(row.printer_id)
  6150. running_printer_ids.add(row.printer_id)
  6151. else:
  6152. row.waiting_reason = "printer_offline"
  6153. # Release the printers whose run has ended. `_drying_in_progress` is
  6154. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6155. # but that call sits behind the auto-drying enabled check, and this
  6156. # method is the one writer that runs whether auto-drying is on or not.
  6157. # With it off, nothing would ever drop the entry short of a print being
  6158. # dispatched to the same printer, so the next scheduled run would wait
  6159. # on "already_drying" forever and `queue_drying_block` would hold the
  6160. # printer's prints too. Covers a run that ended during this pass and one
  6161. # cancelled through the route between passes.
  6162. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6163. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6164. self._drying_in_progress.pop(printer_id, None)
  6165. await db.commit()
  6166. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6167. """Detect completion or interruption of a running scheduled drying.
  6168. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6169. drying. Within the grace window after start we ignore dry_time==0
  6170. (the status lags the command). After that, dry_time==0 near the end
  6171. of the configured duration means completed. Much earlier means the
  6172. run was stopped: re-queue it if a print preempted the dryer, but a
  6173. stop while the printer is idle was deliberate, so cancel the row
  6174. rather than restart drying the user just stopped.
  6175. """
  6176. if row.started_at is None:
  6177. row.started_at = now
  6178. return
  6179. elapsed = (now - row.started_at).total_seconds()
  6180. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6181. return
  6182. state = printer_manager.get_status(row.printer_id)
  6183. if not state:
  6184. return # offline mid-dry; resolve when it reconnects
  6185. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6186. # throw on a malformed id would cost the whole pass including print
  6187. # dispatch, every tick.
  6188. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6189. try:
  6190. dry_time = int(target.get("dry_time") or 0) if target else 0
  6191. except (TypeError, ValueError):
  6192. dry_time = 0
  6193. if dry_time > 0 and is_countdown_parked(target):
  6194. # The printer took the command but the countdown is not running
  6195. # (#2896) and will never reach 0, so the run would stay "running"
  6196. # forever. A print in progress is the likely cause (the power budget
  6197. # is spent), so re-queue it like any interruption; the next start
  6198. # waits for the printer to be idle. Parked on an idle printer is a
  6199. # refusal, not something a retry fixes. The timer itself is left on
  6200. # the printer: it may yet start once power frees up.
  6201. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6202. logger.info(
  6203. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6204. row.id,
  6205. row.ams_id,
  6206. )
  6207. row.status = "pending"
  6208. row.started_at = None
  6209. row.waiting_reason = "interrupted"
  6210. else:
  6211. logger.warning(
  6212. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6213. row.id,
  6214. row.ams_id,
  6215. )
  6216. row.status = "failed"
  6217. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6218. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6219. row.completed_at = now
  6220. return
  6221. if dry_time > 0:
  6222. return
  6223. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6224. row.status = "completed"
  6225. row.completed_at = now
  6226. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6227. row.status = "pending"
  6228. row.started_at = None
  6229. row.waiting_reason = "interrupted"
  6230. else:
  6231. row.status = "cancelled"
  6232. row.completed_at = now
  6233. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6234. """Get all smart plugs associated with a printer."""
  6235. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6236. return list(result.scalars().all())
  6237. @staticmethod
  6238. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6239. """Pick the plug to power-cycle a printer back online with (#2629).
  6240. Only a plug flagged ``controls_printer_power`` can actually bring the
  6241. printer back; waiting for a boot on an accessory (filter fan, lights)
  6242. just burns the power-on timeout and fails the dispatch. Falls back to
  6243. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6244. Callers must pass a non-empty list.
  6245. """
  6246. for plug in auto_on_plugs:
  6247. if plug.controls_printer_power:
  6248. return plug
  6249. return auto_on_plugs[0]
  6250. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6251. # chamber-temperature recommendations BambuStudio ships for the matching
  6252. # filament profile; users can override via Settings → Workflow → Preheat
  6253. # card. "default" applies when a loaded tray's normalised type isn't in
  6254. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6255. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6256. "PLA": 0,
  6257. "PETG": 0,
  6258. "PETG-CF": 40,
  6259. "ABS": 45,
  6260. "ASA": 45,
  6261. "PA": 50,
  6262. "PA-CF": 55,
  6263. "PC": 50,
  6264. "PC-FR": 50,
  6265. "TPU": 0,
  6266. "PVA": 0,
  6267. "default": 0,
  6268. }
  6269. @classmethod
  6270. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6271. """The bundled map under the same key casing a parsed one gets.
  6272. The constant is declared with a lowercase ``default`` because that is
  6273. the key the Settings editor writes and displays. Every read of the map
  6274. happens after ``str(key).upper()``, so handing the constant back as
  6275. declared broke the contract the parser documents: an install that had
  6276. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6277. and the resolution loop's fallback silently found nothing. It read the
  6278. right number only because the bundled default happens to be 0 -- change
  6279. that constant and every unconfigured install would keep preheating to
  6280. zero with no way to tell why.
  6281. """
  6282. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6283. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6284. """Parse the user-configured filament→chamber-target map, falling back
  6285. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6286. are uppercased and the 'default' fallback is always present in the
  6287. returned dict so the resolution loop can index it unconditionally."""
  6288. raw = await self._get_setting(db, "preheat_filament_targets")
  6289. if not raw:
  6290. return self._bundled_preheat_targets()
  6291. try:
  6292. parsed = json.loads(raw)
  6293. if not isinstance(parsed, dict):
  6294. raise ValueError("not an object")
  6295. except (json.JSONDecodeError, ValueError) as exc:
  6296. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6297. return self._bundled_preheat_targets()
  6298. # Coerce values to int; drop unparseable rows so a stray string
  6299. # doesn't crash the loop.
  6300. out: dict[str, int] = {}
  6301. for key, value in parsed.items():
  6302. try:
  6303. out[str(key).upper()] = int(value)
  6304. except (TypeError, ValueError):
  6305. continue
  6306. if "DEFAULT" not in out:
  6307. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6308. return out
  6309. @staticmethod
  6310. def _normalize_filament_type(tray_type: str) -> str:
  6311. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6312. existing drying-preset normalisation (split-at-space, upper-case) so
  6313. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6314. "PA-CF" (no space to split on).
  6315. This is the first stage of ``_resolve_filament_key``, which goes on to
  6316. drop the suffix and consult the alias map; on its own it only decides
  6317. what the tray is called, not which row answers for it.
  6318. Indexing the split rather than testing the input: a tray_type of spaces
  6319. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6320. it through to an IndexError.
  6321. """
  6322. words = (tray_type or "").split()
  6323. return words[0].upper() if words else ""
  6324. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6325. """Per-filament chamber target for one tray's reported type, or 0 when
  6326. the tray is empty / RFID-less and reports no type at all.
  6327. A filled or foamed variant wants its base material's chamber when the
  6328. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6329. not the 0 an unknown type falls to. The specific type is still tried
  6330. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6331. (#2902).
  6332. That lookup is now the shared one, which adds the polyamide aliases on
  6333. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6334. too, rather than the catch-all it was landing on (#3067).
  6335. """
  6336. if not self._normalize_filament_type(tray_type or ""):
  6337. return 0
  6338. key = self._resolve_filament_key(tray_type, targets)
  6339. if key is not None:
  6340. return targets[key]
  6341. # A type the map does not list at all, which is not the same as a tray
  6342. # with nothing in it -- that already returned 0 above.
  6343. return targets.get("DEFAULT", 0)
  6344. def _derive_chamber_target(
  6345. self,
  6346. printer: Printer,
  6347. targets: dict[str, int],
  6348. item: PrintQueueItem | None = None,
  6349. ) -> int:
  6350. """Chamber target for the trays this print actually loads: the max of
  6351. their per-filament targets. Returns 0 when there is nothing to read (no
  6352. status, no AMS telemetry — e.g. external-spool prints) or when every
  6353. tray considered maps to 0, and the chamber phase then short-circuits in
  6354. the main loop.
  6355. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6356. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6357. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6358. plus soak burned ahead of each upload, on a printer whose chamber never
  6359. reaches the target anyway (#2886). An item with no usable mapping falls
  6360. back to scanning every loaded tray: that is the only signal left, and
  6361. narrowing to nothing would skip preheat on prints that genuinely need
  6362. it.
  6363. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6364. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6365. less slots have empty `tray_type` and contribute nothing. The external
  6366. spool is consulted only when the mapping names it (>= 254); it stays
  6367. out of the unnarrowed scan, so an item without a mapping derives from
  6368. the AMS alone exactly as before.
  6369. """
  6370. state = printer_manager.get_status(printer.id)
  6371. if state is None:
  6372. return 0
  6373. raw_data = state.raw_data or {}
  6374. used = _used_global_tray_ids(item)
  6375. ams_list = raw_data.get("ams")
  6376. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6377. if isinstance(ams_list, dict):
  6378. ams_list = ams_list.get("ams") or []
  6379. if not isinstance(ams_list, list):
  6380. ams_list = []
  6381. best = 0
  6382. for ams in ams_list:
  6383. if not isinstance(ams, dict):
  6384. continue
  6385. ams_id = _int_or(ams.get("id"), 0)
  6386. for tray in ams.get("tray") or []:
  6387. # A non-dict entry has never been seen from real firmware, but
  6388. # `.get` on one raises, and nothing between here and
  6389. # `_dispatch_one`'s try/finally catches it — the item would be
  6390. # left holding its dispatch claim. Preheat is best-effort by
  6391. # contract, so step over it instead.
  6392. if not isinstance(tray, dict):
  6393. continue
  6394. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6395. continue
  6396. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6397. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6398. for vt in raw_data.get("vt_tray") or []:
  6399. if not isinstance(vt, dict):
  6400. continue
  6401. # `_build_loaded_filaments` addresses external feeds by the id
  6402. # the firmware reports — 255 main, 254 deputy — defaulting to
  6403. # 254 when the field is absent. Same expression here so the two
  6404. # agree on which entry a mapping's 254/255 refers to.
  6405. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6406. continue
  6407. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6408. return best
  6409. def _release_keep_warm(self, pid: int) -> None:
  6410. """Release keep-warm on a printer that left the candidate set.
  6411. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6412. reports the target we set (``entry.held_target``), so a user or
  6413. subsequent print that changed the bed target since is not clobbered.
  6414. Best-effort, never raises.
  6415. The entry is kept, not dropped, when the printer cannot be reached
  6416. right now: a printer that is briefly offline still has a hot bed, and
  6417. holding the entry is what keeps the max-duration timeout applying and
  6418. lets a later tick retry the release. Only a printer that has left the
  6419. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6420. """
  6421. entry = self._keep_warm.get(pid)
  6422. if entry is None:
  6423. return
  6424. state = printer_manager.get_status(pid)
  6425. client = printer_manager.get_client(pid)
  6426. if state is None or client is None:
  6427. logger.debug(
  6428. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6429. pid,
  6430. )
  6431. return
  6432. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6433. if int(cur_bed_target) != entry.held_target:
  6434. # Someone else owns the bed now, so there is nothing of ours to
  6435. # undo and nothing left to track.
  6436. logger.info(
  6437. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6438. pid,
  6439. int(cur_bed_target),
  6440. entry.held_target,
  6441. )
  6442. self._keep_warm.pop(pid, None)
  6443. return
  6444. try:
  6445. client.set_bed_temperature(0)
  6446. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6447. self._keep_warm.pop(pid, None)
  6448. except Exception as exc:
  6449. # Keep the entry so the next tick tries again rather than leaving
  6450. # the bed hot with nothing tracking it.
  6451. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6452. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6453. """Release printers that dropped out of the keep-warm candidate set.
  6454. Called from ``_apply_keep_warm`` on every tick (with the current
  6455. candidate set), and from ``check_queue``'s no-pending-items early
  6456. return (with an empty candidate set) so orphaned holds still get
  6457. released when the queue empties. Also called with an empty candidate
  6458. set when any of the three gate settings toggles off, so a printer
  6459. whose feature was disabled mid-hold gets its bed released.
  6460. Printers being dispatched this tick are excluded from the bed-off
  6461. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6462. transient 0 in between would just churn against preheat. Ownership of
  6463. the hot bed transfers to the preheat rollback pin instead — if the
  6464. dispatch aborts before the print starts (failed upload, cancelled
  6465. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6466. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6467. is the ONLY thing standing between an aborted dispatch and a bed
  6468. left hot with no owner. A successful print start clears the pin and
  6469. the print's own gcode takes over, as usual.
  6470. """
  6471. for _pid in list(self._keep_warm):
  6472. if _pid in active_candidates:
  6473. continue
  6474. if _pid in dispatched:
  6475. handed_over = self._keep_warm.pop(_pid, None)
  6476. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6477. if handed_over is not None:
  6478. self._preheat_pin_bed[_pid] = handed_over.held_target
  6479. continue
  6480. self._release_keep_warm(_pid)
  6481. async def _apply_keep_warm(
  6482. self,
  6483. db: AsyncSession,
  6484. items: list[PrintQueueItem],
  6485. dispatch_ids: list[int] | set[int],
  6486. busy_printers: set[int],
  6487. require_plate_clear: bool,
  6488. ) -> None:
  6489. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6490. When a printer just finished a job (FINISH state) and the next queued
  6491. item needs chamber heating, hold the bed hot so the chamber stays warm
  6492. during the bed-clearing window. The bed is the chamber's heating
  6493. element here, not a print surface — nothing is printing during the
  6494. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6495. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6496. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6497. aftermarket chamber heaters), raised to the item's own parsed
  6498. bed_temperature when that is higher. Items whose archive metadata has
  6499. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6500. get a hold — chamber need is what gates the feature, not metadata.
  6501. Skips entirely for filaments that map to a 0°C chamber target
  6502. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6503. names, so a hot-chamber spool it never touches does not hold the bed of
  6504. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6505. whole unit, as every item was before. Printers being dispatched this
  6506. cycle are excluded:
  6507. ``_preheat_and_soak`` already handles their bed temperature.
  6508. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6509. released to 0 and the entry is latched ``expired=True`` so
  6510. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6511. MQTT: publish is skipped when firmware already has the target.
  6512. The release sweep runs BEFORE the engagement gate so a printer that
  6513. was owned by keep-warm still gets its bed released when any of the
  6514. three gate settings is toggled off mid-hold. The
  6515. ``check_queue`` early-return-when-no-items path also calls
  6516. ``_sweep_keep_warm`` directly to release orphaned holds.
  6517. """
  6518. dispatch_set = set(dispatch_ids)
  6519. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6520. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6521. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6522. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6523. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6524. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6525. # Release sweep first — must run even when gate_open is False so a
  6526. # printer owned by keep-warm when a gate toggles off gets released.
  6527. self._sweep_keep_warm(
  6528. active_candidates=warm_candidates if gate_open else set(),
  6529. dispatched=dispatched_printers,
  6530. )
  6531. if not gate_open:
  6532. return
  6533. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6534. max_hold_seconds = (
  6535. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6536. )
  6537. now_mono = time.monotonic()
  6538. filament_targets: dict[str, int] | None = None
  6539. for pid in warm_candidates:
  6540. entry = self._keep_warm.get(pid)
  6541. # Latched-expired: max-duration timeout already fired for this
  6542. # printer. Skip until the release sweep drops the entry (i.e.
  6543. # until the printer leaves the candidate set).
  6544. if entry is not None and entry.expired:
  6545. continue
  6546. # These two guards sit ahead of the max-duration check below, so an
  6547. # engaged hold only ages out while its printer is still reachable
  6548. # and still in FINISH. That is deliberate rather than a hole: with
  6549. # no status or no client there is no M140 to send anyway, and the
  6550. # elapsed check runs off `entry.started` so it fires on the first
  6551. # tick after the printer comes back. Leaving FINISH means the plate
  6552. # was cleared, which drops the printer out of `warm_candidates` and
  6553. # hands it to `_release_keep_warm` instead. The invariant worth
  6554. # preserving if this is ever reordered: every path out of an
  6555. # engaged hold ends in a bed-off, whether by timeout or release.
  6556. state = printer_manager.get_status(pid)
  6557. if state is None or state.state != "FINISH":
  6558. continue
  6559. client = printer_manager.get_client(pid)
  6560. if client is None:
  6561. continue
  6562. next_item = next((it for it in items if it.printer_id == pid), None)
  6563. if next_item is None:
  6564. continue
  6565. # Hold temperature: the configured keep-warm temp, raised to the
  6566. # item's own bed temp when the metadata reports a higher one. A
  6567. # missing bed_temperature (Orca gcode.3mf exports parse without
  6568. # one) does NOT skip the hold — chamber need gates the feature.
  6569. archive = next_item.archive
  6570. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6571. bed_target = max(item_bed, hold_temp)
  6572. if bed_target <= 0:
  6573. continue
  6574. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6575. if explicit is not None:
  6576. chamber_needed = int(explicit) > 0
  6577. else:
  6578. if filament_targets is None:
  6579. filament_targets = await self._get_preheat_filament_targets(db)
  6580. printer_obj = await self._get_printer(db, pid)
  6581. chamber_needed = (
  6582. printer_obj is not None
  6583. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6584. )
  6585. if not chamber_needed:
  6586. continue
  6587. # Seed the timer on first engagement; keep it on subsequent ticks
  6588. # (never re-seed — that would defeat the max-duration cap).
  6589. if entry is None:
  6590. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6591. self._keep_warm[pid] = entry
  6592. elapsed = now_mono - entry.started
  6593. if elapsed > max_hold_seconds:
  6594. # Timeout: publish bed → 0 once (if firmware still holds our
  6595. # target) and latch expired. The entry stays until the release
  6596. # sweep drops it, preventing the next tick from re-seeding.
  6597. logger.warning(
  6598. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6599. pid,
  6600. elapsed,
  6601. )
  6602. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6603. if int(cur_bed_target) == entry.held_target:
  6604. try:
  6605. client.set_bed_temperature(0)
  6606. except Exception as exc:
  6607. logger.warning(
  6608. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6609. pid,
  6610. exc,
  6611. )
  6612. else:
  6613. logger.info(
  6614. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6615. pid,
  6616. int(cur_bed_target),
  6617. entry.held_target,
  6618. )
  6619. entry.expired = True
  6620. continue
  6621. # Idempotence: skip publish when firmware already has our target.
  6622. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6623. if int(cur_bed_target) == bed_target:
  6624. entry.held_target = bed_target
  6625. continue
  6626. try:
  6627. client.set_bed_temperature(bed_target)
  6628. entry.held_target = bed_target
  6629. logger.info(
  6630. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6631. bed_target,
  6632. pid,
  6633. )
  6634. except Exception as exc:
  6635. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6636. def _sample_chamber_temps(self) -> None:
  6637. """Record a chamber temperature sample for every connected printer.
  6638. Called once per scheduler tick (every 3–30 s). Entries older than
  6639. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6640. Also evicts per-printer state whose printer_id is no longer registered
  6641. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6642. """
  6643. now = time.monotonic()
  6644. cutoff = now - self._chamber_history_ttl
  6645. statuses = printer_manager.get_all_statuses()
  6646. known_pids = set(statuses.keys())
  6647. for pid, status in statuses.items():
  6648. if status is None or not status.connected:
  6649. continue
  6650. temps = status.temperatures or {}
  6651. chamber = temps.get("chamber")
  6652. if chamber is None:
  6653. continue
  6654. hist = self._chamber_history.setdefault(pid, deque())
  6655. hist.append((now, float(chamber)))
  6656. while hist and hist[0][0] < cutoff:
  6657. hist.popleft()
  6658. # Evict state for printers that are no longer registered with the manager.
  6659. # This is the one place a keep-warm entry is dropped without releasing
  6660. # the bed: the printer is gone from the manager, so there is no client
  6661. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6662. # for printers that are merely unreachable, which is what makes this
  6663. # the terminal case rather than a silent leak.
  6664. for pid in list(self._chamber_history):
  6665. if pid not in known_pids:
  6666. self._chamber_history.pop(pid, None)
  6667. for pid in list(self._keep_warm):
  6668. if pid not in known_pids:
  6669. logger.info(
  6670. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6671. pid,
  6672. )
  6673. self._keep_warm.pop(pid, None)
  6674. for pid in list(self._preheat_pin):
  6675. if pid not in known_pids:
  6676. self._preheat_pin.pop(pid, None)
  6677. self._preheat_pin_bed.pop(pid, None)
  6678. def _chamber_soak_remaining(
  6679. self,
  6680. printer_id: int,
  6681. chamber_target: float,
  6682. soak_seconds: int,
  6683. tolerance: float = 2.0,
  6684. ) -> int:
  6685. """Return how many seconds of soak time are still needed.
  6686. Credits the time the chamber has already spent at temperature against
  6687. the configured soak. The credit may not start earlier than any of:
  6688. * **The newest sample.** Nothing recent means the printer stopped
  6689. reporting mid-observation and the chamber may have cooled unseen, so
  6690. the full soak is required. (A 2 h history whose last reading is half
  6691. an hour old is not evidence of anything — the measured cooling rate
  6692. is fast enough to cross the threshold in that time.)
  6693. * **The most recent contiguous run of samples.** A gap wider than
  6694. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6695. far side is not evidence of temperature.
  6696. * **The end of the most recent real dip below the threshold.**
  6697. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6698. — see that constant for the thermal reasoning. A stray low reading is
  6699. an artifact, and treating it as cooling would discard a soak that
  6700. actually happened.
  6701. Returns ``soak_seconds`` when nothing can be credited (no history,
  6702. stale history, or the chamber is below the threshold right now) and 0
  6703. once the credited time covers the whole soak.
  6704. """
  6705. hist = self._chamber_history.get(printer_id)
  6706. if not hist:
  6707. return soak_seconds
  6708. now = time.monotonic()
  6709. newest_ts, newest_temp = hist[-1]
  6710. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6711. return soak_seconds # stale — no fresh evidence to credit
  6712. threshold = chamber_target - tolerance
  6713. if newest_temp < threshold:
  6714. return soak_seconds # below target right now; nothing is soaked
  6715. samples = list(hist)
  6716. # Earliest point we have unbroken observations for.
  6717. credit_from = samples[-1][0]
  6718. for i in range(len(samples) - 1, 0, -1):
  6719. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6720. break
  6721. credit_from = samples[i - 1][0]
  6722. # Pull the credit forward to the end of the last significant dip. Each
  6723. # excursion is measured between the in-range readings that bracket it,
  6724. # so a lone stray sample is charged one sampling interval rather than
  6725. # zero, and the comparison errs towards calling a dip real.
  6726. i = 0
  6727. while i < len(samples):
  6728. if samples[i][1] >= threshold:
  6729. i += 1
  6730. continue
  6731. j = i
  6732. while j < len(samples) and samples[j][1] < threshold:
  6733. j += 1
  6734. # `newest_temp >= threshold` was checked above, so j is in range.
  6735. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6736. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6737. # Credit resumes at the last below-threshold sample rather than
  6738. # the first good one after it, so a recovered dip over-credits
  6739. # by up to one sampling interval — the opposite lean to the
  6740. # bracketing above. Both are bounded by the sample cadence and
  6741. # dwarfed by the grace period, so neither is worth the extra
  6742. # arithmetic to remove.
  6743. credit_from = max(credit_from, samples[j - 1][0])
  6744. i = j
  6745. return max(0, soak_seconds - int(now - credit_from))
  6746. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6747. """Tell an in-flight dispatch that its item no longer wants to print.
  6748. Called by the queue's cancel and delete routes. Those only write to the
  6749. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6750. observe — so preheat would keep heating for the rest of max_wait + soak
  6751. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6752. blocking every other queued item behind a print that is not happening.
  6753. Signalling in memory rather than re-reading the row keeps this off the
  6754. database entirely: no second session, no transaction held across a long
  6755. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6756. Bambuddy serves from a single uvicorn process with one scheduler task,
  6757. so the route and the dispatch always share this object. The flag is
  6758. advisory — dropping it (e.g. after a restart) only costs a wasted
  6759. preheat, never a wrongly-abandoned print.
  6760. Only ids with a dispatch actually in flight are recorded, so the set
  6761. stays bounded by the upload pool rather than growing once per cancelled
  6762. item for the life of the process. Skipping the rest loses nothing: an
  6763. item that is not in flight cannot start heating later either, because
  6764. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6765. the caller has already committed a terminal status (or deleted the row)
  6766. before calling this.
  6767. """
  6768. if item_id in self._inflight:
  6769. self._cancelled_dispatches.add(item_id)
  6770. # A print sent for it earlier that never started is not one any more.
  6771. self._forget_unstarted_print(item_id, unless_printing=False)
  6772. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6773. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6774. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6775. while it is parked, so the wait is chopped into
  6776. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6777. """
  6778. remaining = float(seconds)
  6779. while remaining > 0:
  6780. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6781. await asyncio.sleep(slice_secs)
  6782. remaining -= slice_secs
  6783. if item_id in self._cancelled_dispatches:
  6784. return False
  6785. return True
  6786. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6787. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6788. The full preheat stage does this as part of its own dispatch: an H2D
  6789. left in heating mode by the ABS job before it would otherwise cook the
  6790. PLA that follows. The skip path never reaches that code, so it calls
  6791. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6792. add to the rollback pin, because a flap set to cooling for a print that
  6793. needs no heat is where it should have been either way.
  6794. Best-effort like everything else in the stage: a refused command logs
  6795. and the dispatch carries on.
  6796. """
  6797. model = printer.model or ""
  6798. if not supports_airduct(model):
  6799. return
  6800. state = printer_manager.get_status(printer.id)
  6801. current = getattr(state, "airduct_mode", None) if state else None
  6802. if current == _AIRDUCT_MODE_COOLING:
  6803. return
  6804. client = printer_manager.get_client(printer.id)
  6805. if client is None:
  6806. return
  6807. try:
  6808. client.set_airduct_mode("cooling")
  6809. except Exception as exc:
  6810. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6811. async def _preheat_and_soak(
  6812. self,
  6813. db: AsyncSession,
  6814. item: PrintQueueItem,
  6815. printer: Printer,
  6816. archive: PrintArchive | None,
  6817. ) -> bool:
  6818. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6819. Returns True when the dispatch should carry on to the upload — including
  6820. every case where preheat is skipped, since a skipped preheat is not a
  6821. reason to abandon the print. Returns False only when the item stopped
  6822. wanting to be printed while the stage was waiting (cancelled or
  6823. deleted); the caller must then abandon the dispatch, and
  6824. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6825. Resolution order:
  6826. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6827. to the global `preheat_enabled` setting; 'on' forces the stage on
  6828. even if the global is off.
  6829. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6830. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6831. across the trays `item.ams_mapping` names (every loaded slot when
  6832. it names none).
  6833. 3. A target of 0 off the filament map skips the whole stage: the
  6834. materials this print loads want no chamber, so there is nothing to
  6835. soak for and the bed phase would only delay the upload (#3041).
  6836. An explicit 0 typed into the per-item override, or a per-item
  6837. 'on', still runs the bed phase and the soak — both are the user
  6838. asking for a warm bed in so many words.
  6839. 4. Three hardware tiers branch the wait loop:
  6840. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6841. send M141 to the resolved target, then wait for the chamber sensor
  6842. to reach it (or the max-wait timeout to elapse).
  6843. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6844. no M141; the bed is the only heat source, so we wait for the chamber
  6845. sensor to rise via bed radiation OR fall through on timeout.
  6846. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6847. temperature; the function just heats the bed and holds for the
  6848. configured soak duration.
  6849. The bed target comes from the archive's parsed metadata
  6850. (`bed_temperature`); if missing the preheat stage logs and returns
  6851. without dispatching anything, rather than guessing at a default that
  6852. might wreck filament setup.
  6853. Failures are logged but never re-raised — preheat is best-effort. A
  6854. printer that goes offline mid-soak, a refused gcode command, or a
  6855. missing temperature reading must not turn into a failed queue item; the
  6856. normal upload + start path runs immediately after this method returns.
  6857. """
  6858. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6859. if override == "off":
  6860. return True
  6861. if override == "inherit":
  6862. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6863. if not enabled:
  6864. return True
  6865. # override == "on" forces the stage on regardless of the global setting.
  6866. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6867. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6868. # Chamber target resolution:
  6869. # 1. Explicit per-item override beats everything (user knows best).
  6870. # 2. Otherwise derive from the filament types this print loads, via
  6871. # the per-filament target map. A PLA-only print derives 0 and the
  6872. # block below skips the stage without the user touching anything,
  6873. # even when an ASA spool is sitting in another slot of the same
  6874. # AMS (#2886).
  6875. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6876. if explicit_target is not None and explicit_target > 0:
  6877. chamber_target = int(explicit_target)
  6878. chamber_source = "item-override"
  6879. elif explicit_target == 0:
  6880. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6881. chamber_source = "item-override-zero"
  6882. else:
  6883. targets = await self._get_preheat_filament_targets(db)
  6884. chamber_target = self._derive_chamber_target(printer, targets, item)
  6885. chamber_source = "filament-map"
  6886. # Nothing to preheat *for*. A zero that came out of the filament map is
  6887. # the map saying this print's materials want no chamber conditioning --
  6888. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6889. # anyway heated the bed and then held it for the full soak, which
  6890. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6891. # own G-code sets the bed the moment it starts, so preheating it here
  6892. # only moves that heating ahead of the upload instead of overlapping
  6893. # with it, and the soak has no chamber to condition (#3041).
  6894. #
  6895. # An explicit statement from the user still runs the stage. Forcing the
  6896. # per-item override to 'on', or typing a chamber target of exactly 0,
  6897. # both mean "preheat the bed for this print" -- the second is
  6898. # documented as doing precisely that. Only the automatic path, the
  6899. # global toggle plus the filament map, short-circuits here.
  6900. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6901. logger.info(
  6902. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6903. "target, so there is nothing to soak for (override=%s model=%s)",
  6904. item.id,
  6905. override,
  6906. printer.model or "",
  6907. )
  6908. self._preheat_flap_to_cooling(item.id, printer)
  6909. return True
  6910. bed_target = await _queued_plate_bed_temperature(item, archive)
  6911. if bed_target <= 0:
  6912. # No bed temperature in the slicer metadata. When the print needs a
  6913. # hot chamber the bed is simply how we heat it, so fall back to the
  6914. # configured chamber-heating bed temperature rather than skipping
  6915. # the whole stage — otherwise the print starts with a cold chamber,
  6916. # which is exactly what preheat exists to prevent. Without a chamber
  6917. # requirement there is nothing to preheat *for*, so skip as before
  6918. # rather than guess a bed temperature for the print itself.
  6919. if chamber_target <= 0:
  6920. logger.info(
  6921. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6922. item.id,
  6923. )
  6924. return True
  6925. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6926. logger.info(
  6927. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6928. "%d°C to drive the chamber to %d°C",
  6929. item.id,
  6930. bed_target,
  6931. chamber_target,
  6932. )
  6933. client = printer_manager.get_client(printer.id)
  6934. if client is None:
  6935. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6936. return True
  6937. model = printer.model or ""
  6938. has_heater = supports_chamber_heater(model)
  6939. has_sensor = supports_chamber_temp(model)
  6940. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6941. # Fast path: if the chamber has been continuously above target for at
  6942. # least soak_seconds and the bed is already at temperature, skip the
  6943. # entire preheat stage. Typical case: keep-warm held the bed between
  6944. # consecutive same-material prints and the chamber never dropped.
  6945. if do_chamber and has_sensor and soak_seconds > 0:
  6946. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6947. if remaining == 0:
  6948. cur = printer_manager.get_status(printer.id)
  6949. if cur:
  6950. cur_temps = cur.temperatures or {}
  6951. if (
  6952. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6953. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6954. ):
  6955. logger.info(
  6956. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6957. "and bed is already at temperature (chamber history fast-path)",
  6958. item.id,
  6959. chamber_target,
  6960. soak_seconds,
  6961. )
  6962. # Still set targets to prevent cooling during the 3MF upload window.
  6963. # Register each successful set in the preheat pin so `_dispatch_one`
  6964. # unwinds them on any non-success exit.
  6965. pin = self._preheat_pin.setdefault(printer.id, set())
  6966. try:
  6967. client.set_bed_temperature(bed_target)
  6968. pin.add("bed")
  6969. self._preheat_pin_bed[printer.id] = bed_target
  6970. except Exception as exc:
  6971. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6972. if supports_airduct(model):
  6973. cur_airduct = getattr(cur, "airduct_mode", None)
  6974. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6975. try:
  6976. client.set_airduct_mode("heating")
  6977. # Only undo what we can see we replaced. `None`
  6978. # means no mode has been observed yet, and
  6979. # rolling that back to cooling would assert a
  6980. # state the printer never reported.
  6981. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6982. pin.add("airduct")
  6983. except Exception as exc:
  6984. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6985. if has_heater:
  6986. try:
  6987. client.set_chamber_temperature(chamber_target)
  6988. pin.add("chamber")
  6989. except Exception as exc:
  6990. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6991. return True
  6992. logger.info(
  6993. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6994. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6995. item.id,
  6996. bed_target,
  6997. chamber_target if do_chamber else 0,
  6998. chamber_source,
  6999. override,
  7000. model,
  7001. has_heater,
  7002. has_sensor,
  7003. max_wait,
  7004. soak_seconds,
  7005. )
  7006. # Preheat rollback registry: everything we set below is recorded here so
  7007. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  7008. # (bed off, chamber off, airduct back to cooling) on any non-success
  7009. # exit. Populated as each command succeeds; consumed and cleared by
  7010. # `_dispatch_one`.
  7011. pin = self._preheat_pin.setdefault(printer.id, set())
  7012. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  7013. # cache the target locally so the polling reads below see consistent
  7014. # state (firmware MQTT echoes lag by ~1s).
  7015. try:
  7016. client.set_bed_temperature(bed_target)
  7017. pin.add("bed")
  7018. self._preheat_pin_bed[printer.id] = bed_target
  7019. except Exception as exc:
  7020. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  7021. return True
  7022. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  7023. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  7024. # left it on, regardless of M141. Default cooling actively vents the
  7025. # chamber, so a `chamber_target > 0` print with the flap stuck in
  7026. # cooling never converges — the heater fights the open exhaust. We
  7027. # flip the flap BEFORE M141 to "heating" when the preheat wants
  7028. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  7029. # on an H2D that was previously running ABS would otherwise stay in
  7030. # heating mode and overheat PLA). The current-state read keeps the
  7031. # command idempotent — no MQTT chatter when the flap is already where
  7032. # we want it.
  7033. if supports_airduct(model):
  7034. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  7035. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  7036. current_state = printer_manager.get_status(printer.id)
  7037. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  7038. if current_airduct != desired_id:
  7039. try:
  7040. client.set_airduct_mode(desired_airduct)
  7041. # As in the fast path: only pin a rollback for a flap we
  7042. # saw in cooling. `current_airduct` of None means no mode
  7043. # has been observed, so there is nothing to restore to.
  7044. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  7045. pin.add("airduct")
  7046. except Exception as exc:
  7047. logger.warning(
  7048. "Queue item %s: preheat airduct %s mode failed: %s",
  7049. item.id,
  7050. desired_airduct,
  7051. exc,
  7052. )
  7053. if do_chamber and has_heater:
  7054. try:
  7055. client.set_chamber_temperature(chamber_target)
  7056. pin.add("chamber")
  7057. except Exception as exc:
  7058. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  7059. # Release the pooled DB connection before the (potentially many-minute)
  7060. # heat-soak wait below (#2572). Every setting this method needs is read
  7061. # above; the wait/soak loop only polls printer_manager state and sleeps —
  7062. # it never touches the DB. Without this the caller's transaction sat
  7063. # "idle in transaction" for the whole soak, pinning one pooled connection
  7064. # per preheating printer. expire_on_commit=False keeps item/printer
  7065. # readable afterwards; there are no pending writes to lose here.
  7066. await db.commit()
  7067. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  7068. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  7069. # Poll every 3s — frequent enough for responsive logging without
  7070. # spamming the MQTT state stream. The "converged" predicate is:
  7071. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  7072. # AND
  7073. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  7074. BED_TOLERANCE = 2.0
  7075. CHAMBER_TOLERANCE = 2.0
  7076. POLL_INTERVAL = 3.0
  7077. deadline = asyncio.get_event_loop().time() + max_wait
  7078. while True:
  7079. state = printer_manager.get_status(printer.id)
  7080. if state is None:
  7081. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  7082. break
  7083. temps = state.temperatures or {}
  7084. bed_now = float(temps.get("bed", 0) or 0)
  7085. chamber_now = float(temps.get("chamber", 0) or 0)
  7086. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  7087. if not do_chamber:
  7088. chamber_ok = True # phase disabled or model has neither sensor nor heater
  7089. elif not has_sensor:
  7090. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  7091. else:
  7092. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  7093. if bed_ok and chamber_ok:
  7094. logger.info(
  7095. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  7096. item.id,
  7097. bed_now,
  7098. chamber_now,
  7099. )
  7100. break
  7101. if asyncio.get_event_loop().time() >= deadline:
  7102. logger.info(
  7103. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7104. item.id,
  7105. bed_now,
  7106. bed_target,
  7107. chamber_now,
  7108. chamber_target if do_chamber else 0,
  7109. )
  7110. break
  7111. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7112. logger.info(
  7113. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7114. item.id,
  7115. )
  7116. return False
  7117. if soak_seconds > 0:
  7118. if do_chamber and has_sensor:
  7119. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7120. else:
  7121. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7122. if remaining > 0:
  7123. logger.info(
  7124. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7125. "has been above target for ~%ds already)",
  7126. item.id,
  7127. remaining,
  7128. soak_seconds,
  7129. soak_seconds - remaining,
  7130. )
  7131. if not await self._preheat_sleep(item.id, remaining):
  7132. logger.info(
  7133. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7134. item.id,
  7135. )
  7136. return False
  7137. else:
  7138. logger.info(
  7139. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7140. item.id,
  7141. chamber_target,
  7142. soak_seconds,
  7143. )
  7144. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7145. return True
  7146. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7147. """Turn on smart plug and wait for printer to connect.
  7148. Returns True if printer connected successfully within timeout.
  7149. """
  7150. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7151. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7152. # Check current plug state
  7153. status = await service.get_status(plug)
  7154. if not status.get("reachable"):
  7155. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7156. return False
  7157. # Turn on if not already on
  7158. if status.get("state") != "ON":
  7159. success = await service.turn_on(plug)
  7160. if not success:
  7161. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7162. return False
  7163. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7164. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7165. # Get printer from database for connection
  7166. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7167. printer = result.scalar_one_or_none()
  7168. if not printer:
  7169. logger.error("Printer %s not found in database", printer_id)
  7170. return False
  7171. # End the pass's transaction before waiting up to minutes for the boot:
  7172. # held open, it pins a pooled connection idle in transaction
  7173. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7174. # through it.
  7175. await db.commit()
  7176. # Wait for printer to boot (give it some time before trying to connect)
  7177. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7178. await asyncio.sleep(30)
  7179. # Try to connect to the printer periodically
  7180. elapsed = 30 # Already waited 30s
  7181. while elapsed < self._power_on_wait_time:
  7182. # Try to connect
  7183. logger.info("Attempting to connect to printer %s...", printer_id)
  7184. try:
  7185. connected = await printer_manager.connect_printer(printer)
  7186. if connected:
  7187. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7188. # Give it a moment to stabilize and get status
  7189. await asyncio.sleep(5)
  7190. return True
  7191. except Exception as e:
  7192. logger.debug("Connection attempt failed: %s", e)
  7193. await asyncio.sleep(self._power_on_check_interval)
  7194. elapsed += self._power_on_check_interval
  7195. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7196. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7197. return False
  7198. async def _check_previous_success(
  7199. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7200. ) -> bool:
  7201. """Check if the previous print on this printer succeeded.
  7202. ``printer_id`` names the printer to look at when the item has none yet
  7203. (a job for any printer of a model, checked against the one offered).
  7204. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7205. deliberate action, not a failure, so subsequent items should still
  7206. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7207. a skip isn't an actual print attempt, so it must not gate downstream
  7208. items — counting it as a failed predecessor was the cascade bug that
  7209. let a single cancellation block 18 items over 3 days for the reporter.
  7210. Only `failed` and `aborted` — real print-attempt failures — block.
  7211. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7212. action — #1818) are also excluded from the lookback so the user can
  7213. clear the gate after fixing the physical issue without having to
  7214. re-queue every downstream job.
  7215. """
  7216. result = await db.execute(
  7217. select(PrintQueueItem)
  7218. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7219. .where(PrintQueueItem.id != item.id)
  7220. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7221. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7222. # A row ended without a completion time must not count as the
  7223. # latest: PostgreSQL sorts NULL first in a descending order.
  7224. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7225. .limit(1)
  7226. )
  7227. prev_item = result.scalar_one_or_none()
  7228. # If no previous item, assume success (first in queue)
  7229. if not prev_item:
  7230. return True
  7231. return prev_item.status in ("completed", "cancelled")
  7232. async def _repoint_siblings_at_archive(
  7233. self,
  7234. db: AsyncSession,
  7235. *,
  7236. consumed_library_file_id: int,
  7237. archive_id: int,
  7238. dispatched_item_id: int,
  7239. ) -> int:
  7240. """Move the other queue items off a library row that is about to be deleted (#2819).
  7241. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7242. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7243. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7244. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7245. clones, so the first dispatch could pull the file out from under rows that
  7246. had not run yet. What those rows did next depended on the database, and
  7247. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7248. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7249. they were left pointing at a row that no longer existed, failing with
  7250. "Library file not found" whenever someone started them -- or sitting
  7251. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7252. constraint, so there the rows were deleted outright and the queued copies
  7253. simply vanished, with no error and no history.
  7254. The archive holds its own copy of the 3MF, so the remaining copies can print
  7255. from it instead. Two things happen here, and both must happen *before* the
  7256. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7257. * every row still naming the file has ``library_file_id`` cleared, which is
  7258. what takes it out of the cascade's reach. That covers rows this cannot
  7259. re-point as well -- a copy already printing from its own archive, and the
  7260. finished ones, which are not spare parts but the record a batch order
  7261. counts its progress from.
  7262. * the rows that still need something to print are pointed at the archive.
  7263. Returns how many items were re-pointed.
  7264. """
  7265. variant_item_ids = (
  7266. (
  7267. await db.execute(
  7268. select(PrintQueueVariant.queue_item_id).where(
  7269. PrintQueueVariant.library_file_id == consumed_library_file_id
  7270. )
  7271. )
  7272. )
  7273. .scalars()
  7274. .all()
  7275. )
  7276. # Candidate rows naming the consumed file have to go rather than be
  7277. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7278. # one out of the cascade. This is what PostgreSQL already does, and
  7279. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7280. # outcome changes -- the two backends simply stop disagreeing about
  7281. # whether the row is still there.
  7282. #
  7283. # It also has to happen before the re-point below: a cross-model item
  7284. # (#671) picks a variant every pass and folds it onto the row, and
  7285. # _resolve_variant clears archive_id as it does so, which would undo the
  7286. # re-point on the very next lap.
  7287. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7288. # An item left with other candidates still has somewhere to go, and those
  7289. # carry their own target model -- pointing it at this archive would print a
  7290. # file the matcher never chose. It is excluded from the re-point and simply
  7291. # re-resolves against what is left.
  7292. surviving_variant_item_ids = set(
  7293. (
  7294. await db.execute(
  7295. select(PrintQueueVariant.queue_item_id).where(
  7296. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7297. )
  7298. )
  7299. )
  7300. .scalars()
  7301. .all()
  7302. )
  7303. repoint_ids = set(
  7304. (
  7305. await db.execute(
  7306. select(PrintQueueItem.id)
  7307. .where(PrintQueueItem.id != dispatched_item_id)
  7308. .where(PrintQueueItem.archive_id.is_(None))
  7309. # "skipped" belongs here with the two live states: it is not
  7310. # terminal. Clearing a printer's previous-success gate puts
  7311. # every item skipped by it back to "pending"
  7312. # (resume_after_failure), and one restored onto a deleted
  7313. # file is the same orphan by a slower route. "failed",
  7314. # "cancelled", "aborted" and "completed" never return.
  7315. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7316. .where(
  7317. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7318. )
  7319. .where(
  7320. or_(
  7321. PrintQueueItem.library_file_id == consumed_library_file_id,
  7322. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7323. )
  7324. )
  7325. )
  7326. )
  7327. .scalars()
  7328. .all()
  7329. )
  7330. if repoint_ids:
  7331. await db.execute(
  7332. update(PrintQueueItem)
  7333. .where(PrintQueueItem.id.in_(repoint_ids))
  7334. .values(
  7335. archive_id=archive_id,
  7336. library_file_id=None,
  7337. # The file this flag named is already consumed. Leaving it set
  7338. # would arm every re-pointed copy to delete whatever library
  7339. # row it is next given.
  7340. cleanup_library_after_dispatch=False,
  7341. )
  7342. )
  7343. logger.info(
  7344. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7345. sorted(repoint_ids),
  7346. archive_id,
  7347. consumed_library_file_id,
  7348. dispatched_item_id,
  7349. )
  7350. # Everything else that still names the file: taken out of the cascade's
  7351. # reach without touching what it prints. The file is gone either way; what
  7352. # this preserves is the row.
  7353. await db.execute(
  7354. update(PrintQueueItem)
  7355. .where(PrintQueueItem.id != dispatched_item_id)
  7356. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7357. .values(library_file_id=None)
  7358. )
  7359. return len(repoint_ids)
  7360. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7361. """Schedule power-off if the queue item enabled auto_off_after.
  7362. Delegates to the smart-plug manager so the off honours each plug's
  7363. configured strategy (time delay or temperature threshold), is cancelled
  7364. if the printer starts printing again, and never cuts power on a loaded
  7365. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7366. powered off on the timeout regardless of print state.
  7367. """
  7368. if not item.auto_off_after:
  7369. return
  7370. try:
  7371. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7372. except Exception as e:
  7373. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7374. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7375. """Get a human-readable name for a queue item."""
  7376. if item.archive_id:
  7377. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7378. archive = result.scalar_one_or_none()
  7379. if archive:
  7380. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7381. if item.library_file_id:
  7382. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7383. library_file = result.scalar_one_or_none()
  7384. if library_file:
  7385. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7386. # A cross-model item (#671) holds no file of its own until a printer is
  7387. # picked, so name it after its first candidate — otherwise every waiting
  7388. # notification for one reads "Job #12". Queried rather than read off
  7389. # item.variants because callers outside the selection loop have not
  7390. # eager-loaded them, and a lazy load raises in async.
  7391. first_variant_name = (
  7392. await db.execute(
  7393. select(LibraryFile.filename)
  7394. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7395. .where(PrintQueueVariant.queue_item_id == item.id)
  7396. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7397. .limit(1)
  7398. )
  7399. ).scalar_one_or_none()
  7400. if first_variant_name:
  7401. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7402. return f"Job #{item.id}"
  7403. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7404. """Get printer by ID."""
  7405. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7406. return result.scalar_one_or_none()
  7407. async def _notify_dispatch_gave_up(
  7408. self,
  7409. queue_item_id: int,
  7410. printer_id: int,
  7411. created_by_id: int | None,
  7412. reason: str = "Printer accepted the file but never started printing",
  7413. ) -> None:
  7414. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7415. Called from the watchdog, which is a background task with no session of
  7416. its own — hence the fresh one here. Best-effort throughout: the row is
  7417. already marked failed and that is the load-bearing part; a notification
  7418. provider being down must not resurrect the retry loop we just stopped.
  7419. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7420. path passes its own, because "accepted the file but never started" is the
  7421. opposite of what happened there — the printer refused it outright (#2732).
  7422. """
  7423. try:
  7424. async with async_session() as db:
  7425. item = await db.get(PrintQueueItem, queue_item_id)
  7426. if not item:
  7427. return
  7428. job_name = await self._get_job_name(db, item)
  7429. printer = await self._get_printer(db, printer_id)
  7430. await notification_service.on_queue_job_failed(
  7431. job_name=job_name,
  7432. printer_id=printer_id,
  7433. printer_name=printer.name if printer else "Unknown",
  7434. reason=reason,
  7435. db=db,
  7436. )
  7437. except Exception as e:
  7438. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7439. try:
  7440. await ws_manager.send_queue_item_failed(
  7441. user_id=created_by_id,
  7442. queue_item_id=queue_item_id,
  7443. printer_id=printer_id,
  7444. reason="never_started",
  7445. )
  7446. except Exception:
  7447. pass # toast is best-effort
  7448. async def _filament_short_on(
  7449. self,
  7450. db: AsyncSession,
  7451. item: PrintQueueItem,
  7452. printer_id: int,
  7453. *,
  7454. require_known: bool = False,
  7455. ) -> bool:
  7456. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7457. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7458. assigned there, with the mapping the item would get there, but changes
  7459. nothing. The model-based matcher uses it to prefer a printer whose
  7460. spools can finish the job.
  7461. False whenever the gate would let the item through: "Print Anyway",
  7462. no mapping, or a check that fails. With ``require_known`` all three of
  7463. those, and any printed slot whose remaining amount is unknown, count
  7464. as short instead: releasing a held job starts it with nobody asked, so
  7465. it needs the amount on record, not merely nothing against it.
  7466. """
  7467. if item.skip_filament_check:
  7468. return False
  7469. try:
  7470. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7471. if not mapping:
  7472. return require_known
  7473. deficit = await compute_deficit_for_queue_item(
  7474. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7475. )
  7476. except Exception as e:
  7477. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7478. return require_known
  7479. return bool(deficit)
  7480. async def _release_short_model_hold(
  7481. self,
  7482. db: AsyncSession,
  7483. item: PrintQueueItem,
  7484. unavailable: set[int],
  7485. require_plate_clear: bool,
  7486. printer_scope: PrinterScope,
  7487. ) -> bool:
  7488. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7489. The deficit gate holds a model-based job on the printer the matcher
  7490. gave it, because "Print Anyway" needs a printer to print on. When
  7491. another idle printer of the job's model has the filament, the job is
  7492. moved to that printer and its hold lifted, and the fixed-printer
  7493. branch dispatches it in this same pass, through the same checks a
  7494. held job meets when the user presses Start. It is moved rather than
  7495. put back in the pool because the model-based branch would pick again
  7496. without requiring the amounts on record (below), and could pick a
  7497. different printer. Only the deficit gate sets ``filament_short``, so a
  7498. job held for any other reason stays held.
  7499. The printer it is held on is left out: a spool loaded there is started
  7500. with Start, as before, rather than while someone may still be loading
  7501. the next one. Each job is checked at most every
  7502. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7503. on each idle printer again.
  7504. Cross-model jobs (#671) stay held: checking a variant writes its file
  7505. onto the item, which would leave a job that is not moved holding
  7506. another variant's file for the printer it waits on.
  7507. A printer qualifies only on a positive finding: every slot the plate
  7508. prints mapped to a spool whose remaining amount is on record and
  7509. enough. A printer whose spools Bambuddy does not track is not one.
  7510. Returns True when the job was moved. A check that fails keeps the hold
  7511. rather than stopping the queue pass.
  7512. """
  7513. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7514. return False
  7515. if not item.target_model or item.variants:
  7516. return False
  7517. now = time.monotonic()
  7518. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7519. return False
  7520. self._short_hold_checked_at[item.id] = now
  7521. try:
  7522. candidates = _candidates_for(item)
  7523. if not candidates:
  7524. return False
  7525. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7526. async def is_short(pid: int) -> bool:
  7527. return await self._filament_short_on(db, item, pid, require_known=True)
  7528. async def unmatched_on(pid: int) -> list[str]:
  7529. return await self._unmatched_on(db, item, pid)
  7530. match_id, _ = await self._find_idle_printer_for_model(
  7531. db,
  7532. item.target_model,
  7533. unavailable | {item.printer_id},
  7534. effective_types,
  7535. item.target_location,
  7536. filament_overrides=filament_overrides,
  7537. require_plate_clear=require_plate_clear,
  7538. printer_scope=printer_scope,
  7539. is_short=is_short,
  7540. unmatched_on=unmatched_on,
  7541. )
  7542. # Every idle printer short comes back as the first of them.
  7543. if match_id is None or await is_short(match_id):
  7544. return False
  7545. except Exception as e:
  7546. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7547. return False
  7548. logger.info(
  7549. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7550. item.id,
  7551. match_id,
  7552. item.printer_id,
  7553. )
  7554. self._short_hold_checked_at.pop(item.id, None)
  7555. item.printer_id = match_id
  7556. # Resolved against the printer it leaves (#3239): the tray mapping and
  7557. # the nozzle positions.
  7558. drop_printer_resolved(item)
  7559. item.manual_start = False
  7560. item.filament_short = False
  7561. item.waiting_reason = None
  7562. await db.commit()
  7563. try:
  7564. printer = await self._get_printer(db, match_id)
  7565. await notification_service.on_queue_job_assigned(
  7566. job_name=await self._get_job_name(db, item),
  7567. printer_id=match_id,
  7568. printer_name=printer.name if printer else "Unknown",
  7569. target_model=item.target_model,
  7570. db=db,
  7571. )
  7572. except Exception as e:
  7573. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7574. return True
  7575. async def _block_on_filament_deficit(
  7576. self,
  7577. db: AsyncSession,
  7578. item: PrintQueueItem,
  7579. ) -> bool:
  7580. """Promote the item to manual_start when the assigned spool is short (#1496).
  7581. Returns True when this dispatch attempt was blocked, False when the
  7582. item is clear to start. A previously-flagged item whose spool has
  7583. since been swapped to one with enough material clears the flag here
  7584. so the next scheduler tick dispatches it.
  7585. """
  7586. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7587. # don't re-flag, don't even compute. Without this short-circuit the
  7588. # scheduler bounces between "user said anyway" (route clears
  7589. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7590. # on identical spool state) (#1698-followup).
  7591. if item.skip_filament_check:
  7592. # #1762 diagnostic: surface the short-circuit at INFO so a
  7593. # future "Print Anyway didn't work" report (e.g. issue #1762
  7594. # comment 3) has actionable evidence in the support bundle
  7595. # without needing DEBUG enabled.
  7596. logger.info(
  7597. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7598. item.id,
  7599. )
  7600. return False
  7601. try:
  7602. deficit = await compute_deficit_for_queue_item(db, item)
  7603. except Exception as e:
  7604. # Never let a flaky deficit check wedge the queue — log and let
  7605. # dispatch proceed. The PrintModal-side check still runs on the
  7606. # manual paths.
  7607. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7608. return False
  7609. if deficit:
  7610. item.filament_short = True
  7611. item.manual_start = True
  7612. await db.commit()
  7613. job_name = await self._get_job_name(db, item)
  7614. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7615. logger.info(
  7616. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7617. item.id,
  7618. len(deficit),
  7619. )
  7620. try:
  7621. await notification_service.on_queue_job_waiting(
  7622. job_name=job_name,
  7623. target_model=(printer.model if printer else "") or "",
  7624. waiting_reason="filament_short",
  7625. db=db,
  7626. printer_id=item.printer_id,
  7627. )
  7628. except Exception as e:
  7629. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7630. return True
  7631. # No deficit — clear any stale flag from a previous tick.
  7632. if item.filament_short:
  7633. item.filament_short = False
  7634. await db.commit()
  7635. return False
  7636. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7637. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7638. Compared the way the matcher compares, so the same hex or a similar one
  7639. is a match. Only slots the plate prints, mapped to a tray the printer
  7640. reports, with a colour on both sides: anything else is not a colour the
  7641. job printed in.
  7642. """
  7643. by_tray = {f["global_tray_id"]: f for f in loaded}
  7644. found = []
  7645. for req in required:
  7646. slot_id = req.get("slot_id") or 0
  7647. if slot_id <= 0 or slot_id > len(mapping):
  7648. continue
  7649. tray_id = mapping[slot_id - 1]
  7650. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7651. if tray is not None and tray.get("color_known") is False:
  7652. # A spool without a colour set is not a different colour.
  7653. continue
  7654. wanted = self._normalize_color_for_compare(req.get("color"))
  7655. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7656. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7657. continue
  7658. found.append(
  7659. {
  7660. "slot_id": slot_id,
  7661. "type": req.get("type") or "",
  7662. "wanted": f"#{wanted.upper()}",
  7663. "got": f"#{got.upper()}",
  7664. "tray": tray_id,
  7665. }
  7666. )
  7667. return found
  7668. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7669. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7670. Read from the mapping the job is about to be sent with, whoever made
  7671. it: the matcher's same-material fallback, a preset match in another
  7672. colour, or a slot picked by hand. The file's colour is the one after
  7673. overrides, so a colour swapped on purpose is not one. None whenever
  7674. there is nothing to compare, and on any failure: a missing note must
  7675. never stop a print.
  7676. """
  7677. try:
  7678. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7679. if not isinstance(mapping, list) or not item.printer_id:
  7680. return None
  7681. status = printer_manager.get_status(item.printer_id)
  7682. if status is None:
  7683. return None
  7684. required = await self._get_filament_requirements(db, item)
  7685. if not required:
  7686. return None
  7687. self._apply_filament_overrides(item, required)
  7688. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7689. except Exception as e:
  7690. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7691. return None
  7692. if found:
  7693. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7694. return json.dumps(found) if found else None
  7695. async def _unmatched_requirements(
  7696. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7697. ) -> list[dict]:
  7698. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7699. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7700. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7701. on why an empty list is not one.
  7702. """
  7703. if mapping is None:
  7704. status = printer_manager.get_status(printer_id)
  7705. if status is None or not self._build_loaded_filaments(status):
  7706. return []
  7707. # Every required slot reads unresolved against an empty mapping.
  7708. mapping = []
  7709. required = await self._get_filament_requirements(db, item)
  7710. if required:
  7711. self._apply_filament_overrides(item, required)
  7712. else:
  7713. # An unreadable 3MF still has its forced colours to go by: they are
  7714. # what the mapping was built from (#3280).
  7715. required = _forced_override_requirements(item)
  7716. return _unresolved_required(required, mapping) if required else []
  7717. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7718. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7719. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7720. Choosing a printer for an "any model" job only checked that each type
  7721. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7722. the spool on the other nozzle, or one spool asked for twice, passes. The
  7723. hold then gave the printer back, and the next pass chose it again.
  7724. Empty when the hold would let the item through, including "Print
  7725. Anyway" and a match that fails: the printer is then chosen as before.
  7726. """
  7727. if item.skip_filament_check:
  7728. return []
  7729. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7730. if key in self._unmatched_memo:
  7731. return list(self._unmatched_memo[key])
  7732. try:
  7733. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7734. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7735. except Exception as e:
  7736. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7737. return []
  7738. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7739. self._unmatched_memo[key] = described
  7740. return list(described)
  7741. async def _block_on_unmatched_filament(
  7742. self,
  7743. db: AsyncSession,
  7744. item: PrintQueueItem,
  7745. release_assignment: bool = False,
  7746. ) -> bool:
  7747. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7748. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7749. goes ahead, letting the printer choose — which is how a job prints in the
  7750. wrong material without anyone being asked. Holding is the same answer the
  7751. deficit gate already gives for "the spool is too light", so it reuses the
  7752. same promote-and-notify machinery.
  7753. Keyed off unresolved slots in the *computed* mapping intersected with the
  7754. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7755. read: on its own it also pads slots this plate does not print, so the
  7756. array alone would hold perfectly good jobs. Reading the mapping rather
  7757. than the printer's loaded filament types also inherits the matcher's
  7758. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7759. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7760. type-only scan would wave that through.
  7761. A mapping that resolved *nothing* is the same finding arriving as an
  7762. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7763. could not replace, and dispatch then goes out as ``use_ams`` with no
  7764. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7765. That is held too, but only once live status positively reports loaded
  7766. trays: #2589's mapping is bogus precisely because the AMS was not known
  7767. yet, and its empty loaded list is that ignorance rather than a miss.
  7768. ``release_assignment`` is for the model-based path, which commits its
  7769. printer choice before the gates run. Holding an "any P2S" job would
  7770. otherwise pin it to the one P2S that could not run it.
  7771. Returns True when this dispatch attempt was blocked.
  7772. """
  7773. if item.skip_filament_check or not item.printer_id:
  7774. return False
  7775. mapping: list | None = None
  7776. if item.ams_mapping:
  7777. try:
  7778. mapping = json.loads(item.ams_mapping)
  7779. except (json.JSONDecodeError, TypeError):
  7780. return False
  7781. if not isinstance(mapping, list):
  7782. return False
  7783. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7784. if not unmatched:
  7785. # No cleanup needed here: once start is pressed the item is no
  7786. # longer staged, and whichever exit runs next overwrites the reason
  7787. # (`hold_item` on the fixed-printer branch, the assignment on the
  7788. # model-based one), as does dispatch.
  7789. return False
  7790. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7791. held_by = item.printer_id
  7792. item.manual_start = True
  7793. # Human-readable: this renders on the queue row.
  7794. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7795. if release_assignment:
  7796. # "Any P2S" means any, so the job returns to the pool rather than
  7797. # waiting on the printer that could not take it. The mapping goes
  7798. # with the assignment: its tray IDs were resolved against the
  7799. # printer being released and mean nothing on the next one (#2799),
  7800. # and keeping them would hold the job again even on a printer that
  7801. # has the filament, since an unresolved slot is deliberately not a
  7802. # conflict worth recomputing over.
  7803. item.printer_id = None
  7804. drop_printer_resolved(item)
  7805. await db.commit()
  7806. job_name = await self._get_job_name(db, item)
  7807. printer = await self._get_printer(db, held_by)
  7808. logger.info(
  7809. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7810. item.id,
  7811. held_by,
  7812. wanted,
  7813. )
  7814. try:
  7815. await notification_service.on_queue_job_waiting(
  7816. job_name=job_name,
  7817. target_model=(printer.model if printer else "") or "",
  7818. waiting_reason=f"needs {wanted}",
  7819. db=db,
  7820. # Released to the pool: no printer holds it any more.
  7821. printer_id=None if release_assignment else held_by,
  7822. )
  7823. except Exception as e:
  7824. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7825. return True
  7826. @staticmethod
  7827. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7828. """The queue item's owner as the row has it now.
  7829. item.created_by_id was read before preheat and upload, which can take
  7830. minutes; deleting the user clears the row, not this session's copy.
  7831. """
  7832. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7833. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7834. """Hand the queue item's owner to printer_manager so the
  7835. print-complete callback can credit the user in PrintLogEntry (#1670).
  7836. No-ops when the item has no `created_by_id` or the referenced user
  7837. row is missing (e.g. user deleted between queue-add and dispatch —
  7838. in that case the print log row falls back to the existing un-credited
  7839. behaviour rather than crashing the dispatch).
  7840. """
  7841. from backend.app.models.user import User
  7842. # Read from the row, not item.created_by_id or db.get: both can still
  7843. # hold a user deleted during the upload, after delete_user forgot them
  7844. # (on SQLite the id may be someone new's by the time the print ends).
  7845. # Joined with the printer too: one deleted during the upload was
  7846. # forgotten as well, and this would write the owner back under its id.
  7847. owner = (
  7848. await db.execute(
  7849. select(User.id, User.username)
  7850. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7851. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7852. .where(PrintQueueItem.id == item.id)
  7853. )
  7854. ).first()
  7855. if owner:
  7856. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7857. if item.printer_id is not None:
  7858. self._unconfirmed_print_user[item.id] = item.printer_id
  7859. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7860. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7861. A cancel lands in another session while the upload runs (the edit route
  7862. even tells users to cancel a job that is being sent). An unconditional
  7863. write here would turn that cancellation into a failure, with a failure
  7864. notification, and block the next job that needs the previous print to
  7865. have succeeded. Returns whether the item was marked failed.
  7866. """
  7867. result = cast(
  7868. CursorResult,
  7869. await db.execute(
  7870. update(PrintQueueItem)
  7871. .where(PrintQueueItem.id == item.id)
  7872. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7873. # Failed before the print started: no slot printed in any colour (#3279).
  7874. .values(
  7875. status="failed",
  7876. error_message=message,
  7877. completed_at=datetime.now(timezone.utc),
  7878. color_substitutions=None,
  7879. )
  7880. .execution_options(synchronize_session=False)
  7881. ),
  7882. )
  7883. await db.commit()
  7884. if result.rowcount == 0:
  7885. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7886. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7887. return False
  7888. await db.refresh(item)
  7889. from backend.app.services.print_batch import refresh_batches_after
  7890. await refresh_batches_after([item.id])
  7891. return True
  7892. @staticmethod
  7893. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7894. """Put a job whose printer turned busy before the start back in the queue.
  7895. Only if it is still printing: a stop that landed meanwhile stands.
  7896. """
  7897. await db.execute(
  7898. update(PrintQueueItem)
  7899. .where(PrintQueueItem.id == item.id)
  7900. .where(PrintQueueItem.status == "printing")
  7901. .values(status="pending", started_at=None, color_substitutions=None)
  7902. .execution_options(synchronize_session=False)
  7903. )
  7904. await db.commit()
  7905. @staticmethod
  7906. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  7907. """Close the dispatch toast of an item the user cancelled while it was sent."""
  7908. try:
  7909. await ws_manager.send_queue_item_failed(
  7910. user_id=toast_uid,
  7911. queue_item_id=item.id,
  7912. printer_id=item.printer_id,
  7913. reason="cancelled_mid_dispatch",
  7914. )
  7915. except Exception:
  7916. pass # toast is best-effort
  7917. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  7918. """Upload file and start print for a queue item.
  7919. Supports two sources:
  7920. - archive_id: Print from an existing archive
  7921. - library_file_id: Print from a library file (file manager)
  7922. """
  7923. logger.info("Starting queue item %s", item.id)
  7924. # Also covers a reservation left active by a process interruption
  7925. # during an earlier attempt. `_dispatch_one` releases this marker on
  7926. # every exit unless start_print() confirms that the command was sent.
  7927. self._unconfirmed_budget_reservations.add(item.id)
  7928. try:
  7929. from backend.app.models.user import User
  7930. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  7931. # Recompute at the final authorization boundary as well as enqueue
  7932. # time. This covers rows created before the server-side estimate
  7933. # migration and prevents any alternate write path from weakening
  7934. # the budget reservation.
  7935. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  7936. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  7937. item.estimated_cost = await estimate_queue_source_cost(
  7938. db,
  7939. archive=archive,
  7940. library_file=library_file,
  7941. plate_id=item.plate_id,
  7942. ams_mapping=item.ams_mapping,
  7943. printer_id=item.printer_id,
  7944. )
  7945. await validate_print_budget(
  7946. db,
  7947. cost_center_id=item.cost_center_id,
  7948. estimated_cost=item.estimated_cost,
  7949. current_user=queue_user,
  7950. exclude_queue_item_id=item.id,
  7951. exclude_reservation_source_type="print_queue",
  7952. exclude_reservation_source_id=item.id,
  7953. )
  7954. budget_reservation = await create_budget_reservation(
  7955. db,
  7956. cost_center_id=item.cost_center_id,
  7957. estimated_cost=item.estimated_cost,
  7958. current_user=queue_user,
  7959. source_type="print_queue",
  7960. source_id=item.id,
  7961. print_archive_id=item.archive_id,
  7962. exclude_queue_item_id=item.id,
  7963. )
  7964. await db.commit()
  7965. except HTTPException as exc:
  7966. if not await self._fail_dispatch(db, item, str(exc.detail)):
  7967. return
  7968. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  7969. await self._power_off_if_needed(db, item)
  7970. return
  7971. # Get printer first (needed for both paths)
  7972. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  7973. printer = result.scalar_one_or_none()
  7974. if not printer:
  7975. if not await self._fail_dispatch(db, item, "Printer not found"):
  7976. return
  7977. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  7978. await self._power_off_if_needed(db, item)
  7979. return
  7980. # Check printer is connected
  7981. if not printer_manager.is_connected(item.printer_id):
  7982. if not await self._fail_dispatch(db, item, "Printer not connected"):
  7983. return
  7984. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  7985. await self._power_off_if_needed(db, item)
  7986. return
  7987. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  7988. # `items` was taken at the top of check_queue, but the user can /cancel
  7989. # any pending row in the gap before we reach this point. Re-read the
  7990. # row and bail out cleanly instead of starting an FTP upload for a row
  7991. # that's already cancelled. The atomic CAS at the pending→printing
  7992. # transition (below, before start_print) is the load-bearing guard;
  7993. # this is the early-exit optimisation that avoids wasted FTP I/O.
  7994. await db.refresh(item)
  7995. if item.status != "pending":
  7996. logger.info(
  7997. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  7998. item.id,
  7999. item.status,
  8000. )
  8001. return
  8002. # Busy-printer guard (#2598). check_queue gates dispatch on
  8003. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  8004. # keep reporting FINISH for tens of seconds *after* it accepted a
  8005. # project_file (see the watchdog's phase-B note). A watchdog revert
  8006. # (#2555) also releases the dispatch hold, so a re-selected item can
  8007. # reach here while its printer has actually started printing. Uploading
  8008. # and dispatching then collides with the live job — the firmware answers
  8009. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  8010. # live state right before the expensive FTP upload: if the printer is
  8011. # busy, leave the item pending and let a later tick dispatch it once the
  8012. # printer is genuinely idle. No wasted upload, no collision.
  8013. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8014. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  8015. logger.info(
  8016. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  8017. "leaving item pending for a later tick (#2598)",
  8018. item.id,
  8019. item.printer_id,
  8020. pre_dispatch_state,
  8021. )
  8022. return
  8023. # Determine source: archive or library file
  8024. archive = None
  8025. library_file = None
  8026. file_path = None
  8027. filename = None
  8028. cleanup_disk_paths: list[Path] = []
  8029. # Set when a dispatch consumes its library file, so the photos can be
  8030. # carried over after the commit that removes the row (#3077).
  8031. consumed_library_file_id: int | None = None
  8032. consumed_photos: list[str] = []
  8033. if item.archive_id:
  8034. # Print from archive
  8035. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  8036. archive = result.scalar_one_or_none()
  8037. if not archive:
  8038. if not await self._fail_dispatch(db, item, "Archive not found"):
  8039. return
  8040. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  8041. await self._power_off_if_needed(db, item)
  8042. return
  8043. # Persist the queue item's selected plate onto the archive so Print
  8044. # History can show the actual plate after cancel/fail/complete (#2603).
  8045. # Only when the archive doesn't already carry one, so a reprint of a
  8046. # plate-specific archive isn't relabelled by a differently-plated
  8047. # queue row.
  8048. if archive.plate_id is None and item.plate_id is not None:
  8049. archive.plate_id = item.plate_id
  8050. # Ask-for-outcome opt-in rides from the queue item to the archive
  8051. # the same way (#1898); never cleared here so a reprint of an
  8052. # archive that already asked keeps asking.
  8053. if item.confirm_outcome:
  8054. archive.confirm_requested = True
  8055. file_path = settings.base_dir / archive.file_path
  8056. filename = archive.filename
  8057. elif item.library_file_id:
  8058. # Print from library file (file manager)
  8059. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  8060. library_file = result.scalar_one_or_none()
  8061. if not library_file:
  8062. # "Not found" covers two different situations and only one of
  8063. # them is recoverable, so say which. A trashed file is still
  8064. # there and restoring it makes a re-queued job work; a file that
  8065. # is really gone needs a different one. Neither is knowable from
  8066. # the queue, which is the whole complaint about this message.
  8067. trashed = (
  8068. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  8069. ).scalar_one_or_none()
  8070. if not await self._fail_dispatch(
  8071. db,
  8072. item,
  8073. (
  8074. f"'{trashed}' is in the library trash — restore it and queue the print again"
  8075. if trashed
  8076. else "Library file not found — it was deleted after this job was queued"
  8077. ),
  8078. ):
  8079. return
  8080. logger.error(
  8081. "Queue item %s: library file %s is %s",
  8082. item.id,
  8083. item.library_file_id,
  8084. "in the trash" if trashed else "gone",
  8085. )
  8086. await self._power_off_if_needed(db, item)
  8087. return
  8088. # Library files store absolute paths
  8089. lib_path = Path(library_file.file_path)
  8090. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  8091. filename = library_file.filename
  8092. # Create archive from library file so usage tracking has access to the 3MF
  8093. queue_item_id = item.id
  8094. # Held separately: a cleanup dispatch clears item.library_file_id
  8095. # below, and the log line at the end of this block reported that
  8096. # cleared field -- so every consumed print logged "from library
  8097. # file None", which is the one case worth being able to trace.
  8098. source_library_file_id = item.library_file_id
  8099. try:
  8100. from backend.app.services.archive import ArchiveService
  8101. archive_service = ArchiveService(db)
  8102. archive = await archive_service.archive_print(
  8103. printer_id=item.printer_id,
  8104. source_file=file_path,
  8105. original_filename=filename,
  8106. created_by_id=item.created_by_id,
  8107. project_id=item.project_id,
  8108. cost_center_id=item.cost_center_id,
  8109. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8110. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8111. )
  8112. if archive:
  8113. item.archive_id = archive.id
  8114. if item.confirm_outcome:
  8115. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8116. if budget_reservation is not None:
  8117. budget_reservation.print_archive_id = archive.id
  8118. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8119. consumed_library_file_id = library_file.id
  8120. item.library_file_id = None
  8121. cleanup_disk_paths.append(file_path)
  8122. if library_file.thumbnail_path:
  8123. thumb_path = Path(library_file.thumbnail_path)
  8124. if not thumb_path.is_absolute():
  8125. thumb_path = settings.base_dir / library_file.thumbnail_path
  8126. cleanup_disk_paths.append(thumb_path)
  8127. # Before the delete, not after: on PostgreSQL the FK
  8128. # cascade would already have taken these rows (#2819).
  8129. await self._repoint_siblings_at_archive(
  8130. db,
  8131. consumed_library_file_id=consumed_library_file_id,
  8132. archive_id=archive.id,
  8133. dispatched_item_id=item.id,
  8134. )
  8135. # Read while the row is still here; the photos move
  8136. # below, once the delete has actually committed.
  8137. consumed_photos = list(library_file.photos or [])
  8138. # The delete clears the link on the earlier archives of
  8139. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8140. # SQLite). This one is loaded, so set it here too, or it
  8141. # keeps the stale id in the session.
  8142. archive.library_file_id = None
  8143. await db.delete(library_file)
  8144. file_path = settings.base_dir / archive.file_path
  8145. filename = archive.filename
  8146. # Commit, not flush — flush opens the SQLite write
  8147. # transaction (item.archive_id update + library_file
  8148. # delete) and would hold the WAL writer lock through the
  8149. # FTP upload below, causing "database is locked" cascades
  8150. # for sensor history + concurrent cancels (#1853).
  8151. await db.commit()
  8152. logger.info(
  8153. "Queue item %s: Created archive %s from library file %s",
  8154. item.id,
  8155. archive.id,
  8156. source_library_file_id,
  8157. )
  8158. except Exception as e:
  8159. logger.warning(
  8160. "Queue item %s: Failed to create archive from library file: %s",
  8161. queue_item_id,
  8162. e,
  8163. exc_info=True,
  8164. )
  8165. await db.rollback()
  8166. item = await db.get(PrintQueueItem, queue_item_id)
  8167. if item:
  8168. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8169. return
  8170. await self._power_off_if_needed(db, item)
  8171. return
  8172. if not archive:
  8173. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8174. return
  8175. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8176. await self._power_off_if_needed(db, item)
  8177. return
  8178. # The photos follow the file into the archive that replaces it, for
  8179. # the same reason the siblings do (#3077). After the commit above,
  8180. # never before it: that commit can fail ("database is locked",
  8181. # #1853) and roll the library row back, and photos already moved
  8182. # would leave it naming a directory that no longer exists. The
  8183. # file and thumbnail unlinks are deferred for the same reason.
  8184. if consumed_library_file_id is not None and consumed_photos:
  8185. # Held as a plain int, read here while the session is still
  8186. # healthy, because the handler below may not touch an ORM
  8187. # instance at all. The commit it exists for fails inside the
  8188. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8189. # first DML statement, so a busy writer surfaces as "database
  8190. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8191. # internally through safe_reraise before re-raising, which
  8192. # expires every loaded instance and leaves the session in
  8193. # pending-rollback state -- so `archive.id` inside the except
  8194. # would itself raise PendingRollbackError and the rollback
  8195. # below would never be reached.
  8196. archive_id = archive.id
  8197. try:
  8198. carried_photos = move_library_photos(
  8199. consumed_library_file_id,
  8200. consumed_photos,
  8201. archive_photos_dir(archive),
  8202. )
  8203. if carried_photos:
  8204. archive.photos = list(archive.photos or []) + carried_photos
  8205. await db.commit()
  8206. except Exception as e:
  8207. # The archive and the delete are already committed; the
  8208. # print goes ahead either way. Worst case the pictures sit
  8209. # unnamed in the archive's own directory.
  8210. #
  8211. # Ints only until the rollback has run, per the note above,
  8212. # which is why this logs queue_item_id and not item.id --
  8213. # the sibling handler forty lines up does the same.
  8214. logger.warning(
  8215. "Queue item %s: failed to carry library photos into archive %s: %s",
  8216. queue_item_id,
  8217. archive_id,
  8218. e,
  8219. )
  8220. await db.rollback()
  8221. # rollback() expires every loaded instance, and in async
  8222. # SQLAlchemy the next plain attribute read is lazy IO
  8223. # outside the greenlet -- MissingGreenlet, which would turn
  8224. # this cosmetic failure into a dispatch crash in exactly the
  8225. # "database is locked" case the block exists for (#1853).
  8226. # The nozzle guard, the upload and the start all keep
  8227. # reading item, archive and printer, so all three go back
  8228. # into the session before falling through.
  8229. item = await db.get(PrintQueueItem, queue_item_id)
  8230. archive = await db.get(PrintArchive, archive_id)
  8231. printer = await db.get(Printer, item.printer_id) if item else None
  8232. if not item or not archive or not printer:
  8233. logger.error(
  8234. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8235. queue_item_id,
  8236. archive_id,
  8237. )
  8238. return
  8239. else:
  8240. # Neither archive nor library file specified
  8241. if not await self._fail_dispatch(db, item, "No source file specified"):
  8242. return
  8243. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8244. await self._power_off_if_needed(db, item)
  8245. return
  8246. # Check file exists on disk
  8247. if not file_path.exists():
  8248. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8249. return
  8250. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8251. await self._power_off_if_needed(db, item)
  8252. return
  8253. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8254. # size dispatched to a printer with a different nozzle installed is
  8255. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8256. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8257. # gives the user no idea what went wrong. Catch it here, before we spend
  8258. # time preheating and uploading, and fail with an actionable message.
  8259. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8260. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8261. # the printer hasn't reported its nozzles yet, we fall through and let the
  8262. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8263. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8264. # as one of the two hotends is a 0.6.
  8265. #
  8266. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8267. # (#2885): the printer fetches one as part of starting the print, so the
  8268. # set to test against is "reachable", not "currently mounted". This runs
  8269. # well before the rack picker at the bottom of this method, so without
  8270. # the rack in scope here that picker never got the chance to run.
  8271. sliced_nozzle = archive.nozzle_diameter if archive else None
  8272. if sliced_nozzle:
  8273. nozzle_status = printer_manager.get_status(item.printer_id)
  8274. installed = _installed_nozzle_diameters(nozzle_status)
  8275. rack = _rack_nozzle_diameters(nozzle_status)
  8276. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8277. if mismatch_msg:
  8278. if not await self._fail_dispatch(db, item, mismatch_msg):
  8279. return
  8280. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8281. await notification_service.on_queue_job_failed(
  8282. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8283. printer_id=printer.id,
  8284. printer_name=printer.name,
  8285. reason=mismatch_msg,
  8286. db=db,
  8287. )
  8288. try:
  8289. await ws_manager.send_queue_item_failed(
  8290. user_id=item.created_by_id,
  8291. queue_item_id=item.id,
  8292. printer_id=item.printer_id,
  8293. reason="nozzle_mismatch",
  8294. )
  8295. except Exception:
  8296. pass
  8297. await self._power_off_if_needed(db, item)
  8298. return
  8299. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8300. # bed (and chamber, if applicable) is at temperature when the firmware
  8301. # starts the actual print routine. Best-effort: any failure logs and
  8302. # falls through to the normal upload+start path rather than turning a
  8303. # configuration issue into a failed queue item.
  8304. # Returns False only when the item was cancelled or deleted while the
  8305. # stage was holding at temperature. Uploading and starting it anyway
  8306. # would print a job the user has already called off, so abandon the
  8307. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8308. if not await self._preheat_and_soak(db, item, printer, archive):
  8309. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8310. return
  8311. # See `_effective_plate_id` for why this is resolved once here rather
  8312. # than each site below repeating `item.plate_id or 1`.
  8313. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8314. # G-code injection for auto-print systems (#422)
  8315. injected_path = None
  8316. # #2547: tracked separately from `injected_path`, which is also set when
  8317. # only a START snippet was injected. Only an END snippet changes what the
  8318. # camera sees at print completion.
  8319. end_gcode_injected = False
  8320. if item.gcode_injection:
  8321. try:
  8322. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8323. if snippets_raw:
  8324. snippets = json.loads(snippets_raw)
  8325. model_snippets = snippets.get(printer.model, {})
  8326. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8327. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8328. if start_gc or end_gc:
  8329. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8330. injected_path = inject_gcode_into_3mf(
  8331. file_path, effective_plate_id, start_gc or None, end_gc or None
  8332. )
  8333. if injected_path:
  8334. file_path = injected_path
  8335. end_gcode_injected = bool(end_gc)
  8336. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8337. else:
  8338. logger.warning(
  8339. "Queue item %s: G-code injection returned no result, using original", item.id
  8340. )
  8341. except Exception as e:
  8342. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8343. # #2547: the finish-photo path can't learn from telemetry that this print
  8344. # ends with user End G-code — which means the plate may be gone by the
  8345. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8346. # the print once the printer confirms it running.
  8347. if end_gcode_injected:
  8348. print_dispatch_context.mark_pending(printer.id)
  8349. # Upload to root directory (not /cache/) - the start_print command references
  8350. # files by name only (ftp://{filename}), so they must be in the root
  8351. remote_filename = derive_remote_filename(filename)
  8352. remote_path = f"/{remote_filename}"
  8353. # Get FTP retry settings
  8354. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8355. logger.info(
  8356. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8357. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8358. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8359. )
  8360. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8361. # Every read this method needs (printer, archive/library, preheat) is
  8362. # done, and the library-file branch already committed its archive
  8363. # creation. Without this the transaction opened by the first SELECT above
  8364. # stays "idle in transaction" for the entire upload — multiple seconds
  8365. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8366. # a farm dispatching many jobs at once then exhausts the pool. This was
  8367. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8368. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8369. # readable; the status writes below (upload-failure path and the
  8370. # pending->printing CAS) transparently open a fresh transaction.
  8371. # The owner is read here, after preheat, so the commit releases this read too.
  8372. toast_uid = await self._queue_owner_id(db, item)
  8373. await db.commit()
  8374. # Delete existing file if present (avoids 553 error on overwrite)
  8375. try:
  8376. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8377. delete_result = await delete_file_async(
  8378. printer.ip_address,
  8379. printer.access_code,
  8380. remote_path,
  8381. socket_timeout=ftp_timeout,
  8382. printer_model=printer.model,
  8383. # This delete and the upload below are one bounded, user-initiated
  8384. # unit -- at most nine connections -- so neither skips on the
  8385. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8386. # trace this delete took the TLS failure and armed the cool-off,
  8387. # and the upload's four attempts were then spent against it
  8388. # without a socket being opened.
  8389. respect_handshake_cooloff=False,
  8390. )
  8391. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8392. except Exception as e:
  8393. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8394. # Dispatch toast — announce the upload start with the total byte
  8395. # count so the frontend can render an honest progress bar.
  8396. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8397. try:
  8398. total_bytes = file_path.stat().st_size
  8399. except OSError:
  8400. total_bytes = 0
  8401. try:
  8402. await ws_manager.send_queue_item_uploading(
  8403. user_id=toast_uid,
  8404. queue_item_id=item.id,
  8405. printer_id=item.printer_id,
  8406. printer_name=printer.name,
  8407. file_name=toast_file_name,
  8408. total_bytes=total_bytes,
  8409. )
  8410. except Exception:
  8411. pass # toast is best-effort
  8412. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8413. # A deadline expiry gets its own message: "check your SD card" is the
  8414. # wrong advice for a link that was simply too slow to finish (#2529).
  8415. upload_error: str | None = None
  8416. # Why the upload failed, straight from the client rather than inferred.
  8417. # Owned here, so a background fetch for another print cannot overwrite
  8418. # it between the failure and the sentence built from it (#2899).
  8419. upload_failure = FtpFailureReport()
  8420. try:
  8421. if ftp_retry_enabled:
  8422. uploaded = await with_ftp_retry(
  8423. upload_file_async,
  8424. printer.ip_address,
  8425. printer.access_code,
  8426. file_path,
  8427. remote_path,
  8428. socket_timeout=ftp_timeout,
  8429. printer_model=printer.model,
  8430. progress_callback=progress_bridge,
  8431. respect_handshake_cooloff=False,
  8432. failure=upload_failure,
  8433. max_retries=ftp_retry_count,
  8434. retry_delay=ftp_retry_delay,
  8435. operation_name=f"Upload print to {printer.name}",
  8436. )
  8437. else:
  8438. uploaded = await upload_file_async(
  8439. printer.ip_address,
  8440. printer.access_code,
  8441. file_path,
  8442. remote_path,
  8443. socket_timeout=ftp_timeout,
  8444. printer_model=printer.model,
  8445. progress_callback=progress_bridge,
  8446. respect_handshake_cooloff=False,
  8447. failure=upload_failure,
  8448. )
  8449. except UploadCancelled as e:
  8450. uploaded = False
  8451. upload_error = (
  8452. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8453. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8454. )
  8455. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8456. except Exception as e:
  8457. uploaded = False
  8458. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8459. # Clean up injected temp file after upload attempt
  8460. if injected_path and injected_path.exists():
  8461. injected_path.unlink(missing_ok=True)
  8462. # Again after the upload, which can take minutes: an owner deleted
  8463. # meanwhile gets no more toasts, and neither does whoever has their id.
  8464. toast_uid = await self._queue_owner_id(db, item)
  8465. # The printer's copy at this path was replaced (or deleted above): the
  8466. # file browser's previews must not show the old one.
  8467. from backend.app.services.printer_file_cache import printer_file_cache
  8468. printer_file_cache.forget(printer.id, remote_path)
  8469. if not uploaded:
  8470. # This used to be one string for every upload failure, telling
  8471. # everyone to check the SD card. The client knows which of seven
  8472. # things went wrong and logs each one differently; it just had no
  8473. # way to say so here, so the card got named even for a TLS
  8474. # handshake that never reached the printer's filesystem (#2899).
  8475. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8476. failure = upload_failure.failure
  8477. if failure is not None and failure.kind is FtpFailureKind.STORAGE:
  8478. try:
  8479. validate_print_filename(remote_filename)
  8480. except InvalidFilenameError as e:
  8481. # This 553 is the file's name, which no card can hold, not
  8482. # the printer's storage: it would be refused on every retry
  8483. # and every printer, so this item fails and the queue goes on.
  8484. upload_error = f"The printer could not create the file {remote_filename!r}: {e}. Rename the file."
  8485. error_msg = upload_error
  8486. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8487. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid, failure.kind)
  8488. return
  8489. if not await self._fail_dispatch(db, item, error_msg):
  8490. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8491. return
  8492. logger.error(
  8493. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8494. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8495. )
  8496. # Send failure notification
  8497. await notification_service.on_queue_job_failed(
  8498. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8499. printer_id=printer.id,
  8500. printer_name=printer.name,
  8501. # The same sentence the queue shows. A push notification saying
  8502. # something different from the UI is its own small bug (#2899).
  8503. reason=error_msg,
  8504. db=db,
  8505. )
  8506. try:
  8507. await ws_manager.send_queue_item_failed(
  8508. user_id=toast_uid,
  8509. queue_item_id=item.id,
  8510. printer_id=item.printer_id,
  8511. reason="upload_failed",
  8512. )
  8513. except Exception:
  8514. pass
  8515. await self._power_off_if_needed(db, item)
  8516. return
  8517. # The printer took a file, so any run of refused uploads is over: the
  8518. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8519. self._upload_refusals.pop(printer.id, None)
  8520. self._upload_refusal_kind.pop(printer.id, None)
  8521. self._upload_refusal_notified.pop(printer.id, None)
  8522. # Parse AMS mapping if stored
  8523. ams_mapping = None
  8524. if item.ams_mapping:
  8525. try:
  8526. ams_mapping = json.loads(item.ams_mapping)
  8527. except json.JSONDecodeError:
  8528. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8529. # Register as expected print so we don't create a duplicate archive
  8530. # Only applicable for archive-based prints
  8531. if archive:
  8532. from backend.app.main import register_expected_print
  8533. register_expected_print(
  8534. item.printer_id,
  8535. remote_filename,
  8536. archive.id,
  8537. ams_mapping=ams_mapping,
  8538. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8539. # no print-start email, and neither does whoever has their id.
  8540. created_by_id=toast_uid,
  8541. cost_center_id=item.cost_center_id,
  8542. # The plate actually dispatched, not the queue item's raw
  8543. # column: on None, `register_expected_print` stores nothing,
  8544. # and `extract_filament_usage_from_3mf` then books every
  8545. # filament in the file rather than the one plate that printed.
  8546. plate_id=effective_plate_id,
  8547. )
  8548. # Registration happens before the print command by necessity (the
  8549. # printer can report the print before the send returns), so record
  8550. # what to undo if we never get as far as sending. `_dispatch_one`
  8551. # rolls back anything still pending here on every exit — exception,
  8552. # early return, or cancel winning the CAS below.
  8553. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8554. # Propagate the queue item's owner into printer_manager so the
  8555. # print-complete callback can credit the user in the PrintLogEntry
  8556. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8557. # items) or when the user clicks the manual-start button.
  8558. await self._propagate_owner_to_printer_manager(db, item)
  8559. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8560. # This prevents phantom reprints if the backend crashes/restarts after the
  8561. # print command is sent but before the status update is committed.
  8562. # If we crash after this commit but before start_print(), the item will be
  8563. # in "printing" status without actually printing - but that's safer than
  8564. # accidentally reprinting the same file hours later.
  8565. #
  8566. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8567. # initial pending read at the top of check_queue and this point) flips
  8568. # the row to "cancelled" in a separate session. Without the WHERE
  8569. # status='pending' clause, the unconditional update here would silently
  8570. # overwrite that cancellation and we'd ship the MQTT start_print below
  8571. # — printer obeys, user sees "I pressed cancel and the print started".
  8572. # rowcount==0 means the user won the race; bail out, best-effort delete
  8573. # the file we just uploaded, do NOT send start_print.
  8574. now_utc = datetime.now(timezone.utc)
  8575. billing_run_id = str(uuid.uuid4())
  8576. # Written with the move to printing, so a retried send replaces the
  8577. # last answer and a cancelled one leaves the row alone (#3279).
  8578. color_substitutions = await self._color_substitutions_for(db, item)
  8579. cas = await db.execute(
  8580. update(PrintQueueItem)
  8581. .where(PrintQueueItem.id == item.id)
  8582. .where(PrintQueueItem.status == "pending")
  8583. .values(
  8584. status="printing",
  8585. started_at=now_utc,
  8586. billing_run_id=billing_run_id,
  8587. color_substitutions=color_substitutions,
  8588. )
  8589. )
  8590. await db.commit()
  8591. if cas.rowcount == 0:
  8592. logger.info(
  8593. "Queue item %s no longer pending at print-command time "
  8594. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8595. item.id,
  8596. )
  8597. try:
  8598. await delete_file_async(
  8599. printer.ip_address,
  8600. printer.access_code,
  8601. remote_path,
  8602. socket_timeout=ftp_timeout,
  8603. printer_model=printer.model,
  8604. )
  8605. except Exception as cleanup_err:
  8606. logger.debug(
  8607. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8608. item.id,
  8609. cleanup_err,
  8610. )
  8611. try:
  8612. await ws_manager.send_queue_item_failed(
  8613. user_id=toast_uid,
  8614. queue_item_id=item.id,
  8615. printer_id=item.printer_id,
  8616. reason="cancelled_mid_dispatch",
  8617. )
  8618. except Exception:
  8619. pass
  8620. return
  8621. # Sync the in-memory item so subsequent code that reads item.status /
  8622. # item.started_at sees the values we just persisted.
  8623. item.status = "printing"
  8624. item.started_at = now_utc
  8625. item.billing_run_id = billing_run_id
  8626. if archive is not None:
  8627. archive.billing_run_id = billing_run_id
  8628. # Legacy transaction deletion used an archive-wide skip flag.
  8629. # A newly dispatched run has its own UUID/tombstone, so it must be
  8630. # billable independently of any older deleted run on this archive.
  8631. archive.wallet_charge_skipped = False
  8632. # Persist before MQTT send so completion and restart recovery can
  8633. # always recover the internal billing identity.
  8634. await db.commit()
  8635. for cleanup_path in cleanup_disk_paths:
  8636. try:
  8637. if cleanup_path.exists():
  8638. cleanup_path.unlink()
  8639. except OSError as cleanup_err:
  8640. logger.warning(
  8641. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8642. json.dumps(
  8643. {
  8644. "queue_item_id": item.id,
  8645. "path": str(cleanup_path),
  8646. "error": str(cleanup_err),
  8647. },
  8648. sort_keys=True,
  8649. ),
  8650. )
  8651. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8652. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8653. # #1898: with the opt-in default-good setting, moving on to the next
  8654. # print resolves the previous print's unanswered outcome prompt as
  8655. # "good" — this path also covers the camera-based plate detection,
  8656. # which releases the gate by allowing dispatch rather than by an
  8657. # explicit acknowledgment. Rides on the dispatch transaction.
  8658. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8659. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8660. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8661. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8662. # Capture state before dispatch so the watchdog can detect whether the
  8663. # printer actually transitioned (#967). Also capture subtask_id so the
  8664. # watchdog can recognise "command landed but state hasn't flipped yet"
  8665. # on slow H2D transitions (#1078).
  8666. pre_status = printer_manager.get_status(item.printer_id)
  8667. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8668. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8669. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8670. # #1721: respect the user's explicit timelapse choice. The #1397
  8671. # force-on at dispatch was removed because it caused per-layer nozzle
  8672. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8673. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8674. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8675. # FINISH-state fallback — no need to force a video.
  8676. effective_timelapse = bool(item.timelapse)
  8677. # Nozzle-rack fallback (#2800). A job that never passed through the
  8678. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8679. # dispatches with no nozzle field at all and chooses for itself — which
  8680. # is how a print levelled on one hotend and then printed on another,
  8681. # millimetres above the plate. Derive the per-slot extruder assignment
  8682. # from the file being dispatched.
  8683. #
  8684. # Done here rather than at queue time because this is the first point
  8685. # that knows both the actual printer and the actual file: an item can
  8686. # be created without a printer (model-based assignment), reassigned
  8687. # afterwards, or have its file swapped for a G-code-injected copy just
  8688. # above. Every queue-creation path — the print dialog, a bulk library
  8689. # add, the webhook, a pipeline run — is covered by the one call.
  8690. # Skipped when the item already carries a Bambu Studio capture: that
  8691. # one wins downstream anyway, so reading the 3MF again would be work
  8692. # thrown away on every dispatch.
  8693. # Rack position resolution (#1784), tried before the #2800 fallback
  8694. # below because it can express what that one cannot: a plate wanting a
  8695. # *different* hotend off the rack per filament group. The position per
  8696. # group is the operator's pick — the 3MF states it nowhere, proven by
  8697. # sending one plate twice with different picks and finding the two
  8698. # files identical bar float noise — so it is resolved here against the
  8699. # rack as it stands right now, after the upload, not at queue time.
  8700. resolved_nozzle_mapping = None
  8701. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8702. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8703. if rack_plan is not None:
  8704. try:
  8705. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8706. except (json.JSONDecodeError, TypeError):
  8707. stored_choice = {}
  8708. logger.warning(
  8709. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8710. item.id,
  8711. item.nozzle_rack_choice,
  8712. )
  8713. # JSON object keys are strings; the groups are ints.
  8714. choice: dict[int, int] = {}
  8715. for key, value in (stored_choice or {}).items():
  8716. try:
  8717. choice[int(key)] = int(value)
  8718. except (TypeError, ValueError):
  8719. continue
  8720. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8721. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8722. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8723. )
  8724. if resolved_nozzle_mapping is None and choice:
  8725. # An explicit pick that no longer holds stops the print. The
  8726. # operator named a hotend; printing from a different one is
  8727. # how a plate gets levelled on one nozzle and drawn with
  8728. # another, millimetres above the bed. Nothing has been sent
  8729. # to the printer yet, so failing here costs only the upload.
  8730. # The file is already on the SD card by this point, and a
  8731. # 3MF left there is a phantom print waiting to be started
  8732. # from the touchscreen. Same cleanup the start_print
  8733. # failure path below does, for the same reason.
  8734. try:
  8735. await delete_file_async(
  8736. printer.ip_address,
  8737. printer.access_code,
  8738. remote_path,
  8739. printer_model=printer.model,
  8740. )
  8741. except Exception:
  8742. pass # Best-effort — don't fail the error handler
  8743. if not await self._fail_dispatch(
  8744. db,
  8745. item,
  8746. (
  8747. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8748. "Edit the item to choose another position."
  8749. ),
  8750. ):
  8751. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8752. return
  8753. logger.warning(
  8754. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8755. item.id,
  8756. printer.name,
  8757. rack_error,
  8758. choice,
  8759. [slot.get("id") for slot in live_rack],
  8760. )
  8761. await notification_service.on_queue_job_failed(
  8762. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8763. printer_id=printer.id,
  8764. printer_name=printer.name,
  8765. reason=item.error_message,
  8766. db=db,
  8767. )
  8768. try:
  8769. await ws_manager.send_queue_item_failed(
  8770. user_id=toast_uid,
  8771. queue_item_id=item.id,
  8772. printer_id=item.printer_id,
  8773. reason="nozzle_rack_pick_stale",
  8774. )
  8775. except Exception:
  8776. pass # Best-effort — don't fail the error handler
  8777. return
  8778. if resolved_nozzle_mapping is None:
  8779. # Nothing was picked and nothing could be assigned. Falls
  8780. # through to the #2800 path, which is what ran before this
  8781. # existed — strictly not worse than today.
  8782. logger.info(
  8783. "Queue item %s: no rack positions assignable (%s); falling back",
  8784. item.id,
  8785. rack_error,
  8786. )
  8787. else:
  8788. logger.info(
  8789. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8790. item.id,
  8791. resolved_nozzle_mapping,
  8792. rack_plan.slot_groups,
  8793. choice or "auto",
  8794. )
  8795. nozzle_slot_extruders = None
  8796. if (
  8797. not item.nozzle_mapping
  8798. and resolved_nozzle_mapping is None
  8799. and file_path is not None
  8800. and is_nozzle_rack_model(printer.model)
  8801. ):
  8802. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8803. if slot_extruders:
  8804. nozzle_slot_extruders = json.dumps(slot_extruders)
  8805. # Every filament this plate prints is on the external spool -> the print
  8806. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8807. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8808. # table", which is what held the reporter's P1S at Heatbed preheating
  8809. # for ten minutes before it gave up (#3087). The MQTT command builder
  8810. # already downgrades a mapping that is *only* external ([254]), but a
  8811. # multi-filament project pads the slots this plate does not print with
  8812. # -1 — BambuStudio's own convention — and down there a -1 is
  8813. # indistinguishable from a slot that never resolved, which must never be
  8814. # sent to the spool holder (#2589). Here the plate's filament list says
  8815. # which is which, so the answer is exact rather than a guess.
  8816. #
  8817. # Deliberately narrow: this fires only when every consumed slot is an
  8818. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8819. # alone and the firmware still rejects the print, exactly as today. And
  8820. # only for single-nozzle printers, mirroring the builder's own reconcile
  8821. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8822. # whether to use the AMS, so it is not ours to rewrite.
  8823. effective_use_ams = item.use_ams
  8824. plate_uses_only_external = False
  8825. if (
  8826. ams_mapping
  8827. and file_path is not None
  8828. # Cheap gate before opening the file: with nothing on the spool
  8829. # holder anywhere in the mapping, no subset of it can be all
  8830. # external, so most dispatches never pay for the parse. The
  8831. # isinstance also keeps a malformed stored mapping (a bare number
  8832. # from a hand-edited row) failing where it always failed, in the
  8833. # command builder, rather than here.
  8834. and isinstance(ams_mapping, list)
  8835. and any(_is_external_tray(t) for t in ams_mapping)
  8836. and not _might_be_dual_nozzle(printer.model, pre_status)
  8837. ):
  8838. from backend.app.services.filament_requirements import extract_filament_requirements
  8839. consumed = _consumed_mapping_entries(
  8840. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8841. )
  8842. if consumed and all(_is_external_tray(t) for t in consumed):
  8843. # Exact for this plate: the command builder must not turn the
  8844. # AMS back on for a real tray another plate of the file uses,
  8845. # whether the job asked for the AMS or already had it off.
  8846. plate_uses_only_external = True
  8847. if plate_uses_only_external and effective_use_ams:
  8848. effective_use_ams = False
  8849. logger.info(
  8850. "Queue item %s: every filament plate %s prints is on the external spool "
  8851. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8852. item.id,
  8853. effective_plate_id,
  8854. ams_mapping,
  8855. )
  8856. # A slot that lost its K-profile selection (a power cycle resets every
  8857. # slot to the default K) would print on the default. The idle check in
  8858. # the status handler normally restores it first, but nothing guarantees
  8859. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8860. # Never allowed to stop the print it is protecting.
  8861. try:
  8862. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8863. except Exception:
  8864. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8865. # Start the print with AMS mapping, plate_id and print options.
  8866. # nozzle_mapping rides through verbatim — JSON string captured from
  8867. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8868. # parses + injects it only for dual-nozzle models so a null on every
  8869. # other model is a transparent pass-through. The rack fallback is
  8870. # resolved down there too, where the live rack position is known.
  8871. started = printer_manager.start_print(
  8872. item.printer_id,
  8873. remote_filename,
  8874. plate_id=effective_plate_id,
  8875. ams_mapping=ams_mapping,
  8876. bed_levelling=item.bed_levelling,
  8877. flow_cali=item.flow_cali,
  8878. vibration_cali=item.vibration_cali,
  8879. layer_inspect=item.layer_inspect,
  8880. timelapse=effective_timelapse,
  8881. use_ams=effective_use_ams,
  8882. plate_uses_only_external=plate_uses_only_external,
  8883. nozzle_offset_cali=item.nozzle_offset_cali,
  8884. nozzle_mapping=item.nozzle_mapping
  8885. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8886. nozzle_slot_extruders=nozzle_slot_extruders,
  8887. )
  8888. if started:
  8889. # The command is away, so the expectation is now legitimate and must
  8890. # survive. Anything still in this dict when _dispatch_one exits gets
  8891. # rolled back.
  8892. self._unconfirmed_expected_print.pop(item.id, None)
  8893. self._unconfirmed_budget_reservations.discard(item.id)
  8894. self._unconfirmed_print_user.pop(item.id, None)
  8895. if item.printer_id is not None:
  8896. self._sent_unstarted_print[item.id] = (
  8897. item.printer_id,
  8898. remote_filename if archive else None,
  8899. archive.id if archive else None,
  8900. )
  8901. # Handoff to the print's own gcode: keep whatever preheat set (bed
  8902. # target, chamber target, airduct heating) — the gcode owns
  8903. # heater/flap control from here. Clearing the pin prevents
  8904. # `_dispatch_one`'s finally from unwinding a live print.
  8905. self._preheat_pin.pop(item.printer_id, None)
  8906. self._preheat_pin_bed.pop(item.printer_id, None)
  8907. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  8908. # No dispatch-toast event here: the legacy bg-dispatch path kept
  8909. # status='processing' from upload start until the printer acked
  8910. # (or timed out). The frontend derives "Awaiting printer…" purely
  8911. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  8912. # event would push the status chip out of 'PROCESSING' prematurely
  8913. # — which is exactly what the screenshot at #1625-followup
  8914. # complained about.
  8915. # Register the local 3MF in the cover-cache so /cover skips FTP
  8916. # (#1166 follow-up). file_path was resolved earlier from either the
  8917. # archive or the library file row.
  8918. if file_path is not None:
  8919. cache_3mf_download(item.printer_id, remote_filename, file_path)
  8920. # Hold the printer against further dispatches until the watchdog
  8921. # confirms the printer transitioned (or until the hard timeout).
  8922. # Prevents multi-plate batches from triple-dispatching onto the
  8923. # same H2D Pro while it digests the first project_file (#1157).
  8924. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  8925. # Watchdog: if the printer never transitions out of pre_state AND
  8926. # never advances subtask_id, the MQTT publish was accepted locally but
  8927. # didn't reach the printer (half-broken session — same shape as
  8928. # #887/#936). Revert the queue item so the next dispatch can pick it
  8929. # up instead of leaving it stuck in "printing" (#967). subtask_id
  8930. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  8931. # that would otherwise cause the item to re-dispatch as a reprint
  8932. # of the just-finished job (#1078).
  8933. if pre_state:
  8934. spawn_background_task(
  8935. self._watchdog_print_start(
  8936. item.id,
  8937. item.printer_id,
  8938. pre_state,
  8939. pre_subtask_id,
  8940. pre_gcode_file,
  8941. created_by_id=toast_uid,
  8942. ),
  8943. name=f"watchdog-print-start-{item.id}",
  8944. )
  8945. # Get estimated time for notification.
  8946. #
  8947. # This used to fall back to `library_file.print_time_seconds`, a column
  8948. # LibraryFile does not have — the print time it knows about lives in
  8949. # `file_metadata`. So a library print whose archive carried no parseable
  8950. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  8951. # AttributeError right here, *after* the printer had already been sent
  8952. # the job: the started-notification never fired, and the exception
  8953. # unwound the whole queue pass, so every other printer still waiting to
  8954. # be dispatched on that tick silently missed its turn.
  8955. #
  8956. # The queue item caches the print time at creation ("Cached from
  8957. # archive/library"), which is the value this was reaching for.
  8958. estimated_time = None
  8959. if archive and archive.print_time_seconds:
  8960. estimated_time = archive.print_time_seconds
  8961. elif item.print_time_seconds:
  8962. estimated_time = item.print_time_seconds
  8963. # Send job started notification
  8964. await notification_service.on_queue_job_started(
  8965. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8966. printer_id=printer.id,
  8967. printer_name=printer.name,
  8968. db=db,
  8969. estimated_time=estimated_time,
  8970. )
  8971. # MQTT relay - publish queue job started
  8972. try:
  8973. await mqtt_relay.on_queue_job_started(
  8974. job_id=item.id,
  8975. filename=filename,
  8976. printer_id=printer.id,
  8977. printer_name=printer.name,
  8978. printer_serial=printer.serial_number,
  8979. )
  8980. except Exception:
  8981. pass # Don't fail if MQTT fails
  8982. else:
  8983. # Clean up uploaded file from SD card to prevent phantom prints
  8984. try:
  8985. await delete_file_async(
  8986. printer.ip_address,
  8987. printer.access_code,
  8988. remote_path,
  8989. printer_model=printer.model,
  8990. )
  8991. except Exception:
  8992. pass # Best-effort — don't fail the error handler
  8993. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  8994. # state can flip from idle to active in the window between the
  8995. # pre-dispatch check above and this publish (the FTP upload takes
  8996. # seconds); start_print() then refuses to send project_file to the
  8997. # now-busy printer and returns False. Failing the item here would be
  8998. # wrong — the printer is fine, it is simply busy — so revert to
  8999. # pending and let a later tick dispatch it once the printer is idle,
  9000. # exactly like the pre-dispatch guard. Only a start_print() False on
  9001. # an idle/unknown printer is a genuine command failure.
  9002. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  9003. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  9004. logger.info(
  9005. "Queue item %s: printer %s became busy (state=%s) before the start "
  9006. "command was sent — deferring, reverting item to pending (#2598)",
  9007. item.id,
  9008. item.printer_id,
  9009. post_dispatch_state,
  9010. )
  9011. await self._defer_until_printer_idle(db, item)
  9012. return
  9013. # Print command failed - revert status
  9014. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  9015. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9016. return
  9017. logger.error(
  9018. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  9019. f"printer_manager.start_print() returned False. "
  9020. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  9021. f"Check printer status and backend logs for details."
  9022. )
  9023. # Send failure notification
  9024. await notification_service.on_queue_job_failed(
  9025. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9026. printer_id=printer.id,
  9027. printer_name=printer.name,
  9028. reason="Failed to send print command to printer - check printer connection and status",
  9029. db=db,
  9030. )
  9031. try:
  9032. await ws_manager.send_queue_item_failed(
  9033. user_id=toast_uid,
  9034. queue_item_id=item.id,
  9035. printer_id=item.printer_id,
  9036. reason="start_command_failed",
  9037. )
  9038. except Exception:
  9039. pass
  9040. await self._power_off_if_needed(db, item)
  9041. @staticmethod
  9042. async def _watchdog_print_start(
  9043. queue_item_id: int,
  9044. printer_id: int,
  9045. pre_state: str,
  9046. pre_subtask_id: str | None = None,
  9047. pre_gcode_file: str | None = None,
  9048. timeout: float = 90.0,
  9049. phase_b_timeout: float = 180.0,
  9050. poll_interval: float = 3.0,
  9051. created_by_id: int | None = None,
  9052. ) -> None:
  9053. """Revert a queue item if the printer never acknowledges the start command.
  9054. Bambuddy optimistically marks the queue item as "printing" right after the
  9055. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  9056. Phase A (up to ``timeout``): wait for either an active-state transition
  9057. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  9058. primary signal; subtask_id advance handles the H2D case where state can
  9059. sit at FINISH for ~50 s after the printer accepted ``project_file``
  9060. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  9061. was lost on a half-broken session (#887/#936) — revert and force
  9062. reconnect (the #967 recovery path).
  9063. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  9064. alone): keep watching for the active-state transition. subtask_id alone
  9065. proves the file landed but not that the printer started — and a printer
  9066. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  9067. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  9068. used to leave the queue item stuck in 'printing' forever because the
  9069. old watchdog returned success as soon as subtask_id advanced. If Phase
  9070. B times out, revert the queue item so the user can retry without
  9071. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  9072. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9073. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  9074. transitions that also don't emit an early subtask_id tick.
  9075. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  9076. refuses to verify our commands will never start this job or any other,
  9077. so waiting out the full 270 s and re-uploading the 3MF twice more only
  9078. burns an upload slot the rest of the farm is queued behind — that path
  9079. is for a printer that might still come good, which this one cannot
  9080. (#2732). It fails the item on the spot with the actual reason instead.
  9081. """
  9082. last_status = None
  9083. landed_on_subtask = False
  9084. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  9085. # every push carrying an `hms` key, so the fault can come and go between
  9086. # 3-second polls. Seeing it once inside the dispatch window is enough.
  9087. command_rejected = False
  9088. # Latched for the same reason as command_rejected: drying can finish, or
  9089. # be stopped by the user, part-way through the dispatch window. Seeing it
  9090. # once is what matters — it is the state the printer was in when it
  9091. # declined to start (#2758).
  9092. drying_ams_ids: list[int] = []
  9093. # The printer answered the start with a refusal: nothing will start,
  9094. # and the command was not lost, so no reconnect either.
  9095. start_refusal: tuple[str, str | None] | None = None
  9096. deadline = time.monotonic() + timeout
  9097. while time.monotonic() < deadline:
  9098. await asyncio.sleep(poll_interval)
  9099. status = printer_manager.get_status(printer_id)
  9100. if not status:
  9101. # Printer disconnected — don't mess with the DB. Drop the
  9102. # in-memory dispatch hold too so a fresh dispatch can retry
  9103. # once the printer comes back; the hard timeout would
  9104. # otherwise hold the printer unnecessarily.
  9105. scheduler._release_dispatch_hold(printer_id)
  9106. return
  9107. last_status = status
  9108. if status.state in _ACTIVE_PRINT_STATES:
  9109. # Printer is actively processing the job — release the
  9110. # post-dispatch hold so the next pending item for this printer
  9111. # can be evaluated normally. We do NOT accept arbitrary state
  9112. # transitions: a printer going FINISH -> IDLE (user dismissed
  9113. # the post-print prompt without accepting our project_file)
  9114. # would otherwise look like "command landed" and leave the
  9115. # queue item stuck in 'printing' forever (#1370).
  9116. scheduler._release_dispatch_hold(printer_id)
  9117. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9118. try:
  9119. await ws_manager.send_queue_item_acked(
  9120. user_id=created_by_id,
  9121. queue_item_id=queue_item_id,
  9122. printer_id=printer_id,
  9123. )
  9124. except Exception:
  9125. pass
  9126. return
  9127. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9128. # Checked only after the active-state exit above: a stale HMS left
  9129. # over from an earlier job must never abort a print that is visibly
  9130. # running. An actually-refused command leaves the printer idle, so
  9131. # this ordering costs the detection nothing.
  9132. if _mqtt_commands_rejected(status):
  9133. command_rejected = True
  9134. break
  9135. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9136. if isinstance(refusal, tuple):
  9137. start_refusal = refusal
  9138. break
  9139. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9140. # Phase A exit — printer accepted the file (subtask_id flipped
  9141. # to our submission id). Don't return yet: the printer may
  9142. # have accepted the command but never actually start (e.g.
  9143. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9144. # B watches for the active-state transition.
  9145. landed_on_subtask = True
  9146. break
  9147. if landed_on_subtask and not command_rejected:
  9148. phase_b_deadline = time.monotonic() + phase_b_timeout
  9149. while time.monotonic() < phase_b_deadline:
  9150. await asyncio.sleep(poll_interval)
  9151. status = printer_manager.get_status(printer_id)
  9152. if not status:
  9153. scheduler._release_dispatch_hold(printer_id)
  9154. return
  9155. last_status = status
  9156. if status.state in _ACTIVE_PRINT_STATES:
  9157. scheduler._release_dispatch_hold(printer_id)
  9158. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9159. try:
  9160. await ws_manager.send_queue_item_acked(
  9161. user_id=created_by_id,
  9162. queue_item_id=queue_item_id,
  9163. printer_id=printer_id,
  9164. )
  9165. except Exception:
  9166. pass
  9167. return
  9168. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9169. # Same ordering rule as Phase A: a running print wins over a
  9170. # lingering HMS.
  9171. if _mqtt_commands_rejected(status):
  9172. command_rejected = True
  9173. break
  9174. # No active-state transition. Revert the item so the scheduler can retry.
  9175. # Drop the in-memory hold so the retry isn't blocked by it.
  9176. scheduler._release_dispatch_hold(printer_id)
  9177. # Logged on every failed dispatch window, not just the last one, so a
  9178. # support bundle shows the correlation from the first attempt rather than
  9179. # only after the retry budget is spent (#2758).
  9180. if drying_ams_ids:
  9181. logger.info(
  9182. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9183. queue_item_id,
  9184. printer_id,
  9185. ", ".join(str(i) for i in drying_ams_ids),
  9186. )
  9187. # Four outcomes from the revert attempt, each routed differently:
  9188. # "reverted": row flipped from printing -> pending, run recovery
  9189. # "gave_up": same, but the retry budget is spent — row failed
  9190. # rather than pending, so it stops going round again
  9191. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9192. # on_print_complete or user). Skip recovery entirely
  9193. # — the print clearly landed somewhere even if the
  9194. # watchdog didn't see the active-state transition.
  9195. # "revert_failed": SQLite contention exhausted retries. Still run
  9196. # recovery so the MQTT session gets a fresh client_id
  9197. # on the half-broken-session path.
  9198. #
  9199. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9200. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9201. # the watchdog again. For a printer that is genuinely wedged that loop never
  9202. # ends — the reporter had one printer "since this morning still not launch"
  9203. # — and each lap also consumes an upload slot that the other printers in the
  9204. # farm are waiting on. Retrying is right; retrying forever is not.
  9205. async def _do_revert(db):
  9206. item = await db.get(PrintQueueItem, queue_item_id)
  9207. if not item or item.status != "printing":
  9208. return "already_moved_on"
  9209. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9210. item.started_at = None
  9211. # The print never started: no slot printed in any colour (#3279).
  9212. item.color_substitutions = None
  9213. # Charge the attempt to the candidate that was actually dispatched, so
  9214. # a cross-model item (#671) reaches for its other file next lap instead
  9215. # of retrying the printer that just failed to start. Matched by file
  9216. # because that is what the resolver copied onto the row.
  9217. if item.library_file_id is not None:
  9218. await db.execute(
  9219. update(PrintQueueVariant)
  9220. .where(PrintQueueVariant.queue_item_id == item.id)
  9221. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9222. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9223. )
  9224. if command_rejected:
  9225. # No retry budget for this one: the printer refused to verify the
  9226. # command, and re-uploading the same 3MF to the same printer will
  9227. # be refused the same way. Fail now with the fix rather than after
  9228. # three laps of a message about SD cards (#2732).
  9229. item.status = "failed"
  9230. item.error_message = (
  9231. "The printer rejected the print command: MQTT command verification failed "
  9232. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9233. "then start the job again."
  9234. )
  9235. item.completed_at = datetime.now(timezone.utc)
  9236. await db.commit()
  9237. return "command_rejected"
  9238. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9239. item.status = "failed"
  9240. if drying_ams_ids:
  9241. # #2758: the generic message below sent the reporter looking
  9242. # at the SD card while the actual obstacle — AMS units in a
  9243. # drying cycle — was on screen the whole time. Name what we
  9244. # observed and let the user judge it; Bambuddy does not stop
  9245. # the cycle itself, because on this hardware drying can run
  9246. # alongside a print and stopping it may not be the fix.
  9247. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9248. item.error_message = (
  9249. f"The printer accepted the file but never started printing, after "
  9250. f"{item.dispatch_attempts} attempts. {units} "
  9251. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9252. f"some printers refuse to begin a print while an AMS is in a drying "
  9253. f"cycle, and an AMS drying without its external power supply can also "
  9254. f"leave too little power for the start-of-print calibration. Stop the "
  9255. f"drying, or connect the AMS power supply, and start the job again."
  9256. )
  9257. else:
  9258. item.error_message = (
  9259. f"The printer accepted the file but never started printing, after "
  9260. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9261. f"prompt or error, confirm its SD card is readable, and start the job again."
  9262. )
  9263. item.completed_at = datetime.now(timezone.utc)
  9264. await release_budget_reservation(
  9265. db,
  9266. source_type="print_queue",
  9267. source_id=item.id,
  9268. status="released",
  9269. )
  9270. await db.commit()
  9271. return "gave_up"
  9272. item.status = "pending"
  9273. await db.commit()
  9274. return "reverted"
  9275. try:
  9276. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9277. except Exception as e:
  9278. logger.warning(
  9279. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9280. "scheduler may keep treating this item as in-flight",
  9281. queue_item_id,
  9282. printer_id,
  9283. e,
  9284. )
  9285. revert_outcome = "revert_failed"
  9286. if revert_outcome in ("command_rejected", "gave_up"):
  9287. # The item is failed: its print user and expected print must not
  9288. # pass the printer's next print off as Bambuddy's.
  9289. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9290. from backend.app.services.print_batch import refresh_batches_after
  9291. await refresh_batches_after([queue_item_id])
  9292. elif revert_outcome == "reverted":
  9293. # Another try claims the printer again. Until then no print on it
  9294. # is vouched for as this item's, except a late start of its file.
  9295. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9296. elif revert_outcome == "already_moved_on":
  9297. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9298. if revert_outcome == "already_moved_on":
  9299. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9300. # other path) already moved the item past 'printing', don't run the
  9301. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9302. # session breaks ongoing prints on the same printer.
  9303. return
  9304. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9305. if revert_outcome == "command_rejected":
  9306. logger.error(
  9307. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9308. "failed) — the print command was rejected, not lost. Failing the item "
  9309. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9310. queue_item_id,
  9311. printer_id,
  9312. HMS_MQTT_VERIFY_FAILED,
  9313. )
  9314. await scheduler._notify_dispatch_gave_up(
  9315. queue_item_id,
  9316. printer_id,
  9317. created_by_id,
  9318. reason="Printer rejected the print command (MQTT command verification failed)",
  9319. )
  9320. # Same reasoning as the landed_on_subtask path below: the file is on
  9321. # the printer and a forced reconnect would only add 0500_4003 to a
  9322. # problem that has nothing to do with the MQTT session (#1150).
  9323. return
  9324. if revert_outcome == "gave_up":
  9325. logger.error(
  9326. "Queue item %s: printer %d never started the print after %d dispatch "
  9327. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9328. "re-uploading it again (#2555)",
  9329. queue_item_id,
  9330. printer_id,
  9331. DISPATCH_MAX_ATTEMPTS,
  9332. total_timeout,
  9333. )
  9334. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9335. elif revert_outcome == "reverted":
  9336. if start_refusal is not None:
  9337. logger.warning(
  9338. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9339. "reverted to 'pending' for retry",
  9340. queue_item_id,
  9341. printer_id,
  9342. start_refusal[0],
  9343. start_refusal[1],
  9344. )
  9345. elif landed_on_subtask:
  9346. logger.warning(
  9347. "Queue item %s: printer %d accepted project_file (subtask_id "
  9348. "advanced) but never transitioned to an active state within "
  9349. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9350. "for retry (#1678)",
  9351. queue_item_id,
  9352. printer_id,
  9353. total_timeout,
  9354. )
  9355. else:
  9356. logger.warning(
  9357. "Queue item %s: printer %d did not respond to print command within "
  9358. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9359. "for retry (#967)",
  9360. queue_item_id,
  9361. printer_id,
  9362. timeout,
  9363. pre_state,
  9364. pre_subtask_id,
  9365. )
  9366. # Phase B was entered iff subtask_id advanced, which means the
  9367. # project_file landed on the printer. A forced reconnect at this point
  9368. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9369. # skip the recovery entirely.
  9370. if landed_on_subtask or start_refusal is not None:
  9371. return
  9372. # Phase A timeout path: if the printer's gcode_file changed since
  9373. # pre-dispatch, the project_file command landed and the printer is
  9374. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9375. # If gcode_file is unchanged, the publish was silently swallowed
  9376. # (#887/#936) and force_reconnect recovery is what we want.
  9377. client = printer_manager.get_client(printer_id)
  9378. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9379. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9380. if publish_landed:
  9381. logger.warning(
  9382. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9383. "received the command and is parsing slowly. Skipping forced "
  9384. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9385. queue_item_id,
  9386. current_gcode_file,
  9387. pre_gcode_file,
  9388. )
  9389. elif client and hasattr(client, "force_reconnect_stale_session"):
  9390. client.force_reconnect_stale_session(
  9391. f"queue print command unacknowledged after {timeout:.0f}s "
  9392. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9393. )
  9394. # Global scheduler instance
  9395. scheduler = PrintScheduler()