print_scheduler.py 530 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478
  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. # Archives a library dispatch still in flight is adding its run to:
  1190. # archive_id -> item_id. Uploads run in parallel, and an archive holds
  1191. # one active run, so a second dispatch of the same file must not take
  1192. # it before the first one's print shows as running. Released by
  1193. # `_dispatch_one` when the dispatch ends; same threading as above.
  1194. self._archive_claims: dict[int, int] = {}
  1195. # Expected prints registered by `_start_print` that have not yet had a
  1196. # print command sent. Populated at registration, dropped once
  1197. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1198. # other exit. Same threading argument as `_inflight` above: one
  1199. # sequential caller, callbacks on the same loop, so no lock.
  1200. # item_id -> (printer_id, remote_filename, archive_id)
  1201. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1202. # Budget reservations created for a dispatch whose print command has
  1203. # not been confirmed yet. `_dispatch_one` releases these on every
  1204. # unsuccessful exit; a successful start removes the item id and leaves
  1205. # the reservation for finance_billing to consume with the archive.
  1206. self._unconfirmed_budget_reservations: set[int] = set()
  1207. # The print user `_start_print` handed to printer_manager for an item
  1208. # whose print command has not been sent yet (item_id -> printer_id).
  1209. # `_dispatch_one` takes it back on every unsuccessful exit, like the
  1210. # expected print above: it marks the printer's next print as Bambuddy's.
  1211. self._unconfirmed_print_user: dict[int, int] = {}
  1212. # Prints whose command went out but which the printer has not been
  1213. # seen starting yet: item_id -> (printer_id, remote_filename, archive_id),
  1214. # the file and archive None for a library print. The watchdog drops the
  1215. # entry once the print runs, and withdraws what it stands for when the
  1216. # print never starts (see `_forget_unstarted_print`).
  1217. self._sent_unstarted_print: dict[int, tuple[int, str | None, int | None]] = {}
  1218. # Chamber temperature history for smart soak-time reduction.
  1219. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1220. # Entries older than _chamber_history_ttl are pruned on write.
  1221. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1222. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1223. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1224. # Populated on engagement in `_apply_keep_warm`, cleared by
  1225. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1226. # when a gate setting toggles off mid-hold — the release publishes
  1227. # bed → 0 first).
  1228. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1229. # Preheat rollback registry: printer_id -> subset of
  1230. # {"bed", "chamber", "airduct"} listing which preheat commands
  1231. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1232. # every entry still present at exit unless the print successfully
  1233. # started, so a failed upload / cancel / exception never leaves the
  1234. # printer heating for a job that isn't happening.
  1235. self._preheat_pin: dict[int, set[str]] = {}
  1236. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1237. # rollback can tell its own target from one someone else has since
  1238. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1239. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1240. self._preheat_pin_bed: dict[int, int] = {}
  1241. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1242. # its preheat was still holding at temperature. Set by
  1243. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1244. # `_preheat_sleep`, and cleared when the dispatch exits.
  1245. self._cancelled_dispatches: set[int] = set()
  1246. # printer_id -> monotonic time it was first seen terminal while one of
  1247. # its queue rows was still 'printing'. Reset by any non-terminal
  1248. # observation, so it measures an unbroken run rather than a total.
  1249. # In-memory on purpose: a restart re-arms the grace period, which only
  1250. # delays a recovery that is already the exceptional path (#2829).
  1251. self._terminal_since: dict[int, float] = {}
  1252. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1253. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1254. # across idle printers repeats that for every one of them in a single
  1255. # pass. Cleared at the top of each pass so a re-sliced file is never
  1256. # served from a previous tick.
  1257. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1258. # Per-pass memo for `_unmatched_on` (#3280): choosing a printer asks the
  1259. # matcher about every idle candidate, and a pass can ask again for the
  1260. # same job and printer (another variant, a previous-print retry, the
  1261. # low-filament move). Cleared with the requirement memo.
  1262. self._unmatched_memo: dict[tuple, list[str]] = {}
  1263. # When each "any model" job held for low filament last looked for
  1264. # another printer (#3137), by queue item id.
  1265. self._short_hold_checked_at: dict[int, float] = {}
  1266. async def run(self):
  1267. """Main loop - check queue every interval."""
  1268. self._running = True
  1269. logger.info("Print scheduler started")
  1270. await self._clear_stale_dispatch_claims(at_startup=True)
  1271. while self._running:
  1272. dispatched = False
  1273. try:
  1274. self._sample_chamber_temps()
  1275. # No-op while any upload is in flight; on a quiet tick it releases
  1276. # a claim whose best-effort clear failed (e.g. the database was
  1277. # briefly unreachable), instead of leaving the row wedged until
  1278. # the next restart.
  1279. await self._clear_stale_dispatch_claims()
  1280. await self._close_stranded_printing_items()
  1281. dispatched = await self.check_queue()
  1282. except Exception as e:
  1283. logger.error("Scheduler error: %s", e)
  1284. # Re-check quickly after a productive pass so a draining batch does
  1285. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1286. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1287. async def _close_stranded_printing_items(self) -> None:
  1288. """Close a ``printing`` row the completion event never closed (#2829).
  1289. ``on_print_complete`` refuses to close a row when the completion's
  1290. subtask name disagrees with the file the row was dispatched with, so a
  1291. completion meant for something else (the printer's own
  1292. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1293. The refusal has no way back, though: nothing else ever closes the row,
  1294. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1295. one bad comparison wedges that printer's queue until a human presses
  1296. cancel. That is what #2829's reporters hit, and the guard's own
  1297. docstring already called stranding the worse of the two failures.
  1298. This is the way back. When a row has been ``printing`` while its
  1299. printer sat in a terminal state for the whole grace period, the print
  1300. is over however the event was read, and the row is closed with the
  1301. status the printer's own state implies.
  1302. Deliberately conservative:
  1303. * Only a connected printer counts. A disconnected one has a stale
  1304. ``state`` and proves nothing.
  1305. * The clock is reset by any non-terminal observation, so this cannot
  1306. fire on a printer that is merely between stages.
  1307. * The grace period is far longer than the gap between a printer
  1308. finishing and its completion arriving, so the normal path always
  1309. wins the race and this only ever sees genuine strandings.
  1310. What it does *not* do is replay the completion's side effects --
  1311. notifications, billing, auto-off. It restores the queue, which is the
  1312. harm being undone; the archive was updated by the normal path
  1313. regardless, since only the queue block refuses. A recovery that
  1314. silently re-fired notifications minutes late would be its own bug.
  1315. """
  1316. try:
  1317. async with async_session() as db:
  1318. result = await db.execute(
  1319. select(PrintQueueItem)
  1320. .where(PrintQueueItem.status == "printing")
  1321. .where(PrintQueueItem.printer_id.is_not(None))
  1322. )
  1323. items = list(result.scalars().all())
  1324. if not items:
  1325. self._terminal_since.clear()
  1326. return
  1327. now = time.monotonic()
  1328. seen_printers: set[int] = set()
  1329. closed = False
  1330. for item in items:
  1331. printer_id = item.printer_id
  1332. seen_printers.add(printer_id)
  1333. state = printer_manager.get_status(printer_id)
  1334. status = _terminal_queue_status(state)
  1335. if status is None:
  1336. self._terminal_since.pop(printer_id, None)
  1337. continue
  1338. since = self._terminal_since.setdefault(printer_id, now)
  1339. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1340. continue
  1341. item.status = status
  1342. item.completed_at = datetime.now(timezone.utc)
  1343. closed = True
  1344. # The printer is idle: nothing it prints next is this item's.
  1345. self._forget_unstarted_print(item.id, unless_printing=True)
  1346. logger.warning(
  1347. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1348. "closing it as %s. Its completion event was never matched to it, which blocks "
  1349. "every later job for this printer (#2829).",
  1350. item.id,
  1351. printer_id,
  1352. getattr(state, "state", None),
  1353. now - since,
  1354. status,
  1355. )
  1356. if closed:
  1357. await db.commit()
  1358. from backend.app.services.print_batch import refresh_batches_after
  1359. await refresh_batches_after([item.id for item in items if item.status != "printing"])
  1360. for printer_id in list(self._terminal_since):
  1361. if printer_id not in seen_printers:
  1362. del self._terminal_since[printer_id]
  1363. except Exception as e:
  1364. # Best-effort, same as the claim sweep beside it: a recovery path
  1365. # that can itself break the scheduler loop is worse than the strand.
  1366. logger.error("Stranded-item sweep failed: %s", e)
  1367. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1368. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1369. A claim is only ever held by a live dispatch coroutine, so when this
  1370. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1371. is stale. At startup that is trivially true — no coroutine survives a
  1372. restart. It is equally true on any later tick where no upload is running,
  1373. which is what makes this safe to repeat rather than only run once.
  1374. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1375. the database is briefly unreachable at exactly the moment dispatch ends,
  1376. the claim survives and the row is wedged out of the selection query. That
  1377. used to last until the next restart (#2702 follow-up, seen when
  1378. PostgreSQL refused a connection mid-dispatch).
  1379. ``_inflight`` is populated when the task is spawned, before the coroutine
  1380. claims its row, and pruned by a done-callback that cannot run before the
  1381. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1382. race window and needs no age threshold. A size-derived upload deadline
  1383. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1384. """
  1385. if self._inflight:
  1386. return
  1387. try:
  1388. async with async_session() as db:
  1389. res = await db.execute(
  1390. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1391. )
  1392. await db.commit()
  1393. if res.rowcount:
  1394. logger.info(
  1395. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1396. res.rowcount,
  1397. " at startup" if at_startup else "",
  1398. )
  1399. except Exception as exc:
  1400. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1401. def stop(self):
  1402. """Stop the scheduler."""
  1403. self._running = False
  1404. logger.info("Print scheduler stopped")
  1405. def forget_printer(self, printer_id: int) -> None:
  1406. """Drop what is kept for a deleted printer, so the next printer given its
  1407. id (SQLite reuses it) starts clean: refused uploads and failed power-ons
  1408. would keep it out of dispatch for up to an hour.
  1409. A dispatch already in flight keeps its own state (_inflight, the preheat
  1410. pins, unconfirmed prints): it unwinds that when it ends.
  1411. """
  1412. for keyed in (
  1413. self._upload_backoff,
  1414. self._upload_refusals,
  1415. self._upload_refusal_kind,
  1416. self._upload_refusal_notified,
  1417. self._wake_failures,
  1418. self._drying_in_progress,
  1419. self._dispatch_holds,
  1420. self._chamber_history,
  1421. self._keep_warm,
  1422. self._terminal_since,
  1423. ):
  1424. keyed.pop(printer_id, None)
  1425. for keyed in (self._auto_dry_units, self._auto_dry_above):
  1426. for key in [key for key in keyed if key[0] == printer_id]:
  1427. del keyed[key]
  1428. for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
  1429. del self._sent_unstarted_print[item_id]
  1430. async def check_queue(self) -> bool:
  1431. """Check for prints ready to start.
  1432. Returns True if this pass dispatched at least one item, so the caller
  1433. can loop again quickly instead of sleeping the full interval (#2555).
  1434. """
  1435. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1436. self._filament_req_memo.clear()
  1437. self._unmatched_memo.clear()
  1438. async with async_session() as db:
  1439. # Check if shortest-job-first scheduling is enabled
  1440. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1441. # Get all pending items in the one order the queue page shows them
  1442. # in (#3200). The first eligible item takes a printer, so this order
  1443. # decides who wins a printer that a pinned job and an "Any <model>"
  1444. # job both want. It used to start with ``printer_id``, which made the
  1445. # lane outrank the position: SQLite sorts NULL first, so model-based
  1446. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1447. # Neither is what the user dragged into place.
  1448. if sjf_enabled:
  1449. # SJF: items already jumped get top priority (starvation guard),
  1450. # then sort by print_time ascending. Items with no print time go
  1451. # last, and position breaks ties.
  1452. result = await db.execute(
  1453. select(PrintQueueItem)
  1454. .where(PrintQueueItem.status == "pending")
  1455. # Never re-select a row a dispatch worker has already claimed
  1456. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1457. # below, and the guard that lets an orphaned claim be ignored
  1458. # until startup reconciliation clears it.
  1459. .where(PrintQueueItem.dispatching_at.is_(None))
  1460. # archive/library_file are read by the cross-model gate
  1461. # (#2578); eager-load once per pass instead of a lazy-load
  1462. # (which would raise in async) per item.
  1463. .options(
  1464. selectinload(PrintQueueItem.archive),
  1465. selectinload(PrintQueueItem.library_file),
  1466. # Cross-model candidates (#671), plus each candidate's file
  1467. # for the same cross-model gate. Lazy-loading either would
  1468. # raise in async.
  1469. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1470. )
  1471. .order_by(
  1472. PrintQueueItem.been_jumped.desc(),
  1473. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1474. PrintQueueItem.position,
  1475. PrintQueueItem.id,
  1476. )
  1477. )
  1478. else:
  1479. result = await db.execute(
  1480. select(PrintQueueItem)
  1481. .where(PrintQueueItem.status == "pending")
  1482. # Skip rows already claimed by a dispatch worker (#2615).
  1483. .where(PrintQueueItem.dispatching_at.is_(None))
  1484. .options(
  1485. selectinload(PrintQueueItem.archive),
  1486. selectinload(PrintQueueItem.library_file),
  1487. # Cross-model candidates (#671), plus each candidate's file
  1488. # for the same cross-model gate. Lazy-loading either would
  1489. # raise in async.
  1490. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1491. )
  1492. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1493. )
  1494. items = list(result.scalars().all())
  1495. # Drop rows whose upload is still in flight from an earlier pass
  1496. # (#2602). They stay `pending` until the upload finishes, so without
  1497. # this a fast tick would re-select and re-dispatch the same row.
  1498. # Belt-and-suspenders with the printer exclusion below.
  1499. if self._inflight:
  1500. inflight_ids = set(self._inflight)
  1501. items = [it for it in items if it.id not in inflight_ids]
  1502. # Read plate-clear setting once per queue check. Default MUST be
  1503. # False to match the schema (SettingsSchema.require_plate_clear
  1504. # defaults False) and the frontend (toggle + card badge both treat a
  1505. # missing value as off). When no settings row exists, a True default
  1506. # here re-enabled the plate-clear gate the UI showed as disabled,
  1507. # blocking dispatch to FINISH-state printers forever with no UI path
  1508. # to clear it (#1865).
  1509. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1510. # Dispatch and track scheduled drying runs (#2638)
  1511. await self._check_scheduled_dryings(db)
  1512. if not items:
  1513. # No dispatchable pending items — still check auto-drying on idle
  1514. # printers, but keep any printer with an upload still in flight
  1515. # from an earlier pass out of it (#2602): its print is imminent,
  1516. # so it must not be auto-dried in the gap before the row flips to
  1517. # printing. Report the pass as productive while uploads run so the
  1518. # loop stays on the fast interval.
  1519. #
  1520. # Also release any keep-warm holds that got orphaned by the queue
  1521. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1522. # this early return, so call it directly with an empty candidate
  1523. # set. Without this, a printer whose queued item was cancelled or
  1524. # deleted would keep its bed at target until the max-duration
  1525. # timeout expired.
  1526. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1527. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1528. await self._check_auto_drying(db, [], inflight_printers)
  1529. await self._check_filament_low(db)
  1530. await self._check_stock_forecast(db)
  1531. return bool(self._inflight)
  1532. logger.info(
  1533. "Queue check: found %d pending items: %s",
  1534. len(items),
  1535. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1536. )
  1537. # Forget jobs that left the queue since they were last checked.
  1538. pending_ids = {i.id for i in items}
  1539. self._short_hold_checked_at = {
  1540. item_id: at for item_id, at in self._short_hold_checked_at.items() if item_id in pending_ids
  1541. }
  1542. # Seed busy_printers with printers that already have an item in 'printing'
  1543. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1544. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1545. # lag several seconds behind the print command, so the next check_queue
  1546. # tick still sees IDLE and would double-dispatch onto the same printer.
  1547. # Without this guard, two pending items targeting the same printer
  1548. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1549. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1550. busy_result = await db.execute(
  1551. select(PrintQueueItem.printer_id)
  1552. .where(PrintQueueItem.status == "printing")
  1553. .where(PrintQueueItem.printer_id.is_not(None))
  1554. )
  1555. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1556. # Why each printer left this pass, recorded where the decision is
  1557. # made rather than re-derived when the summary is logged. #3018's
  1558. # bundle shows what the old summary produced: "printer 1 not
  1559. # available -- connected=True, state=IDLE" immediately followed by a
  1560. # dispatch to printer 1. Two things went wrong at once. The line read
  1561. # live state at log time, which by then no longer matched the state
  1562. # the decision was made on; and `busy_printers` holds both printers
  1563. # that cannot take work and printers this pass has claimed for it,
  1564. # which are opposite facts. It is the first line anyone greps for
  1565. # "why did my item not go out", so it has to say which.
  1566. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1567. # Printers this pass is dispatching to. They are in busy_printers so
  1568. # nothing else in the pass targets them -- that is a reservation, not
  1569. # an obstruction, and the summary says so.
  1570. claimed_printers: set[int] = set()
  1571. def mark_busy(printer_id: int, reason: str) -> None:
  1572. """Take ``printer_id`` out of this pass, recording why.
  1573. First reason wins: a printer already excluded by a stronger fact
  1574. -- a print running on it -- must not be relabelled by a weaker
  1575. check that ran later and would have excluded it anyway.
  1576. """
  1577. busy_printers.add(printer_id)
  1578. busy_reasons.setdefault(printer_id, reason)
  1579. def claim_printer(printer_id: int) -> None:
  1580. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1581. claimed_printers.add(printer_id)
  1582. mark_busy(printer_id, "selected for dispatch in this pass")
  1583. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1584. # worded for a different audience: the log wants "still inside its
  1585. # post-dispatch hold window", the queue row wants to know the printer
  1586. # is taken and nothing is broken. Only the cases that would read wrong
  1587. # as a plain "Busy" are recorded here; the rest fall back to it.
  1588. item_hold_reasons: dict[int, str] = {}
  1589. # Names and models for the printers this pass may have to write a
  1590. # waiting reason about, read once rather than per skip per tick. The
  1591. # model-based branch already has its names from `_printers_for_model`.
  1592. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1593. pinned_printers: dict[int, tuple[str, str]] = {}
  1594. if pinned_printer_ids:
  1595. pinned_rows = await db.execute(
  1596. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1597. )
  1598. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1599. def printer_label(printer_id: int) -> str:
  1600. """What to call this printer in a queue row."""
  1601. entry = pinned_printers.get(printer_id)
  1602. return (entry[0] if entry else "") or f"printer {printer_id}"
  1603. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1604. """Record why *item* is not going out, in the words the queue row shows.
  1605. The fixed-printer branch's single writer for ``waiting_reason``
  1606. (#3074). Before this, the sensor interlock was the only thing that
  1607. wrote the field there, so an item pinned to a printer that was
  1608. merely printing sat at `pending` with nothing to show for it —
  1609. indistinguishable from a queue that had stopped working — while
  1610. the same job queued as "Any <model>" explained itself.
  1611. Every exit from that branch now calls this, which is also what
  1612. replaced the interlock's old habit of clearing the field up front:
  1613. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1614. because whichever exit runs next overwrites it and the dispatch
  1615. path clears it.
  1616. A notification goes out when this item starts asking for
  1617. something, and only then: the new reason needs the user, and what
  1618. it replaced did not. "What it replaced did not" has to include a
  1619. busy-only reason, not just an empty one. The sequence this branch
  1620. actually produces is a print running (``Busy: X1C-01``) and then
  1621. the plate it left behind (``Waiting for plate confirmation``), and
  1622. testing "was the field empty" would call that no transition at all
  1623. and stay quiet through the one case worth saying out loud.
  1624. The cost is that a printer dropping offline, coming back busy and
  1625. dropping again asks twice rather than once. That is the honest
  1626. reading — it went wrong twice — and the alternative was a rule
  1627. that never fired for the case this was built for.
  1628. *notify* is how a caller opts out. The sensor interlock does: it
  1629. has never sent this notification, and a change about what the
  1630. queue *displays* is not the place to start (#1148).
  1631. """
  1632. if item.waiting_reason == reason:
  1633. return
  1634. # Busy-only and empty are the same thing here: neither is the
  1635. # queue asking the user for anything.
  1636. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1637. item.waiting_reason = reason
  1638. await db.commit()
  1639. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1640. return
  1641. try:
  1642. job_name = await self._get_job_name(db, item)
  1643. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1644. await notification_service.on_queue_job_waiting(
  1645. job_name=job_name,
  1646. target_model=(entry[1] if entry else "") or "",
  1647. waiting_reason=reason,
  1648. db=db,
  1649. printer_id=item.printer_id,
  1650. )
  1651. except Exception as e:
  1652. # A queue that cannot say why it is waiting is the bug being
  1653. # fixed here; a queue that stops dispatching because a
  1654. # notification provider is down would be a worse one.
  1655. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1656. async def hold_for_printer(
  1657. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1658. ) -> None:
  1659. """Take *printer_id* out of this pass and tell the item's owner why."""
  1660. mark_busy(printer_id, log_reason)
  1661. item_hold_reasons.setdefault(printer_id, item_reason)
  1662. await hold_item(item, item_reason)
  1663. # Defense-in-depth (#1157): augment busy_printers with any printer
  1664. # still in its post-dispatch hold window. Empirically, the DB seed
  1665. # above can miss in-flight items in a multi-plate batch — same-file
  1666. # plates were being dispatched 30 s apart while the H2D was still
  1667. # digesting the first project_file. The hold is keyed in-memory and
  1668. # released by the watchdog on the success path, so it adds a layer
  1669. # that doesn't depend on DB row visibility or completion-callback
  1670. # timing.
  1671. for held_printer_id in list(self._dispatch_holds.keys()):
  1672. if self._printer_in_dispatch_hold(held_printer_id):
  1673. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1674. # Exclude printers whose upload is still in flight from an earlier
  1675. # pass (#2602). The row is `pending` until the upload finishes and
  1676. # the printing-state seed / dispatch hold above only arm once the
  1677. # upload completes, so this is what holds the printer (and, via
  1678. # busy_printers, its auto-drying) out of the pass during the upload.
  1679. for _task, inflight_pid in self._inflight.values():
  1680. if inflight_pid is not None:
  1681. mark_busy(inflight_pid, "an upload to it is still in flight")
  1682. # Snapshot taken here, before the item loop adds anything (#2801).
  1683. #
  1684. # The three sources above all mean the same thing: a print on this
  1685. # printer is running or imminent. Everything the loop adds below
  1686. # means only "the queue could not dispatch to it this pass", which
  1687. # is a different statement -- a printer waiting on a plate-clear
  1688. # acknowledgment, an offline printer, one with no matching file.
  1689. #
  1690. # Auto-drying must only see the first kind. Reading the whole set
  1691. # as "is currently printing" is what put a plate-held printer down
  1692. # the mid-print path: it capped the drying temperature, logged the
  1693. # cycle as (mid-print), and skipped the very gate that was supposed
  1694. # to hold it. The interlock block below already documents the same
  1695. # hazard and works around it by staying out of busy_printers; this
  1696. # generalises that workaround instead of repeating it per case.
  1697. dispatching_printers: set[int] = set(busy_printers)
  1698. # Printers whose last upload never reached them (#3210). After the
  1699. # snapshot above on purpose: such a printer is idle, not about to
  1700. # print, and auto-drying must keep treating it as idle.
  1701. now_mono = time.monotonic()
  1702. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1703. # can leave them out: there is no print to keep a bed warm for.
  1704. # Their holds are written silently: the refusal that put a printer
  1705. # here sent the "job waiting" notification for its run (#3409).
  1706. backoff_printers: set[int] = set()
  1707. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1708. if now_mono >= retry_at:
  1709. del self._upload_backoff[backoff_pid]
  1710. continue
  1711. backoff_printers.add(backoff_pid)
  1712. mark_busy(
  1713. backoff_pid,
  1714. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1715. )
  1716. item_hold_reasons.setdefault(
  1717. backoff_pid,
  1718. _refused_upload_hold_reason(printer_label(backoff_pid), self._upload_refusal_kind.get(backoff_pid)),
  1719. )
  1720. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1721. # enclosure door left open, say. The fixed-printer branch turns
  1722. # this into a waiting_reason the user can act on; the model-based
  1723. # branch hides these printers from the matcher so an "Any <model>"
  1724. # job runs on a sibling instead of queueing behind the held one.
  1725. #
  1726. # Deliberately NOT merged into busy_printers, even though that set
  1727. # already means "unavailable this pass". _check_auto_drying reads
  1728. # it as "is currently printing" and would put an idle-but-held
  1729. # printer down the mid-print drying path, which caps the drying
  1730. # temperature and skips the queue-only gating. A held printer is
  1731. # idle; it should dry exactly as it did before.
  1732. #
  1733. # Only sensors we actually read and found alerting appear here; see
  1734. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1735. # holds nothing.
  1736. interlocked: dict[int, str] = {}
  1737. try:
  1738. interlocked = await ha_sensor_manager.blocked_printers(db)
  1739. except Exception as e:
  1740. # Never let the interlock stop the queue running. A broken
  1741. # lookup means no holds, not no dispatches.
  1742. logger.warning("Home Assistant interlock check failed: %s", e)
  1743. interlocked = {}
  1744. # Printers a smart plug can bring back, read once for the whole pass
  1745. # (#2786). Used by the model-based branch both to word "Offline" in
  1746. # the waiting reason and to decide what the wake step may switch on.
  1747. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1748. # At most one power-on per queue check. Each one blocks this loop
  1749. # for the boot wait, so a queue of ten class-targeted jobs must not
  1750. # switch on ten printers inside a single pass — the next pass wakes
  1751. # the next one (#2786).
  1752. power_on_attempted = False
  1753. # Log skip reasons once per queue check (not per item)
  1754. skip_reasons: dict[str, int] = {}
  1755. # Items selected for dispatch in this pass, one per printer. The
  1756. # loop below only *decides* — the uploads happen afterwards, in
  1757. # parallel (#2555). See _dispatch_selected().
  1758. dispatch_ids: list[int] = []
  1759. # Library rows queued with `cleanup_library_after_dispatch` (the
  1760. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1761. # that prints them: the row is deleted and the 3MF is unlinked from
  1762. # disk. That was safe only because dispatch was serial. Run two of
  1763. # them against the same row at once and the second DELETE matches no
  1764. # row (StaleDataError), and the winner's unlink can pull the file out
  1765. # from under the loser's in-flight upload.
  1766. #
  1767. # Only the cleanup flag mutates the row. An ordinary library print
  1768. # just reads it, so the common fan-out — one file, many printers,
  1769. # which is exactly the reporter's workload — still goes out fully in
  1770. # parallel. Narrow the guard to the mutating case; do not serialise
  1771. # the case the whole fix exists for.
  1772. dispatch_libs: set[int] = set()
  1773. consumed_libs: set[int] = set()
  1774. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1775. """True if dispatching `candidate` now would race another item's cleanup."""
  1776. lib_id = candidate.library_file_id
  1777. if lib_id is None:
  1778. return False
  1779. if candidate.cleanup_library_after_dispatch:
  1780. # We would delete a row someone else in this pass is reading.
  1781. return lib_id in dispatch_libs
  1782. # Someone else in this pass will delete the row out from under us.
  1783. return lib_id in consumed_libs
  1784. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1785. lib_id = candidate.library_file_id
  1786. if lib_id is None:
  1787. return
  1788. dispatch_libs.add(lib_id)
  1789. if candidate.cleanup_library_after_dispatch:
  1790. consumed_libs.add(lib_id)
  1791. # Printer scope of each job's creator (#1727), so an "any <model>"
  1792. # job only lands on a printer its creator may use. Loaded lazily,
  1793. # once per creator per pass.
  1794. from backend.app.core.auth import is_auth_enabled
  1795. scope_auth_enabled = await is_auth_enabled(db)
  1796. creator_scopes: dict[int, PrinterScope] = {}
  1797. # Printers a model job passes over while drying blocks the queue,
  1798. # as a pinned job waits for its own. A parked timer never ends,
  1799. # so it does not hold (#2896).
  1800. drying_held: set[int] = (
  1801. {pid for pid in self._drying_in_progress if not self._drying_is_only_parked(pid)}
  1802. if self._drying_in_progress and await self._get_bool_setting(db, "queue_drying_block")
  1803. else set()
  1804. )
  1805. async def _creator_scope(user_id: int | None) -> PrinterScope:
  1806. if not scope_auth_enabled or user_id is None:
  1807. return ALL_PRINTERS
  1808. if user_id not in creator_scopes:
  1809. creator_scopes[user_id] = await resolve_user_id_printer_scope(db, user_id)
  1810. return creator_scopes[user_id]
  1811. for item in items:
  1812. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1813. if item.scheduled_time:
  1814. sched = item.scheduled_time
  1815. if sched.tzinfo is None:
  1816. sched = sched.replace(tzinfo=timezone.utc)
  1817. if sched > datetime.now(timezone.utc):
  1818. # Waiting on the clock, not on a printer.
  1819. await hold_item(item, None)
  1820. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1821. continue
  1822. # Skip items that require manual start, except an "any model"
  1823. # job held for low filament that another idle printer can now
  1824. # run: that one is moved there and carries on below (#3137).
  1825. if item.manual_start and not (
  1826. item.filament_short
  1827. and await self._release_short_model_hold(
  1828. db,
  1829. item,
  1830. busy_printers | interlocked.keys() | drying_held,
  1831. require_plate_clear,
  1832. await _creator_scope(item.created_by_id),
  1833. )
  1834. ):
  1835. # Waiting on the user, not on a printer. Cleared here because
  1836. # this is the last pass that will look at the row: a staged
  1837. # item never reaches the branches below again, so a reason
  1838. # left from before it was staged would stand forever (#3074).
  1839. # The one exception is the unmatched-filament hold, whose
  1840. # reason was written at staging and is why the item waits:
  1841. # it names the filament to load (#2799). Pressing start
  1842. # clears manual_start, and the branches below overwrite it.
  1843. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1844. await hold_item(item, keep)
  1845. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1846. continue
  1847. if item.printer_id and item.printer_id not in pinned_printers:
  1848. # Moved by the release above to a printer no row named when
  1849. # the labels were read.
  1850. moved_to = await self._get_printer(db, item.printer_id)
  1851. if moved_to is not None:
  1852. pinned_printers[item.printer_id] = (moved_to.name or "", moved_to.model or "")
  1853. if item.printer_id:
  1854. # Its creator may no longer use this printer (#1727): an
  1855. # admin took it away from their group after the job was
  1856. # queued, say to keep it free for a training session. Held,
  1857. # not failed, so it starts if access comes back or the user
  1858. # moves it to a printer they still have.
  1859. if not (await _creator_scope(item.created_by_id)).allows(item.printer_id):
  1860. await hold_item(
  1861. item,
  1862. "Its owner no longer has access to this printer — move it to another printer",
  1863. notify=False,
  1864. )
  1865. skip_reasons["printer_out_of_scope"] = skip_reasons.get("printer_out_of_scope", 0) + 1
  1866. continue
  1867. # Held by a sensor interlock (#1148). Checked before the
  1868. # busy_printers test that would otherwise swallow it
  1869. # silently — "waiting for a printer" and "waiting for you
  1870. # to shut the enclosure" need to read differently, and only
  1871. # one of them is something the user can fix.
  1872. #
  1873. # It used to be the only thing that wrote a waiting_reason on
  1874. # this branch, and it cleared the field up front so a lifted
  1875. # hold could not leave a shut door reading "Waiting on
  1876. # Enclosure Door". `hold_item` carries that guarantee now —
  1877. # every exit below writes — so the clear is gone and the
  1878. # interlock is an ordinary hold like the rest (#3074).
  1879. interlock_reason = interlocked.get(item.printer_id)
  1880. if interlock_reason:
  1881. # Silent, exactly as it has always been. #1148 built this
  1882. # as a hold that shows on the row, never as an alert, and
  1883. # routing it through the shared writer must not quietly
  1884. # turn every open door into a notification.
  1885. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1886. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1887. continue
  1888. # Specific printer assignment (existing behavior)
  1889. if item.printer_id in busy_printers:
  1890. # Whatever took the printer out of this pass — a print
  1891. # already running on it, a post-dispatch hold, an upload
  1892. # still in flight, an item ahead of this one in the same
  1893. # pass — reads the same way from the queue: the printer is
  1894. # taken and this item is in line for it. The exceptions
  1895. # that do not (an offline printer, say) recorded their own
  1896. # wording in `item_hold_reasons` when they held it.
  1897. await hold_item(
  1898. item,
  1899. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1900. notify=item.printer_id not in backoff_printers,
  1901. )
  1902. continue
  1903. # Check if printer is idle
  1904. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1905. printer_connected = printer_manager.is_connected(item.printer_id)
  1906. # If printer not connected, try to power on via smart plug
  1907. if not printer_connected:
  1908. plugs = await self._get_smart_plugs(db, item.printer_id)
  1909. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1910. if auto_on_plugs:
  1911. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1912. # Power on using the plug that actually feeds the printer, and
  1913. # wait for it to boot on that one only (#2629).
  1914. primary_plug = self._pick_power_plug(auto_on_plugs)
  1915. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1916. if powered_on:
  1917. # Also turn on any remaining auto_on plugs (e.g., filter)
  1918. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1919. try:
  1920. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1921. if await service.turn_on(extra_plug):
  1922. await publish_plug_state(
  1923. extra_plug.id,
  1924. extra_plug.name,
  1925. extra_plug.printer_id,
  1926. on=True,
  1927. ha_entity_id=extra_plug.ha_entity_id,
  1928. )
  1929. logger.info(
  1930. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1931. )
  1932. except Exception as e:
  1933. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1934. printer_connected = True
  1935. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1936. else:
  1937. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1938. await hold_for_printer(
  1939. item,
  1940. item.printer_id,
  1941. "smart-plug power-on failed",
  1942. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1943. )
  1944. continue
  1945. else:
  1946. # No plug or auto_on disabled. Worded exactly as the
  1947. # model-based branch words it (#2786): this is the one
  1948. # entry on that list the user has to act on, because
  1949. # Bambuddy will never switch this printer on itself.
  1950. await hold_for_printer(
  1951. item,
  1952. item.printer_id,
  1953. "offline, with no smart plug to power it on",
  1954. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1955. )
  1956. continue
  1957. # Check if printer is idle (busy with another print)
  1958. if not printer_idle:
  1959. await hold_for_printer(
  1960. item,
  1961. item.printer_id,
  1962. "not idle",
  1963. self._pinned_hold_reason(
  1964. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1965. ),
  1966. )
  1967. continue
  1968. # Drying blocks the queue, if the user asked it to. A hold
  1969. # is a skip like any other, so it belongs here with the
  1970. # rest of the availability checks.
  1971. # A parked timer (#2896) never ends, so it must not hold the
  1972. # queue; it stays tracked so the stop paths still reach it.
  1973. if (
  1974. self._drying_in_progress.get(item.printer_id)
  1975. and not self._drying_is_only_parked(item.printer_id)
  1976. and await self._get_bool_setting(db, "queue_drying_block")
  1977. ):
  1978. # Busy-shaped on purpose: the cycle ends on its own and
  1979. # the job goes out, so there is nothing to alert about.
  1980. await hold_for_printer(
  1981. item,
  1982. item.printer_id,
  1983. "drying, and drying is set to block the queue",
  1984. f"Busy: {printer_label(item.printer_id)} (drying)",
  1985. )
  1986. continue
  1987. # Check condition (previous print success)
  1988. if item.require_previous_success:
  1989. if not await self._check_previous_success(db, item):
  1990. item.status = "skipped"
  1991. item.error_message = "Previous print failed or was aborted"
  1992. item.completed_at = datetime.now(timezone.utc)
  1993. # Not pending any more, so not waiting for anything.
  1994. item.waiting_reason = None
  1995. await db.commit()
  1996. logger.info("Skipped queue item %s - previous print failed", item.id)
  1997. # Send notification
  1998. job_name = await self._get_job_name(db, item)
  1999. printer = await self._get_printer(db, item.printer_id)
  2000. await notification_service.on_queue_job_skipped(
  2001. job_name=job_name,
  2002. printer_id=item.printer_id,
  2003. printer_name=printer.name if printer else "Unknown",
  2004. reason="Previous print failed or was aborted",
  2005. db=db,
  2006. )
  2007. continue
  2008. # Resolve the AMS mapping when it's missing OR unresolved
  2009. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  2010. # frontend status-load race can persist [-1] (#2589) — and
  2011. # must be recomputed from live trays rather than trusted.
  2012. if await _edited_since_loaded(db, item):
  2013. continue
  2014. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  2015. if unmappable:
  2016. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  2017. continue
  2018. # Filament-deficit pre-dispatch check (#1496). If the
  2019. # assigned spool can't satisfy any required slot grams,
  2020. # promote the item to manual_start so the user must
  2021. # acknowledge via the ▶ button (which re-checks live).
  2022. if await self._block_on_filament_deficit(db, item):
  2023. # Now staged for the user to start by hand, and the row
  2024. # shows the filament-short badge instead. Cleared because
  2025. # a staged item never reaches this branch again.
  2026. await hold_item(item, None)
  2027. continue
  2028. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  2029. # than let the printer pick a substitute for a slot the
  2030. # matcher could not resolve on this printer.
  2031. if await self._block_on_unmatched_filament(db, item):
  2032. continue
  2033. # Hold this item back for the next pass rather than racing
  2034. # another dispatch over the same transient library row. The
  2035. # printer is still marked busy so a later item does not jump
  2036. # its place in this printer's queue.
  2037. if _library_row_conflict(item):
  2038. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2039. await hold_for_printer(
  2040. item,
  2041. item.printer_id,
  2042. "holding its place while another item releases a library row",
  2043. f"Busy: {printer_label(item.printer_id)}",
  2044. )
  2045. continue
  2046. # Print takes priority: stop a cycle Bambuddy armed, now
  2047. # that this item is definitely going out.
  2048. #
  2049. # Placement is the whole point (#2801). This used to sit up
  2050. # with the availability checks, inside the not-idle branch
  2051. # -- so it fired only on the passes where the print was NOT
  2052. # going to start, and never on the ones where it was.
  2053. # Drying is not one of the things `_is_printer_idle` looks
  2054. # at, so a stop could never have unblocked that printer
  2055. # anyway; the cycle was spent for nothing, auto-drying
  2056. # re-armed on the next tick, and a plate left
  2057. # unacknowledged turned that into a loop on the scheduler
  2058. # interval. Every skip between there and here -- a failed
  2059. # previous print, an unmappable item, a filament deficit, a
  2060. # contested library row -- is another way to lose a cycle
  2061. # for a print that never happens, which is why this waits
  2062. # until the decision is actually made.
  2063. if self._drying_in_progress.get(
  2064. item.printer_id
  2065. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  2066. await self._stop_drying(item.printer_id)
  2067. # Queue the dispatch instead of running it here — see
  2068. # _dispatch_selected(). busy_printers still gets the printer
  2069. # immediately, so nothing else in this pass can target it.
  2070. #
  2071. # The reason goes first: this item is not waiting for anything
  2072. # any more, and the model-based branch clears its own at the
  2073. # equivalent moment (#3074).
  2074. await hold_item(item, None)
  2075. _claim_library_row(item)
  2076. dispatch_ids.append(item.id)
  2077. claim_printer(item.printer_id)
  2078. # SJF starvation guard: mark items that were jumped
  2079. if sjf_enabled and item.print_time_seconds is not None:
  2080. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  2081. for other in items:
  2082. if (
  2083. other.id != item.id
  2084. and other.id not in dispatch_ids
  2085. and other.status == "pending"
  2086. and _could_take_printer(other, item.printer_id, pinned_model)
  2087. and not other.been_jumped
  2088. and other.position < item.position
  2089. and (
  2090. other.print_time_seconds is None
  2091. or other.print_time_seconds > item.print_time_seconds
  2092. )
  2093. ):
  2094. other.been_jumped = True
  2095. await db.commit()
  2096. elif item.target_model or item.variants:
  2097. # Model-based assignment - find any idle printer of matching model.
  2098. # A plain model-based item has exactly one candidate, built from
  2099. # its own columns. A cross-model item (#671) has one per sliced
  2100. # variant and takes the first that matches, walking them in the
  2101. # user's priority order so the pick is reproducible when more
  2102. # than one printer is free in the same pass.
  2103. candidates = _candidates_for(item)
  2104. item_scope = await _creator_scope(item.created_by_id)
  2105. printer_id = None
  2106. chosen: _ModelCandidate | None = None
  2107. per_model_reasons: list[tuple[str | None, str]] = []
  2108. # Candidates that cleared the cross-model gate below. The
  2109. # smart-plug wake step may only consider these — waking a
  2110. # printer for a file that can never legally run on it is
  2111. # worse than not waking at all (#2786).
  2112. wakeable_candidates: list[_ModelCandidate] = []
  2113. # Printers passed over because their last print failed.
  2114. gate_blocked: set[int] = set()
  2115. if not candidates:
  2116. # Every candidate file has been deleted or trashed out from
  2117. # under this item. Hold it with something the user can act
  2118. # on rather than letting it look dispatchable forever.
  2119. per_model_reasons.append(
  2120. (
  2121. item.target_model,
  2122. "Every file for this job has been deleted — add a file back or remove the item",
  2123. )
  2124. )
  2125. for candidate in candidates:
  2126. effective_types, filament_overrides = _filament_constraints(candidate)
  2127. # Cross-model safety gate (#2578): never hand a 3MF sliced
  2128. # for an incompatible model to a printer, no matter how the
  2129. # row got into the DB (old rows, direct API writes). Held
  2130. # as pending with an actionable waiting_reason — the user
  2131. # fixes it by editing the item's target model.
  2132. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  2133. per_model_reasons.append(
  2134. (
  2135. candidate.target_model,
  2136. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  2137. f"{candidate.target_model} — edit the item and fix its target model",
  2138. )
  2139. )
  2140. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  2141. continue
  2142. wakeable_candidates.append(candidate)
  2143. async def is_short(
  2144. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2145. ) -> bool:
  2146. # The check reads the file and plate off the item,
  2147. # so it must hold this candidate's. Resolving is
  2148. # safe to repeat, and the winner is resolved again
  2149. # below.
  2150. self._resolve_variant(item, candidate)
  2151. return await self._filament_short_on(db, item, pid)
  2152. async def unmatched_on(
  2153. pid: int, item: PrintQueueItem = item, candidate: _ModelCandidate = candidate
  2154. ) -> list[str]:
  2155. self._resolve_variant(item, candidate)
  2156. return await self._unmatched_on(db, item, pid)
  2157. while True:
  2158. match_id, match_reason = await self._find_idle_printer_for_model(
  2159. db,
  2160. candidate.target_model,
  2161. # Sensor-held printers are unavailable to the
  2162. # matcher but stay out of busy_printers itself
  2163. # (#1148) — see where `interlocked` is built.
  2164. busy_printers | interlocked.keys() | gate_blocked | drying_held,
  2165. effective_types,
  2166. item.target_location,
  2167. filament_overrides=filament_overrides,
  2168. require_plate_clear=require_plate_clear,
  2169. wakeable_ids=wakeable_printer_ids,
  2170. printer_scope=item_scope,
  2171. is_short=is_short,
  2172. drying_ids=drying_held,
  2173. unmatched_on=unmatched_on,
  2174. refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
  2175. )
  2176. # "Only if the previous print succeeded" is about the
  2177. # printer the job lands on: one whose last print failed
  2178. # is passed over for another of the model.
  2179. if (
  2180. match_id
  2181. and item.require_previous_success
  2182. and not await self._check_previous_success(db, item, printer_id=match_id)
  2183. ):
  2184. gate_blocked.add(match_id)
  2185. continue
  2186. break
  2187. if match_id:
  2188. printer_id = match_id
  2189. chosen = candidate
  2190. break
  2191. per_model_reasons.append((candidate.target_model, match_reason or ""))
  2192. # Nothing is available and nothing has been woken this pass:
  2193. # switch one matching printer on. Assignment is left to the
  2194. # next pass, which sees the booted printer's live state
  2195. # instead of guessing at it seconds after connect (#2786).
  2196. if printer_id is None and not power_on_attempted and wakeable_candidates:
  2197. woken_id, attempted_id = await self._wake_printer_for_model(
  2198. db,
  2199. wakeable_candidates,
  2200. item.target_location,
  2201. busy_printers | interlocked.keys(),
  2202. wakeable_printer_ids,
  2203. require_plate_clear,
  2204. printer_scope=item_scope,
  2205. )
  2206. # An attempt spends the pass's one wake whether or not
  2207. # it worked: it has already blocked the queue loop for
  2208. # the boot wait. A failed printer is held out of later
  2209. # passes by its own cool-off, deliberately NOT by
  2210. # busy_printers — it is off, not busy, and labelling it
  2211. # busy would both misdescribe it in every later item's
  2212. # waiting reason and suppress the notification, since
  2213. # an all-busy reason is treated as needing no action.
  2214. power_on_attempted = attempted_id is not None
  2215. if woken_id is not None:
  2216. # Hold this item back rather than dispatching onto a
  2217. # printer whose AMS has not reported yet.
  2218. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  2219. continue
  2220. if printer_id is None and gate_blocked:
  2221. # The matcher reports the printers passed over as busy;
  2222. # what holds the job is their failed last print.
  2223. per_model_reasons = [(item.target_model, MODEL_GATE_WAIT_REASON)]
  2224. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  2225. # Fold the winning variant's file and settings onto the item
  2226. # before anything else looks at them — the guards below and
  2227. # every step of the dispatch read the item's own columns.
  2228. if chosen is not None:
  2229. self._resolve_variant(item, chosen)
  2230. # Update waiting_reason if changed and send notification when first waiting
  2231. if item.waiting_reason != waiting_reason:
  2232. was_waiting = item.waiting_reason is not None
  2233. previous_reason = item.waiting_reason
  2234. item.waiting_reason = waiting_reason
  2235. await db.commit()
  2236. # Send waiting notification only when transitioning to waiting state
  2237. # and the reason requires user action (not just "all printers busy")
  2238. # Also when a job that only waited for a busy printer
  2239. # now waits on something the user has to do.
  2240. if (
  2241. waiting_reason
  2242. and (not was_waiting or self._is_busy_only(previous_reason or ""))
  2243. and not _asks_nothing_new(waiting_reason)
  2244. ):
  2245. job_name = await self._get_job_name(db, item)
  2246. await notification_service.on_queue_job_waiting(
  2247. job_name=job_name,
  2248. target_model=_candidate_model_label(candidates) or item.target_model,
  2249. waiting_reason=waiting_reason,
  2250. db=db,
  2251. )
  2252. if printer_id:
  2253. # Before claiming the printer: hold back rather than race
  2254. # another dispatch over the same transient library row.
  2255. # Checked here so a held item does not get a printer
  2256. # assigned and then sit on it. See _library_row_conflict().
  2257. #
  2258. # No busy_printers.add() here, unlike the fixed-printer
  2259. # branch above: that one protects its printer's own queue
  2260. # ordering, but this item was never assigned to `printer_id`
  2261. # — the matcher merely offered it. Marking it busy would
  2262. # strand an idle printer for the rest of the pass.
  2263. if _library_row_conflict(item):
  2264. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  2265. continue
  2266. if await _edited_since_loaded(db, item):
  2267. continue
  2268. # Assign printer and start - clear waiting reason
  2269. item.printer_id = printer_id
  2270. item.waiting_reason = None
  2271. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  2272. # Send assignment notification
  2273. job_name = await self._get_job_name(db, item)
  2274. printer = await self._get_printer(db, printer_id)
  2275. await notification_service.on_queue_job_assigned(
  2276. job_name=job_name,
  2277. printer_id=printer_id,
  2278. printer_name=printer.name if printer else "Unknown",
  2279. target_model=item.target_model,
  2280. db=db,
  2281. )
  2282. # A mapping on this item was not made for the printer just
  2283. # picked: it came with a job moved here from a fixed
  2284. # printer, or from a variant. Its tray IDs can name a
  2285. # tray of the right type in another colour here, which
  2286. # the fit check lets through (#3239). Match afresh, by
  2287. # type and colour.
  2288. if item.ams_mapping:
  2289. logger.info(
  2290. "Queue item %s: dropping stored ams_mapping %s, not made for printer %s",
  2291. item.id,
  2292. item.ams_mapping,
  2293. printer_id,
  2294. )
  2295. item.ams_mapping = None
  2296. # On a nozzle-rack printer its own nozzle mapping likewise
  2297. # (set through the API or an order's plate spec): it names
  2298. # rack positions, and the dispatch sends a stored one as-is
  2299. # instead of resolving this printer's rack. Elsewhere it
  2300. # holds extruder indices, the same on every printer of the
  2301. # model (an H2D VP keeps the slicer's for that reason), and
  2302. # one that came with the chosen variant belongs to that
  2303. # variant's file: both stay.
  2304. if (
  2305. (chosen is None or chosen.variant is None)
  2306. and printer is not None
  2307. and is_nozzle_rack_model(printer.model)
  2308. ):
  2309. item.nozzle_mapping = None
  2310. # Resolve the AMS mapping for the assigned printer. It is
  2311. # always missing here, so this computes it, and it also
  2312. # self-heals a bogus stored [-1] (#2589).
  2313. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2314. if unmappable:
  2315. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2316. continue
  2317. # Filament-deficit pre-dispatch check (#1496).
  2318. if await self._block_on_filament_deficit(db, item):
  2319. continue
  2320. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2321. # selection already filters on filament type, so this is a
  2322. # backstop for an AMS that changed between assignment and
  2323. # dispatch, and for a type loaded on the wrong nozzle.
  2324. # The assignment made above is released with the hold —
  2325. # this item asked for a model, not this printer.
  2326. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2327. continue
  2328. # As for a pinned job: drying stops once the print is
  2329. # decided, unless it may run through it.
  2330. if self._drying_in_progress.get(
  2331. printer_id
  2332. ) and not await self._drying_may_continue_through_print(db, printer_id):
  2333. await self._stop_drying(printer_id)
  2334. _claim_library_row(item)
  2335. dispatch_ids.append(item.id)
  2336. claim_printer(printer_id)
  2337. # SJF starvation guard: mark items that were jumped
  2338. if sjf_enabled and item.print_time_seconds is not None:
  2339. for other in items:
  2340. if (
  2341. other.id != item.id
  2342. and other.id not in dispatch_ids
  2343. and other.status == "pending"
  2344. and _could_take_printer(other, printer_id, item.target_model)
  2345. and not other.been_jumped
  2346. and other.position < item.position
  2347. and (
  2348. other.print_time_seconds is None
  2349. or other.print_time_seconds > item.print_time_seconds
  2350. )
  2351. ):
  2352. other.been_jumped = True
  2353. await db.commit()
  2354. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2355. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2356. # skip summary that only lands after the transfers have finished is
  2357. # useless for working out why an item did not go out.
  2358. if skip_reasons:
  2359. logger.info("Queue skip summary: %s", skip_reasons)
  2360. for pid in sorted(busy_printers):
  2361. reason = busy_reasons.get(pid, "no reason recorded")
  2362. if pid in claimed_printers:
  2363. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2364. continue
  2365. # The three live fields stay, because they are what someone
  2366. # reading a bundle wants next -- but they are labelled as read
  2367. # now, not as the state the decision was made on, which is what
  2368. # made the old line contradict itself.
  2369. state = printer_manager.get_status(pid)
  2370. logger.info(
  2371. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2372. pid,
  2373. reason,
  2374. printer_manager.is_connected(pid),
  2375. state.state if state else "NO_STATUS",
  2376. printer_manager.is_awaiting_plate_clear(pid),
  2377. )
  2378. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2379. # selection and `_launch_uploads`, so anything raising here would
  2380. # discard this tick's selections — computed AMS mappings and all —
  2381. # and, on a persistent fault, stop the queue dispatching entirely.
  2382. # Same reasoning as the deficit check's guard below: never let an
  2383. # auxiliary check wedge the queue. The bed simply stays wherever it
  2384. # was, and the next tick tries again.
  2385. try:
  2386. await self._apply_keep_warm(
  2387. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2388. )
  2389. except Exception as e:
  2390. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2391. # Read the concurrency limit BEFORE the commit below, not inside
  2392. # _dispatch_selected(). A SELECT on this session after the commit
  2393. # implicitly opens a fresh transaction that nothing then closes, and
  2394. # it would stay open for the whole dispatch — minutes of "idle in
  2395. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2396. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2397. # checkpointed while every dispatch is writing to it.
  2398. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2399. # Selection is done; every decision above is recorded on `db`
  2400. # (model-based printer assignment, computed ams_mapping). Flush it
  2401. # before the dispatch tasks open their own sessions, or they will
  2402. # read a row that still says printer_id=None. This also releases the
  2403. # connection back to the pool for the duration of the dispatch.
  2404. await db.commit()
  2405. if dispatch_ids:
  2406. item_printers = {it.id: it.printer_id for it in items}
  2407. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2408. # Auto-drying: start drying on idle printers that have no pending queue items
  2409. await self._check_auto_drying(db, items, dispatching_printers)
  2410. # Low filament: alert on assigned spools that have crossed their
  2411. # low-stock threshold (#2913). Runs on both paths out of this method
  2412. # for the same reason auto-drying does — an empty queue does not mean
  2413. # the spools in the printers stopped mattering.
  2414. await self._check_filament_low(db)
  2415. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2416. # is about to run out before a replenishment could arrive (#2955).
  2417. await self._check_stock_forecast(db)
  2418. # Keep the loop on the fast interval while any upload is in flight so
  2419. # a slot freed mid-tick refills within seconds rather than after the
  2420. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2421. # deferred because the pool was full) also counts as productive.
  2422. return bool(dispatch_ids) or bool(self._inflight)
  2423. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2424. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2425. Dispatch used to happen inline in the selection loop: ``await
  2426. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2427. performs the FTP upload, that serialized every printer behind every
  2428. other printer's transfer even though the printers are independent
  2429. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2430. gather was awaited before ``check_queue`` returned, so the run loop
  2431. stayed blocked until the *slowest* upload in the batch finished — a
  2432. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2433. 93-printer farm even as other printers came free (#2602).
  2434. Each upload now runs as an independent background task tracked in
  2435. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2436. `pending` until their upload completes) and their printers from the
  2437. next pass's selection, and this method launches at most
  2438. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2439. the next fast tick instead of waiting out the whole batch. The bound
  2440. exists because the printers are independent but the host is not: each
  2441. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2442. file handle.
  2443. The no-overlapping-dispatch invariant the batch-await used to provide
  2444. is now carried by the in-flight exclusion in check_queue. Everything
  2445. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2446. per-printer hold, and each item's independent failure handling — still
  2447. lives in ``_start_print`` and runs per task exactly as before.
  2448. Synchronous on purpose: it registers every launched task into
  2449. ``self._inflight`` before returning, so the next (sequential) tick sees
  2450. an accurate in-flight count with no interleaving await.
  2451. """
  2452. free = limit - len(self._inflight)
  2453. if free <= 0:
  2454. logger.info(
  2455. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2456. len(self._inflight),
  2457. limit,
  2458. len(item_ids),
  2459. item_ids,
  2460. )
  2461. return
  2462. to_launch = item_ids[:free]
  2463. deferred = item_ids[free:]
  2464. logger.info(
  2465. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2466. len(to_launch),
  2467. len(self._inflight),
  2468. limit,
  2469. f" — deferring {deferred} to a later tick" if deferred else "",
  2470. )
  2471. for item_id in to_launch:
  2472. task = spawn_background_task(
  2473. self._dispatch_one(item_id, item_printers.get(item_id)),
  2474. name=f"queue-upload-{item_id}",
  2475. )
  2476. self._inflight[item_id] = (task, item_printers.get(item_id))
  2477. # Prune on completion so the freed slot is refillable next tick.
  2478. # spawn_background_task already logs any uncaught exception; this
  2479. # only reclaims the pool slot (fires on success, failure, or cancel).
  2480. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2481. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2482. """Upload + start one queue item in its own session (pool worker, #2602).
  2483. Its own session: pool workers run concurrently and an AsyncSession is
  2484. not safe to share across tasks; it also keeps a slow upload from pinning
  2485. the scheduler's session (and, on SQLite, its transaction) open for the
  2486. transfer's duration.
  2487. ``selected_printer_id`` is the printer this item was selected for, taken
  2488. from the same snapshot the caller used. It exists so the preheat pin can
  2489. be unwound on the paths that never reach the ``finally`` below — see the
  2490. claim failure a few lines down. Optional so the direct-call tests keep
  2491. working; when it is absent those paths simply behave as they did before.
  2492. """
  2493. async with async_session() as item_db:
  2494. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2495. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2496. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2497. # routes reject reassignment (409), so printer_id can't change out from
  2498. # under the in-flight upload and split the queue row from the
  2499. # archive/expected-print/physical command.
  2500. if not await self._claim_for_dispatch(item_db, item_id, selected_printer_id):
  2501. logger.info(
  2502. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2503. item_id,
  2504. )
  2505. # This return is outside the try/finally below, so the rollback
  2506. # has to happen here. Selecting this item already handed any
  2507. # keep-warm hold on its printer over to the preheat pin
  2508. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2509. # unwind it. Bailing without doing so leaves the bed hot with
  2510. # nothing tracking it: the keep-warm entry is gone, so the
  2511. # max-duration cap no longer applies, and if this was the
  2512. # printer's last pending item nothing else will ever turn it
  2513. # off. Reachable whenever a cancel or delete lands between
  2514. # selection and the claim.
  2515. if selected_printer_id is not None:
  2516. self._rollback_preheat_pin(item_id, selected_printer_id)
  2517. return
  2518. # Seeded from the caller's snapshot so the `item vanished` return
  2519. # below still unwinds the pin; overwritten with the row's own
  2520. # printer_id as soon as we have it.
  2521. item_printer_id: int | None = selected_printer_id
  2522. try:
  2523. item = await item_db.get(PrintQueueItem, item_id)
  2524. if not item:
  2525. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2526. return
  2527. item_printer_id = item.printer_id
  2528. await self._start_print(item_db, item)
  2529. finally:
  2530. # Undo an expected-print registration whose print command never
  2531. # went out. One choke point covers every way `_start_print` can
  2532. # end without sending: a raised exception (a DB failure mid-
  2533. # dispatch is the reported case), an early return, a cancel
  2534. # winning the #1853 CAS, or `start_print()` returning False.
  2535. # A confirmed send removes the entry itself, so this is a no-op
  2536. # on the happy path.
  2537. self._rollback_unconfirmed_expected_print(item_id)
  2538. # Likewise the print user it set: the printer's next print is
  2539. # not this item's.
  2540. self._rollback_unconfirmed_print_user(item_id)
  2541. # A sent print now shows as running on its archive; an unsent
  2542. # one leaves it free again.
  2543. self._release_archive_claims(item_id)
  2544. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2545. # reservation survives only after start_print() accepted the
  2546. # command. Failure, cancellation, deferral, and exceptions all
  2547. # release it here.
  2548. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2549. # Unwind preheat state (bed/chamber/airduct) if the
  2550. # dispatch aborted before the print's own gcode took over.
  2551. # `_start_print` clears the pin on successful `start_print()`;
  2552. # anything still present here is by definition an aborted
  2553. # dispatch and gets rolled back so the printer isn't left
  2554. # heating for a job that isn't happening.
  2555. if item_printer_id is not None:
  2556. self._rollback_preheat_pin(item_id, item_printer_id)
  2557. # The cancellation flag only has meaning while this dispatch is
  2558. # running; drop it so the set cannot grow without bound and a
  2559. # re-queued item never inherits a stale cancellation.
  2560. self._cancelled_dispatches.discard(item_id)
  2561. # Release the claim on every exit. Once dispatch has finished the
  2562. # row's status carries the lock (printing/failed/cancelled are all
  2563. # != pending), so the token is only needed for the duration of the
  2564. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2565. # dispatchable again on the next tick.
  2566. await self._clear_dispatch_claim(item_db, item_id)
  2567. async def _requeue_after_upload_refused(
  2568. self,
  2569. db: AsyncSession,
  2570. item: PrintQueueItem,
  2571. printer: Printer,
  2572. error_msg: str,
  2573. toast_uid: int | None,
  2574. kind: FtpFailureKind,
  2575. ) -> None:
  2576. """Put an item back in the queue after its file never reached the printer (#3210).
  2577. The printer goes into `_upload_backoff`, which keeps every item away
  2578. from it until the window ends. The window grows with each refusal in a
  2579. row; see ``_upload_backoff_seconds``.
  2580. An item pinned to this printer keeps it, waits there, and is the one
  2581. that knocks again. An item for "Any <model>" goes back to the pool
  2582. instead, so another printer of the model can take it (#3409). Only the
  2583. assignment goes: the next model assignment drops whatever on the row
  2584. was worked out for one printer, as it does for every model job.
  2585. The first refusal in a run sends the one "Job waiting" notification,
  2586. and a later one only if it asks for something else (a card after a
  2587. dropped connection). It cannot wait for the hold the way it used to: a
  2588. released item is not held on this printer, so nothing would say why
  2589. it stopped. A job cancelled or moved during the upload sends none.
  2590. `dispatch_attempts` is not charged: that budget bounds a printer that
  2591. takes the file and then never starts, which this is not.
  2592. """
  2593. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2594. self._upload_refusals[printer.id] = refusals
  2595. self._upload_refusal_kind[printer.id] = kind
  2596. backoff = _upload_backoff_seconds(refusals)
  2597. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2598. released = False
  2599. if item.target_model:
  2600. # Only while it is still pending on this printer: a cancel, or a
  2601. # move the user made during the upload, stands.
  2602. result = cast(
  2603. CursorResult,
  2604. await db.execute(
  2605. update(PrintQueueItem)
  2606. .where(PrintQueueItem.id == item.id)
  2607. .where(PrintQueueItem.status == "pending")
  2608. .where(PrintQueueItem.printer_id == printer.id)
  2609. .values(printer_id=None, error_message=None)
  2610. .execution_options(synchronize_session=False)
  2611. ),
  2612. )
  2613. await db.commit()
  2614. released = result.rowcount > 0
  2615. elif item.error_message:
  2616. # The row is still `pending` -- it only moves to `printing` after a
  2617. # successful upload -- so there is no status to write back. Writing
  2618. # one anyway would undo a cancel that landed during the upload.
  2619. item.error_message = None
  2620. await db.commit()
  2621. logger.warning(
  2622. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue%s; "
  2623. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2624. item.id,
  2625. printer.id,
  2626. printer.name,
  2627. error_msg,
  2628. " and returned to the pool" if released else "",
  2629. refusals,
  2630. backoff,
  2631. )
  2632. reason = _refused_upload_hold_reason(printer.name or f"printer {printer.id}", kind)
  2633. if self._upload_refusal_notified.get(printer.id) != reason and await self._still_waiting_on(
  2634. db, item.id, None if released else printer.id
  2635. ):
  2636. self._upload_refusal_notified[printer.id] = reason
  2637. try:
  2638. await notification_service.on_queue_job_waiting(
  2639. job_name=await self._get_job_name(db, item),
  2640. target_model=item.target_model or printer.model or "",
  2641. waiting_reason=reason,
  2642. db=db,
  2643. printer_id=printer.id,
  2644. )
  2645. except Exception as e:
  2646. # The job is safe in the queue either way.
  2647. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  2648. try:
  2649. # Closes the dispatch toast for this attempt. Without it the toast
  2650. # keeps spinning on an upload that has ended.
  2651. await ws_manager.send_queue_item_failed(
  2652. user_id=toast_uid,
  2653. queue_item_id=item.id,
  2654. printer_id=printer.id,
  2655. reason="upload_failed",
  2656. )
  2657. except Exception:
  2658. pass # toast is best-effort
  2659. @staticmethod
  2660. async def _still_waiting_on(db: AsyncSession, item_id: int, printer_id: int | None) -> bool:
  2661. """Whether the item is still pending, on *printer_id* (None: unassigned)."""
  2662. row = (
  2663. await db.execute(
  2664. select(PrintQueueItem.status, PrintQueueItem.printer_id).where(PrintQueueItem.id == item_id)
  2665. )
  2666. ).one_or_none()
  2667. return row is not None and row.status == "pending" and row.printer_id == printer_id
  2668. def _rollback_unconfirmed_print_user(self, item_id: int) -> None:
  2669. printer_id = self._unconfirmed_print_user.pop(item_id, None)
  2670. if printer_id is not None:
  2671. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2672. def _forget_unstarted_print(self, item_id: int, *, unless_printing: bool, keep_expected: bool = False) -> None:
  2673. """Withdraw the expected print and print user of a sent print that never started.
  2674. Both tell the rest of Bambuddy that the printer's next print is this
  2675. item's: left behind, a print started by hand later is taken for it.
  2676. With ``unless_printing``, a printer that is printing after all keeps
  2677. them, as that print is most likely this one starting late.
  2678. ``keep_expected`` withdraws only the print user, which vouches for any
  2679. print on the printer. The expected print names this item's file, so a
  2680. late start of it is still matched to its archive.
  2681. """
  2682. sent = self._sent_unstarted_print.get(item_id)
  2683. if sent is None:
  2684. return
  2685. printer_id, remote_filename, archive_id = sent
  2686. if unless_printing:
  2687. status = printer_manager.get_status(printer_id)
  2688. if status is not None and status.state in _ACTIVE_PRINT_STATES:
  2689. return
  2690. printer_manager.clear_current_print_user_for_item(printer_id, item_id)
  2691. if keep_expected:
  2692. return
  2693. del self._sent_unstarted_print[item_id]
  2694. if remote_filename is not None and archive_id is not None:
  2695. try:
  2696. from backend.app.main import unregister_expected_print
  2697. unregister_expected_print(printer_id, remote_filename, archive_id)
  2698. except Exception:
  2699. logger.warning("Queue item %s: failed to unregister expected print", item_id)
  2700. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2701. """Drop an expectation for a print command that was never sent.
  2702. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2703. where the interesting exception is usually the one already propagating.
  2704. """
  2705. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2706. if pending is None:
  2707. return
  2708. printer_id, remote_filename, archive_id = pending
  2709. try:
  2710. from backend.app.main import unregister_expected_print
  2711. unregister_expected_print(printer_id, remote_filename, archive_id)
  2712. except Exception:
  2713. logger.warning(
  2714. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2715. item_id,
  2716. printer_id,
  2717. remote_filename,
  2718. archive_id,
  2719. exc_info=True,
  2720. )
  2721. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2722. """Release a queue reservation without touching the dispatch session."""
  2723. if item_id not in self._unconfirmed_budget_reservations:
  2724. return
  2725. for attempt in range(1, 4):
  2726. async with async_session() as cleanup_db:
  2727. try:
  2728. await release_budget_reservation(
  2729. cleanup_db,
  2730. source_type="print_queue",
  2731. source_id=item_id,
  2732. status="released",
  2733. )
  2734. await cleanup_db.commit()
  2735. self._unconfirmed_budget_reservations.discard(item_id)
  2736. return
  2737. except Exception as exc:
  2738. try:
  2739. await cleanup_db.rollback()
  2740. except Exception:
  2741. pass
  2742. if attempt == 3:
  2743. logger.error(
  2744. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2745. item_id,
  2746. attempt,
  2747. exc,
  2748. )
  2749. return
  2750. await asyncio.sleep(0.5 * attempt)
  2751. @staticmethod
  2752. def _reported_bed_target(printer_id: int) -> int | None:
  2753. """The bed target firmware currently reports, or None if it can't be read.
  2754. None means "no evidence", not "zero" — callers must not treat it as a
  2755. temperature. Deliberately total: this feeds cleanup paths that run in a
  2756. ``finally``, where a malformed status must not become the exception the
  2757. caller sees.
  2758. """
  2759. try:
  2760. state = printer_manager.get_status(printer_id)
  2761. if state is None:
  2762. return None
  2763. temps = state.temperatures
  2764. if not isinstance(temps, dict):
  2765. return None
  2766. return int(float(temps.get("bed_target", 0) or 0))
  2767. except (TypeError, ValueError, AttributeError):
  2768. return None
  2769. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2770. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2771. Turns the bed heater off, the chamber heater off, and opens the
  2772. airduct flap back to cooling — for whichever of those preheat
  2773. actually applied. `_start_print` clears the pin on successful
  2774. `start_print()`; anything still present when `_dispatch_one` exits
  2775. is by definition an aborted dispatch and gets rolled back here.
  2776. The bed is the one action that can be declined: if firmware has since
  2777. been given a target other than the one we pinned, it belongs to someone
  2778. else and is left alone. See the comment at that branch.
  2779. Also called directly from `_dispatch_one`'s claim-failure return, which
  2780. never reaches the ``finally``.
  2781. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2782. """
  2783. pin = self._preheat_pin.pop(printer_id, set())
  2784. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2785. if not pin:
  2786. return
  2787. client = printer_manager.get_client(printer_id)
  2788. if client is None:
  2789. logger.info(
  2790. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2791. item_id,
  2792. printer_id,
  2793. )
  2794. return
  2795. if "bed" in pin:
  2796. # Only undo our own target. If firmware reports something else, the
  2797. # user or another writer owns the bed now and zeroing it would
  2798. # clobber their choice -- the same guard `_release_keep_warm`
  2799. # applies to a keep-warm hold.
  2800. #
  2801. # Every uncertain case switches the bed off rather than leaving it:
  2802. # no recorded target (a pin written before this bookkeeping, or a
  2803. # setter that raised after pinning) and an unreadable status both
  2804. # fall through. A bed left hot with no owner is the worse failure,
  2805. # and this runs in a `finally` where raising would mask the real
  2806. # exception.
  2807. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2808. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2809. logger.info(
  2810. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2811. item_id,
  2812. printer_id,
  2813. cur_bed_target,
  2814. pinned_bed,
  2815. )
  2816. else:
  2817. try:
  2818. client.set_bed_temperature(0)
  2819. except Exception as exc:
  2820. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2821. if "chamber" in pin:
  2822. try:
  2823. client.set_chamber_temperature(0)
  2824. except Exception as exc:
  2825. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2826. if "airduct" in pin:
  2827. try:
  2828. client.set_airduct_mode("cooling")
  2829. except Exception as exc:
  2830. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2831. logger.info(
  2832. "Dispatch item %s (printer %d): preheat rollback → %s",
  2833. item_id,
  2834. printer_id,
  2835. sorted(pin),
  2836. )
  2837. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int, printer_id: int | None = None) -> bool:
  2838. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2839. Returns True if this call won the claim, False if the row was already
  2840. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2841. the load-bearing guard against reassign-during-dispatch (#2615).
  2842. ``printer_id`` is the printer the item was selected for: a row moved to
  2843. another printer since is not claimed, and the next pass selects it for
  2844. that one."""
  2845. query = (
  2846. update(PrintQueueItem)
  2847. .where(PrintQueueItem.id == item_id)
  2848. .where(PrintQueueItem.status == "pending")
  2849. .where(PrintQueueItem.dispatching_at.is_(None))
  2850. )
  2851. if printer_id is not None:
  2852. query = query.where(PrintQueueItem.printer_id == printer_id)
  2853. res = await db.execute(query.values(dispatching_at=datetime.now(timezone.utc)))
  2854. await db.commit()
  2855. return res.rowcount > 0
  2856. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2857. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2858. mask the dispatch outcome.
  2859. Retried, because the failure mode in practice is transient and narrow: a
  2860. database that is momentarily unreachable — PostgreSQL out of connection
  2861. slots is the observed case — refuses this write for a second or two while
  2862. the dispatch that just ended is still holding the row out of the selection
  2863. query. One attempt was enough to wedge the item; a couple of spaced
  2864. attempts clear it. Each attempt rolls back first, since a failed write
  2865. leaves the session needing it before it can be reused.
  2866. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2867. on the next quiet tick.
  2868. """
  2869. for attempt in range(1, 4):
  2870. try:
  2871. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2872. await db.commit()
  2873. return
  2874. except Exception as exc:
  2875. try:
  2876. await db.rollback()
  2877. except Exception:
  2878. pass
  2879. if attempt == 3:
  2880. logger.warning(
  2881. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2882. "— a later quiet tick will release it",
  2883. item_id,
  2884. attempt,
  2885. exc,
  2886. )
  2887. return
  2888. await asyncio.sleep(0.5 * attempt)
  2889. async def _printers_for_model(
  2890. self,
  2891. db: AsyncSession,
  2892. model: str,
  2893. target_location: str | None = None,
  2894. printer_scope: PrinterScope = ALL_PRINTERS,
  2895. ) -> list[Printer]:
  2896. """Active printers of *model*, optionally narrowed to one location.
  2897. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2898. answer "which printers can this job run on" from one query — a job can
  2899. only be woken onto a printer the matcher would also have considered.
  2900. ``printer_scope`` is the job creator's (#1727).
  2901. """
  2902. normalized_model = normalize_printer_model(model) or model
  2903. query = (
  2904. select(Printer)
  2905. .where(func.lower(Printer.model) == normalized_model.lower())
  2906. .where(Printer.is_active == True) # noqa: E712
  2907. )
  2908. if target_location:
  2909. query = query.where(Printer.location == target_location)
  2910. if (clause := printer_scope.where_strict(Printer.id)) is not None:
  2911. query = query.where(clause)
  2912. result = await db.execute(query)
  2913. return list(result.scalars().all())
  2914. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2915. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2916. Read once per queue check rather than per printer: it decides both
  2917. whether the wake step has anything to do and how an offline printer is
  2918. worded in the waiting reason — "Offline" and "offline with no Auto On
  2919. plug" are different problems, and the second is the one the user has to
  2920. fix themselves (#2786).
  2921. """
  2922. result = await db.execute(
  2923. select(SmartPlug.printer_id)
  2924. .where(SmartPlug.printer_id.is_not(None))
  2925. .where(SmartPlug.enabled == True) # noqa: E712
  2926. .where(SmartPlug.auto_on == True) # noqa: E712
  2927. )
  2928. return {pid for (pid,) in result.all() if pid is not None}
  2929. def _wake_recently_failed(self, printer_id: int) -> bool:
  2930. """True while this printer's failed power-on is still cooling off (#2786)."""
  2931. deadline = self._wake_failures.get(printer_id)
  2932. if deadline is None:
  2933. return False
  2934. if time.monotonic() >= deadline:
  2935. del self._wake_failures[printer_id]
  2936. return False
  2937. return True
  2938. async def _wake_printer_for_model(
  2939. self,
  2940. db: AsyncSession,
  2941. candidates: list[_ModelCandidate],
  2942. target_location: str | None,
  2943. exclude_ids: set[int],
  2944. wakeable_ids: set[int],
  2945. require_plate_clear: bool,
  2946. printer_scope: PrinterScope = ALL_PRINTERS,
  2947. ) -> tuple[int | None, int | None]:
  2948. """Power on one offline printer a model-based item could run on (#2786).
  2949. The fixed-printer branch has powered a printer on since smart plugs
  2950. existed. The model-based branch never could: its matcher drops an
  2951. offline printer into the "Offline:" waiting reason and nothing looks at
  2952. its plugs, so a class-targeted job with every matching printer switched
  2953. off sat pending forever. The reporter's log is the controlled
  2954. experiment — the same item, same plug, same Auto On setting, dispatched
  2955. the moment they edited it onto a specific printer.
  2956. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2957. power-on was actually tried, so the caller can tell "nothing here was
  2958. wakeable" (both None — cheap, other items may still find something)
  2959. from "we tried and it did not come up" (only ``attempted_id`` — the
  2960. boot timeout has already been spent).
  2961. A printer whose last known trays cannot satisfy the job is passed over
  2962. rather than woken (#2876): the colours are readable while it is off, so
  2963. switching a farm on one machine at a time to discover them wakes
  2964. printers that could never have taken the job.
  2965. Deliberately does NOT go on to match the job once a printer is up: AMS
  2966. trays arrive with the first status push after connect, so a filament
  2967. check against a printer that booted seconds ago can reject the printer
  2968. we just woke. The next queue pass matches it with live state.
  2969. At most one printer per pass. Each wake blocks the queue loop for the
  2970. boot wait, and a queue of ten class-targeted jobs must not switch on
  2971. ten printers inside one check.
  2972. """
  2973. for candidate in candidates:
  2974. if not candidate.target_model:
  2975. continue
  2976. required_types, filament_overrides = _filament_constraints(candidate)
  2977. printers = await self._printers_for_model(db, candidate.target_model, target_location, printer_scope)
  2978. for printer in sorted(printers, key=lambda p: p.id):
  2979. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2980. continue
  2981. if printer_manager.is_connected(printer.id):
  2982. continue
  2983. if self._wake_recently_failed(printer.id):
  2984. # Its plug did not bring it back a moment ago. Move on to a
  2985. # sibling instead of spending this pass — and every pass —
  2986. # on the same printer.
  2987. continue
  2988. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2989. # Waking this one buys nothing: it would boot into IDLE and
  2990. # then be held by the plate-clear gate, which is exactly
  2991. # what the reporter's log shows happening for 80 minutes
  2992. # after a fixed-printer wake. The flag is Bambuddy-side and
  2993. # persisted, so it is readable while the printer is off.
  2994. logger.info(
  2995. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2996. printer.id,
  2997. candidate.target_model,
  2998. )
  2999. continue
  3000. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  3001. if shortfall:
  3002. logger.info(
  3003. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  3004. printer.id,
  3005. candidate.target_model,
  3006. ", ".join(shortfall),
  3007. )
  3008. continue
  3009. plugs = await self._get_smart_plugs(db, printer.id)
  3010. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  3011. if not auto_on_plugs:
  3012. # wakeable_ids said otherwise — the plug changed under us
  3013. # mid-pass. Nothing to do but move on.
  3014. continue
  3015. logger.info(
  3016. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  3017. candidate.target_model,
  3018. printer.id,
  3019. )
  3020. primary_plug = self._pick_power_plug(auto_on_plugs)
  3021. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  3022. logger.warning(
  3023. "Could not power on printer %s via smart plug; not trying it again for %ss",
  3024. printer.id,
  3025. self._wake_failure_cooloff,
  3026. )
  3027. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  3028. return None, printer.id
  3029. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  3030. try:
  3031. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  3032. if await service.turn_on(extra_plug):
  3033. await publish_plug_state(
  3034. extra_plug.id,
  3035. extra_plug.name,
  3036. extra_plug.printer_id,
  3037. on=True,
  3038. ha_entity_id=extra_plug.ha_entity_id,
  3039. )
  3040. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  3041. except Exception as e:
  3042. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  3043. return printer.id, printer.id
  3044. return None, None
  3045. async def _find_idle_printer_for_model(
  3046. self,
  3047. db: AsyncSession,
  3048. model: str,
  3049. exclude_ids: set[int],
  3050. required_filament_types: list[str] | None = None,
  3051. target_location: str | None = None,
  3052. filament_overrides: list[dict] | None = None,
  3053. require_plate_clear: bool = True,
  3054. wakeable_ids: set[int] | None = None,
  3055. printer_scope: PrinterScope = ALL_PRINTERS,
  3056. is_short: Callable[[int], Awaitable[bool]] | None = None,
  3057. drying_ids: set[int] | None = None,
  3058. unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
  3059. refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
  3060. ) -> tuple[int | None, str | None]:
  3061. """Find an idle, connected printer matching the model with compatible filaments.
  3062. Args:
  3063. db: Database session
  3064. model: Printer model to match (e.g., "X1C", "P1S")
  3065. exclude_ids: Printer IDs to exclude (already busy)
  3066. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  3067. If provided, only printers with all required types loaded will match.
  3068. target_location: Optional location filter. If provided, only printers in this location are considered.
  3069. filament_overrides: Optional list of override dicts. Each entry may include
  3070. ``force_color_match: true`` to require an exact type+color match
  3071. on the printer for that slot. Without the flag the existing
  3072. colour-preference logic applies.
  3073. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  3074. offline printer is worded: one Bambuddy will switch on reads
  3075. differently from one the user has to go and switch on themselves.
  3076. is_short: Says whether a printer's spools are too light for the job (#3137).
  3077. A printer it flags is passed over while another eligible one
  3078. is not. When every eligible printer is short, the first is
  3079. returned all the same, so the deficit gate holds the job there
  3080. and "Print Anyway" still has a printer to print on.
  3081. drying_ids: Excluded printers held by a drying cycle; named "(drying)"
  3082. in the reason, as a pinned job's wait is.
  3083. unmatched_on: Names the filaments the slot matcher would leave without a
  3084. tray on a printer (#3280). A printer it names any for is
  3085. passed over like one missing a filament type: the checks
  3086. above only ask whether each type and forced colour is
  3087. loaded somewhere, not on the right nozzle or once per slot.
  3088. refused_uploads: Excluded printers out of dispatch after a refused upload,
  3089. with why (#3409). Each is named with the reason its own
  3090. queue rows show, not as "Busy".
  3091. Returns:
  3092. Tuple of (printer_id, waiting_reason):
  3093. - (printer_id, None) if a matching printer was found
  3094. - (None, reason) if no printer is available, with explanation
  3095. """
  3096. normalized_model = normalize_printer_model(model) or model
  3097. printers = await self._printers_for_model(db, model, target_location, printer_scope)
  3098. location_suffix = f" in {target_location}" if target_location else ""
  3099. if not printers:
  3100. return None, f"No active {normalized_model} printers{location_suffix} configured"
  3101. # Separate force-matched overrides from preference-only overrides
  3102. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3103. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3104. # Track reasons for skipping printers
  3105. printers_busy = []
  3106. # Printers out of dispatch after a refused upload, worded as the
  3107. # printer's own queue rows word it: "Busy" would read as printing (#3409).
  3108. printers_refused: list[str] = []
  3109. printers_offline = []
  3110. printers_offline_no_plug = []
  3111. printers_missing_filament: list[tuple[str, list[str]]] = []
  3112. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  3113. # The first eligible printer that is short on filament, kept in case
  3114. # every eligible printer is (#3137).
  3115. short_fallback: int | None = None
  3116. for printer in printers:
  3117. if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
  3118. printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
  3119. continue
  3120. if printer.id in exclude_ids:
  3121. # Printer is already claimed by another job in this scheduling run.
  3122. # For force-color jobs, still check if the color would match — if not,
  3123. # report it as a color mismatch rather than plain "Busy" so the user
  3124. # knows the job needs a filament change, not just to wait for availability.
  3125. if force_overrides and not pref_overrides:
  3126. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3127. if missing_colors:
  3128. printers_missing_filament.append((printer.name, missing_colors))
  3129. continue
  3130. printers_busy.append(f"{printer.name} (drying)" if printer.id in (drying_ids or ()) else printer.name)
  3131. continue
  3132. is_connected = printer_manager.is_connected(printer.id)
  3133. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  3134. if not is_connected:
  3135. # An offline printer whose last known filament cannot run this
  3136. # job is reported as needing filament rather than as offline
  3137. # (#2876). It is also the printer the smart-plug step will now
  3138. # decline to switch on, and "Offline:" on its own would leave
  3139. # that decision looking like nothing happening at all.
  3140. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  3141. if shortfall:
  3142. printers_missing_filament.append((printer.name, shortfall))
  3143. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  3144. printers_offline_no_plug.append(printer.name)
  3145. else:
  3146. printers_offline.append(printer.name)
  3147. continue
  3148. if not is_idle:
  3149. # Printer is currently printing. For force-color jobs, check whether the
  3150. # loaded color would satisfy the requirement — if not, surface it as a
  3151. # color-mismatch reason rather than plain "Busy" so the user understands
  3152. # that the job is waiting for a filament change, not just printer availability.
  3153. if force_overrides and not pref_overrides:
  3154. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3155. if missing_colors:
  3156. printers_missing_filament.append((printer.name, missing_colors))
  3157. logger.debug(
  3158. "Printer %s (%s) is busy but also has wrong force-color: %s",
  3159. printer.id,
  3160. printer.name,
  3161. missing_colors,
  3162. )
  3163. continue
  3164. printers_busy.append(printer.name)
  3165. continue
  3166. # Validate filament compatibility if required types are specified
  3167. if required_filament_types:
  3168. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  3169. if missing:
  3170. # When force_overrides are present, enrich missing entries with color info
  3171. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  3172. if force_overrides:
  3173. force_color_map = {
  3174. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  3175. for o in force_overrides
  3176. }
  3177. missing_enriched = [
  3178. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3179. for t in missing
  3180. ]
  3181. printers_missing_filament.append((printer.name, missing_enriched))
  3182. else:
  3183. printers_missing_filament.append((printer.name, missing))
  3184. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  3185. continue
  3186. # Force color match: ALL flagged slots must have an exact type+color match
  3187. if force_overrides:
  3188. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  3189. if missing_colors:
  3190. printers_missing_filament.append((printer.name, missing_colors))
  3191. logger.debug(
  3192. "Skipping printer %s (%s) - missing force-matched colors: %s",
  3193. printer.id,
  3194. printer.name,
  3195. missing_colors,
  3196. )
  3197. continue
  3198. # The matcher has the last word: a printer it cannot map would be
  3199. # held and given back, then chosen again on the next pass (#3280).
  3200. if unmatched_on is not None:
  3201. unmatched = await unmatched_on(printer.id)
  3202. if unmatched:
  3203. printers_missing_filament.append((printer.name, unmatched))
  3204. logger.debug(
  3205. "Skipping printer %s (%s) - the matcher leaves unmapped: %s",
  3206. printer.id,
  3207. printer.name,
  3208. unmatched,
  3209. )
  3210. continue
  3211. # If preference-only overrides exist, rank by color matches (existing behaviour)
  3212. if pref_overrides:
  3213. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  3214. if color_matches > 0:
  3215. candidates.append((printer.id, color_matches))
  3216. else:
  3217. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  3218. printers_missing_filament.append((printer.name, override_colors))
  3219. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  3220. continue
  3221. else:
  3222. # No preference ordering needed: the first eligible printer
  3223. # wins, unless its spools are too light for the job (#3137).
  3224. if is_short is not None and await is_short(printer.id):
  3225. if short_fallback is None:
  3226. short_fallback = printer.id
  3227. logger.info(
  3228. "Model-based assignment: passing over printer %s (%s), not enough filament",
  3229. printer.id,
  3230. printer.name,
  3231. )
  3232. continue
  3233. return printer.id, None
  3234. # If we have candidates from preference override matching, pick the one with most color matches
  3235. if candidates:
  3236. candidates.sort(key=lambda c: c[1], reverse=True)
  3237. if is_short is not None:
  3238. for candidate_id, _ in candidates:
  3239. if not await is_short(candidate_id):
  3240. return candidate_id, None
  3241. logger.info(
  3242. "Model-based assignment: passing over printer %s, not enough filament",
  3243. candidate_id,
  3244. )
  3245. return candidates[0][0], None
  3246. if short_fallback is not None:
  3247. return short_fallback, None
  3248. # Build waiting reason from what we found
  3249. reasons = []
  3250. if printers_missing_filament:
  3251. # Filament/color mismatch is most actionable - show first
  3252. if force_overrides and not pref_overrides:
  3253. # All mismatches are force-color failures — use descriptive message only;
  3254. # but only if there are no busy printers that DO have the matching color.
  3255. # If a printer has the right color but is busy, surface "Busy" instead so
  3256. # the user knows the job will start automatically once that printer is free.
  3257. # Same for a printer that is merely offline: Bambuddy switches that one on
  3258. # by itself, so the job is not actually waiting on anybody to change a
  3259. # spool (#2876 — offline printers reach this list now that a switched-off
  3260. # printer's own filament is read).
  3261. if not printers_busy and not printers_offline and not printers_refused:
  3262. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  3263. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  3264. # else: fall through — the self-resolving entries are appended below
  3265. else:
  3266. names_and_missing = [
  3267. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  3268. ]
  3269. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  3270. reasons.extend(printers_refused)
  3271. if printers_busy:
  3272. reasons.append(f"Busy: {', '.join(printers_busy)}")
  3273. if printers_offline:
  3274. reasons.append(f"Offline: {', '.join(printers_offline)}")
  3275. if printers_offline_no_plug:
  3276. # Named separately because it is the one entry on this list the
  3277. # user has to act on: no enabled Auto On plug means Bambuddy will
  3278. # never power this printer on for the queue (#2786).
  3279. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  3280. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  3281. @staticmethod
  3282. def _is_busy_only(waiting_reason: str) -> bool:
  3283. """Check if the waiting reason only contains 'Busy' entries.
  3284. When all matching printers are simply busy printing, the queued job
  3285. will start automatically once a printer finishes — no user action
  3286. is required, so we skip the notification.
  3287. """
  3288. parts = [p.strip() for p in waiting_reason.split(" | ")]
  3289. return all(p.startswith("Busy:") for p in parts)
  3290. def _get_missing_force_color_slots(
  3291. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  3292. ) -> list[str]:
  3293. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  3294. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  3295. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  3296. with an exact type+color match.
  3297. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  3298. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  3299. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  3300. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  3301. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  3302. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  3303. setups are unaffected.
  3304. Returns:
  3305. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  3306. """
  3307. if raw_data is None:
  3308. status = printer_manager.get_status(printer_id)
  3309. if not status:
  3310. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  3311. raw_data = status.raw_data
  3312. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  3313. loaded: list[tuple[str, str, str]] = []
  3314. for ams_unit in raw_data.get("ams", []):
  3315. for tray in ams_unit.get("tray", []):
  3316. tray_type = tray.get("tray_type")
  3317. if tray_type:
  3318. color_norm = self._normalize_color_for_compare(self._normalize_color(tray.get("tray_color")))
  3319. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  3320. for vt in raw_data.get("vt_tray") or []:
  3321. vt_type = vt.get("tray_type")
  3322. if vt_type:
  3323. color_norm = self._normalize_color_for_compare(self._normalize_color(vt.get("tray_color")))
  3324. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  3325. # One spool per slot, the way the matcher assigns them: two slots asking
  3326. # for the same filament need two spools of it (#3280). Slots naming a
  3327. # variant go first and take that variant before a spool naming none, so
  3328. # a slot open to any variant cannot use up the one a later slot needs.
  3329. missing = []
  3330. taken: set[int] = set()
  3331. for o in sorted(force_overrides, key=lambda o: not o.get("tray_info_idx")):
  3332. o_type = canonical_filament_type(o.get("type") or "")
  3333. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3334. o_idx = o.get("tray_info_idx") or ""
  3335. fits = [
  3336. i
  3337. for i, (t_type, t_color, t_idx) in enumerate(loaded)
  3338. if i not in taken
  3339. and t_type == o_type
  3340. and t_color == o_color
  3341. and (not o_idx or not t_idx or o_idx == t_idx)
  3342. ]
  3343. pick = next((i for i in fits if o_idx and loaded[i][2] == o_idx), fits[0] if fits else None)
  3344. if pick is not None:
  3345. taken.add(pick)
  3346. else:
  3347. color_label = o.get("color_name") or o.get("color", "?")
  3348. missing.append(f"{o_type} ({color_label})")
  3349. return missing
  3350. def _get_missing_filament_types(
  3351. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  3352. ) -> list[str]:
  3353. """Get the list of required filament types that are not loaded on the printer.
  3354. Args:
  3355. printer_id: The printer ID
  3356. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  3357. Returns:
  3358. List of missing filament types (empty if all are loaded)
  3359. """
  3360. if raw_data is None:
  3361. status = printer_manager.get_status(printer_id)
  3362. if not status:
  3363. return required_types # Can't determine, assume all missing
  3364. raw_data = status.raw_data
  3365. # Collect all filament types loaded on this printer (AMS units + external spool)
  3366. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  3367. loaded_types: set[str] = set()
  3368. # Check AMS units (stored in raw_data["ams"])
  3369. ams_data = raw_data.get("ams", [])
  3370. if ams_data:
  3371. for ams_unit in ams_data:
  3372. for tray in ams_unit.get("tray", []):
  3373. tray_type = tray.get("tray_type")
  3374. if tray_type:
  3375. loaded_types.add(canonical_filament_type(tray_type))
  3376. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  3377. for vt in raw_data.get("vt_tray") or []:
  3378. vt_type = vt.get("tray_type")
  3379. if vt_type:
  3380. loaded_types.add(canonical_filament_type(vt_type))
  3381. # Find which required types are missing (using canonical type for equivalence)
  3382. missing = []
  3383. for req_type in required_types:
  3384. if canonical_filament_type(req_type) not in loaded_types:
  3385. missing.append(req_type)
  3386. return missing
  3387. def _count_override_color_matches(
  3388. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  3389. ) -> int:
  3390. """Count how many filament overrides have an exact color match on the printer.
  3391. Used to prefer printers that already have the desired override colors loaded.
  3392. """
  3393. if raw_data is None:
  3394. status = printer_manager.get_status(printer_id)
  3395. if not status:
  3396. return 0
  3397. raw_data = status.raw_data
  3398. # Collect loaded filaments' type+color pairs
  3399. loaded: set[tuple[str, str]] = set()
  3400. for ams_unit in raw_data.get("ams", []):
  3401. for tray in ams_unit.get("tray", []):
  3402. tray_type = tray.get("tray_type")
  3403. # `or ""`, not a dict default: a slot can carry the key with a
  3404. # null value, and this now runs against switched-off printers
  3405. # too, where nobody is watching for the AttributeError.
  3406. tray_color = tray.get("tray_color") or ""
  3407. if tray_type:
  3408. color_norm = tray_color.replace("#", "").lower()[:6]
  3409. loaded.add((canonical_filament_type(tray_type), color_norm))
  3410. for vt in raw_data.get("vt_tray") or []:
  3411. vt_type = vt.get("tray_type")
  3412. if vt_type:
  3413. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  3414. loaded.add((canonical_filament_type(vt_type), color_norm))
  3415. # Types compared as the type check compares them: a PA12-CF override
  3416. # is met by PA-CF in its colour.
  3417. matches = 0
  3418. for o in overrides:
  3419. o_type = canonical_filament_type(o.get("type") or "")
  3420. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  3421. if (o_type, o_color) in loaded:
  3422. matches += 1
  3423. return matches
  3424. @staticmethod
  3425. def _tray_reading(printer_id: int) -> dict:
  3426. """The best tray reading available for a printer that is not printing.
  3427. Live status first: a printer keeps its last status after the power
  3428. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  3429. leaves ``raw_data`` alone. The manager's own record is the fallback,
  3430. for when the client itself has been dropped and taken its status with
  3431. it — which is what every power-on attempt does.
  3432. An empty result means "we have never heard", not "nothing is loaded":
  3433. the two are indistinguishable from here, and only the second would be
  3434. safe to act on.
  3435. """
  3436. status = printer_manager.get_status(printer_id)
  3437. raw = (status.raw_data if status else None) or {}
  3438. for ams_unit in raw.get("ams") or []:
  3439. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  3440. return raw
  3441. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  3442. return raw
  3443. return printer_manager.last_known_trays(printer_id)
  3444. def _cached_filament_shortfall(
  3445. self,
  3446. printer_id: int,
  3447. required_types: list[str] | None,
  3448. filament_overrides: list[dict] | None,
  3449. ) -> list[str]:
  3450. """What a switched-off printer's last known filament cannot provide (#2876).
  3451. The smart-plug wake step used to consider only the model, so a job for a
  3452. colour loaded on the last printer in ID order switched on every earlier
  3453. one in turn, evaluated it, rejected it on colour and left it running.
  3454. Bambuddy knew those colours the whole time. This asks the same three
  3455. questions the matcher asks a live printer — required types, forced
  3456. colours, preferred colours — of the trays it last reported, and returns
  3457. the answers in the same shape the "Waiting for filament" reason uses.
  3458. Empty means the printer may still be able to take the job.
  3459. Fails open, and deliberately: with no tray reading (never connected
  3460. since Bambuddy started, or the cache dropped by a reconnect) this
  3461. returns nothing to report and the printer is treated as it was before.
  3462. A farm restarted while its printers were off must not conclude that
  3463. none of them can print.
  3464. """
  3465. if not required_types and not filament_overrides:
  3466. return []
  3467. raw_data = self._tray_reading(printer_id)
  3468. if not raw_data:
  3469. return []
  3470. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  3471. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  3472. if required_types:
  3473. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  3474. if missing:
  3475. # Same enrichment the live path applies: a bare "PLA" is not
  3476. # much help when what is missing is a particular PLA.
  3477. force_color_map = {
  3478. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  3479. }
  3480. return [
  3481. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  3482. for t in missing
  3483. ]
  3484. if force_overrides:
  3485. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3486. if missing_colors:
  3487. return missing_colors
  3488. # Preference overrides read as a preference but the matcher treats zero
  3489. # matches as a skip, so a printer with none of the wanted colours is
  3490. # rejected there too. Waking it would only produce that same rejection.
  3491. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3492. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3493. return []
  3494. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3495. """Fold the winning candidate's file and settings onto the queue row (#671).
  3496. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3497. never escapes the selection loop. By the time the pass commits, the row
  3498. looks exactly like an ordinary single-file model-based item, so the upload,
  3499. archive creation, expected-print registration, print history and reprint
  3500. paths need no knowledge that variants exist.
  3501. No-ops for a non-variant candidate, which is already the item's own columns.
  3502. Safe to run and re-run: the item's file columns are only ever *read* when it
  3503. has no variants, so an item that gets resolved and then skipped (library-row
  3504. conflict, previous-print gate) is simply resolved again on the next pass.
  3505. """
  3506. variant = candidate.variant
  3507. if variant is None:
  3508. return
  3509. item.library_file_id = variant.library_file_id
  3510. item.library_file = variant.library_file
  3511. # The dispatcher checks archive_id first and would print that instead of
  3512. # the file we just picked. Creation refuses to combine the two, so this
  3513. # only ever fires on a hand-written row — clear it rather than silently
  3514. # dispatch something the matcher never considered.
  3515. item.archive_id = None
  3516. item.archive = None
  3517. item.target_model = variant.target_model
  3518. item.plate_id = variant.plate_id
  3519. item.ams_mapping = variant.ams_mapping
  3520. item.nozzle_mapping = variant.nozzle_mapping
  3521. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3522. item.filament_overrides = variant.filament_overrides
  3523. item.required_filament_types = variant.required_filament_types
  3524. if variant.print_time_seconds is not None:
  3525. # The row carried the shortest candidate's estimate so SJF could order
  3526. # it before a printer was known; now that one is chosen, record what is
  3527. # actually going to run so history and the ETA agree with reality.
  3528. item.print_time_seconds = variant.print_time_seconds
  3529. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3530. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3531. Recomputes from live printer status when the stored mapping is missing OR
  3532. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3533. frontend status-load race can serialize [-1] before the printer's AMS
  3534. trays are known (#2589) — and must not be trusted: downstream it would be
  3535. silently downgraded to external-spool mode and print against an empty
  3536. feed. A resolved mapping is re-checked against the target printer's
  3537. live trays before it is trusted (#2799) and recomputed when it does not
  3538. fit. When it does fit, its resolved slots are kept as they are and only
  3539. the slots the plate prints that are still unresolved are matched again;
  3540. all of it is left alone when the user has acknowledged it with "Print
  3541. Anyway".
  3542. When recompute cannot resolve it either (no compatible tray loaded), the
  3543. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3544. external selection. On a printer that reported loaded trays,
  3545. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3546. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3547. and the firmware surfaces a clear AMS-mapping error instead of silently
  3548. printing to the empty external feed.
  3549. Returns an actionable message when that firmware error is the only
  3550. possible outcome — the matcher ran, matched nothing, and the printer has
  3551. no AMS to load a different spool into (#2771). The caller fails the item
  3552. on it instead of spending an upload on a print that cannot start.
  3553. Returns None everywhere else, including every case where we simply lack
  3554. the data to judge, so dispatch is only ever blocked on a positive
  3555. finding.
  3556. """
  3557. stored_mapping: list | None = None
  3558. if item.ams_mapping:
  3559. try:
  3560. stored_mapping = json.loads(item.ams_mapping)
  3561. except (json.JSONDecodeError, TypeError):
  3562. stored_mapping = None
  3563. # Present and resolved. Global tray IDs only mean something relative to
  3564. # the printer they were resolved against, so "resolved" is not the same
  3565. # as "resolved *here*" — check the mapping still fits the printer that
  3566. # is about to run this item before trusting it (#2799). "Print anyway"
  3567. # is the user overriding exactly this judgement, so it short-circuits.
  3568. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3569. if item.skip_filament_check:
  3570. return None
  3571. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3572. if conflict is None:
  3573. # It fits, but a slot the plate prints may still be empty: the
  3574. # spool was missing when it was mapped, and has perhaps been
  3575. # loaded since. Nothing else would ever look at that slot again,
  3576. # so a job held for it would be held again on every Start.
  3577. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3578. if filled is not None:
  3579. item.ams_mapping = json.dumps(filled)
  3580. logger.info(
  3581. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3582. item.id,
  3583. stored_mapping,
  3584. printer_id,
  3585. filled,
  3586. )
  3587. await db.commit()
  3588. return None
  3589. logger.warning(
  3590. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3591. item.id,
  3592. stored_mapping,
  3593. printer_id,
  3594. conflict,
  3595. )
  3596. # Drop it before recomputing so a failed recompute cannot fall back
  3597. # to the mapping we just rejected.
  3598. item.ams_mapping = None
  3599. stored_mapping = None
  3600. await db.commit()
  3601. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3602. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3603. item.ams_mapping = json.dumps(computed_mapping)
  3604. logger.info(
  3605. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3606. item.id,
  3607. printer_id,
  3608. computed_mapping,
  3609. )
  3610. await db.commit()
  3611. return None
  3612. external_only = await self._external_spool_only_mapping(db, printer_id, item)
  3613. if external_only is not None:
  3614. item.ams_mapping = json.dumps(external_only)
  3615. logger.info(
  3616. "Queue item %s: printer %s has no AMS and its external spool has no filament set; "
  3617. "mapping every filament to it: %s",
  3618. item.id,
  3619. printer_id,
  3620. external_only,
  3621. )
  3622. await db.commit()
  3623. return None
  3624. if _mapping_is_all_unresolved(stored_mapping):
  3625. logger.warning(
  3626. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3627. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3628. item.id,
  3629. stored_mapping,
  3630. printer_id,
  3631. )
  3632. item.ams_mapping = None
  3633. await db.commit()
  3634. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3635. async def _external_spool_only_mapping(
  3636. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  3637. ) -> list[int] | None:
  3638. """Every filament on the external spool, for a printer that has nothing else (#3239).
  3639. A printer without an AMS prints from its external spool, and an external
  3640. spool whose filament was never set reports no type, so the matcher has
  3641. nothing to match. Sent without a mapping, the print goes out with the AMS
  3642. on and the firmware rejects it with 0700_8012. A stored ``[254]`` used
  3643. to carry such a job through; a job placed by model or location no longer
  3644. keeps one, and one queued that way never had one.
  3645. Only on a positive report: the printer has said it has no AMS, it has a
  3646. single external feed (a dual-nozzle printer's feeds steer nozzles, which
  3647. is not ours to pick), and no feed has a filament set — with one set, the
  3648. matcher has already given its answer. Not for a job that asked for its
  3649. colours to be matched strictly: a spool without a filament set has no
  3650. colour to check. Returns None otherwise.
  3651. """
  3652. if item.filament_overrides:
  3653. try:
  3654. overrides = json.loads(item.filament_overrides)
  3655. except (json.JSONDecodeError, TypeError):
  3656. return None
  3657. if not isinstance(overrides, list) or any(
  3658. isinstance(o, dict) and o.get("force_color_match") for o in overrides
  3659. ):
  3660. return None
  3661. status = printer_manager.get_status(printer_id)
  3662. if status is None or not isinstance(status.raw_data, dict):
  3663. return None
  3664. ams_units = status.raw_data.get("ams")
  3665. if not isinstance(ams_units, list) or ams_units:
  3666. return None
  3667. vt_trays = status.raw_data.get("vt_tray")
  3668. if not isinstance(vt_trays, list) or len(vt_trays) != 1 or not isinstance(vt_trays[0], dict):
  3669. return None
  3670. if self._build_loaded_filaments(status):
  3671. return None
  3672. printer = await self._get_printer(db, printer_id)
  3673. if _might_be_dual_nozzle(printer.model if printer else None, status):
  3674. return None
  3675. external = _int_or(vt_trays[0].get("id"), _EXTERNAL_TRAY_ID_MIN)
  3676. if external < _EXTERNAL_TRAY_ID_MIN:
  3677. return None
  3678. required = await self._get_filament_requirements(db, item)
  3679. slot_ids = [r.get("slot_id") for r in required or []]
  3680. slot_ids = [s for s in slot_ids if isinstance(s, int) and s > 0]
  3681. if not slot_ids:
  3682. return None
  3683. mapping = [-1] * max(slot_ids)
  3684. for slot_id in slot_ids:
  3685. mapping[slot_id - 1] = external
  3686. return mapping
  3687. async def _fill_unresolved_slots(
  3688. self,
  3689. db: AsyncSession,
  3690. printer_id: int,
  3691. item: PrintQueueItem,
  3692. stored_mapping: list | None,
  3693. ) -> list | None:
  3694. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3695. Every resolved entry is kept, so a tray the user picked by hand stays
  3696. picked. Only the plate's unresolved slots are matched, and only against
  3697. trays the mapping does not already use: the matcher never gives two
  3698. slots one tray, and filling a gap with a tray the user assigned to
  3699. another slot would print that slot's filament twice.
  3700. Returns None when there is nothing to fill or nothing could be filled.
  3701. """
  3702. if not isinstance(stored_mapping, list) or not stored_mapping:
  3703. return None
  3704. required = await self._get_filament_requirements(db, item)
  3705. if not required:
  3706. return None
  3707. self._apply_filament_overrides(item, required)
  3708. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3709. if not gaps:
  3710. return None
  3711. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3712. computed = await self._compute_ams_mapping_for_printer(
  3713. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3714. )
  3715. if not computed:
  3716. return None
  3717. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3718. filled = False
  3719. for slot_id in gaps:
  3720. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3721. if _is_tray_id(tray) and tray >= 0:
  3722. merged[slot_id - 1] = tray
  3723. filled = True
  3724. return merged if filled else None
  3725. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3726. """What a staged item would be held for if it were started now (#2799).
  3727. The Start button asks this before releasing an item, so that a job whose
  3728. filament is still not loaded offers "Print Anyway" instead of being
  3729. released, held again by the scheduler and leaving no way past the hold.
  3730. It reaches the same answer the dispatch path would: a stored mapping
  3731. that fits is kept and only its gaps are matched again, and one that
  3732. does not fit (or is missing) is replaced by a fresh match.
  3733. Returns the missing filaments, described the way the queue row
  3734. describes them, or None when nothing is missing or there is not enough
  3735. evidence to say: no printer yet (a model-based item picks one at
  3736. dispatch), no status, no trays reported, or no readable 3MF.
  3737. """
  3738. if item.skip_filament_check or not item.printer_id:
  3739. return None
  3740. status = printer_manager.get_status(item.printer_id)
  3741. if status is None or not self._build_loaded_filaments(status):
  3742. return None
  3743. # Called from a request, not from a pass: drop whatever the last pass
  3744. # memoised so this reads the file as it is now. A pass running at the
  3745. # same time only loses its cache.
  3746. self._filament_req_memo.clear()
  3747. mapping: list | None = None
  3748. if item.ams_mapping:
  3749. try:
  3750. mapping = json.loads(item.ams_mapping)
  3751. except (json.JSONDecodeError, TypeError):
  3752. mapping = None
  3753. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3754. mapping = None
  3755. if mapping is not None:
  3756. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3757. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3758. else:
  3759. mapping = None
  3760. if mapping is None:
  3761. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3762. required = await self._get_filament_requirements(db, item)
  3763. if required:
  3764. self._apply_filament_overrides(item, required)
  3765. else:
  3766. # The same fallback the hold uses, or Start would release a job the
  3767. # next pass holds again (#3280).
  3768. required = _forced_override_requirements(item)
  3769. if not required:
  3770. return None
  3771. missing = _unresolved_required(required, mapping)
  3772. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3773. async def _stored_mapping_conflict(
  3774. self,
  3775. db: AsyncSession,
  3776. printer_id: int,
  3777. item: PrintQueueItem,
  3778. stored_mapping: list | None,
  3779. ) -> str | None:
  3780. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3781. A mapping is a list of global tray IDs, and those are only meaningful
  3782. relative to the printer they were resolved against — the same rule
  3783. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3784. arrives at a printer it was not resolved for:
  3785. * the print dialog stamps one mapping onto every selected printer, so a
  3786. mapping computed against the first printer is dispatched verbatim to
  3787. the rest, whose AMS slot order differs;
  3788. * a spool is moved between queueing and dispatch.
  3789. Both end the same way: the slot index still resolves, so nothing looks
  3790. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3791. the firmware's own type check, so a PETG slot happily prints in ASA.
  3792. Returns a short reason when the mapping names a tray this printer does
  3793. not have loaded, points a slot at a tray holding a different filament
  3794. type, or points it at an external spool this printer reports empty while
  3795. its AMS holds that slot's filament (#3239). Returns None when the
  3796. mapping fits, and — deliberately — whenever we lack the evidence to
  3797. judge, so a recompute only ever follows a positive finding.
  3798. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3799. matcher had nothing, not that the mapping belongs to another printer,
  3800. and destroying a partially hand-resolved mapping over it would lose the
  3801. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3802. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3803. item when that finds nothing.
  3804. """
  3805. if not isinstance(stored_mapping, list) or not stored_mapping:
  3806. return None
  3807. status = printer_manager.get_status(printer_id)
  3808. if status is None:
  3809. return None
  3810. loaded = self._build_loaded_filaments(status)
  3811. if not loaded:
  3812. # Nothing reported yet (reconnect, first push pending). Saying
  3813. # "tray not loaded" here would recompute against an AMS we cannot
  3814. # see, which is how #2589 produced a bogus all-[-1] in the first
  3815. # place.
  3816. return None
  3817. by_tray = {f["global_tray_id"]: f for f in loaded}
  3818. # Cheap pass first, on live status alone: every tray the mapping names
  3819. # has to exist here. This catches a foreign mapping without opening the
  3820. # 3MF, which is worth doing because the parse below is neither cached
  3821. # nor free.
  3822. for index, tray in enumerate(stored_mapping):
  3823. if not _is_tray_id(tray) or tray < 0:
  3824. continue
  3825. if tray in by_tray:
  3826. continue
  3827. if tray >= 254:
  3828. # An external feed we have not heard about is absence of
  3829. # evidence about *that slot* — the rest of the mapping is still
  3830. # worth judging, so skip it rather than abandoning the pass.
  3831. continue
  3832. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3833. # Only now is the 3MF worth opening: the type check needs to know what
  3834. # each slot actually asked for. The external spool is checked the same
  3835. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3836. # two printers with different filament in the external feed is the same
  3837. # failure this method exists to catch.
  3838. required = await self._get_filament_requirements(db, item)
  3839. if not required:
  3840. return None
  3841. self._apply_filament_overrides(item, required)
  3842. # External feeds the printer reports and reports as empty. That is
  3843. # evidence, unlike an external feed it says nothing about (#3239).
  3844. empty_external: set[int] = set()
  3845. vt_trays = status.raw_data.get("vt_tray") if isinstance(status.raw_data, dict) else None
  3846. for vt in vt_trays if isinstance(vt_trays, list) else []:
  3847. if isinstance(vt, dict) and not vt.get("tray_type"):
  3848. try:
  3849. empty_external.add(int(vt.get("id", 254)))
  3850. except (TypeError, ValueError):
  3851. continue
  3852. for req in required:
  3853. slot_id = req.get("slot_id") or 0
  3854. if slot_id <= 0:
  3855. continue
  3856. if slot_id > len(stored_mapping):
  3857. return f"slot {slot_id} is not covered by the mapping"
  3858. tray = stored_mapping[slot_id - 1]
  3859. if not _is_tray_id(tray) or tray < 0:
  3860. continue
  3861. loaded_tray = by_tray.get(tray)
  3862. if loaded_tray is None:
  3863. # A mapping made for a printer that feeds this slot from its
  3864. # external spool, sent to one whose external spool is empty and
  3865. # whose AMS holds the filament (#3239). Only then: an external
  3866. # spool can be loaded without its filament set, and on a printer
  3867. # with nothing else to offer that job printed before. The colour
  3868. # has to match too: with only another colour in the AMS, the
  3869. # printer asking for the spool beats printing in that colour.
  3870. want = canonical_filament_type(req.get("type"))
  3871. if tray >= 254 and tray in empty_external and want:
  3872. ams_tray = next(
  3873. (
  3874. f
  3875. for f in loaded
  3876. if not f.get("is_external")
  3877. and canonical_filament_type(f.get("type")) == want
  3878. and self._colors_are_similar(f.get("color"), req.get("color"))
  3879. ),
  3880. None,
  3881. )
  3882. if ams_tray is not None:
  3883. return (
  3884. f"slot {slot_id} points at the external spool, which is empty, "
  3885. f"while tray {ams_tray['global_tray_id']} holds {ams_tray.get('type')}"
  3886. )
  3887. continue
  3888. want = canonical_filament_type(req.get("type"))
  3889. have = canonical_filament_type(loaded_tray.get("type"))
  3890. if want and have and want != have:
  3891. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3892. # A forced slot fits only a tray the matcher would give it (#3280).
  3893. if req.get("force_color_match"):
  3894. want_idx = req.get("tray_info_idx") or ""
  3895. have_idx = loaded_tray.get("tray_info_idx") or ""
  3896. if self._normalize_color_for_compare(req.get("color")) != self._normalize_color_for_compare(
  3897. loaded_tray.get("color")
  3898. ) or (want_idx and have_idx and want_idx != have_idx):
  3899. return (
  3900. f"slot {slot_id} is forced to {req.get('type')} {req.get('color')} "
  3901. f"but tray {tray} holds {loaded_tray.get('type')} {loaded_tray.get('color')}"
  3902. )
  3903. return None
  3904. async def _unmappable_without_ams_message(
  3905. self,
  3906. db: AsyncSession,
  3907. printer_id: int,
  3908. item: PrintQueueItem,
  3909. computed_mapping: list[int] | None,
  3910. ) -> str | None:
  3911. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3912. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3913. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3914. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3915. uploaded several megabytes and burned its dispatch retries. This method
  3916. speaks only for the AMS-less case: there is nothing to resume into — the
  3917. external spool holder is the whole inventory — so the useful answer is to
  3918. say which filament is missing and stop. With an AMS attached it returns
  3919. None: where live status reported loaded trays,
  3920. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3921. reported none the print goes out and the firmware error is the answer —
  3922. the user can load the right spool and press Resume.
  3923. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3924. every branch that lacks the evidence to be sure returns None.
  3925. """
  3926. # None means the matcher never ran (no requirements parsed from the 3MF,
  3927. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3928. # dispatch as they always have.
  3929. if not _mapping_is_all_unresolved(computed_mapping):
  3930. return None
  3931. status = printer_manager.get_status(printer_id)
  3932. if status is None:
  3933. return None
  3934. # "No AMS" has to be a fact the printer stated, not the absence of a
  3935. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3936. # handled and is preserved across partial pushes thereafter, so a missing
  3937. # key means we have not heard yet — most likely a reconnect, where the
  3938. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3939. # empty list is the positive report of a printer with no AMS.
  3940. ams_units = status.raw_data.get("ams")
  3941. if not isinstance(ams_units, list) or ams_units:
  3942. return None
  3943. required = await self._get_filament_requirements(db, item)
  3944. loaded = self._build_loaded_filaments(status)
  3945. if not required or not loaded:
  3946. # Both were non-empty moments ago or the matcher could not have run.
  3947. # If the picture changed under us, say nothing rather than fail an
  3948. # item on stale evidence.
  3949. return None
  3950. self._apply_filament_overrides(item, required)
  3951. if any(r.get("force_color_match") for r in required):
  3952. # A forced colour is a spool the user can load on the external
  3953. # holder, so the unmatched hold stages the job instead (#3280).
  3954. return None
  3955. return _unmatched_filament_message(required, loaded)
  3956. async def _fail_unmappable_item(
  3957. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3958. ) -> None:
  3959. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3960. This replaces a failure, not a success: without it the item is uploaded,
  3961. rejected by the firmware with 0700_8012, retried twice more and failed
  3962. anyway with "never started the print after N dispatch attempts". So this
  3963. applies on the model-based path too. There it is rarely reached: choosing
  3964. the printer already asks the matcher (``_unmatched_on``, #3280) and passes
  3965. over one it cannot map, so an "Any <model>" job tries its siblings and
  3966. otherwise waits; this remains for a match that failed at selection time.
  3967. """
  3968. item.status = "failed"
  3969. item.error_message = message
  3970. item.completed_at = datetime.now(timezone.utc)
  3971. item.waiting_reason = None
  3972. await db.commit()
  3973. from backend.app.services.print_batch import refresh_batches_after
  3974. await refresh_batches_after([item.id])
  3975. logger.warning(
  3976. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3977. item.id,
  3978. printer_id,
  3979. message,
  3980. )
  3981. job_name = await self._get_job_name(db, item)
  3982. printer = await self._get_printer(db, printer_id)
  3983. await notification_service.on_queue_job_failed(
  3984. job_name=job_name,
  3985. printer_id=printer_id,
  3986. printer_name=printer.name if printer else "Unknown",
  3987. reason=message,
  3988. db=db,
  3989. )
  3990. try:
  3991. await ws_manager.send_queue_item_failed(
  3992. user_id=item.created_by_id,
  3993. queue_item_id=item.id,
  3994. printer_id=printer_id,
  3995. reason="filament_unmappable",
  3996. )
  3997. except Exception:
  3998. pass
  3999. async def _compute_ams_mapping_for_printer(
  4000. self,
  4001. db: AsyncSession,
  4002. printer_id: int,
  4003. item: PrintQueueItem,
  4004. *,
  4005. only_slots: set[int] | None = None,
  4006. reserved_trays: set[int] | None = None,
  4007. ) -> list[int] | None:
  4008. """Compute AMS mapping for a printer based on filament requirements.
  4009. Called when a queue item has no ams_mapping set — either for model-based
  4010. items after printer assignment, or printer-specific items (e.g. from VP).
  4011. Args:
  4012. db: Database session
  4013. printer_id: The assigned printer ID
  4014. item: The queue item (contains archive_id or library_file_id)
  4015. only_slots: Match only these filament slots; every other slot comes
  4016. back unresolved (-1). Used to fill the gaps of a stored mapping.
  4017. reserved_trays: Global tray IDs to leave out of the match, because
  4018. the stored mapping already gives them to another slot.
  4019. Returns:
  4020. AMS mapping array or None if no mapping needed/possible
  4021. """
  4022. # Get printer status
  4023. status = printer_manager.get_status(printer_id)
  4024. if not status:
  4025. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  4026. return None
  4027. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  4028. # either extruder, so the per-nozzle hard filter below must NOT apply.
  4029. # Otherwise a print on one nozzle can't use a spool physically loaded in
  4030. # an AMS on the *other* nozzle, and the matcher falls through to a
  4031. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  4032. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  4033. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  4034. # Get filament requirements from source file
  4035. filament_reqs = await self._get_filament_requirements(db, item)
  4036. if not filament_reqs:
  4037. # When the 3MF can't be read but force-color overrides are present, build a
  4038. # direct mapping from the overrides so the printer uses the correct AMS slot.
  4039. if item.filament_overrides:
  4040. try:
  4041. overrides = json.loads(item.filament_overrides)
  4042. force_overrides = [o for o in overrides if o.get("force_color_match")]
  4043. if force_overrides:
  4044. logger.info(
  4045. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  4046. "force-color override(s)",
  4047. item.id,
  4048. len(force_overrides),
  4049. )
  4050. return self._build_override_direct_mapping(force_overrides, status)
  4051. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4052. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  4053. logger.debug("No filament requirements found for queue item %s", item.id)
  4054. return None
  4055. self._apply_filament_overrides(item, filament_reqs)
  4056. if only_slots is not None:
  4057. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  4058. if not filament_reqs:
  4059. return None
  4060. # Build loaded filaments from printer status
  4061. loaded_filaments = self._build_loaded_filaments(status)
  4062. if reserved_trays:
  4063. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  4064. if not loaded_filaments:
  4065. logger.debug("No filaments loaded on printer %s", printer_id)
  4066. return None
  4067. # Check if user prefers lowest remaining filament when multiple spools match
  4068. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  4069. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  4070. # Without backup, the printer will not switch to a second spool when the
  4071. # picked one runs out — so sorting toward the lowest leaves the print
  4072. # at risk of running dry mid-job. None (unknown: no status report with
  4073. # cfg or home_flag yet) preserves today's behaviour intentionally.
  4074. if prefer_lowest and status.ams_filament_backup is False:
  4075. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  4076. prefer_lowest = False
  4077. # When the preference is on, surface Bambuddy's inventory-side
  4078. # remaining for each slot that's bound to a tracked spool, so the
  4079. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  4080. # entirely when the preference is off — no behaviour change for
  4081. # users who haven't opted in.
  4082. inventory_remain_overrides: dict[int, float] | None = None
  4083. if prefer_lowest:
  4084. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  4085. # Compute mapping: match required filaments to available slots
  4086. return self._match_filaments_to_slots(
  4087. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  4088. )
  4089. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  4090. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  4091. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  4092. diagnosis (#2771) describes the filament the matcher actually looked
  4093. for, not the one the 3MF was sliced with — naming the pre-override
  4094. filament in a user-facing error would send the user to load the wrong
  4095. spool.
  4096. """
  4097. if not item.filament_overrides:
  4098. return
  4099. try:
  4100. overrides = json.loads(item.filament_overrides)
  4101. override_map = {o["slot_id"]: o for o in overrides}
  4102. for req in filament_reqs:
  4103. if req["slot_id"] in override_map:
  4104. override = override_map[req["slot_id"]]
  4105. req["type"] = override["type"]
  4106. req["color"] = override["color"]
  4107. # A manual/preference override SWAPS the slot's filament, so the
  4108. # 3MF's original tray_info_idx now points at the old spool and must
  4109. # be cleared — matching then falls back to type+colour. A
  4110. # force_color_match override is not a swap: it carries the 3MF's
  4111. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  4112. # it here too, letting the matcher pin the correct variant slot on a
  4113. # printer holding two same-colour spools of different variants (#2650).
  4114. # A spool that names no variant still counts; one naming another
  4115. # variant does not, as in `_get_missing_force_color_slots` (#3280).
  4116. req["tray_info_idx"] = (
  4117. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  4118. )
  4119. # The matcher satisfies a forced slot only the way
  4120. # `_get_missing_force_color_slots` does, never by a similar
  4121. # colour or the type alone (#3280).
  4122. req["force_color_match"] = bool(override.get("force_color_match"))
  4123. logger.debug(
  4124. "Queue item %s: Override slot %d -> %s %s",
  4125. item.id,
  4126. req["slot_id"],
  4127. override["type"],
  4128. override["color"],
  4129. )
  4130. except (json.JSONDecodeError, KeyError, TypeError) as e:
  4131. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  4132. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  4133. """Build an AMS mapping directly from force-color overrides without a 3MF.
  4134. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  4135. slice_info is missing or unreadable) but ``force_color_match`` overrides
  4136. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  4137. treated as the filament requirement for that slot and matched against the
  4138. current AMS state of the printer.
  4139. Returns the same format as ``_match_filaments_to_slots``, or None when
  4140. the AMS has no loaded filaments.
  4141. """
  4142. loaded = self._build_loaded_filaments(status)
  4143. if not loaded:
  4144. return None
  4145. reqs = [
  4146. {
  4147. "slot_id": o["slot_id"],
  4148. "type": o.get("type", ""),
  4149. "color": o.get("color", ""),
  4150. # These are all force_color_match overrides, so the idx (when the
  4151. # 3MF carried one) is the intended variant, not a stale swap —
  4152. # keep it so the matcher pins the right variant slot (#2650); a
  4153. # spool naming another variant does not satisfy it (#3280).
  4154. "tray_info_idx": o.get("tray_info_idx", ""),
  4155. "force_color_match": True,
  4156. }
  4157. for o in force_overrides
  4158. ]
  4159. return self._match_filaments_to_slots(reqs, loaded)
  4160. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  4161. """Resolve the queue item's source 3MF and parse the per-slot
  4162. filament requirements out of it. Thin DB-resolver wrapper around
  4163. ``filament_requirements.extract_filament_requirements`` so the VP
  4164. queue-mode write path (#1188) can reuse the same parser at upload
  4165. time.
  4166. """
  4167. from backend.app.services.filament_requirements import extract_filament_requirements
  4168. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  4169. # so every caller gets its own copy — a shared list would leak one
  4170. # item's overrides into the next item that happens to print the same
  4171. # plate.
  4172. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  4173. if memo_key in self._filament_req_memo:
  4174. cached = self._filament_req_memo[memo_key]
  4175. return [dict(r) for r in cached] if cached else None
  4176. file_path: Path | None = None
  4177. if item.archive_id:
  4178. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4179. archive = result.scalar_one_or_none()
  4180. if archive:
  4181. file_path = settings.base_dir / archive.file_path
  4182. elif item.library_file_id:
  4183. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4184. library_file = result.scalar_one_or_none()
  4185. if library_file:
  4186. lib_path = Path(library_file.file_path)
  4187. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4188. if not file_path or not file_path.exists():
  4189. self._filament_req_memo[memo_key] = None
  4190. return None
  4191. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  4192. self._filament_req_memo[memo_key] = filaments or None
  4193. return [dict(r) for r in filaments] if filaments else None
  4194. def _build_loaded_filaments(self, status) -> list[dict]:
  4195. """Build list of loaded filaments from printer status.
  4196. Args:
  4197. status: PrinterState from printer_manager
  4198. Returns:
  4199. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  4200. """
  4201. filaments = []
  4202. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  4203. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  4204. # Routes external spools to an extruder (#2771). Mirrors
  4205. # `buildLoadedFilaments` in the frontend.
  4206. vt_trays = status.raw_data.get("vt_tray") or []
  4207. is_dual_nozzle = reports_two_nozzles(status)
  4208. # Parse AMS units from raw_data
  4209. ams_data = status.raw_data.get("ams", [])
  4210. for ams_unit in ams_data:
  4211. ams_id = int(ams_unit.get("id", 0))
  4212. trays = ams_unit.get("tray", [])
  4213. is_ht = 128 <= ams_id <= 135 # AMS-HT unit ids; a regular AMS may list fewer trays
  4214. for tray in trays:
  4215. tray_type = tray.get("tray_type")
  4216. if tray_type:
  4217. tray_id = int(tray.get("id", 0))
  4218. tray_color = tray.get("tray_color", "")
  4219. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  4220. tray_info_idx = tray.get("tray_info_idx", "")
  4221. # Normalize color: remove alpha, add hash
  4222. color = self._normalize_color(tray_color)
  4223. # Calculate global tray ID
  4224. # AMS-HT units have IDs starting at 128 with a single tray
  4225. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  4226. filaments.append(
  4227. {
  4228. "type": tray_type,
  4229. "color": color,
  4230. # `color` reads a missing colour as #808080; this
  4231. # says whether the printer reported one at all.
  4232. "color_known": bool(tray_color),
  4233. "tray_info_idx": tray_info_idx,
  4234. "ams_id": ams_id,
  4235. "tray_id": tray_id,
  4236. "is_ht": is_ht,
  4237. "is_external": False,
  4238. "global_tray_id": global_tray_id,
  4239. "extruder_id": ams_extruder_map.get(str(ams_id)),
  4240. "remain": tray.get("remain", -1),
  4241. }
  4242. )
  4243. # Check external spool(s) (vt_tray is a list)
  4244. for idx, vt in enumerate(vt_trays):
  4245. if vt.get("tray_type"):
  4246. color = self._normalize_color(vt.get("tray_color", ""))
  4247. tray_id = int(vt.get("id", 254))
  4248. filaments.append(
  4249. {
  4250. "type": vt["tray_type"],
  4251. "color": color,
  4252. "color_known": bool(vt.get("tray_color")),
  4253. "tray_info_idx": vt.get("tray_info_idx", ""),
  4254. "ams_id": -1,
  4255. "tray_id": idx,
  4256. "is_ht": False,
  4257. "is_external": True,
  4258. "global_tray_id": tray_id,
  4259. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  4260. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  4261. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  4262. "remain": vt.get("remain", -1),
  4263. }
  4264. )
  4265. return filaments
  4266. def _normalize_color(self, color: str | None) -> str:
  4267. """Normalize color to #RRGGBB format."""
  4268. if not color:
  4269. return "#808080"
  4270. hex_color = color.replace("#", "")[:6]
  4271. return f"#{hex_color}"
  4272. def _normalize_color_for_compare(self, color: str | None) -> str:
  4273. """Normalize color for comparison (lowercase, no hash)."""
  4274. if not color:
  4275. return ""
  4276. return color.replace("#", "").lower()[:6]
  4277. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  4278. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  4279. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  4280. stays the per-channel box that shipped — this only decides which of
  4281. several eligible spools is closest, so nothing becomes usable or
  4282. unusable because of it.
  4283. It ranks by how far apart the colours *look*, not how far apart their
  4284. numbers are. RGB distance overweights blue badly enough to invert the
  4285. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  4286. the nearer of two eligible spools by RGB and the further by a factor of
  4287. four once measured perceptually.
  4288. Alpha is ignored, deliberately: the alpha a slicer writes for a
  4289. transparent filament is not a colour the user chose, and counting it
  4290. would stop a transparent filament matching itself.
  4291. """
  4292. return perceptual_color_distance(color1, color2)
  4293. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  4294. """Check if two colors are visually similar within a threshold."""
  4295. hex1 = self._normalize_color_for_compare(color1)
  4296. hex2 = self._normalize_color_for_compare(color2)
  4297. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  4298. return False
  4299. try:
  4300. r1 = int(hex1[0:2], 16)
  4301. g1 = int(hex1[2:4], 16)
  4302. b1 = int(hex1[4:6], 16)
  4303. r2 = int(hex2[0:2], 16)
  4304. g2 = int(hex2[2:4], 16)
  4305. b2 = int(hex2[4:6], 16)
  4306. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  4307. except ValueError:
  4308. return False
  4309. async def _build_inventory_remain_overrides(
  4310. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  4311. ) -> dict[int, float]:
  4312. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  4313. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  4314. The MQTT ``remain`` field on a tray is the printer firmware's
  4315. RFID-decremented value, which has two limitations the "Prefer Lowest
  4316. Remaining Filament" feature has been ignoring (#1508):
  4317. - it's only meaningful for Bambu RFID spools; everything else reports
  4318. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  4319. compare equal and the sort collapses to AMS-slot order — the user
  4320. who's curating inventory weights gets the lower-slot pick instead
  4321. of the lower-remaining pick;
  4322. - even when set, it's the *printer's* counter, not Bambuddy's
  4323. ``label_weight - weight_used`` (internal mode) or Spoolman's
  4324. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  4325. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  4326. When the user has bound a spool to a slot, their own inventory
  4327. tracking is authoritative; this helper surfaces that value so the
  4328. sort can prefer it. Slots without a binding are absent from the
  4329. returned map — the caller then falls back to MQTT ``remain`` for
  4330. those, preserving the pre-#1508 behaviour for un-tracked spools.
  4331. Returns an empty map on any failure (no inventory bindings, DB
  4332. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  4333. is a preference, not a guarantee.
  4334. """
  4335. if not loaded:
  4336. return {}
  4337. # External / virtual-tray slots are tracked separately from AMS — skip
  4338. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  4339. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  4340. # match is fiddly and out of scope for this fix).
  4341. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  4342. if not tracked_slots:
  4343. return {}
  4344. is_spoolman = await self._is_spoolman_mode(db)
  4345. overrides: dict[int, float] = {}
  4346. if is_spoolman:
  4347. result = await db.execute(
  4348. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  4349. )
  4350. assignments = list(result.scalars().all())
  4351. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  4352. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  4353. for ams_id, tray_id, gtid in tracked_slots:
  4354. spoolman_id = by_slot.get((ams_id, tray_id))
  4355. if spoolman_id is None:
  4356. continue
  4357. grams = await _spoolman_remaining_grams(spoolman_id)
  4358. if grams is not None:
  4359. overrides[gtid] = grams
  4360. return overrides
  4361. # Internal inventory mode (default). selectinload matches the pattern
  4362. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  4363. # plus an eager-loaded relationship rather than an explicit join, so
  4364. # the row-attribute shape is exactly what those routes already rely on.
  4365. result = await db.execute(
  4366. select(SpoolAssignment)
  4367. .options(selectinload(SpoolAssignment.spool))
  4368. .where(SpoolAssignment.printer_id == printer_id)
  4369. )
  4370. assignments = list(result.scalars().all())
  4371. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  4372. for ams_id, tray_id, gtid in tracked_slots:
  4373. spool = by_slot.get((ams_id, tray_id))
  4374. if spool is None:
  4375. continue
  4376. label = float(spool.label_weight or 0)
  4377. used = float(spool.weight_used or 0)
  4378. overrides[gtid] = max(0.0, label - used)
  4379. return overrides
  4380. @staticmethod
  4381. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  4382. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  4383. here to avoid making this module import-dependent on that private
  4384. helper's signature."""
  4385. try:
  4386. from backend.app.api.routes.settings import get_setting
  4387. v = await get_setting(db, "spoolman_enabled")
  4388. return bool(v) and v.lower() == "true"
  4389. except Exception:
  4390. return False
  4391. @staticmethod
  4392. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  4393. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  4394. Three bands, matched to the emission order in ``_build_loaded_filaments``
  4395. so a tied sort produces the same physical-position order the pre-#1508
  4396. stable sort did (preserves the regression-free baseline):
  4397. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  4398. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  4399. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  4400. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  4401. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  4402. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  4403. """
  4404. if ams_id is None or ams_id < 0:
  4405. return 10_000
  4406. if ams_id >= 128:
  4407. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  4408. return ams_id * 4 + (tray_id or 0)
  4409. @staticmethod
  4410. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  4411. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  4412. Two-tier ordering: inventory-tracked spools always sort BEFORE
  4413. non-tracked spools (the user has told us they care about these
  4414. specifically), then ascending by remaining within each tier, then
  4415. ascending by AMS slot position as the deterministic tie-breaker.
  4416. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  4417. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  4418. because the tier flag dominates — which is what lets us mix grams
  4419. (inventory) and percent (MQTT) without a unit conversion.
  4420. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  4421. spools the printer DOES know something about sort ahead of those
  4422. it knows nothing about — preserves pre-#1508 behaviour for the
  4423. no-inventory-binding case.
  4424. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  4425. external on ties, matching the legacy emission-order stable sort.
  4426. """
  4427. gtid = f.get("global_tray_id")
  4428. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  4429. if overrides and gtid in overrides:
  4430. return (0, overrides[gtid], slot_order)
  4431. remain = f.get("remain", -1)
  4432. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  4433. def _match_filaments_to_slots(
  4434. self,
  4435. required: list[dict],
  4436. loaded: list[dict],
  4437. prefer_lowest: bool = False,
  4438. inventory_remain_overrides: dict[int, float] | None = None,
  4439. fts_installed: bool = False,
  4440. ) -> list[int] | None:
  4441. """Match required filaments to loaded filaments and build AMS mapping.
  4442. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  4443. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  4444. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  4445. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  4446. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  4447. matching among those trays.
  4448. Args:
  4449. required: List of required filaments with slot_id, type, color, tray_info_idx
  4450. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  4451. Returns:
  4452. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  4453. """
  4454. if not required:
  4455. return None
  4456. # Track used trays to avoid duplicate assignment
  4457. used_tray_ids: set[int] = set()
  4458. comparisons = []
  4459. # Forced slots first: a slot that would take any tray of its type must
  4460. # not take the one tray a forced slot can use (#3280). The mapping is
  4461. # built by slot_id below, so the order only decides who goes first.
  4462. # Among forced slots, those naming a variant first, as
  4463. # `_get_missing_force_color_slots` counts them.
  4464. for req in sorted(
  4465. required,
  4466. key=lambda r: (
  4467. not r.get("force_color_match"),
  4468. bool(r.get("force_color_match")) and not r.get("tray_info_idx"),
  4469. ),
  4470. ):
  4471. req_type = (req.get("type") or "").upper()
  4472. req_color = req.get("color", "")
  4473. req_tray_info_idx = req.get("tray_info_idx", "")
  4474. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  4475. idx_match = None
  4476. exact_match = None
  4477. similar_match = None
  4478. similar_distance = float("inf")
  4479. type_only_match = None
  4480. # Get available trays (not already used)
  4481. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  4482. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  4483. # Hard filter — cross-nozzle assignment causes print failures
  4484. # ("position of left hotend is abnormal"), so never fall back.
  4485. # Skipped when an FTS is installed: it routes any AMS slot to either
  4486. # extruder, so restricting to one nozzle would wrongly exclude the
  4487. # correct spool sitting in the other nozzle's AMS (#2186).
  4488. req_nozzle_id = req.get("nozzle_id")
  4489. if req_nozzle_id is not None and not fts_installed:
  4490. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  4491. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  4492. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  4493. # _prefer_lowest_sort_key for the full rationale.
  4494. if prefer_lowest:
  4495. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4496. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  4497. # One line per filament req so a bug report can be diagnosed
  4498. # without enabling debug logging: shows what the matcher saw
  4499. # (req shape + sorted candidate trays with their remain values
  4500. # and any inventory override that was applied). Mirrored by
  4501. # the picked-match log at the bottom of the loop.
  4502. logger.info(
  4503. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  4504. req.get("slot_id"),
  4505. req_type,
  4506. req_color,
  4507. req_tray_info_idx,
  4508. req_nozzle_id,
  4509. [
  4510. {
  4511. "gtid": f.get("global_tray_id"),
  4512. "type": f.get("type"),
  4513. "color": f.get("color"),
  4514. "tii": f.get("tray_info_idx"),
  4515. "remain": f.get("remain"),
  4516. "inv_g": (
  4517. inventory_remain_overrides.get(f.get("global_tray_id"))
  4518. if inventory_remain_overrides
  4519. else None
  4520. ),
  4521. }
  4522. for f in available
  4523. ],
  4524. )
  4525. # A forced slot takes only what `_get_missing_force_color_slots`
  4526. # accepts: same type, exact colour, and the same variant when both
  4527. # sides name one -- preferring the tray that does. Nothing looser:
  4528. # the model-based path holds a job the printer cannot satisfy this
  4529. # way, and a printer-pinned job fell through to type_only and
  4530. # printed in whatever colour came first (#3280).
  4531. forced = bool(req.get("force_color_match"))
  4532. if forced:
  4533. want_type = canonical_filament_type(req_type)
  4534. want_color = self._normalize_color_for_compare(req_color)
  4535. candidates = [
  4536. f
  4537. for f in available
  4538. if canonical_filament_type((f.get("type") or "").upper()) == want_type
  4539. and self._normalize_color_for_compare(f.get("color", "")) == want_color
  4540. and (
  4541. not req_tray_info_idx
  4542. or not f.get("tray_info_idx")
  4543. or f.get("tray_info_idx") == req_tray_info_idx
  4544. )
  4545. ]
  4546. exact_match = next(
  4547. (f for f in candidates if req_tray_info_idx and f.get("tray_info_idx") == req_tray_info_idx),
  4548. candidates[0] if candidates else None,
  4549. )
  4550. # Check if tray_info_idx is unique among available trays
  4551. if req_tray_info_idx and not forced:
  4552. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  4553. if len(idx_matches) == 1:
  4554. # Unique tray_info_idx - use it as definitive match
  4555. idx_match = idx_matches[0]
  4556. logger.debug(
  4557. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  4558. f"-> tray {idx_match['global_tray_id']}"
  4559. )
  4560. elif len(idx_matches) > 1:
  4561. # Multiple trays with same tray_info_idx - use color matching among them
  4562. logger.debug(
  4563. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  4564. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  4565. )
  4566. if prefer_lowest:
  4567. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  4568. # Use color matching within this subset
  4569. for f in idx_matches:
  4570. f_color = f.get("color", "")
  4571. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4572. if not exact_match:
  4573. exact_match = f
  4574. elif self._colors_are_similar(f_color, req_color):
  4575. distance = self._color_distance(f_color, req_color)
  4576. if distance is not None and distance < similar_distance:
  4577. similar_match = f
  4578. similar_distance = distance
  4579. elif not type_only_match:
  4580. type_only_match = f
  4581. # If no idx_match yet, do standard type/color matching on all available trays
  4582. if not forced and not idx_match and not exact_match and not similar_match and not type_only_match:
  4583. for f in available:
  4584. f_type = (f.get("type") or "").upper()
  4585. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  4586. continue
  4587. # Type matches - check color
  4588. f_color = f.get("color", "")
  4589. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  4590. if not exact_match:
  4591. exact_match = f
  4592. elif self._colors_are_similar(f_color, req_color):
  4593. # Nearest wins, not first-in-tray-order. `available` is
  4594. # already in the caller's order (slot order, or the
  4595. # prefer-lowest sort), and `<` keeps the earliest of
  4596. # equally close spools — so that order survives as the
  4597. # tie-break (#2804).
  4598. distance = self._color_distance(f_color, req_color)
  4599. if distance is not None and distance < similar_distance:
  4600. similar_match = f
  4601. similar_distance = distance
  4602. elif not type_only_match:
  4603. type_only_match = f
  4604. match = idx_match or exact_match or similar_match or type_only_match
  4605. if match:
  4606. used_tray_ids.add(match["global_tray_id"])
  4607. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  4608. else:
  4609. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  4610. # Which bucket won, always — not only under Prefer Lowest (#2804).
  4611. # "Why did it pick that spool" is the question every wrong-filament
  4612. # report starts with, and a `similar_color` win is now a ranked
  4613. # choice among several eligible spools rather than whichever tray
  4614. # came first, so it is worth being able to see after the fact.
  4615. # Pairs with the "available (sorted)" log above when Prefer Lowest
  4616. # is on (#1766).
  4617. if match:
  4618. bucket = (
  4619. "idx"
  4620. if idx_match is not None
  4621. else "exact_color"
  4622. if exact_match is not None
  4623. else "similar_color"
  4624. if similar_match is not None
  4625. else "type_only"
  4626. )
  4627. logger.info(
  4628. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4629. match["global_tray_id"],
  4630. bucket,
  4631. req.get("slot_id"),
  4632. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4633. )
  4634. else:
  4635. logger.info(
  4636. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r%s)",
  4637. req.get("slot_id"),
  4638. req_type,
  4639. req_color,
  4640. req_tray_info_idx,
  4641. ", force color match" if forced else "",
  4642. )
  4643. # Build mapping array
  4644. if not comparisons:
  4645. return None
  4646. max_slot_id = max(c["slot_id"] for c in comparisons)
  4647. if max_slot_id <= 0:
  4648. return None
  4649. mapping = [-1] * max_slot_id
  4650. for c in comparisons:
  4651. slot_id = c["slot_id"]
  4652. if slot_id and slot_id > 0:
  4653. mapping[slot_id - 1] = c["global_tray_id"]
  4654. return mapping
  4655. def _mark_printer_dispatched(
  4656. self,
  4657. printer_id: int,
  4658. pre_state: str | None,
  4659. pre_subtask_id: str | None,
  4660. ) -> None:
  4661. """Record that a print command was just sent to ``printer_id``.
  4662. Held until either the watchdog observes a state/subtask transition
  4663. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4664. """
  4665. if not pre_state:
  4666. # No pre_state means we can't detect a transition — fall back to a
  4667. # pure time-based hold using empty string as a sentinel that won't
  4668. # match any real printer state.
  4669. pre_state = ""
  4670. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4671. def _release_dispatch_hold(self, printer_id: int) -> None:
  4672. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4673. self._dispatch_holds.pop(printer_id, None)
  4674. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4675. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4676. Returns False (and clears the hold) once any of these are true:
  4677. - hard timeout (``_dispatch_max_hold``) has elapsed
  4678. - the printer has transitioned out of pre_state and we're past the
  4679. minimum cooldown
  4680. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4681. past the minimum cooldown
  4682. Otherwise the printer is held — caller should treat it as busy.
  4683. """
  4684. entry = self._dispatch_holds.get(printer_id)
  4685. if not entry:
  4686. return False
  4687. started_at, pre_state, pre_subtask_id = entry
  4688. elapsed = time.monotonic() - started_at
  4689. if elapsed >= self._dispatch_max_hold:
  4690. self._dispatch_holds.pop(printer_id, None)
  4691. return False
  4692. # Without a pre_state we can't detect a transition — fall back to the
  4693. # min cooldown alone, then drop the hold.
  4694. if not pre_state:
  4695. if elapsed >= self._dispatch_min_cooldown:
  4696. self._dispatch_holds.pop(printer_id, None)
  4697. return False
  4698. return True
  4699. status = printer_manager.get_status(printer_id)
  4700. current_state = getattr(status, "state", None) if status else None
  4701. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4702. transitioned = (current_state is not None and current_state != pre_state) or (
  4703. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4704. )
  4705. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4706. self._dispatch_holds.pop(printer_id, None)
  4707. return False
  4708. return True
  4709. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4710. """Check if a printer is connected and idle."""
  4711. if not printer_manager.is_connected(printer_id):
  4712. logger.debug("Printer %d: not connected", printer_id)
  4713. return False
  4714. state = printer_manager.get_status(printer_id)
  4715. if not state:
  4716. logger.debug("Printer %d: no status available", printer_id)
  4717. return False
  4718. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4719. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4720. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4721. # printer, it boots back into IDLE with no memory of the previous finish; without
  4722. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4723. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4724. logger.debug(
  4725. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4726. printer_id,
  4727. state.state,
  4728. )
  4729. return False
  4730. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4731. if not idle:
  4732. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4733. return False
  4734. # A print would run from the SD card the firmware is being written to.
  4735. from backend.app.services.firmware_update import upload_in_progress
  4736. if upload_in_progress(printer_id):
  4737. logger.debug("Printer %d: not idle — firmware upload in progress", printer_id)
  4738. return False
  4739. return True
  4740. @staticmethod
  4741. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4742. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4743. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4744. and that the fixed-printer branch has already found connected, so the two
  4745. offline cases answer at their own exits and never arrive here.
  4746. The default is the model-based branch's ``Busy:`` wording, which
  4747. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4748. the right answer for the connected-but-no-telemetry second or two after a
  4749. reconnect: the model-based branch has always reported it that way, and it
  4750. is not something to wake anybody up for.
  4751. A plate nobody has confirmed is the one case here that does not resolve
  4752. itself — somebody has to walk over to the printer — so it is worded as
  4753. itself and allowed to notify.
  4754. """
  4755. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4756. return f"Waiting for plate confirmation: {printer_name}"
  4757. return f"Busy: {printer_name}"
  4758. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4759. """Read a setting value from the database."""
  4760. result = await db.execute(select(Settings).where(Settings.key == key))
  4761. setting = result.scalar_one_or_none()
  4762. return setting.value if setting else None
  4763. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4764. """Read a boolean setting from the database."""
  4765. result = await db.execute(select(Settings).where(Settings.key == key))
  4766. setting = result.scalar_one_or_none()
  4767. if setting:
  4768. return setting.value.lower() == "true"
  4769. return default
  4770. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4771. """Read an int setting; falls back to default on missing/unparseable rows."""
  4772. result = await db.execute(select(Settings).where(Settings.key == key))
  4773. setting = result.scalar_one_or_none()
  4774. if setting and setting.value:
  4775. try:
  4776. return int(setting.value)
  4777. except ValueError:
  4778. pass
  4779. return default
  4780. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4781. """Get drying presets (user-configured or built-in defaults)."""
  4782. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4783. setting = result.scalar_one_or_none()
  4784. if setting and setting.value:
  4785. try:
  4786. presets = json.loads(setting.value)
  4787. if isinstance(presets, dict) and presets:
  4788. return presets
  4789. except json.JSONDecodeError:
  4790. pass
  4791. return self.DEFAULT_DRYING_PRESETS
  4792. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4793. """Per-filament humidity thresholds (#1605).
  4794. Returns the user-configured overrides map keyed by normalized filament
  4795. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4796. unknown / unmapped types. Empty / unset → empty dict, in which case
  4797. callers fall back to ``ams_humidity_fair``.
  4798. """
  4799. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4800. setting = result.scalar_one_or_none()
  4801. if not setting or not setting.value:
  4802. return {}
  4803. try:
  4804. data = json.loads(setting.value)
  4805. except json.JSONDecodeError:
  4806. return {}
  4807. if not isinstance(data, dict):
  4808. return {}
  4809. out: dict[str, int] = {}
  4810. for key, value in data.items():
  4811. try:
  4812. out[str(key).upper() if key != "default" else "default"] = int(value)
  4813. except (TypeError, ValueError):
  4814. continue
  4815. return out
  4816. # Materials whose AMS spelling differs from the key the tables above use.
  4817. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4818. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4819. # good PA row (#3067).
  4820. #
  4821. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4822. # The drying popover has resolved these correctly since #2774 and the
  4823. # scheduler never did, which is exactly why #3067's reporter could dry a
  4824. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4825. #
  4826. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4827. # of nylon, so it is the one entry that is a judgement rather than a
  4828. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4829. # way, and PA's row is the hottest the table has. Drying it there is closer
  4830. # to right than not drying it at all, which is what it got before.
  4831. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4832. "NYLON": "PA",
  4833. "PA6": "PA",
  4834. "PA11": "PA",
  4835. "PA12": "PA",
  4836. "PAHT": "PA",
  4837. "PPA": "PA",
  4838. }
  4839. @classmethod
  4840. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4841. """The key in *table* that answers for this tray's material, or None.
  4842. The printer reports the material in ``tray_type``, and it spells filled
  4843. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4844. tables here are keyed by base material, so matching the raw string alone
  4845. found a row for 8 of the 41 types a printer can report and skipped the
  4846. rest -- silently, because every caller reads "no row" as "nothing to do
  4847. for this tray". Auto-drying therefore ignored every composite spool on
  4848. the install (#3067).
  4849. Exact match first, so a table the user has extended with a row of its
  4850. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4851. base material's. Then the suffix is dropped, then the alias map above
  4852. answers for the polyamide spellings.
  4853. Returns None rather than a default: what to do with an unrecognised
  4854. material differs per caller, and only the caller knows whether "no row"
  4855. means skip the tray or fall back to a catch-all. Nothing here invents a
  4856. temperature for a material the table does not list.
  4857. """
  4858. raw = cls._normalize_filament_type(tray_type or "")
  4859. if not raw:
  4860. return None
  4861. for candidate in (raw, raw.split("-")[0]):
  4862. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4863. if key in table:
  4864. return key
  4865. return None
  4866. @staticmethod
  4867. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4868. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4869. For mixed filament types loaded into one AMS, returns the most
  4870. restrictive (lowest) threshold across all loaded tray types — matches
  4871. the conservative-params strategy already used for drying temp/hours.
  4872. Empty / unloaded trays contribute no constraint. Unknown types use the
  4873. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4874. when no per-type map is configured at all.
  4875. """
  4876. default = thresholds.get("default", fallback)
  4877. if not thresholds:
  4878. return fallback
  4879. candidates: list[int] = []
  4880. for tray in trays:
  4881. tray_type = str(tray.get("tray_type") or "").strip()
  4882. if not tray_type:
  4883. continue
  4884. # A composite carries its base material's threshold when it has no
  4885. # row of its own, the same way it takes its drying preset (#3067).
  4886. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4887. candidates.append(thresholds[key] if key is not None else default)
  4888. if not candidates:
  4889. return default
  4890. return min(candidates)
  4891. def _get_conservative_drying_params(
  4892. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4893. ) -> tuple[int, int, str] | None:
  4894. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4895. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4896. """
  4897. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4898. hours_key = f"{temp_key}_hours"
  4899. min_temp = None
  4900. max_hours = None
  4901. filament_type = ""
  4902. for tray in trays:
  4903. tray_type = tray.get("tray_type", "")
  4904. if not tray_type:
  4905. continue
  4906. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4907. # which is what stopped auto-drying on every composite spool (#3067).
  4908. base_type = self._resolve_filament_key(tray_type, presets)
  4909. if base_type is None:
  4910. continue
  4911. # The table is user-editable JSON with no per-row validation, so a
  4912. # row can be present and empty. That has always meant "skip this
  4913. # material", and it has to keep meaning it: the reads below fall
  4914. # back to 55C/12h per missing field, which is a temperature nobody
  4915. # chose and would deform a PLA spool.
  4916. preset = presets[base_type]
  4917. if not preset:
  4918. continue
  4919. temp = preset.get(temp_key, 55)
  4920. hours = preset.get(hours_key, 12)
  4921. # Conservative: lowest temp, longest duration
  4922. if min_temp is None or temp < min_temp:
  4923. min_temp = temp
  4924. if max_hours is None or hours > max_hours:
  4925. max_hours = hours
  4926. if not filament_type:
  4927. filament_type = base_type
  4928. if min_temp is None:
  4929. return None
  4930. return (min_temp, max_hours or 12, filament_type)
  4931. async def _check_filament_low(self, db: AsyncSession) -> None:
  4932. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4933. ``on_filament_low`` has had a column, a schema field, a route, a template
  4934. and a UI toggle since the notification system was built, and no caller --
  4935. so the toggle could be switched on and could never fire. This is the
  4936. producer.
  4937. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4938. ``low_stock_threshold_pct`` override is already exactly this decision:
  4939. already configurable, already surfaced, already driving the Inventory
  4940. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4941. consulted -- it has been measured up to 56 points out against a scale,
  4942. which is not a number to page someone on.
  4943. Only slots with an assigned spool produce an event. A slot Bambuddy
  4944. cannot resolve to a spool has no remaining weight it can stand behind,
  4945. and guessing one is how the remain percentage would have got in.
  4946. """
  4947. from backend.app.models.spool import Spool
  4948. # Time-gated rather than run on every pass. run() sleeps
  4949. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4950. # early-return path counts as productive while an upload is in flight
  4951. # (#2602), so an unthrottled check would re-read the whole spool
  4952. # collection every 3 seconds for the length of a batch drain. In
  4953. # Spoolman mode that is a request storm against a third-party service,
  4954. # which is the thing this producer's design note argues against; and
  4955. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4956. # check_queue holding the scheduler's session, so the outage would
  4957. # throttle the print queue itself. A low spool is not a 3-second
  4958. # concern -- the idle interval is the natural resolution.
  4959. now = time.monotonic()
  4960. if now < self._filament_low_next_check:
  4961. return
  4962. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4963. try:
  4964. # on_filament_low defaults to off on every provider, so on most
  4965. # installs nobody wants this alert. Without this the check would
  4966. # still read every assigned spool each interval -- the whole
  4967. # collection over HTTP in Spoolman mode -- for an event that is
  4968. # switched off. One query against the provider table settles it
  4969. # before any spool work, the same guard the bed-cooled waiter uses.
  4970. # No printer_id: this asks whether any provider wants the event at
  4971. # all; per-printer scoping is applied when the event is sent.
  4972. #
  4973. # While nobody wants it, no pass sees a slot go back above its
  4974. # threshold, so nothing can re-arm; a spool refilled under the same
  4975. # id in that time would stay silenced until a restart. Forgetting
  4976. # what was sent is right anyway: whoever switches the event back on
  4977. # is told about the spools that are low now.
  4978. #
  4979. # The MQTT relay publishes the same event, so a connected relay is
  4980. # reason enough to run the check. Its record is forgotten when the
  4981. # relay is switched off, not when the broker drops: a reconnect must
  4982. # not re-send every low slot.
  4983. notify = bool(await notification_service._get_providers_for_event(db, "on_filament_low", fleet_wide=True))
  4984. relay = mqtt_relay.enabled and mqtt_relay.connected
  4985. if not notify:
  4986. self._notified_filament_low.clear()
  4987. if not mqtt_relay.enabled:
  4988. self._relayed_filament_low.clear()
  4989. if not notify and not relay:
  4990. return
  4991. global_threshold = await self._get_low_stock_threshold(db)
  4992. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4993. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4994. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4995. if spoolman_on:
  4996. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4997. else:
  4998. rows = (
  4999. await db.execute(
  5000. select(SpoolAssignment, Spool)
  5001. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  5002. # An archived spool is not stock. The Inventory page's
  5003. # Low Stock count skips them (InventoryPage.tsx:1089)
  5004. # and get_all_spools without allow_archived already
  5005. # excludes them in Spoolman mode, so without this the
  5006. # internal path is the only one that alerts on them.
  5007. .where(Spool.archived_at.is_(None))
  5008. )
  5009. ).all()
  5010. for assignment, spool in rows:
  5011. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  5012. if pct is None:
  5013. continue
  5014. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  5015. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  5016. pct,
  5017. threshold,
  5018. spool.color_name,
  5019. )
  5020. if not slots:
  5021. # Nothing resolvable this pass. Deliberately not clearing the
  5022. # notified set: a Spoolman that is briefly unreachable would
  5023. # otherwise re-alert on every spool as soon as it came back.
  5024. return
  5025. await self._emit_filament_low(db, slots, notify=notify, relay=relay)
  5026. except Exception as e:
  5027. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  5028. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  5029. """The global low-stock percentage, defaulting to the schema's 20.0."""
  5030. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  5031. if raw is None or raw.value is None:
  5032. return 20.0
  5033. try:
  5034. value = float(raw.value)
  5035. except (TypeError, ValueError):
  5036. return 20.0
  5037. return value if 0 < value <= 100 else 20.0
  5038. async def _filament_low_slots_spoolman(
  5039. self, db: AsyncSession, global_threshold: float
  5040. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  5041. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  5042. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  5043. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  5044. so the global threshold is the only one that applies here. That matches
  5045. what the Inventory page already does in this mode.
  5046. One ``get_all_spools`` call covers every slot rather than a request per
  5047. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  5048. without ``allow_archived`` -- which is the behaviour the internal path
  5049. has to ask for explicitly.
  5050. An unreachable Spoolman returns no slots rather than raising. It is an
  5051. ordinary state for a third-party service, not an error in this pass: the
  5052. caller's "nothing resolvable" branch already leaves the notified set
  5053. alone, which is exactly right here, whereas letting it reach the broad
  5054. ``except`` would write a full traceback every time the check runs.
  5055. """
  5056. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5057. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5058. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  5059. if not assignments:
  5060. return {}
  5061. client = await get_spoolman_client()
  5062. if client is None:
  5063. return {}
  5064. try:
  5065. all_spools = await client.get_all_spools()
  5066. except SpoolmanUnavailableError as e:
  5067. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  5068. return {}
  5069. by_id: dict[int, dict] = {}
  5070. for raw in all_spools:
  5071. raw_id = raw.get("id")
  5072. if isinstance(raw_id, int):
  5073. by_id[raw_id] = raw
  5074. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  5075. for assignment in assignments:
  5076. raw = by_id.get(assignment.spoolman_spool_id)
  5077. if raw is None:
  5078. continue
  5079. try:
  5080. mapped = _map_spoolman_spool(raw)
  5081. except ValueError:
  5082. continue
  5083. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  5084. if pct is None:
  5085. continue
  5086. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  5087. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  5088. return slots
  5089. async def _emit_filament_low(
  5090. self,
  5091. db: AsyncSession,
  5092. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]],
  5093. *,
  5094. notify: bool = True,
  5095. relay: bool = False,
  5096. ) -> None:
  5097. """Send one notification and/or MQTT relay event per slot that has newly crossed its threshold."""
  5098. printers: dict[int, Printer] = {}
  5099. for key, (pct, threshold, color) in slots.items():
  5100. printer_id, ams_id, tray_id, spool_id = key
  5101. if pct >= threshold:
  5102. # Back above the line: re-arm rather than expire on a timer, so a
  5103. # refilled slot can alert again and a spool sitting just under the
  5104. # threshold stays quiet.
  5105. self._notified_filament_low.discard(key)
  5106. self._relayed_filament_low.discard(key)
  5107. continue
  5108. send_notification = notify and key not in self._notified_filament_low
  5109. # Only while connected, so a crossing the relay missed reaches it
  5110. # after the reconnect.
  5111. send_relay = relay and key not in self._relayed_filament_low
  5112. if not send_notification and not send_relay:
  5113. continue
  5114. # Marked before sending, which is a choice rather than the only
  5115. # option, and it is the opposite failure mode from the one the
  5116. # debounce argues against: one transient provider failure loses this
  5117. # alert until the spool goes back above the threshold and crosses it
  5118. # again. Marking after a successful send would trade that for
  5119. # re-alerting on every pass while a provider is down -- which is the
  5120. # repetition the whole debounce exists to prevent, and the louder of
  5121. # the two failures. A spool that is low stays low, so the next real
  5122. # signal is not far away; a provider stuck retrying is a signal that
  5123. # never stops.
  5124. if send_notification:
  5125. self._notified_filament_low.add(key)
  5126. if send_relay:
  5127. self._relayed_filament_low.add(key)
  5128. if printer_id not in printers:
  5129. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5130. if printer is None:
  5131. continue
  5132. printers[printer_id] = printer
  5133. printer = printers[printer_id]
  5134. slot = _ams_slot_label(ams_id, tray_id)
  5135. if send_notification:
  5136. try:
  5137. await notification_service.on_filament_low(
  5138. printer_id,
  5139. printer.name,
  5140. slot,
  5141. int(pct),
  5142. db,
  5143. color=color,
  5144. )
  5145. except Exception as e:
  5146. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  5147. if send_relay:
  5148. try:
  5149. await mqtt_relay.on_filament_low(
  5150. printer_id, printer.name, printer.serial_number, slot, int(pct), color, spool_id
  5151. )
  5152. except Exception as e:
  5153. logger.warning("Low-filament MQTT relay event failed for slot %s: %s", key, e)
  5154. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  5155. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  5156. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  5157. a schema field, a template and a UI toggle, and nothing that computes the
  5158. condition -- the Forecast panel does it in the browser, so with no page
  5159. open nothing could ever alert. This runs the same arithmetic
  5160. (``stock_forecast``) from the scheduler loop.
  5161. An alert is sent when a SKU *moves into* a condition, once, and again
  5162. after the condition has cleared. A SKU that worsens from reorder to break
  5163. alerts again as a break, because the panel treats the two as exclusive; one
  5164. that eases from break back to reorder does not alert again.
  5165. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  5166. while it is still low tells you.
  5167. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  5168. loop runs every 3 s while an upload is in flight, and the whole spool
  5169. collection is read over HTTP in Spoolman mode. Both events default to off
  5170. on every provider, so nothing is read unless a provider wants one.
  5171. """
  5172. now = time.monotonic()
  5173. if now < self._stock_forecast_next_check:
  5174. return
  5175. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  5176. try:
  5177. if self._stock_alerts_persisted is None:
  5178. await self._load_stock_alerts(db)
  5179. wanted = {
  5180. "reorder": bool(
  5181. await notification_service._get_providers_for_event(db, "on_stock_reorder_alert", fleet_wide=True)
  5182. ),
  5183. "break": bool(
  5184. await notification_service._get_providers_for_event(db, "on_stock_break_alert", fleet_wide=True)
  5185. ),
  5186. }
  5187. if not any(wanted.values()):
  5188. # Nobody wants either event. Forget what was sent, so whoever
  5189. # switches one on is told about the SKUs that are low now.
  5190. self._notified_stock_alerts.clear()
  5191. await self._save_stock_alerts(db)
  5192. return
  5193. forecasts = await self._stock_forecasts(db)
  5194. if forecasts is None:
  5195. # Spoolman unreachable. Deliberately not clearing the notified
  5196. # set: a brief outage would otherwise re-alert every SKU when it
  5197. # came back.
  5198. return
  5199. await self._emit_stock_alerts(db, forecasts, wanted)
  5200. await self._save_stock_alerts(db)
  5201. except Exception as e:
  5202. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  5203. def _serialize_stock_alerts(self) -> str:
  5204. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  5205. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  5206. return json.dumps(rows)
  5207. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  5208. """Read the notified set saved by the last run, once per process.
  5209. A missing or unreadable row is an empty set: the worst that does is one
  5210. repeat of what a restart used to cause every time.
  5211. """
  5212. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  5213. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  5214. if raw and raw.value:
  5215. try:
  5216. for key, kind, events in json.loads(raw.value):
  5217. if len(key) == 4 and kind in ("reorder", "break"):
  5218. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  5219. except (ValueError, TypeError):
  5220. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  5221. loaded = {}
  5222. self._notified_stock_alerts = loaded
  5223. self._stock_alerts_persisted = self._serialize_stock_alerts()
  5224. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  5225. """Write the notified set to its settings row if it changed since it was last read or written."""
  5226. serialized = self._serialize_stock_alerts()
  5227. if serialized == self._stock_alerts_persisted:
  5228. return
  5229. from backend.app.core.db_dialect import upsert_setting
  5230. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  5231. await db.commit()
  5232. self._stock_alerts_persisted = serialized
  5233. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  5234. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  5235. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  5236. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  5237. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  5238. sku_settings = {
  5239. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  5240. lead_time_days=row.lead_time_days,
  5241. safety_margin_value=row.safety_margin_value,
  5242. safety_margin_unit=row.safety_margin_unit,
  5243. alerts_snoozed=bool(row.alerts_snoozed),
  5244. )
  5245. for row in sku_rows
  5246. }
  5247. if await self._get_bool_setting(db, "spoolman_enabled"):
  5248. spools = await self._stock_spools_spoolman()
  5249. if spools is None:
  5250. return None
  5251. # The Spoolman spools' own rows (#3407), keyed by Spoolman id. Never
  5252. # the built-in ones: a Spoolman id that matches a local spool id
  5253. # (left over from before Spoolman was switched on) would borrow an
  5254. # unrelated spool's history (#3406).
  5255. history = await self._stock_usage_history(db, spoolman=True)
  5256. history = {
  5257. spool.id: stock_forecast.own_records(spool, history[spool.id])
  5258. for spool in spools
  5259. if spool.id in history
  5260. }
  5261. else:
  5262. spools = await self._stock_spools_internal(db)
  5263. history = await self._stock_usage_history(db)
  5264. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  5265. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  5266. from backend.app.models.spool import Spool
  5267. # Every spool: stock, the recently archived ones that count towards the
  5268. # rate, and the older ones that tell it the SKU was in use before its
  5269. # window (#3407). stock_forecast.forecast_all sorts them.
  5270. rows = (await db.execute(select(Spool))).scalars().all()
  5271. return [
  5272. stock_forecast.StockSpool(
  5273. id=spool.id,
  5274. material=spool.material,
  5275. subtype=spool.subtype,
  5276. brand=spool.brand,
  5277. color_name=spool.color_name,
  5278. label_weight=float(spool.label_weight or 0),
  5279. weight_used=float(spool.weight_used or 0),
  5280. weight_used_baseline=float(spool.weight_used_baseline or 0),
  5281. created_at=spool.created_at,
  5282. archived_at=spool.archived_at,
  5283. last_used_at=spool.last_used,
  5284. )
  5285. for spool in rows
  5286. ]
  5287. async def _stock_usage_history(
  5288. self, db: AsyncSession, *, spoolman: bool = False
  5289. ) -> dict[int, list[stock_forecast.UsageRecord]]:
  5290. """Usage rows by spool id, for one inventory: its own ids, as the forecast
  5291. panel reads them from the usage endpoint."""
  5292. from backend.app.models.spool_usage_history import SpoolUsageHistory
  5293. spool_id = SpoolUsageHistory.spoolman_spool_id if spoolman else SpoolUsageHistory.spool_id
  5294. rows = (
  5295. await db.execute(
  5296. select(spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  5297. .where(
  5298. SpoolUsageHistory.spoolman_spool_id.is_not(None)
  5299. if spoolman
  5300. else SpoolUsageHistory.spoolman_spool_id.is_(None)
  5301. )
  5302. .order_by(SpoolUsageHistory.created_at.desc())
  5303. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  5304. )
  5305. ).all()
  5306. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  5307. for spool_id, created_at, weight_used in rows:
  5308. # A deleted spool's usage forecasts no stock. Skipped here rather than
  5309. # filtered before the limit, so the window matches the forecast panel's.
  5310. if created_at is None or spool_id is None:
  5311. continue
  5312. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  5313. return history
  5314. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  5315. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  5316. Archived ones too: a recently used-up spool counts towards its SKU's
  5317. rate (#3399). ``_map_spoolman_spool`` is the same mapping the Inventory
  5318. page (and so the panel) reads; it dates archiving by the spool's last
  5319. use, as Spoolman records no archive date.
  5320. """
  5321. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  5322. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  5323. client = await get_spoolman_client()
  5324. if client is None:
  5325. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  5326. return None
  5327. try:
  5328. raw_spools = await client.get_all_spools(allow_archived=True)
  5329. except SpoolmanUnavailableError as e:
  5330. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  5331. return None
  5332. spools: list[stock_forecast.StockSpool] = []
  5333. for raw in raw_spools:
  5334. try:
  5335. mapped = _map_spoolman_spool(raw)
  5336. except ValueError:
  5337. continue
  5338. created_at = _spoolman_time(mapped.get("created_at"))
  5339. archived_at = None
  5340. if raw.get("archived"):
  5341. # Archived without a date to tell when: not stock, and too old to
  5342. # count towards the rate.
  5343. archived_at = _spoolman_time(mapped.get("archived_at")) or datetime(1970, 1, 1, tzinfo=timezone.utc)
  5344. spools.append(
  5345. stock_forecast.StockSpool(
  5346. id=mapped["id"],
  5347. material=mapped["material"],
  5348. subtype=mapped.get("subtype"),
  5349. brand=mapped.get("brand"),
  5350. color_name=mapped.get("color_name"),
  5351. label_weight=float(mapped.get("label_weight") or 0),
  5352. weight_used=float(mapped.get("weight_used") or 0),
  5353. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  5354. created_at=created_at,
  5355. archived_at=archived_at,
  5356. first_used_at=_spoolman_time(mapped.get("first_used")),
  5357. last_used_at=_spoolman_time(mapped.get("last_used")),
  5358. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  5359. )
  5360. )
  5361. return spools
  5362. async def _emit_stock_alerts(
  5363. self,
  5364. db: AsyncSession,
  5365. forecasts: stock_forecast.ForecastMap,
  5366. wanted: dict[str, bool],
  5367. ) -> None:
  5368. """Send the notifications for each SKU that has moved into a stock alert condition.
  5369. A SKU in break has also reached its reorder point, so both events apply to
  5370. it: the break event goes to providers that have it on, and the reorder event
  5371. to the providers that have only that one on. A provider with both on gets the
  5372. break and no second message.
  5373. What is remembered per SKU is the condition and which events had a
  5374. subscriber when it was sent. An event with no subscriber is forgotten, so
  5375. switching it on later reports the SKUs already in that condition.
  5376. """
  5377. active_events = {event for event, on in wanted.items() if on}
  5378. for key, (forecast, spool) in forecasts.items():
  5379. kind: str | None = None
  5380. if not forecast.snoozed:
  5381. if forecast.stock_break_alert:
  5382. kind = "break"
  5383. elif forecast.reorder_alert:
  5384. kind = "reorder"
  5385. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  5386. events = applicable & active_events
  5387. if not events:
  5388. self._notified_stock_alerts.pop(key, None)
  5389. continue
  5390. previous = self._notified_stock_alerts.get(key)
  5391. told = (previous[1] & active_events) if previous else frozenset()
  5392. # Trimmed to the events this condition can send. That is what makes easing from
  5393. # break back to reorder silent (the reorder event was told with the break) and
  5394. # worsening again news again (the break event is no longer remembered).
  5395. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  5396. # Recorded before sending, for the reason _emit_filament_low gives: a
  5397. # provider that is down should lose this alert, not repeat it every hour.
  5398. to_send = events - told
  5399. # Both flags imply a positive rate and so a day count.
  5400. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  5401. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  5402. color = None if spool.color_name_is_synthesized else spool.color_name
  5403. try:
  5404. if "break" in to_send:
  5405. await notification_service.on_stock_break_alert(
  5406. spool.material,
  5407. spool.brand,
  5408. forecast.remaining_g,
  5409. rate,
  5410. days_left,
  5411. forecast.effective_lead_time_days,
  5412. db,
  5413. subtype=spool.subtype,
  5414. color=color,
  5415. )
  5416. if "reorder" in to_send:
  5417. await notification_service.on_stock_reorder_alert(
  5418. spool.material,
  5419. spool.brand,
  5420. forecast.remaining_g,
  5421. rate,
  5422. days_left,
  5423. db,
  5424. subtype=spool.subtype,
  5425. color=color,
  5426. skip_break_subscribers=kind == "break",
  5427. )
  5428. except Exception as e:
  5429. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  5430. # A SKU with no spools left is no longer alerting.
  5431. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  5432. del self._notified_stock_alerts[key]
  5433. @staticmethod
  5434. async def _creator_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  5435. """The printers a job's creator may use (#1727), as the queue pass reads them."""
  5436. from backend.app.core.auth import is_auth_enabled
  5437. if user_id is None or not await is_auth_enabled(db):
  5438. return ALL_PRINTERS
  5439. return await resolve_user_id_printer_scope(db, user_id)
  5440. async def _model_job_printer_ids(
  5441. self,
  5442. db: AsyncSession,
  5443. item: PrintQueueItem,
  5444. scope: PrinterScope,
  5445. cache: dict[tuple[str, str | None, int | None], set[int]],
  5446. ) -> set[int]:
  5447. """Every printer an "Any <model>" job could land on: the active printers
  5448. of each of its candidate models, in its location, that its creator may use.
  5449. ``cache`` holds one lookup per model, location and creator for the pass,
  5450. so a long queue of model jobs does not query once per job."""
  5451. printer_ids: set[int] = set()
  5452. for candidate in _candidates_for(item):
  5453. if not candidate.target_model:
  5454. continue
  5455. key = (candidate.target_model, item.target_location, item.created_by_id)
  5456. if key not in cache:
  5457. printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
  5458. cache[key] = {printer.id for printer in printers}
  5459. printer_ids |= cache[key]
  5460. return printer_ids
  5461. async def _check_auto_drying(
  5462. self,
  5463. db: AsyncSession,
  5464. queue_items: list[PrintQueueItem],
  5465. dispatching_printers: set[int],
  5466. ):
  5467. """Start drying on idle printers based on humidity.
  5468. Three modes (can all be enabled independently):
  5469. - queue_drying_enabled: Dry between scheduled queue prints
  5470. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  5471. - print_drying_enabled: Also evaluate printers that are currently printing,
  5472. when model+firmware supports "Print While Drying" (gated by
  5473. supports_drying_while_printing). Drying temperature is capped at
  5474. max(40, preset_temp - 5) to protect spools mid-print.
  5475. """
  5476. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  5477. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  5478. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  5479. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  5480. # The wait belongs to ambient drying: the settings UI only shows it while
  5481. # ambient drying is on, so a value left behind when ambient is turned off
  5482. # must not keep delaying the one path that still reaches the wait gate
  5483. # without it (a mid-print start under print_drying).
  5484. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  5485. # Clear every streak as soon as the wait is inactive. An early return (or
  5486. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  5487. # a quick toggle-on inherit an old streak.
  5488. if not sustained_wait_active:
  5489. self._auto_dry_above.clear()
  5490. if not queue_drying_enabled and not ambient_drying_enabled:
  5491. # Stop active drying on all printers if both features disabled
  5492. if self._drying_in_progress:
  5493. for pid in list(self._drying_in_progress):
  5494. if pid in self._scheduled_drying_printer_ids:
  5495. continue
  5496. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  5497. await self._stop_drying(pid)
  5498. return
  5499. # Update drying state from printer status (handles backend restart)
  5500. self._sync_drying_state()
  5501. # Find printers with scheduled items (for queue drying mode)
  5502. # An "Any <model>" job counts for every printer it could land on.
  5503. printers_with_scheduled: set[int] = set()
  5504. # Printers with a job that could start now: the ones block mode keeps
  5505. # a new cycle off. A job waiting for its start time is what queue
  5506. # drying dries ahead of.
  5507. printers_with_ready_items: set[int] = set()
  5508. now_utc = datetime.now(timezone.utc)
  5509. creator_scopes: dict[int | None, PrinterScope] = {}
  5510. model_printers: dict[tuple[str, str | None, int | None], set[int]] = {}
  5511. for item in queue_items:
  5512. if item.printer_id:
  5513. item_printers = {item.printer_id}
  5514. elif item.target_model or item.variants:
  5515. if item.created_by_id not in creator_scopes:
  5516. creator_scopes[item.created_by_id] = await self._creator_printer_scope(db, item.created_by_id)
  5517. item_printers = await self._model_job_printer_ids(
  5518. db, item, creator_scopes[item.created_by_id], model_printers
  5519. )
  5520. else:
  5521. continue
  5522. if item.scheduled_time and not item.manual_start:
  5523. printers_with_scheduled |= item_printers
  5524. sched = item.scheduled_time
  5525. if sched is not None and sched.tzinfo is None:
  5526. sched = sched.replace(tzinfo=timezone.utc)
  5527. if sched is None or sched <= now_utc:
  5528. printers_with_ready_items |= item_printers
  5529. # If only queue mode is on and no printers have scheduled items, stop drying
  5530. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  5531. # may still be eligible for mid-print drying regardless of queue state).
  5532. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  5533. for pid in list(self._drying_in_progress):
  5534. if pid in self._scheduled_drying_printer_ids:
  5535. continue
  5536. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  5537. await self._stop_drying(pid)
  5538. return
  5539. # Get humidity threshold (global fallback)
  5540. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  5541. setting = result.scalar_one_or_none()
  5542. global_humidity_threshold = int(setting.value) if setting else 60
  5543. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  5544. # to the global threshold for every AMS unit.
  5545. per_type_thresholds = await self._get_humidity_thresholds(db)
  5546. # Get drying presets
  5547. presets = await self._get_drying_presets(db)
  5548. # Determine if drying should be skipped for printers with pending items
  5549. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  5550. # Get all active printers
  5551. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  5552. for printer in all_printers.scalars():
  5553. pid = printer.id
  5554. # Resolve model+firmware up front — needed to decide whether this printer
  5555. # qualifies for mid-print drying (busy printer on capable hardware).
  5556. state = printer_manager.get_status(pid)
  5557. if not state:
  5558. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  5559. continue
  5560. model = printer_manager.get_model(pid)
  5561. firmware = state.firmware_version
  5562. # "Mid-print" has to mean the printer is actually printing (#2801).
  5563. # It used to be inferred from the dispatch set, which also holds
  5564. # printers that merely could not be dispatched to -- so a printer
  5565. # sitting in FINISH behind an unacknowledged plate was treated as
  5566. # printing, had its drying temperature capped by the mid-print
  5567. # spool protection, and was logged as (mid-print) while idle.
  5568. is_printing = state.state in _ACTIVE_PRINT_STATES
  5569. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  5570. # A printer whose print is running or imminent is left alone unless
  5571. # it can dry through it. `dispatching_printers` is deliberately the
  5572. # narrow set: running, held post-dispatch, or mid-upload.
  5573. if (is_printing or pid in dispatching_printers) and not mid_print:
  5574. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  5575. continue
  5576. if not mid_print:
  5577. # In queue-only mode, only dry printers that have scheduled prints
  5578. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  5579. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  5580. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  5581. await self._stop_drying(pid)
  5582. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  5583. continue
  5584. # When block mode is on, don't START new drying on printers with
  5585. # a job that could start now: the cycle would hold it. One
  5586. # scheduled for later may pre-dry; if the cycle is still running
  5587. # at its time, the hold applies then. Already-drying printers go
  5588. # through so humidity auto-stop logic still runs.
  5589. if block_for_drying and pid in printers_with_ready_items and not self._drying_in_progress.get(pid):
  5590. logger.debug("Auto-drying: printer %d skipped — has a job ready to start (block mode)", pid)
  5591. continue
  5592. if not printer_manager.is_connected(pid):
  5593. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  5594. continue
  5595. # Plate-clear is deliberately ignored here (#2801). It answers
  5596. # "is the bed ready for the next job", which says nothing about
  5597. # whether the AMS may heat -- and the gap between a finished print
  5598. # and the acknowledgment is exactly when drying is most useful,
  5599. # because the printer is free and nobody is waiting on it. Leaving
  5600. # the plate unacknowledged is also how people hold the queue by
  5601. # hand, and that hold should not cost them their drying.
  5602. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  5603. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  5604. continue
  5605. # Check drying capability. For mid-print path, supports_drying_while_printing
  5606. # was already verified when computing mid_print above.
  5607. if not mid_print and not supports_drying(model, firmware):
  5608. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  5609. continue
  5610. # Check each AMS unit from raw_data
  5611. ams_list = state.raw_data.get("ams", [])
  5612. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  5613. for ams_data in ams_list:
  5614. module_type = str(ams_data.get("module_type") or "")
  5615. ams_id = int(ams_data.get("id", 0))
  5616. # Only n3f/n3s support drying
  5617. if module_type not in ("n3f", "n3s"):
  5618. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  5619. continue
  5620. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  5621. # Most-restrictive of all loaded tray types; falls back to the
  5622. # global threshold when no overrides are configured.
  5623. trays = ams_data.get("tray", []) or []
  5624. humidity_threshold = self.resolve_humidity_threshold(
  5625. trays, per_type_thresholds, global_humidity_threshold
  5626. )
  5627. dry_time = int(ams_data.get("dry_time") or 0)
  5628. # Read humidity as a percentage. The 1-5 index is never
  5629. # substituted: it is inverted, and being unable to exceed any
  5630. # threshold it would read as "dry" forever (#3140). ``None``
  5631. # already means "skip this unit" everywhere below.
  5632. humidity_pct = ams_humidity_percent(ams_data)
  5633. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  5634. unit_key = (pid, ams_id)
  5635. unit_state = self._auto_dry_units.get(unit_key)
  5636. # Already drying — let it run to its configured duration (#1892).
  5637. #
  5638. # We deliberately do NOT stop drying from a humidity re-check here.
  5639. # Relative humidity drops steeply in heated air, so the AMS sensor
  5640. # reads ~15-20% within minutes of the dryer starting even while the
  5641. # filament is still saturated. A humidity-based early-stop therefore
  5642. # always fires at the minimum-time floor, truncating both user-started
  5643. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  5644. # The firmware stops when the configured duration elapses; scheduling
  5645. # stops (print takes priority, queue no longer needs drying) are
  5646. # handled separately via _stop_drying().
  5647. if dry_time > 0:
  5648. if pid not in self._drying_in_progress:
  5649. # Drying we didn't start (manual or from before restart) —
  5650. # track it so scheduling stops still apply; never auto-stop it.
  5651. self._drying_in_progress[pid] = time.monotonic()
  5652. if unit_state is not None:
  5653. unit_state["running"] = True
  5654. logger.debug(
  5655. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  5656. pid,
  5657. ams_id,
  5658. dry_time,
  5659. humidity,
  5660. )
  5661. continue
  5662. # Nothing is drying. Close out a cycle we armed ourselves and
  5663. # judge whether it achieved anything (#2770).
  5664. #
  5665. # "Achieved anything" is measured against the LOWEST reading any
  5666. # cycle on this unit has ended at, not against the threshold and
  5667. # not against the previous cycle. A spool that is genuinely wet
  5668. # in a humid room comes down slowly — 40, 37, 35 — and must be
  5669. # allowed to keep going for as long as it is still coming down,
  5670. # however far it still is from the threshold. What must not
  5671. # continue is a cycle that ends exactly where the last one did,
  5672. # which is the reporter's signature: 15, 15, 16, 15, forever.
  5673. # Comparing against the running minimum rather than the previous
  5674. # end is what stops a sensor oscillating by one point between two
  5675. # values from reading as progress every other cycle.
  5676. if unit_state is not None and unit_state.pop("running", False):
  5677. unit_state["ended_at"] = time.monotonic()
  5678. # The streak that armed this cycle is spent; the next one
  5679. # starts fresh (and accumulates through the re-arm cooldown
  5680. # below, so the wait overlaps the cooldown, never stacks on
  5681. # top of it).
  5682. self._auto_dry_above.pop(unit_key, None)
  5683. if humidity is not None and humidity > humidity_threshold:
  5684. best = unit_state.get("best_end_humidity")
  5685. if isinstance(best, int) and humidity < best:
  5686. # Still coming down. Keep going, however far the
  5687. # threshold still is.
  5688. unproductive = 0
  5689. else:
  5690. unproductive = int(unit_state.get("unproductive", 0)) + 1
  5691. if not isinstance(best, int) or humidity < best:
  5692. unit_state["best_end_humidity"] = humidity
  5693. unit_state["unproductive"] = unproductive
  5694. logger.info(
  5695. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  5696. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  5697. pid,
  5698. ams_id,
  5699. humidity,
  5700. humidity_threshold,
  5701. unit_state.get("best_end_humidity"),
  5702. unproductive,
  5703. )
  5704. # A cycle that ended at or below the threshold needs no
  5705. # counter reset here: the branch below drops the whole entry.
  5706. # Humidity below threshold — no need to start drying. This is
  5707. # also the only thing that lifts a suspension: the reading we
  5708. # gave up on has come down, so auto-drying works again and the
  5709. # unit goes back to having no history at all.
  5710. if humidity is None or humidity <= humidity_threshold:
  5711. if unit_state is not None and unit_state.get("suspended"):
  5712. logger.info(
  5713. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  5714. "threshold, resuming automatic drying",
  5715. pid,
  5716. ams_id,
  5717. humidity,
  5718. humidity_threshold,
  5719. )
  5720. # Clear the judgement, keep the clock (#2801). Dropping the
  5721. # whole entry also dropped `ended_at`, and with it the
  5722. # 30-minute cooldown -- so a reading that dips to the
  5723. # threshold as the AMS cools and comes back above it once
  5724. # warm wiped its own history and re-armed immediately. That
  5725. # oscillation is the very thing #2770's cooldown exists to
  5726. # ride out, and it is worst at exactly the margin that makes
  5727. # a unit dry repeatedly: a point or two above the threshold.
  5728. if unit_state is not None:
  5729. unit_state.pop("suspended", None)
  5730. unit_state.pop("unproductive", None)
  5731. unit_state.pop("best_end_humidity", None)
  5732. # A real below-threshold reading ends any sustained-wait
  5733. # streak (#2518) -- "continuously above" means exactly that.
  5734. # An absent reading (humidity is None) is no-information and
  5735. # leaves the streak alone; the observation-gap guard handles
  5736. # a prolonged sensor silence.
  5737. if humidity is not None:
  5738. _above = self._auto_dry_above.pop(unit_key, None)
  5739. if _above is not None and sustained_wait_active:
  5740. logger.info(
  5741. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  5742. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5743. pid,
  5744. ams_id,
  5745. humidity,
  5746. time.monotonic() - _above["since"],
  5747. sustained_minutes,
  5748. humidity_threshold,
  5749. )
  5750. logger.debug(
  5751. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5752. pid,
  5753. ams_id,
  5754. humidity,
  5755. humidity_threshold,
  5756. )
  5757. continue
  5758. # Sustained-humidity streak (#2518): updated on every pass that
  5759. # observes the reading above the threshold, BEFORE the
  5760. # suspension/cooldown gates below -- a suspended or cooling-down
  5761. # unit still accumulates streak time, so the wait overlaps those
  5762. # gates instead of stacking after them. Inert when the feature
  5763. # is off: no entries are written, and an entry left over from a
  5764. # toggle-off is dropped so it cannot seed a stale streak later.
  5765. if sustained_wait_active:
  5766. _now = time.monotonic()
  5767. # Four missed scheduler passes, floored: a single slow pass
  5768. # must not void a streak, but the ceiling has to scale with
  5769. # the cadence or a slow loop silently restarts every streak.
  5770. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5771. _above = self._auto_dry_above.get(unit_key)
  5772. if _above is None:
  5773. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5774. elif _now - _above["last"] > _gap_ceiling:
  5775. # Restart, and say so at the same level as the dip
  5776. # reset: a silent restart voids the streak invisibly,
  5777. # and a user who set a long wait and never gets a dry
  5778. # has no way to see why.
  5779. logger.info(
  5780. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5781. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5782. pid,
  5783. ams_id,
  5784. _now - _above["last"],
  5785. _gap_ceiling,
  5786. sustained_minutes,
  5787. )
  5788. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5789. else:
  5790. _above["last"] = _now
  5791. else:
  5792. self._auto_dry_above.pop(unit_key, None)
  5793. if unit_state is not None:
  5794. if unit_state.get("suspended"):
  5795. logger.debug(
  5796. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5797. "above the %d%% threshold",
  5798. pid,
  5799. ams_id,
  5800. int(unit_state.get("unproductive", 0)),
  5801. humidity_threshold,
  5802. )
  5803. continue
  5804. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5805. unit_state["suspended"] = True
  5806. logger.warning(
  5807. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5808. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5809. "higher while it is warm, so a threshold in that range can never be reached and "
  5810. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5811. pid,
  5812. ams_id,
  5813. int(unit_state.get("unproductive", 0)),
  5814. humidity,
  5815. humidity_threshold,
  5816. )
  5817. await self._notify_auto_drying_suspended(
  5818. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5819. )
  5820. continue
  5821. ended_at = unit_state.get("ended_at")
  5822. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5823. logger.debug(
  5824. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5825. "cycle before the humidity reading is worth acting on",
  5826. pid,
  5827. ams_id,
  5828. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5829. )
  5830. continue
  5831. # Check cannot-dry reasons (power constraints etc.). Sits
  5832. # ahead of the sustained wait so a unit the firmware refuses
  5833. # to dry never logs a wait it was never going to cash in.
  5834. sf_reasons = ams_data.get("dry_sf_reason", [])
  5835. if sf_reasons:
  5836. logger.debug(
  5837. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5838. pid,
  5839. ams_id,
  5840. sf_reasons,
  5841. )
  5842. continue
  5843. # Sustained-humidity wait (#2518): ambient-triggered starts
  5844. # wait; only a printer with a scheduled queue item pending
  5845. # keeps the instant behavior, because that drying has a real
  5846. # deadline. Mid-print is deliberately NOT exempt while ambient
  5847. # drying is on: a humidity start on a printer that happens to be
  5848. # printing is as vulnerable to a lid-open spike as one on an idle
  5849. # printer (proven live: a 2-point threshold crossing mid-print
  5850. # bought a parked 12h command). Inactive when ambient drying is
  5851. # off: print_drying then still starts mid-print cycles on its own
  5852. # (#1816, "regardless of queue state"), and those stay instant.
  5853. if sustained_wait_active and pid not in printers_with_scheduled:
  5854. _above = self._auto_dry_above.get(unit_key)
  5855. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5856. if _waited < sustained_minutes * 60:
  5857. logger.debug(
  5858. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5859. "threshold for %.0fs of the required %dm",
  5860. pid,
  5861. ams_id,
  5862. humidity,
  5863. humidity_threshold,
  5864. _waited,
  5865. sustained_minutes,
  5866. )
  5867. continue
  5868. # Get conservative drying params for mixed filaments
  5869. params = self._get_conservative_drying_params(trays, module_type, presets)
  5870. if not params:
  5871. logger.debug(
  5872. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5873. )
  5874. continue
  5875. temp, duration_hours, filament_type = params
  5876. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5877. # "drying temperature must not exceed the filament's softening temperature"
  5878. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5879. # ineffective and firmware will reject anyway.
  5880. if mid_print:
  5881. temp = max(40, temp - 5)
  5882. # Start drying
  5883. logger.info(
  5884. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5885. "starting %s drying at %d°C for %dh%s",
  5886. pid,
  5887. ams_id,
  5888. humidity,
  5889. humidity_threshold,
  5890. filament_type,
  5891. temp,
  5892. duration_hours,
  5893. " (mid-print)" if mid_print else "",
  5894. )
  5895. success = printer_manager.send_drying_command(
  5896. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5897. )
  5898. if success:
  5899. self._drying_in_progress[pid] = time.monotonic()
  5900. armed = self._auto_dry_units.setdefault(
  5901. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5902. )
  5903. armed["running"] = True
  5904. async def _notify_auto_drying_suspended(
  5905. self,
  5906. db: AsyncSession,
  5907. printer: Printer,
  5908. ams_id: int,
  5909. humidity: int,
  5910. threshold: int,
  5911. cycles: int,
  5912. ) -> None:
  5913. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5914. Fires once per suspension — the caller sets ``suspended`` before calling
  5915. and every later pass short-circuits on it — because the whole point is
  5916. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5917. building needs that to reach them, and the hourly humidity alarm they
  5918. are already getting says the opposite of what happened here.
  5919. Never raises: a notification provider being down must not stop the
  5920. suspension itself from taking effect.
  5921. """
  5922. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5923. try:
  5924. await notification_service.on_ams_drying_suspended(
  5925. printer.id,
  5926. printer.name,
  5927. ams_label,
  5928. float(humidity),
  5929. float(threshold),
  5930. cycles,
  5931. db,
  5932. )
  5933. except Exception as e:
  5934. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5935. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5936. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5937. The unproductive-cycle counter exists to notice that *drying* is not
  5938. moving the humidity reading. A cycle that ended because somebody sent a
  5939. stop says nothing about that — it was cut short before it had a chance —
  5940. so counting it would suspend auto-drying for a reason that has nothing to
  5941. do with the loop the counter is there to break.
  5942. Two callers, both of them a stop Bambuddy is responsible for: the
  5943. print-takes-priority stop below, and the manual Stop button. Left
  5944. uncalled, an install that dries between queue jobs would suspend its own
  5945. auto-drying after two prints interrupted a dry — exactly the install
  5946. queue-drying exists for.
  5947. The rest of the unit's history is kept: the cooldown before re-arming
  5948. still applies, and an earlier count still stands.
  5949. """
  5950. state = self._auto_dry_units.get((printer_id, ams_id))
  5951. if state is not None:
  5952. state.pop("running", None)
  5953. state["ended_at"] = time.monotonic()
  5954. # A stopped cycle spends the streak that armed it, same as a completed
  5955. # one (#2518).
  5956. self._auto_dry_above.pop((printer_id, ams_id), None)
  5957. def _sync_drying_state(self):
  5958. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5959. One direction only: it prunes, it never adds. A printer drying without an
  5960. entry here — because the user started the cycle from Studio, the printer's
  5961. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5962. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5963. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5964. That is deliberate for now rather than an oversight: populating this from
  5965. telemetry would hand the scheduler authority to stop drying a user started
  5966. by hand. It also means the backend-restart case this used to claim to
  5967. handle is not handled.
  5968. """
  5969. to_remove = []
  5970. for pid in self._drying_in_progress:
  5971. state = printer_manager.get_status(pid)
  5972. if not state:
  5973. to_remove.append(pid)
  5974. continue
  5975. # Check if any AMS unit is still drying
  5976. ams_list = state.raw_data.get("ams", [])
  5977. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5978. if not any_drying:
  5979. to_remove.append(pid)
  5980. for pid in to_remove:
  5981. self._drying_in_progress.pop(pid, None)
  5982. # A printer that has gone away entirely takes its per-AMS auto-drying
  5983. # history with it (#2770), so a printer deleted and re-added does not
  5984. # inherit a suspension it never earned.
  5985. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5986. self._auto_dry_units.pop(key, None)
  5987. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5988. # printer starts a fresh wait, and vanished printers do not leak
  5989. # entries.
  5990. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5991. self._auto_dry_above.pop(key, None)
  5992. @staticmethod
  5993. def _drying_is_only_parked(printer_id: int) -> bool:
  5994. """True when every AMS unit with a drying timer on this printer is parked.
  5995. A parked timer (#2896: the command was taken but the countdown never
  5996. runs) does not end on its own, so nothing may wait on it. False when no
  5997. unit reports a timer yet -- a command just sent that the firmware has not
  5998. reported back is real drying about to begin.
  5999. """
  6000. state = printer_manager.get_status(printer_id)
  6001. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  6002. timed = []
  6003. for unit in units:
  6004. try:
  6005. if int(unit.get("dry_time") or 0) > 0:
  6006. timed.append(unit)
  6007. except (TypeError, ValueError):
  6008. continue
  6009. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  6010. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  6011. """True when a running cycle can be left alone while the next print runs.
  6012. Some hardware dries happily through a print and #2758 settled that we
  6013. should not tear those cycles down: the X2D there was refusing to
  6014. *start* a job, which is a different problem, and stopping drying before
  6015. every dispatch would throw away cycles the printer was content to run.
  6016. Where the model cannot do it, or the user has not enabled it, the print
  6017. takes priority and the cycle stops -- which is what the queue_drying_block
  6018. setting has always promised in its off position.
  6019. """
  6020. if not await self._get_bool_setting(db, "print_drying_enabled"):
  6021. return False
  6022. status = printer_manager.get_status(printer_id)
  6023. return supports_drying_while_printing(
  6024. printer_manager.get_model(printer_id),
  6025. status.firmware_version if status else None,
  6026. )
  6027. async def _stop_drying(self, printer_id: int):
  6028. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  6029. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  6030. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  6031. enough to kill a cycle the user had started by hand on a *different*
  6032. unit of the same printer (#2801). That contradicted the contract
  6033. ``_sync_drying_state`` already documents -- the entry gate deliberately
  6034. only knows about cycles Bambuddy began, so the action must not reach
  6035. past them either.
  6036. """
  6037. state = printer_manager.get_status(printer_id)
  6038. if not state:
  6039. self._drying_in_progress.pop(printer_id, None)
  6040. return
  6041. ams_list = state.raw_data.get("ams", [])
  6042. for ams_data in ams_list:
  6043. dry_time = int(ams_data.get("dry_time") or 0)
  6044. if dry_time > 0:
  6045. ams_id = int(ams_data.get("id", 0))
  6046. if (printer_id, ams_id) not in self._auto_dry_units:
  6047. logger.debug(
  6048. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  6049. printer_id,
  6050. ams_id,
  6051. )
  6052. continue
  6053. logger.info(
  6054. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  6055. printer_id,
  6056. ams_id,
  6057. )
  6058. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  6059. self.forget_auto_dry_cycle(printer_id, ams_id)
  6060. self._drying_in_progress.pop(printer_id, None)
  6061. # Scheduled manual drying (#2638) -----------------------------------
  6062. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  6063. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  6064. async def _check_scheduled_dryings(self, db: AsyncSession):
  6065. """Dispatch due scheduled drying runs and track running ones."""
  6066. now = utcnow_naive()
  6067. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  6068. # Monotonic, so a clock adjustment cannot park the prune for hours.
  6069. since_prune = time.monotonic()
  6070. if (
  6071. self._last_scheduled_drying_prune is None
  6072. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  6073. ):
  6074. self._last_scheduled_drying_prune = since_prune
  6075. await db.execute(
  6076. delete(ScheduledDrying).where(
  6077. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  6078. ScheduledDrying.completed_at.is_not(None),
  6079. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  6080. )
  6081. )
  6082. # Same order as the list route: with two rows due on one printer the
  6083. # earliest scheduled wins rather than whatever the DB hands back first.
  6084. result = await db.execute(
  6085. select(ScheduledDrying)
  6086. .where(ScheduledDrying.status.in_(("pending", "running")))
  6087. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  6088. )
  6089. rows = list(result.scalars().all())
  6090. # Rebuild from the DB every tick so route-side cancels and completions
  6091. # show up. Auto-drying's stop-all branches check this set before
  6092. # stopping anything (#2638).
  6093. # Kept from the previous pass so a run that ended between passes — a
  6094. # cancel through the route, say — can still be released below.
  6095. previously_running = self._scheduled_drying_printer_ids
  6096. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6097. running_printer_ids = set(self._scheduled_drying_printer_ids)
  6098. # Model and firmware come from the printer row, not the live state.
  6099. printer_ids = {row.printer_id for row in rows}
  6100. printers_by_id: dict[int, Printer] = {}
  6101. if printer_ids:
  6102. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  6103. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  6104. for row in rows:
  6105. if row.status == "running":
  6106. self._update_running_scheduled_drying(row, now)
  6107. continue
  6108. if row.start_after is not None and row.start_after > now:
  6109. continue
  6110. state = printer_manager.get_status(row.printer_id)
  6111. if not state:
  6112. row.waiting_reason = "printer_offline"
  6113. continue
  6114. # Same preflight the immediate endpoint runs. Without it the publish
  6115. # succeeds, the row goes to running, the printer ignores the command
  6116. # and the run silently cancels itself after the grace window.
  6117. printer = printers_by_id.get(row.printer_id)
  6118. unsupported = drying_preflight.check_drying_supported(
  6119. printer.model if printer else None, state.firmware_version
  6120. )
  6121. if unsupported:
  6122. row.status = "failed"
  6123. row.error_message = unsupported
  6124. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  6125. row.completed_at = now
  6126. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  6127. continue
  6128. if (
  6129. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  6130. ) or row.printer_id in running_printer_ids:
  6131. row.waiting_reason = "already_drying"
  6132. continue
  6133. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6134. row.waiting_reason = "printer_busy"
  6135. continue
  6136. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6137. if target is None:
  6138. row.waiting_reason = "ams_not_found"
  6139. continue
  6140. blocking = drying_preflight.blocking_reason_codes(target)
  6141. if blocking:
  6142. # Keep the power case distinct; it needs the user to act, so the
  6143. # card can say so instead of waiting silently.
  6144. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  6145. continue
  6146. filament = drying_preflight.resolve_filament(target, row.filament)
  6147. logger.info(
  6148. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  6149. row.id,
  6150. row.printer_id,
  6151. row.ams_id,
  6152. row.temp,
  6153. row.duration_hours,
  6154. )
  6155. success = printer_manager.send_drying_command(
  6156. row.printer_id,
  6157. row.ams_id,
  6158. row.temp,
  6159. row.duration_hours,
  6160. mode=1,
  6161. filament=filament,
  6162. rotate_tray=row.rotate_tray,
  6163. )
  6164. if success:
  6165. row.status = "running"
  6166. row.started_at = now
  6167. row.waiting_reason = None
  6168. row.filament = filament
  6169. self._drying_in_progress[row.printer_id] = time.monotonic()
  6170. self._scheduled_drying_printer_ids.add(row.printer_id)
  6171. running_printer_ids.add(row.printer_id)
  6172. else:
  6173. row.waiting_reason = "printer_offline"
  6174. # Release the printers whose run has ended. `_drying_in_progress` is
  6175. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  6176. # but that call sits behind the auto-drying enabled check, and this
  6177. # method is the one writer that runs whether auto-drying is on or not.
  6178. # With it off, nothing would ever drop the entry short of a print being
  6179. # dispatched to the same printer, so the next scheduled run would wait
  6180. # on "already_drying" forever and `queue_drying_block` would hold the
  6181. # printer's prints too. Covers a run that ended during this pass and one
  6182. # cancelled through the route between passes.
  6183. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  6184. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  6185. self._drying_in_progress.pop(printer_id, None)
  6186. await db.commit()
  6187. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  6188. """Detect completion or interruption of a running scheduled drying.
  6189. The firmware reports remaining minutes in ams.dry_time; 0 means not
  6190. drying. Within the grace window after start we ignore dry_time==0
  6191. (the status lags the command). After that, dry_time==0 near the end
  6192. of the configured duration means completed. Much earlier means the
  6193. run was stopped: re-queue it if a print preempted the dryer, but a
  6194. stop while the printer is idle was deliberate, so cancel the row
  6195. rather than restart drying the user just stopped.
  6196. """
  6197. if row.started_at is None:
  6198. row.started_at = now
  6199. return
  6200. elapsed = (now - row.started_at).total_seconds()
  6201. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  6202. return
  6203. state = printer_manager.get_status(row.printer_id)
  6204. if not state:
  6205. return # offline mid-dry; resolve when it reconnects
  6206. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  6207. # throw on a malformed id would cost the whole pass including print
  6208. # dispatch, every tick.
  6209. target = drying_preflight.find_ams_unit(state, row.ams_id)
  6210. try:
  6211. dry_time = int(target.get("dry_time") or 0) if target else 0
  6212. except (TypeError, ValueError):
  6213. dry_time = 0
  6214. if dry_time > 0 and is_countdown_parked(target):
  6215. # The printer took the command but the countdown is not running
  6216. # (#2896) and will never reach 0, so the run would stay "running"
  6217. # forever. A print in progress is the likely cause (the power budget
  6218. # is spent), so re-queue it like any interruption; the next start
  6219. # waits for the printer to be idle. Parked on an idle printer is a
  6220. # refusal, not something a retry fixes. The timer itself is left on
  6221. # the printer: it may yet start once power frees up.
  6222. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6223. logger.info(
  6224. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  6225. row.id,
  6226. row.ams_id,
  6227. )
  6228. row.status = "pending"
  6229. row.started_at = None
  6230. row.waiting_reason = "interrupted"
  6231. else:
  6232. logger.warning(
  6233. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  6234. row.id,
  6235. row.ams_id,
  6236. )
  6237. row.status = "failed"
  6238. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  6239. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  6240. row.completed_at = now
  6241. return
  6242. if dry_time > 0:
  6243. return
  6244. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  6245. row.status = "completed"
  6246. row.completed_at = now
  6247. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  6248. row.status = "pending"
  6249. row.started_at = None
  6250. row.waiting_reason = "interrupted"
  6251. else:
  6252. row.status = "cancelled"
  6253. row.completed_at = now
  6254. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  6255. """Get all smart plugs associated with a printer."""
  6256. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  6257. return list(result.scalars().all())
  6258. @staticmethod
  6259. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  6260. """Pick the plug to power-cycle a printer back online with (#2629).
  6261. Only a plug flagged ``controls_printer_power`` can actually bring the
  6262. printer back; waiting for a boot on an accessory (filter fan, lights)
  6263. just burns the power-on timeout and fails the dispatch. Falls back to
  6264. the first plug when none is flagged, which is the pre-#2629 behaviour.
  6265. Callers must pass a non-empty list.
  6266. """
  6267. for plug in auto_on_plugs:
  6268. if plug.controls_printer_power:
  6269. return plug
  6270. return auto_on_plugs[0]
  6271. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  6272. # chamber-temperature recommendations BambuStudio ships for the matching
  6273. # filament profile; users can override via Settings → Workflow → Preheat
  6274. # card. "default" applies when a loaded tray's normalised type isn't in
  6275. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  6276. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  6277. "PLA": 0,
  6278. "PETG": 0,
  6279. "PETG-CF": 40,
  6280. "ABS": 45,
  6281. "ASA": 45,
  6282. "PA": 50,
  6283. "PA-CF": 55,
  6284. "PC": 50,
  6285. "PC-FR": 50,
  6286. "TPU": 0,
  6287. "PVA": 0,
  6288. "default": 0,
  6289. }
  6290. @classmethod
  6291. def _bundled_preheat_targets(cls) -> dict[str, int]:
  6292. """The bundled map under the same key casing a parsed one gets.
  6293. The constant is declared with a lowercase ``default`` because that is
  6294. the key the Settings editor writes and displays. Every read of the map
  6295. happens after ``str(key).upper()``, so handing the constant back as
  6296. declared broke the contract the parser documents: an install that had
  6297. never touched the setting returned a dict with no ``DEFAULT`` in it,
  6298. and the resolution loop's fallback silently found nothing. It read the
  6299. right number only because the bundled default happens to be 0 -- change
  6300. that constant and every unconfigured install would keep preheating to
  6301. zero with no way to tell why.
  6302. """
  6303. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  6304. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  6305. """Parse the user-configured filament→chamber-target map, falling back
  6306. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  6307. are uppercased and the 'default' fallback is always present in the
  6308. returned dict so the resolution loop can index it unconditionally."""
  6309. raw = await self._get_setting(db, "preheat_filament_targets")
  6310. if not raw:
  6311. return self._bundled_preheat_targets()
  6312. try:
  6313. parsed = json.loads(raw)
  6314. if not isinstance(parsed, dict):
  6315. raise ValueError("not an object")
  6316. except (json.JSONDecodeError, ValueError) as exc:
  6317. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  6318. return self._bundled_preheat_targets()
  6319. # Coerce values to int; drop unparseable rows so a stray string
  6320. # doesn't crash the loop.
  6321. out: dict[str, int] = {}
  6322. for key, value in parsed.items():
  6323. try:
  6324. out[str(key).upper()] = int(value)
  6325. except (TypeError, ValueError):
  6326. continue
  6327. if "DEFAULT" not in out:
  6328. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  6329. return out
  6330. @staticmethod
  6331. def _normalize_filament_type(tray_type: str) -> str:
  6332. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  6333. existing drying-preset normalisation (split-at-space, upper-case) so
  6334. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  6335. "PA-CF" (no space to split on).
  6336. This is the first stage of ``_resolve_filament_key``, which goes on to
  6337. drop the suffix and consult the alias map; on its own it only decides
  6338. what the tray is called, not which row answers for it.
  6339. Indexing the split rather than testing the input: a tray_type of spaces
  6340. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  6341. it through to an IndexError.
  6342. """
  6343. words = (tray_type or "").split()
  6344. return words[0].upper() if words else ""
  6345. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  6346. """Per-filament chamber target for one tray's reported type, or 0 when
  6347. the tray is empty / RFID-less and reports no type at all.
  6348. A filled or foamed variant wants its base material's chamber when the
  6349. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  6350. not the 0 an unknown type falls to. The specific type is still tried
  6351. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  6352. (#2902).
  6353. That lookup is now the shared one, which adds the polyamide aliases on
  6354. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  6355. too, rather than the catch-all it was landing on (#3067).
  6356. """
  6357. if not self._normalize_filament_type(tray_type or ""):
  6358. return 0
  6359. key = self._resolve_filament_key(tray_type, targets)
  6360. if key is not None:
  6361. return targets[key]
  6362. # A type the map does not list at all, which is not the same as a tray
  6363. # with nothing in it -- that already returned 0 above.
  6364. return targets.get("DEFAULT", 0)
  6365. def _derive_chamber_target(
  6366. self,
  6367. printer: Printer,
  6368. targets: dict[str, int],
  6369. item: PrintQueueItem | None = None,
  6370. ) -> int:
  6371. """Chamber target for the trays this print actually loads: the max of
  6372. their per-filament targets. Returns 0 when there is nothing to read (no
  6373. status, no AMS telemetry — e.g. external-spool prints) or when every
  6374. tray considered maps to 0, and the chamber phase then short-circuits in
  6375. the main loop.
  6376. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  6377. Scanning the whole unit instead meant one ASA spool parked in the AMS
  6378. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  6379. plus soak burned ahead of each upload, on a printer whose chamber never
  6380. reaches the target anyway (#2886). An item with no usable mapping falls
  6381. back to scanning every loaded tray: that is the only signal left, and
  6382. narrowing to nothing would skip preheat on prints that genuinely need
  6383. it.
  6384. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  6385. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  6386. less slots have empty `tray_type` and contribute nothing. The external
  6387. spool is consulted only when the mapping names it (>= 254); it stays
  6388. out of the unnarrowed scan, so an item without a mapping derives from
  6389. the AMS alone exactly as before.
  6390. """
  6391. state = printer_manager.get_status(printer.id)
  6392. if state is None:
  6393. return 0
  6394. raw_data = state.raw_data or {}
  6395. used = _used_global_tray_ids(item)
  6396. ams_list = raw_data.get("ams")
  6397. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  6398. if isinstance(ams_list, dict):
  6399. ams_list = ams_list.get("ams") or []
  6400. if not isinstance(ams_list, list):
  6401. ams_list = []
  6402. best = 0
  6403. for ams in ams_list:
  6404. if not isinstance(ams, dict):
  6405. continue
  6406. ams_id = _int_or(ams.get("id"), 0)
  6407. for tray in ams.get("tray") or []:
  6408. # A non-dict entry has never been seen from real firmware, but
  6409. # `.get` on one raises, and nothing between here and
  6410. # `_dispatch_one`'s try/finally catches it — the item would be
  6411. # left holding its dispatch claim. Preheat is best-effort by
  6412. # contract, so step over it instead.
  6413. if not isinstance(tray, dict):
  6414. continue
  6415. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  6416. continue
  6417. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  6418. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  6419. for vt in raw_data.get("vt_tray") or []:
  6420. if not isinstance(vt, dict):
  6421. continue
  6422. # `_build_loaded_filaments` addresses external feeds by the id
  6423. # the firmware reports — 255 main, 254 deputy — defaulting to
  6424. # 254 when the field is absent. Same expression here so the two
  6425. # agree on which entry a mapping's 254/255 refers to.
  6426. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  6427. continue
  6428. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  6429. return best
  6430. def _release_keep_warm(self, pid: int) -> None:
  6431. """Release keep-warm on a printer that left the candidate set.
  6432. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  6433. reports the target we set (``entry.held_target``), so a user or
  6434. subsequent print that changed the bed target since is not clobbered.
  6435. Best-effort, never raises.
  6436. The entry is kept, not dropped, when the printer cannot be reached
  6437. right now: a printer that is briefly offline still has a hot bed, and
  6438. holding the entry is what keeps the max-duration timeout applying and
  6439. lets a later tick retry the release. Only a printer that has left the
  6440. manager entirely gives up on that, in ``_sample_chamber_temps``.
  6441. """
  6442. entry = self._keep_warm.get(pid)
  6443. if entry is None:
  6444. return
  6445. state = printer_manager.get_status(pid)
  6446. client = printer_manager.get_client(pid)
  6447. if state is None or client is None:
  6448. logger.debug(
  6449. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  6450. pid,
  6451. )
  6452. return
  6453. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6454. if int(cur_bed_target) != entry.held_target:
  6455. # Someone else owns the bed now, so there is nothing of ours to
  6456. # undo and nothing left to track.
  6457. logger.info(
  6458. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  6459. pid,
  6460. int(cur_bed_target),
  6461. entry.held_target,
  6462. )
  6463. self._keep_warm.pop(pid, None)
  6464. return
  6465. try:
  6466. client.set_bed_temperature(0)
  6467. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  6468. self._keep_warm.pop(pid, None)
  6469. except Exception as exc:
  6470. # Keep the entry so the next tick tries again rather than leaving
  6471. # the bed hot with nothing tracking it.
  6472. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  6473. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  6474. """Release printers that dropped out of the keep-warm candidate set.
  6475. Called from ``_apply_keep_warm`` on every tick (with the current
  6476. candidate set), and from ``check_queue``'s no-pending-items early
  6477. return (with an empty candidate set) so orphaned holds still get
  6478. released when the queue empties. Also called with an empty candidate
  6479. set when any of the three gate settings toggles off, so a printer
  6480. whose feature was disabled mid-hold gets its bed released.
  6481. Printers being dispatched this tick are excluded from the bed-off
  6482. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  6483. transient 0 in between would just churn against preheat. Ownership of
  6484. the hot bed transfers to the preheat rollback pin instead — if the
  6485. dispatch aborts before the print starts (failed upload, cancelled
  6486. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  6487. skips (e.g. the item has no bed_temperature metadata) the pin entry
  6488. is the ONLY thing standing between an aborted dispatch and a bed
  6489. left hot with no owner. A successful print start clears the pin and
  6490. the print's own gcode takes over, as usual.
  6491. """
  6492. for _pid in list(self._keep_warm):
  6493. if _pid in active_candidates:
  6494. continue
  6495. if _pid in dispatched:
  6496. handed_over = self._keep_warm.pop(_pid, None)
  6497. self._preheat_pin.setdefault(_pid, set()).add("bed")
  6498. if handed_over is not None:
  6499. self._preheat_pin_bed[_pid] = handed_over.held_target
  6500. continue
  6501. self._release_keep_warm(_pid)
  6502. async def _apply_keep_warm(
  6503. self,
  6504. db: AsyncSession,
  6505. items: list[PrintQueueItem],
  6506. dispatch_ids: list[int] | set[int],
  6507. busy_printers: set[int],
  6508. require_plate_clear: bool,
  6509. ) -> None:
  6510. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  6511. When a printer just finished a job (FINISH state) and the next queued
  6512. item needs chamber heating, hold the bed hot so the chamber stays warm
  6513. during the bed-clearing window. The bed is the chamber's heating
  6514. element here, not a print surface — nothing is printing during the
  6515. hold and the dispatched print's own preheat/gcode re-targets the bed —
  6516. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  6517. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  6518. aftermarket chamber heaters), raised to the item's own parsed
  6519. bed_temperature when that is higher. Items whose archive metadata has
  6520. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  6521. get a hold — chamber need is what gates the feature, not metadata.
  6522. Skips entirely for filaments that map to a 0°C chamber target
  6523. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  6524. names, so a hot-chamber spool it never touches does not hold the bed of
  6525. a PLA job (#2886). An item still awaiting its mapping is judged on the
  6526. whole unit, as every item was before. Printers being dispatched this
  6527. cycle are excluded:
  6528. ``_preheat_and_soak`` already handles their bed temperature.
  6529. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  6530. released to 0 and the entry is latched ``expired=True`` so
  6531. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  6532. MQTT: publish is skipped when firmware already has the target.
  6533. The release sweep runs BEFORE the engagement gate so a printer that
  6534. was owned by keep-warm still gets its bed released when any of the
  6535. three gate settings is toggled off mid-hold. The
  6536. ``check_queue`` early-return-when-no-items path also calls
  6537. ``_sweep_keep_warm`` directly to release orphaned holds.
  6538. """
  6539. dispatch_set = set(dispatch_ids)
  6540. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  6541. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  6542. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  6543. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  6544. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6545. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  6546. # Release sweep first — must run even when gate_open is False so a
  6547. # printer owned by keep-warm when a gate toggles off gets released.
  6548. self._sweep_keep_warm(
  6549. active_candidates=warm_candidates if gate_open else set(),
  6550. dispatched=dispatched_printers,
  6551. )
  6552. if not gate_open:
  6553. return
  6554. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6555. max_hold_seconds = (
  6556. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  6557. )
  6558. now_mono = time.monotonic()
  6559. filament_targets: dict[str, int] | None = None
  6560. for pid in warm_candidates:
  6561. entry = self._keep_warm.get(pid)
  6562. # Latched-expired: max-duration timeout already fired for this
  6563. # printer. Skip until the release sweep drops the entry (i.e.
  6564. # until the printer leaves the candidate set).
  6565. if entry is not None and entry.expired:
  6566. continue
  6567. # These two guards sit ahead of the max-duration check below, so an
  6568. # engaged hold only ages out while its printer is still reachable
  6569. # and still in FINISH. That is deliberate rather than a hole: with
  6570. # no status or no client there is no M140 to send anyway, and the
  6571. # elapsed check runs off `entry.started` so it fires on the first
  6572. # tick after the printer comes back. Leaving FINISH means the plate
  6573. # was cleared, which drops the printer out of `warm_candidates` and
  6574. # hands it to `_release_keep_warm` instead. The invariant worth
  6575. # preserving if this is ever reordered: every path out of an
  6576. # engaged hold ends in a bed-off, whether by timeout or release.
  6577. state = printer_manager.get_status(pid)
  6578. if state is None or state.state != "FINISH":
  6579. continue
  6580. client = printer_manager.get_client(pid)
  6581. if client is None:
  6582. continue
  6583. next_item = next((it for it in items if it.printer_id == pid), None)
  6584. if next_item is None:
  6585. continue
  6586. # Hold temperature: the configured keep-warm temp, raised to the
  6587. # item's own bed temp when the metadata reports a higher one. A
  6588. # missing bed_temperature (Orca gcode.3mf exports parse without
  6589. # one) does NOT skip the hold — chamber need gates the feature.
  6590. archive = next_item.archive
  6591. item_bed = await _queued_plate_bed_temperature(next_item, archive)
  6592. bed_target = max(item_bed, hold_temp)
  6593. if bed_target <= 0:
  6594. continue
  6595. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  6596. if explicit is not None:
  6597. chamber_needed = int(explicit) > 0
  6598. else:
  6599. if filament_targets is None:
  6600. filament_targets = await self._get_preheat_filament_targets(db)
  6601. printer_obj = await self._get_printer(db, pid)
  6602. chamber_needed = (
  6603. printer_obj is not None
  6604. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  6605. )
  6606. if not chamber_needed:
  6607. continue
  6608. # Seed the timer on first engagement; keep it on subsequent ticks
  6609. # (never re-seed — that would defeat the max-duration cap).
  6610. if entry is None:
  6611. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  6612. self._keep_warm[pid] = entry
  6613. elapsed = now_mono - entry.started
  6614. if elapsed > max_hold_seconds:
  6615. # Timeout: publish bed → 0 once (if firmware still holds our
  6616. # target) and latch expired. The entry stays until the release
  6617. # sweep drops it, preventing the next tick from re-seeding.
  6618. logger.warning(
  6619. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  6620. pid,
  6621. elapsed,
  6622. )
  6623. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6624. if int(cur_bed_target) == entry.held_target:
  6625. try:
  6626. client.set_bed_temperature(0)
  6627. except Exception as exc:
  6628. logger.warning(
  6629. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  6630. pid,
  6631. exc,
  6632. )
  6633. else:
  6634. logger.info(
  6635. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  6636. pid,
  6637. int(cur_bed_target),
  6638. entry.held_target,
  6639. )
  6640. entry.expired = True
  6641. continue
  6642. # Idempotence: skip publish when firmware already has our target.
  6643. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  6644. if int(cur_bed_target) == bed_target:
  6645. entry.held_target = bed_target
  6646. continue
  6647. try:
  6648. client.set_bed_temperature(bed_target)
  6649. entry.held_target = bed_target
  6650. logger.info(
  6651. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  6652. bed_target,
  6653. pid,
  6654. )
  6655. except Exception as exc:
  6656. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  6657. def _sample_chamber_temps(self) -> None:
  6658. """Record a chamber temperature sample for every connected printer.
  6659. Called once per scheduler tick (every 3–30 s). Entries older than
  6660. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  6661. Also evicts per-printer state whose printer_id is no longer registered
  6662. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  6663. """
  6664. now = time.monotonic()
  6665. cutoff = now - self._chamber_history_ttl
  6666. statuses = printer_manager.get_all_statuses()
  6667. known_pids = set(statuses.keys())
  6668. for pid, status in statuses.items():
  6669. if status is None or not status.connected:
  6670. continue
  6671. temps = status.temperatures or {}
  6672. chamber = temps.get("chamber")
  6673. if chamber is None:
  6674. continue
  6675. hist = self._chamber_history.setdefault(pid, deque())
  6676. hist.append((now, float(chamber)))
  6677. while hist and hist[0][0] < cutoff:
  6678. hist.popleft()
  6679. # Evict state for printers that are no longer registered with the manager.
  6680. # This is the one place a keep-warm entry is dropped without releasing
  6681. # the bed: the printer is gone from the manager, so there is no client
  6682. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  6683. # for printers that are merely unreachable, which is what makes this
  6684. # the terminal case rather than a silent leak.
  6685. for pid in list(self._chamber_history):
  6686. if pid not in known_pids:
  6687. self._chamber_history.pop(pid, None)
  6688. for pid in list(self._keep_warm):
  6689. if pid not in known_pids:
  6690. logger.info(
  6691. "Queue: dropping keep-warm state for printer %d — no longer registered",
  6692. pid,
  6693. )
  6694. self._keep_warm.pop(pid, None)
  6695. for pid in list(self._preheat_pin):
  6696. if pid not in known_pids:
  6697. self._preheat_pin.pop(pid, None)
  6698. self._preheat_pin_bed.pop(pid, None)
  6699. def _chamber_soak_remaining(
  6700. self,
  6701. printer_id: int,
  6702. chamber_target: float,
  6703. soak_seconds: int,
  6704. tolerance: float = 2.0,
  6705. ) -> int:
  6706. """Return how many seconds of soak time are still needed.
  6707. Credits the time the chamber has already spent at temperature against
  6708. the configured soak. The credit may not start earlier than any of:
  6709. * **The newest sample.** Nothing recent means the printer stopped
  6710. reporting mid-observation and the chamber may have cooled unseen, so
  6711. the full soak is required. (A 2 h history whose last reading is half
  6712. an hour old is not evidence of anything — the measured cooling rate
  6713. is fast enough to cross the threshold in that time.)
  6714. * **The most recent contiguous run of samples.** A gap wider than
  6715. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  6716. far side is not evidence of temperature.
  6717. * **The end of the most recent real dip below the threshold.**
  6718. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  6719. — see that constant for the thermal reasoning. A stray low reading is
  6720. an artifact, and treating it as cooling would discard a soak that
  6721. actually happened.
  6722. Returns ``soak_seconds`` when nothing can be credited (no history,
  6723. stale history, or the chamber is below the threshold right now) and 0
  6724. once the credited time covers the whole soak.
  6725. """
  6726. hist = self._chamber_history.get(printer_id)
  6727. if not hist:
  6728. return soak_seconds
  6729. now = time.monotonic()
  6730. newest_ts, newest_temp = hist[-1]
  6731. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6732. return soak_seconds # stale — no fresh evidence to credit
  6733. threshold = chamber_target - tolerance
  6734. if newest_temp < threshold:
  6735. return soak_seconds # below target right now; nothing is soaked
  6736. samples = list(hist)
  6737. # Earliest point we have unbroken observations for.
  6738. credit_from = samples[-1][0]
  6739. for i in range(len(samples) - 1, 0, -1):
  6740. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  6741. break
  6742. credit_from = samples[i - 1][0]
  6743. # Pull the credit forward to the end of the last significant dip. Each
  6744. # excursion is measured between the in-range readings that bracket it,
  6745. # so a lone stray sample is charged one sampling interval rather than
  6746. # zero, and the comparison errs towards calling a dip real.
  6747. i = 0
  6748. while i < len(samples):
  6749. if samples[i][1] >= threshold:
  6750. i += 1
  6751. continue
  6752. j = i
  6753. while j < len(samples) and samples[j][1] < threshold:
  6754. j += 1
  6755. # `newest_temp >= threshold` was checked above, so j is in range.
  6756. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6757. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6758. # Credit resumes at the last below-threshold sample rather than
  6759. # the first good one after it, so a recovered dip over-credits
  6760. # by up to one sampling interval — the opposite lean to the
  6761. # bracketing above. Both are bounded by the sample cadence and
  6762. # dwarfed by the grace period, so neither is worth the extra
  6763. # arithmetic to remove.
  6764. credit_from = max(credit_from, samples[j - 1][0])
  6765. i = j
  6766. return max(0, soak_seconds - int(now - credit_from))
  6767. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6768. """Tell an in-flight dispatch that its item no longer wants to print.
  6769. Called by the queue's cancel and delete routes. Those only write to the
  6770. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6771. observe — so preheat would keep heating for the rest of max_wait + soak
  6772. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6773. blocking every other queued item behind a print that is not happening.
  6774. Signalling in memory rather than re-reading the row keeps this off the
  6775. database entirely: no second session, no transaction held across a long
  6776. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6777. Bambuddy serves from a single uvicorn process with one scheduler task,
  6778. so the route and the dispatch always share this object. The flag is
  6779. advisory — dropping it (e.g. after a restart) only costs a wasted
  6780. preheat, never a wrongly-abandoned print.
  6781. Only ids with a dispatch actually in flight are recorded, so the set
  6782. stays bounded by the upload pool rather than growing once per cancelled
  6783. item for the life of the process. Skipping the rest loses nothing: an
  6784. item that is not in flight cannot start heating later either, because
  6785. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6786. the caller has already committed a terminal status (or deleted the row)
  6787. before calling this.
  6788. """
  6789. if item_id in self._inflight:
  6790. self._cancelled_dispatches.add(item_id)
  6791. # A print sent for it earlier that never started is not one any more.
  6792. self._forget_unstarted_print(item_id, unless_printing=False)
  6793. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6794. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6795. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6796. while it is parked, so the wait is chopped into
  6797. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6798. """
  6799. remaining = float(seconds)
  6800. while remaining > 0:
  6801. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6802. await asyncio.sleep(slice_secs)
  6803. remaining -= slice_secs
  6804. if item_id in self._cancelled_dispatches:
  6805. return False
  6806. return True
  6807. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6808. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6809. The full preheat stage does this as part of its own dispatch: an H2D
  6810. left in heating mode by the ABS job before it would otherwise cook the
  6811. PLA that follows. The skip path never reaches that code, so it calls
  6812. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6813. add to the rollback pin, because a flap set to cooling for a print that
  6814. needs no heat is where it should have been either way.
  6815. Best-effort like everything else in the stage: a refused command logs
  6816. and the dispatch carries on.
  6817. """
  6818. model = printer.model or ""
  6819. if not supports_airduct(model):
  6820. return
  6821. state = printer_manager.get_status(printer.id)
  6822. current = getattr(state, "airduct_mode", None) if state else None
  6823. if current == _AIRDUCT_MODE_COOLING:
  6824. return
  6825. client = printer_manager.get_client(printer.id)
  6826. if client is None:
  6827. return
  6828. try:
  6829. client.set_airduct_mode("cooling")
  6830. except Exception as exc:
  6831. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6832. async def _preheat_and_soak(
  6833. self,
  6834. db: AsyncSession,
  6835. item: PrintQueueItem,
  6836. printer: Printer,
  6837. archive: PrintArchive | None,
  6838. ) -> bool:
  6839. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6840. Returns True when the dispatch should carry on to the upload — including
  6841. every case where preheat is skipped, since a skipped preheat is not a
  6842. reason to abandon the print. Returns False only when the item stopped
  6843. wanting to be printed while the stage was waiting (cancelled or
  6844. deleted); the caller must then abandon the dispatch, and
  6845. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6846. Resolution order:
  6847. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6848. to the global `preheat_enabled` setting; 'on' forces the stage on
  6849. even if the global is off.
  6850. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6851. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6852. across the trays `item.ams_mapping` names (every loaded slot when
  6853. it names none).
  6854. 3. A target of 0 off the filament map skips the whole stage: the
  6855. materials this print loads want no chamber, so there is nothing to
  6856. soak for and the bed phase would only delay the upload (#3041).
  6857. An explicit 0 typed into the per-item override, or a per-item
  6858. 'on', still runs the bed phase and the soak — both are the user
  6859. asking for a warm bed in so many words.
  6860. 4. Three hardware tiers branch the wait loop:
  6861. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6862. send M141 to the resolved target, then wait for the chamber sensor
  6863. to reach it (or the max-wait timeout to elapse).
  6864. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6865. no M141; the bed is the only heat source, so we wait for the chamber
  6866. sensor to rise via bed radiation OR fall through on timeout.
  6867. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6868. temperature; the function just heats the bed and holds for the
  6869. configured soak duration.
  6870. The bed target comes from the archive's parsed metadata
  6871. (`bed_temperature`); if missing the preheat stage logs and returns
  6872. without dispatching anything, rather than guessing at a default that
  6873. might wreck filament setup.
  6874. Failures are logged but never re-raised — preheat is best-effort. A
  6875. printer that goes offline mid-soak, a refused gcode command, or a
  6876. missing temperature reading must not turn into a failed queue item; the
  6877. normal upload + start path runs immediately after this method returns.
  6878. """
  6879. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6880. if override == "off":
  6881. return True
  6882. if override == "inherit":
  6883. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6884. if not enabled:
  6885. return True
  6886. # override == "on" forces the stage on regardless of the global setting.
  6887. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6888. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6889. # Chamber target resolution:
  6890. # 1. Explicit per-item override beats everything (user knows best).
  6891. # 2. Otherwise derive from the filament types this print loads, via
  6892. # the per-filament target map. A PLA-only print derives 0 and the
  6893. # block below skips the stage without the user touching anything,
  6894. # even when an ASA spool is sitting in another slot of the same
  6895. # AMS (#2886).
  6896. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6897. if explicit_target is not None and explicit_target > 0:
  6898. chamber_target = int(explicit_target)
  6899. chamber_source = "item-override"
  6900. elif explicit_target == 0:
  6901. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6902. chamber_source = "item-override-zero"
  6903. else:
  6904. targets = await self._get_preheat_filament_targets(db)
  6905. chamber_target = self._derive_chamber_target(printer, targets, item)
  6906. chamber_source = "filament-map"
  6907. # Nothing to preheat *for*. A zero that came out of the filament map is
  6908. # the map saying this print's materials want no chamber conditioning --
  6909. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6910. # anyway heated the bed and then held it for the full soak, which
  6911. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6912. # own G-code sets the bed the moment it starts, so preheating it here
  6913. # only moves that heating ahead of the upload instead of overlapping
  6914. # with it, and the soak has no chamber to condition (#3041).
  6915. #
  6916. # An explicit statement from the user still runs the stage. Forcing the
  6917. # per-item override to 'on', or typing a chamber target of exactly 0,
  6918. # both mean "preheat the bed for this print" -- the second is
  6919. # documented as doing precisely that. Only the automatic path, the
  6920. # global toggle plus the filament map, short-circuits here.
  6921. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6922. logger.info(
  6923. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6924. "target, so there is nothing to soak for (override=%s model=%s)",
  6925. item.id,
  6926. override,
  6927. printer.model or "",
  6928. )
  6929. self._preheat_flap_to_cooling(item.id, printer)
  6930. return True
  6931. bed_target = await _queued_plate_bed_temperature(item, archive)
  6932. if bed_target <= 0:
  6933. # No bed temperature in the slicer metadata. When the print needs a
  6934. # hot chamber the bed is simply how we heat it, so fall back to the
  6935. # configured chamber-heating bed temperature rather than skipping
  6936. # the whole stage — otherwise the print starts with a cold chamber,
  6937. # which is exactly what preheat exists to prevent. Without a chamber
  6938. # requirement there is nothing to preheat *for*, so skip as before
  6939. # rather than guess a bed temperature for the print itself.
  6940. if chamber_target <= 0:
  6941. logger.info(
  6942. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6943. item.id,
  6944. )
  6945. return True
  6946. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6947. logger.info(
  6948. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6949. "%d°C to drive the chamber to %d°C",
  6950. item.id,
  6951. bed_target,
  6952. chamber_target,
  6953. )
  6954. client = printer_manager.get_client(printer.id)
  6955. if client is None:
  6956. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6957. return True
  6958. model = printer.model or ""
  6959. has_heater = supports_chamber_heater(model)
  6960. has_sensor = supports_chamber_temp(model)
  6961. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6962. # Fast path: if the chamber has been continuously above target for at
  6963. # least soak_seconds and the bed is already at temperature, skip the
  6964. # entire preheat stage. Typical case: keep-warm held the bed between
  6965. # consecutive same-material prints and the chamber never dropped.
  6966. if do_chamber and has_sensor and soak_seconds > 0:
  6967. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6968. if remaining == 0:
  6969. cur = printer_manager.get_status(printer.id)
  6970. if cur:
  6971. cur_temps = cur.temperatures or {}
  6972. if (
  6973. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6974. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6975. ):
  6976. logger.info(
  6977. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6978. "and bed is already at temperature (chamber history fast-path)",
  6979. item.id,
  6980. chamber_target,
  6981. soak_seconds,
  6982. )
  6983. # Still set targets to prevent cooling during the 3MF upload window.
  6984. # Register each successful set in the preheat pin so `_dispatch_one`
  6985. # unwinds them on any non-success exit.
  6986. pin = self._preheat_pin.setdefault(printer.id, set())
  6987. try:
  6988. client.set_bed_temperature(bed_target)
  6989. pin.add("bed")
  6990. self._preheat_pin_bed[printer.id] = bed_target
  6991. except Exception as exc:
  6992. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6993. if supports_airduct(model):
  6994. cur_airduct = getattr(cur, "airduct_mode", None)
  6995. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6996. try:
  6997. client.set_airduct_mode("heating")
  6998. # Only undo what we can see we replaced. `None`
  6999. # means no mode has been observed yet, and
  7000. # rolling that back to cooling would assert a
  7001. # state the printer never reported.
  7002. if cur_airduct == _AIRDUCT_MODE_COOLING:
  7003. pin.add("airduct")
  7004. except Exception as exc:
  7005. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  7006. if has_heater:
  7007. try:
  7008. client.set_chamber_temperature(chamber_target)
  7009. pin.add("chamber")
  7010. except Exception as exc:
  7011. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  7012. return True
  7013. logger.info(
  7014. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  7015. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  7016. item.id,
  7017. bed_target,
  7018. chamber_target if do_chamber else 0,
  7019. chamber_source,
  7020. override,
  7021. model,
  7022. has_heater,
  7023. has_sensor,
  7024. max_wait,
  7025. soak_seconds,
  7026. )
  7027. # Preheat rollback registry: everything we set below is recorded here so
  7028. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  7029. # (bed off, chamber off, airduct back to cooling) on any non-success
  7030. # exit. Populated as each command succeeds; consumed and cleared by
  7031. # `_dispatch_one`.
  7032. pin = self._preheat_pin.setdefault(printer.id, set())
  7033. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  7034. # cache the target locally so the polling reads below see consistent
  7035. # state (firmware MQTT echoes lag by ~1s).
  7036. try:
  7037. client.set_bed_temperature(bed_target)
  7038. pin.add("bed")
  7039. self._preheat_pin_bed[printer.id] = bed_target
  7040. except Exception as exc:
  7041. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  7042. return True
  7043. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  7044. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  7045. # left it on, regardless of M141. Default cooling actively vents the
  7046. # chamber, so a `chamber_target > 0` print with the flap stuck in
  7047. # cooling never converges — the heater fights the open exhaust. We
  7048. # flip the flap BEFORE M141 to "heating" when the preheat wants
  7049. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  7050. # on an H2D that was previously running ABS would otherwise stay in
  7051. # heating mode and overheat PLA). The current-state read keeps the
  7052. # command idempotent — no MQTT chatter when the flap is already where
  7053. # we want it.
  7054. if supports_airduct(model):
  7055. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  7056. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  7057. current_state = printer_manager.get_status(printer.id)
  7058. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  7059. if current_airduct != desired_id:
  7060. try:
  7061. client.set_airduct_mode(desired_airduct)
  7062. # As in the fast path: only pin a rollback for a flap we
  7063. # saw in cooling. `current_airduct` of None means no mode
  7064. # has been observed, so there is nothing to restore to.
  7065. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  7066. pin.add("airduct")
  7067. except Exception as exc:
  7068. logger.warning(
  7069. "Queue item %s: preheat airduct %s mode failed: %s",
  7070. item.id,
  7071. desired_airduct,
  7072. exc,
  7073. )
  7074. if do_chamber and has_heater:
  7075. try:
  7076. client.set_chamber_temperature(chamber_target)
  7077. pin.add("chamber")
  7078. except Exception as exc:
  7079. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  7080. # Release the pooled DB connection before the (potentially many-minute)
  7081. # heat-soak wait below (#2572). Every setting this method needs is read
  7082. # above; the wait/soak loop only polls printer_manager state and sleeps —
  7083. # it never touches the DB. Without this the caller's transaction sat
  7084. # "idle in transaction" for the whole soak, pinning one pooled connection
  7085. # per preheating printer. expire_on_commit=False keeps item/printer
  7086. # readable afterwards; there are no pending writes to lose here.
  7087. await db.commit()
  7088. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  7089. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  7090. # Poll every 3s — frequent enough for responsive logging without
  7091. # spamming the MQTT state stream. The "converged" predicate is:
  7092. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  7093. # AND
  7094. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  7095. BED_TOLERANCE = 2.0
  7096. CHAMBER_TOLERANCE = 2.0
  7097. POLL_INTERVAL = 3.0
  7098. deadline = asyncio.get_event_loop().time() + max_wait
  7099. while True:
  7100. state = printer_manager.get_status(printer.id)
  7101. if state is None:
  7102. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  7103. break
  7104. temps = state.temperatures or {}
  7105. bed_now = float(temps.get("bed", 0) or 0)
  7106. chamber_now = float(temps.get("chamber", 0) or 0)
  7107. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  7108. if not do_chamber:
  7109. chamber_ok = True # phase disabled or model has neither sensor nor heater
  7110. elif not has_sensor:
  7111. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  7112. else:
  7113. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  7114. if bed_ok and chamber_ok:
  7115. logger.info(
  7116. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  7117. item.id,
  7118. bed_now,
  7119. chamber_now,
  7120. )
  7121. break
  7122. if asyncio.get_event_loop().time() >= deadline:
  7123. logger.info(
  7124. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  7125. item.id,
  7126. bed_now,
  7127. bed_target,
  7128. chamber_now,
  7129. chamber_target if do_chamber else 0,
  7130. )
  7131. break
  7132. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  7133. logger.info(
  7134. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  7135. item.id,
  7136. )
  7137. return False
  7138. if soak_seconds > 0:
  7139. if do_chamber and has_sensor:
  7140. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  7141. else:
  7142. remaining = soak_seconds # no sensor — can't verify history, run full soak
  7143. if remaining > 0:
  7144. logger.info(
  7145. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  7146. "has been above target for ~%ds already)",
  7147. item.id,
  7148. remaining,
  7149. soak_seconds,
  7150. soak_seconds - remaining,
  7151. )
  7152. if not await self._preheat_sleep(item.id, remaining):
  7153. logger.info(
  7154. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  7155. item.id,
  7156. )
  7157. return False
  7158. else:
  7159. logger.info(
  7160. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  7161. item.id,
  7162. chamber_target,
  7163. soak_seconds,
  7164. )
  7165. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  7166. return True
  7167. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  7168. """Turn on smart plug and wait for printer to connect.
  7169. Returns True if printer connected successfully within timeout.
  7170. """
  7171. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  7172. service = await smart_plug_manager.get_service_for_plug(plug, db)
  7173. # Check current plug state
  7174. status = await service.get_status(plug)
  7175. if not status.get("reachable"):
  7176. logger.warning("Smart plug '%s' is not reachable", plug.name)
  7177. return False
  7178. # Turn on if not already on
  7179. if status.get("state") != "ON":
  7180. success = await service.turn_on(plug)
  7181. if not success:
  7182. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  7183. return False
  7184. await publish_plug_state(plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id)
  7185. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  7186. # Get printer from database for connection
  7187. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7188. printer = result.scalar_one_or_none()
  7189. if not printer:
  7190. logger.error("Printer %s not found in database", printer_id)
  7191. return False
  7192. # End the pass's transaction before waiting up to minutes for the boot:
  7193. # held open, it pins a pooled connection idle in transaction
  7194. # (PostgreSQL) and a stale read snapshot (SQLite). Nothing below reads
  7195. # through it.
  7196. await db.commit()
  7197. # Wait for printer to boot (give it some time before trying to connect)
  7198. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  7199. await asyncio.sleep(30)
  7200. # Try to connect to the printer periodically
  7201. elapsed = 30 # Already waited 30s
  7202. while elapsed < self._power_on_wait_time:
  7203. # Try to connect
  7204. logger.info("Attempting to connect to printer %s...", printer_id)
  7205. try:
  7206. connected = await printer_manager.connect_printer(printer)
  7207. if connected:
  7208. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  7209. # Give it a moment to stabilize and get status
  7210. await asyncio.sleep(5)
  7211. return True
  7212. except Exception as e:
  7213. logger.debug("Connection attempt failed: %s", e)
  7214. await asyncio.sleep(self._power_on_check_interval)
  7215. elapsed += self._power_on_check_interval
  7216. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  7217. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  7218. return False
  7219. async def _check_previous_success(
  7220. self, db: AsyncSession, item: PrintQueueItem, printer_id: int | None = None
  7221. ) -> bool:
  7222. """Check if the previous print on this printer succeeded.
  7223. ``printer_id`` names the printer to look at when the item has none yet
  7224. (a job for any printer of a model, checked against the one offered).
  7225. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  7226. deliberate action, not a failure, so subsequent items should still
  7227. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  7228. a skip isn't an actual print attempt, so it must not gate downstream
  7229. items — counting it as a failed predecessor was the cascade bug that
  7230. let a single cancellation block 18 items over 3 days for the reporter.
  7231. Only `failed` and `aborted` — real print-attempt failures — block.
  7232. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  7233. action — #1818) are also excluded from the lookback so the user can
  7234. clear the gate after fixing the physical issue without having to
  7235. re-queue every downstream job.
  7236. """
  7237. result = await db.execute(
  7238. select(PrintQueueItem)
  7239. .where(PrintQueueItem.printer_id == (printer_id if printer_id is not None else item.printer_id))
  7240. .where(PrintQueueItem.id != item.id)
  7241. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  7242. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  7243. # A row ended without a completion time must not count as the
  7244. # latest: PostgreSQL sorts NULL first in a descending order.
  7245. .order_by(PrintQueueItem.completed_at.desc().nulls_last(), PrintQueueItem.id.desc())
  7246. .limit(1)
  7247. )
  7248. prev_item = result.scalar_one_or_none()
  7249. # If no previous item, assume success (first in queue)
  7250. if not prev_item:
  7251. return True
  7252. return prev_item.status in ("completed", "cancelled")
  7253. def _release_archive_claims(self, item_id: int) -> None:
  7254. for archive_id in [a for a, owner in self._archive_claims.items() if owner == item_id]:
  7255. del self._archive_claims[archive_id]
  7256. async def _claim_reusable_archive(
  7257. self, db: AsyncSession, item: PrintQueueItem, file_path: Path
  7258. ) -> PrintArchive | None:
  7259. """The archive a library dispatch adds its run to, claimed for it, or
  7260. None for a new one.
  7261. The same file of the same owner, in the same project, archived from
  7262. this library file or from none (one since deleted, or a print started
  7263. elsewhere), with its copy of the file still on disk. Only an idle
  7264. archive: it holds one active run, so while one of its prints is
  7265. queued, being sent, running, or still finishing (its timelapse),
  7266. another print of the file gets an archive of its own, as before.
  7267. """
  7268. from backend.app.main import _active_prints, _archive_runs_finishing
  7269. from backend.app.services.archive import ArchiveService
  7270. # Off the file as it is now: the stored hash is not refreshed when the
  7271. # file changes on disk (an external folder, overwritten in place).
  7272. content_hash = await asyncio.to_thread(ArchiveService.compute_file_hash, file_path)
  7273. owner = (
  7274. PrintArchive.created_by_id.is_(None)
  7275. if item.created_by_id is None
  7276. else PrintArchive.created_by_id == item.created_by_id
  7277. )
  7278. project = (
  7279. PrintArchive.project_id.is_(None) if item.project_id is None else PrintArchive.project_id == item.project_id
  7280. )
  7281. candidates = (
  7282. await db.scalars(
  7283. select(PrintArchive)
  7284. .where(
  7285. PrintArchive.content_hash == content_hash,
  7286. owner,
  7287. project,
  7288. or_(PrintArchive.library_file_id == item.library_file_id, PrintArchive.library_file_id.is_(None)),
  7289. PrintArchive.deleted_at.is_(None),
  7290. PrintArchive.status != "printing",
  7291. )
  7292. .order_by(PrintArchive.id.desc())
  7293. )
  7294. ).all()
  7295. if not candidates:
  7296. return None
  7297. # A dispatch sets the item's archive while the item is still pending
  7298. # and keeps it through printing, so this also covers a print being
  7299. # sent or waiting to start. (The expected-print table can't say that:
  7300. # a print start leaves one of its names there for two hours.)
  7301. queued = set(
  7302. (
  7303. await db.scalars(
  7304. select(PrintQueueItem.archive_id).where(
  7305. PrintQueueItem.archive_id.in_([c.id for c in candidates]),
  7306. PrintQueueItem.status.in_(("pending", "printing")),
  7307. PrintQueueItem.id != item.id,
  7308. )
  7309. )
  7310. ).all()
  7311. )
  7312. for candidate in candidates:
  7313. if not candidate.file_path or not (settings.base_dir / candidate.file_path).is_file():
  7314. continue
  7315. # No await from here to the claim: two parallel dispatches of the
  7316. # file cannot both take it.
  7317. if (
  7318. candidate.id in queued
  7319. or candidate.id in self._archive_claims
  7320. or candidate.id in _active_prints.values()
  7321. or candidate.id in _archive_runs_finishing
  7322. ):
  7323. continue
  7324. self._archive_claims[candidate.id] = item.id
  7325. return candidate
  7326. return None
  7327. async def _repoint_siblings_at_archive(
  7328. self,
  7329. db: AsyncSession,
  7330. *,
  7331. consumed_library_file_id: int,
  7332. archive_id: int,
  7333. dispatched_item_id: int,
  7334. ) -> int:
  7335. """Move the other queue items off a library row that is about to be deleted (#2819).
  7336. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  7337. upload-and-print flow uploads a transient file, prints it, and deletes it.
  7338. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  7339. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  7340. clones, so the first dispatch could pull the file out from under rows that
  7341. had not run yet. What those rows did next depended on the database, and
  7342. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  7343. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  7344. they were left pointing at a row that no longer existed, failing with
  7345. "Library file not found" whenever someone started them -- or sitting
  7346. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  7347. constraint, so there the rows were deleted outright and the queued copies
  7348. simply vanished, with no error and no history.
  7349. The archive holds its own copy of the 3MF, so the remaining copies can print
  7350. from it instead. Two things happen here, and both must happen *before* the
  7351. delete -- afterwards there is nothing left to repair on PostgreSQL:
  7352. * every row still naming the file has ``library_file_id`` cleared, which is
  7353. what takes it out of the cascade's reach. That covers rows this cannot
  7354. re-point as well -- a copy already printing from its own archive, and the
  7355. finished ones, which are not spare parts but the record a batch order
  7356. counts its progress from.
  7357. * the rows that still need something to print are pointed at the archive.
  7358. Returns how many items were re-pointed.
  7359. """
  7360. variant_item_ids = (
  7361. (
  7362. await db.execute(
  7363. select(PrintQueueVariant.queue_item_id).where(
  7364. PrintQueueVariant.library_file_id == consumed_library_file_id
  7365. )
  7366. )
  7367. )
  7368. .scalars()
  7369. .all()
  7370. )
  7371. # Candidate rows naming the consumed file have to go rather than be
  7372. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  7373. # one out of the cascade. This is what PostgreSQL already does, and
  7374. # _candidates_for skips such a variant on SQLite anyway, so no selection
  7375. # outcome changes -- the two backends simply stop disagreeing about
  7376. # whether the row is still there.
  7377. #
  7378. # It also has to happen before the re-point below: a cross-model item
  7379. # (#671) picks a variant every pass and folds it onto the row, and
  7380. # _resolve_variant clears archive_id as it does so, which would undo the
  7381. # re-point on the very next lap.
  7382. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  7383. # An item left with other candidates still has somewhere to go, and those
  7384. # carry their own target model -- pointing it at this archive would print a
  7385. # file the matcher never chose. It is excluded from the re-point and simply
  7386. # re-resolves against what is left.
  7387. surviving_variant_item_ids = set(
  7388. (
  7389. await db.execute(
  7390. select(PrintQueueVariant.queue_item_id).where(
  7391. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  7392. )
  7393. )
  7394. )
  7395. .scalars()
  7396. .all()
  7397. )
  7398. repoint_ids = set(
  7399. (
  7400. await db.execute(
  7401. select(PrintQueueItem.id)
  7402. .where(PrintQueueItem.id != dispatched_item_id)
  7403. .where(PrintQueueItem.archive_id.is_(None))
  7404. # "skipped" belongs here with the two live states: it is not
  7405. # terminal. Clearing a printer's previous-success gate puts
  7406. # every item skipped by it back to "pending"
  7407. # (resume_after_failure), and one restored onto a deleted
  7408. # file is the same orphan by a slower route. "failed",
  7409. # "cancelled", "aborted" and "completed" never return.
  7410. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  7411. .where(
  7412. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  7413. )
  7414. .where(
  7415. or_(
  7416. PrintQueueItem.library_file_id == consumed_library_file_id,
  7417. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  7418. )
  7419. )
  7420. )
  7421. )
  7422. .scalars()
  7423. .all()
  7424. )
  7425. if repoint_ids:
  7426. await db.execute(
  7427. update(PrintQueueItem)
  7428. .where(PrintQueueItem.id.in_(repoint_ids))
  7429. .values(
  7430. archive_id=archive_id,
  7431. library_file_id=None,
  7432. # The file this flag named is already consumed. Leaving it set
  7433. # would arm every re-pointed copy to delete whatever library
  7434. # row it is next given.
  7435. cleanup_library_after_dispatch=False,
  7436. )
  7437. )
  7438. logger.info(
  7439. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  7440. sorted(repoint_ids),
  7441. archive_id,
  7442. consumed_library_file_id,
  7443. dispatched_item_id,
  7444. )
  7445. # Everything else that still names the file: taken out of the cascade's
  7446. # reach without touching what it prints. The file is gone either way; what
  7447. # this preserves is the row.
  7448. await db.execute(
  7449. update(PrintQueueItem)
  7450. .where(PrintQueueItem.id != dispatched_item_id)
  7451. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  7452. .values(library_file_id=None)
  7453. )
  7454. return len(repoint_ids)
  7455. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  7456. """Schedule power-off if the queue item enabled auto_off_after.
  7457. Delegates to the smart-plug manager so the off honours each plug's
  7458. configured strategy (time delay or temperature threshold), is cancelled
  7459. if the printer starts printing again, and never cuts power on a loaded
  7460. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  7461. powered off on the timeout regardless of print state.
  7462. """
  7463. if not item.auto_off_after:
  7464. return
  7465. try:
  7466. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  7467. except Exception as e:
  7468. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  7469. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  7470. """Get a human-readable name for a queue item."""
  7471. if item.archive_id:
  7472. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7473. archive = result.scalar_one_or_none()
  7474. if archive:
  7475. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7476. if item.library_file_id:
  7477. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7478. library_file = result.scalar_one_or_none()
  7479. if library_file:
  7480. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7481. # A cross-model item (#671) holds no file of its own until a printer is
  7482. # picked, so name it after its first candidate — otherwise every waiting
  7483. # notification for one reads "Job #12". Queried rather than read off
  7484. # item.variants because callers outside the selection loop have not
  7485. # eager-loaded them, and a lazy load raises in async.
  7486. first_variant_name = (
  7487. await db.execute(
  7488. select(LibraryFile.filename)
  7489. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  7490. .where(PrintQueueVariant.queue_item_id == item.id)
  7491. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  7492. .limit(1)
  7493. )
  7494. ).scalar_one_or_none()
  7495. if first_variant_name:
  7496. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  7497. return f"Job #{item.id}"
  7498. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  7499. """Get printer by ID."""
  7500. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7501. return result.scalar_one_or_none()
  7502. async def _notify_dispatch_gave_up(
  7503. self,
  7504. queue_item_id: int,
  7505. printer_id: int,
  7506. created_by_id: int | None,
  7507. reason: str = "Printer accepted the file but never started printing",
  7508. ) -> None:
  7509. """Tell the user the queue item was failed after exhausting its dispatch retries.
  7510. Called from the watchdog, which is a background task with no session of
  7511. its own — hence the fresh one here. Best-effort throughout: the row is
  7512. already marked failed and that is the load-bearing part; a notification
  7513. provider being down must not resurrect the retry loop we just stopped.
  7514. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  7515. path passes its own, because "accepted the file but never started" is the
  7516. opposite of what happened there — the printer refused it outright (#2732).
  7517. """
  7518. try:
  7519. async with async_session() as db:
  7520. item = await db.get(PrintQueueItem, queue_item_id)
  7521. if not item:
  7522. return
  7523. job_name = await self._get_job_name(db, item)
  7524. printer = await self._get_printer(db, printer_id)
  7525. await notification_service.on_queue_job_failed(
  7526. job_name=job_name,
  7527. printer_id=printer_id,
  7528. printer_name=printer.name if printer else "Unknown",
  7529. reason=reason,
  7530. db=db,
  7531. )
  7532. except Exception as e:
  7533. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  7534. try:
  7535. await ws_manager.send_queue_item_failed(
  7536. user_id=created_by_id,
  7537. queue_item_id=queue_item_id,
  7538. printer_id=printer_id,
  7539. reason="never_started",
  7540. )
  7541. except Exception:
  7542. pass # toast is best-effort
  7543. async def _filament_short_on(
  7544. self,
  7545. db: AsyncSession,
  7546. item: PrintQueueItem,
  7547. printer_id: int,
  7548. *,
  7549. require_known: bool = False,
  7550. ) -> bool:
  7551. """Would ``item`` be held for a filament deficit on ``printer_id`` (#3137)?
  7552. Asks what ``_block_on_filament_deficit`` would answer once the item is
  7553. assigned there, with the mapping the item would get there, but changes
  7554. nothing. The model-based matcher uses it to prefer a printer whose
  7555. spools can finish the job.
  7556. False whenever the gate would let the item through: "Print Anyway",
  7557. no mapping, or a check that fails. With ``require_known`` all three of
  7558. those, and any printed slot whose remaining amount is unknown, count
  7559. as short instead: releasing a held job starts it with nobody asked, so
  7560. it needs the amount on record, not merely nothing against it.
  7561. """
  7562. if item.skip_filament_check:
  7563. return False
  7564. try:
  7565. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7566. if not mapping:
  7567. return require_known
  7568. deficit = await compute_deficit_for_queue_item(
  7569. db, item, printer_id=printer_id, ams_mapping=mapping, require_known=require_known
  7570. )
  7571. except Exception as e:
  7572. logger.warning("Filament deficit check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7573. return require_known
  7574. return bool(deficit)
  7575. async def _release_short_model_hold(
  7576. self,
  7577. db: AsyncSession,
  7578. item: PrintQueueItem,
  7579. unavailable: set[int],
  7580. require_plate_clear: bool,
  7581. printer_scope: PrinterScope,
  7582. ) -> bool:
  7583. """Free an "any model" job held for low filament once a printer can run it (#3137).
  7584. The deficit gate holds a model-based job on the printer the matcher
  7585. gave it, because "Print Anyway" needs a printer to print on. When
  7586. another idle printer of the job's model has the filament, the job is
  7587. moved to that printer and its hold lifted, and the fixed-printer
  7588. branch dispatches it in this same pass, through the same checks a
  7589. held job meets when the user presses Start. It is moved rather than
  7590. put back in the pool because the model-based branch would pick again
  7591. without requiring the amounts on record (below), and could pick a
  7592. different printer. Only the deficit gate sets ``filament_short``, so a
  7593. job held for any other reason stays held.
  7594. The printer it is held on is left out: a spool loaded there is started
  7595. with Start, as before, rather than while someone may still be loading
  7596. the next one. Each job is checked at most every
  7597. ``_SHORT_HOLD_RECHECK_SECONDS``, as every check matches its filament
  7598. on each idle printer again.
  7599. Cross-model jobs (#671) stay held: checking a variant writes its file
  7600. onto the item, which would leave a job that is not moved holding
  7601. another variant's file for the printer it waits on.
  7602. A printer qualifies only on a positive finding: every slot the plate
  7603. prints mapped to a spool whose remaining amount is on record and
  7604. enough. A printer whose spools Bambuddy does not track is not one.
  7605. Returns True when the job was moved. A check that fails keeps the hold
  7606. rather than stopping the queue pass.
  7607. """
  7608. if not item.filament_short or item.skip_filament_check or item.printer_id is None:
  7609. return False
  7610. if not item.target_model or item.variants:
  7611. return False
  7612. now = time.monotonic()
  7613. if now - self._short_hold_checked_at.get(item.id, float("-inf")) < _SHORT_HOLD_RECHECK_SECONDS:
  7614. return False
  7615. self._short_hold_checked_at[item.id] = now
  7616. try:
  7617. candidates = _candidates_for(item)
  7618. if not candidates:
  7619. return False
  7620. effective_types, filament_overrides = _filament_constraints(candidates[0])
  7621. async def is_short(pid: int) -> bool:
  7622. return await self._filament_short_on(db, item, pid, require_known=True)
  7623. async def unmatched_on(pid: int) -> list[str]:
  7624. return await self._unmatched_on(db, item, pid)
  7625. match_id, _ = await self._find_idle_printer_for_model(
  7626. db,
  7627. item.target_model,
  7628. unavailable | {item.printer_id},
  7629. effective_types,
  7630. item.target_location,
  7631. filament_overrides=filament_overrides,
  7632. require_plate_clear=require_plate_clear,
  7633. printer_scope=printer_scope,
  7634. is_short=is_short,
  7635. unmatched_on=unmatched_on,
  7636. )
  7637. # Every idle printer short comes back as the first of them.
  7638. if match_id is None or await is_short(match_id):
  7639. return False
  7640. except Exception as e:
  7641. logger.warning("Queue item %s: looking for another printer failed: %s", item.id, e)
  7642. return False
  7643. logger.info(
  7644. "Queue item %s: printer %s has the filament it was short of on printer %s — moving it there",
  7645. item.id,
  7646. match_id,
  7647. item.printer_id,
  7648. )
  7649. self._short_hold_checked_at.pop(item.id, None)
  7650. item.printer_id = match_id
  7651. # Resolved against the printer it leaves (#3239): the tray mapping and
  7652. # the nozzle positions.
  7653. drop_printer_resolved(item)
  7654. item.manual_start = False
  7655. item.filament_short = False
  7656. item.waiting_reason = None
  7657. await db.commit()
  7658. try:
  7659. printer = await self._get_printer(db, match_id)
  7660. await notification_service.on_queue_job_assigned(
  7661. job_name=await self._get_job_name(db, item),
  7662. printer_id=match_id,
  7663. printer_name=printer.name if printer else "Unknown",
  7664. target_model=item.target_model,
  7665. db=db,
  7666. )
  7667. except Exception as e:
  7668. logger.debug("Assignment notification failed for item %s: %s", item.id, e)
  7669. return True
  7670. async def _block_on_filament_deficit(
  7671. self,
  7672. db: AsyncSession,
  7673. item: PrintQueueItem,
  7674. ) -> bool:
  7675. """Promote the item to manual_start when the assigned spool is short (#1496).
  7676. Returns True when this dispatch attempt was blocked, False when the
  7677. item is clear to start. A previously-flagged item whose spool has
  7678. since been swapped to one with enough material clears the flag here
  7679. so the next scheduler tick dispatches it.
  7680. """
  7681. # User has explicitly acknowledged the deficit ("Print Anyway") —
  7682. # don't re-flag, don't even compute. Without this short-circuit the
  7683. # scheduler bounces between "user said anyway" (route clears
  7684. # manual_start) and "scheduler re-blocked" (this method re-flags it
  7685. # on identical spool state) (#1698-followup).
  7686. if item.skip_filament_check:
  7687. # #1762 diagnostic: surface the short-circuit at INFO so a
  7688. # future "Print Anyway didn't work" report (e.g. issue #1762
  7689. # comment 3) has actionable evidence in the support bundle
  7690. # without needing DEBUG enabled.
  7691. logger.info(
  7692. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  7693. item.id,
  7694. )
  7695. return False
  7696. try:
  7697. deficit = await compute_deficit_for_queue_item(db, item)
  7698. except Exception as e:
  7699. # Never let a flaky deficit check wedge the queue — log and let
  7700. # dispatch proceed. The PrintModal-side check still runs on the
  7701. # manual paths.
  7702. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  7703. return False
  7704. if deficit:
  7705. item.filament_short = True
  7706. item.manual_start = True
  7707. await db.commit()
  7708. job_name = await self._get_job_name(db, item)
  7709. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  7710. logger.info(
  7711. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  7712. item.id,
  7713. len(deficit),
  7714. )
  7715. try:
  7716. await notification_service.on_queue_job_waiting(
  7717. job_name=job_name,
  7718. target_model=(printer.model if printer else "") or "",
  7719. waiting_reason="filament_short",
  7720. db=db,
  7721. printer_id=item.printer_id,
  7722. )
  7723. except Exception as e:
  7724. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  7725. return True
  7726. # No deficit — clear any stale flag from a previous tick.
  7727. if item.filament_short:
  7728. item.filament_short = False
  7729. await db.commit()
  7730. return False
  7731. def _find_color_substitutions(self, required: list[dict], mapping: list, loaded: list[dict]) -> list[dict]:
  7732. """The slots ``mapping`` gives a spool of another colour than they ask for (#3279).
  7733. Compared the way the matcher compares, so the same hex or a similar one
  7734. is a match. Only slots the plate prints, mapped to a tray the printer
  7735. reports, with a colour on both sides: anything else is not a colour the
  7736. job printed in.
  7737. """
  7738. by_tray = {f["global_tray_id"]: f for f in loaded}
  7739. found = []
  7740. for req in required:
  7741. slot_id = req.get("slot_id") or 0
  7742. if slot_id <= 0 or slot_id > len(mapping):
  7743. continue
  7744. tray_id = mapping[slot_id - 1]
  7745. tray = by_tray.get(tray_id) if _is_tray_id(tray_id) else None
  7746. if tray is not None and tray.get("color_known") is False:
  7747. # A spool without a colour set is not a different colour.
  7748. continue
  7749. wanted = self._normalize_color_for_compare(req.get("color"))
  7750. got = self._normalize_color_for_compare(tray.get("color")) if tray else ""
  7751. if not wanted or not got or wanted == got or self._colors_are_similar(wanted, got):
  7752. continue
  7753. found.append(
  7754. {
  7755. "slot_id": slot_id,
  7756. "type": req.get("type") or "",
  7757. "wanted": f"#{wanted.upper()}",
  7758. "got": f"#{got.upper()}",
  7759. "tray": tray_id,
  7760. }
  7761. )
  7762. return found
  7763. async def _color_substitutions_for(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
  7764. """``item``'s colour substitutions as stored on the row, or None (#3279).
  7765. Read from the mapping the job is about to be sent with, whoever made
  7766. it: the matcher's same-material fallback, a preset match in another
  7767. colour, or a slot picked by hand. The file's colour is the one after
  7768. overrides, so a colour swapped on purpose is not one. None whenever
  7769. there is nothing to compare, and on any failure: a missing note must
  7770. never stop a print.
  7771. """
  7772. try:
  7773. mapping = json.loads(item.ams_mapping) if item.ams_mapping else None
  7774. if not isinstance(mapping, list) or not item.printer_id:
  7775. return None
  7776. status = printer_manager.get_status(item.printer_id)
  7777. if status is None:
  7778. return None
  7779. required = await self._get_filament_requirements(db, item)
  7780. if not required:
  7781. return None
  7782. self._apply_filament_overrides(item, required)
  7783. found = self._find_color_substitutions(required, mapping, self._build_loaded_filaments(status))
  7784. except Exception as e:
  7785. logger.debug("Queue item %s: colour comparison failed: %s", item.id, e)
  7786. return None
  7787. if found:
  7788. logger.info("Queue item %s: sent with another colour than the file asks for: %s", item.id, found)
  7789. return json.dumps(found) if found else None
  7790. async def _unmatched_requirements(
  7791. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, mapping: list | None
  7792. ) -> list[dict]:
  7793. """The requirements ``mapping`` leaves without a tray on ``printer_id`` (#2799).
  7794. ``None`` is a mapping that resolved nothing. Only a printer that reported
  7795. loaded trays makes that a finding — see ``_block_on_unmatched_filament``
  7796. on why an empty list is not one.
  7797. """
  7798. if mapping is None:
  7799. status = printer_manager.get_status(printer_id)
  7800. if status is None or not self._build_loaded_filaments(status):
  7801. return []
  7802. # Every required slot reads unresolved against an empty mapping.
  7803. mapping = []
  7804. required = await self._get_filament_requirements(db, item)
  7805. if required:
  7806. self._apply_filament_overrides(item, required)
  7807. else:
  7808. # An unreadable 3MF still has its forced colours to go by: they are
  7809. # what the mapping was built from (#3280).
  7810. required = _forced_override_requirements(item)
  7811. return _unresolved_required(required, mapping) if required else []
  7812. async def _unmatched_on(self, db: AsyncSession, item: PrintQueueItem, printer_id: int) -> list[str]:
  7813. """What ``item`` would be held for on ``printer_id``, as the queue row names it.
  7814. Asks the matcher and the unmatched-filament hold, but changes nothing.
  7815. Choosing a printer for an "any model" job only checked that each type
  7816. and forced colour was loaded somewhere, which a dual-nozzle printer with
  7817. the spool on the other nozzle, or one spool asked for twice, passes. The
  7818. hold then gave the printer back, and the next pass chose it again.
  7819. Empty when the hold would let the item through, including "Print
  7820. Anyway" and a match that fails: the printer is then chosen as before.
  7821. """
  7822. if item.skip_filament_check:
  7823. return []
  7824. key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
  7825. if key in self._unmatched_memo:
  7826. return list(self._unmatched_memo[key])
  7827. try:
  7828. mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  7829. unmatched = await self._unmatched_requirements(db, item, printer_id, mapping)
  7830. except Exception as e:
  7831. logger.warning("Filament match check failed for item %s on printer %s: %s", item.id, printer_id, e)
  7832. return []
  7833. described = [_describe_filament(req, "nozzle_id") for req in unmatched]
  7834. self._unmatched_memo[key] = described
  7835. return list(described)
  7836. async def _block_on_unmatched_filament(
  7837. self,
  7838. db: AsyncSession,
  7839. item: PrintQueueItem,
  7840. release_assignment: bool = False,
  7841. ) -> bool:
  7842. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  7843. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  7844. goes ahead, letting the printer choose — which is how a job prints in the
  7845. wrong material without anyone being asked. Holding is the same answer the
  7846. deficit gate already gives for "the spool is too light", so it reuses the
  7847. same promote-and-notify machinery.
  7848. Keyed off unresolved slots in the *computed* mapping intersected with the
  7849. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  7850. read: on its own it also pads slots this plate does not print, so the
  7851. array alone would hold perfectly good jobs. Reading the mapping rather
  7852. than the printer's loaded filament types also inherits the matcher's
  7853. per-nozzle restriction for free — a dual-nozzle printer carrying the
  7854. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  7855. type-only scan would wave that through.
  7856. A mapping that resolved *nothing* is the same finding arriving as an
  7857. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  7858. could not replace, and dispatch then goes out as ``use_ams`` with no
  7859. table at all — several megabytes uploaded for an 0700_8012 rejection.
  7860. That is held too, but only once live status positively reports loaded
  7861. trays: #2589's mapping is bogus precisely because the AMS was not known
  7862. yet, and its empty loaded list is that ignorance rather than a miss.
  7863. ``release_assignment`` is for the model-based path, which commits its
  7864. printer choice before the gates run. Holding an "any P2S" job would
  7865. otherwise pin it to the one P2S that could not run it.
  7866. Returns True when this dispatch attempt was blocked.
  7867. """
  7868. if item.skip_filament_check or not item.printer_id:
  7869. return False
  7870. mapping: list | None = None
  7871. if item.ams_mapping:
  7872. try:
  7873. mapping = json.loads(item.ams_mapping)
  7874. except (json.JSONDecodeError, TypeError):
  7875. return False
  7876. if not isinstance(mapping, list):
  7877. return False
  7878. unmatched = await self._unmatched_requirements(db, item, item.printer_id, mapping)
  7879. if not unmatched:
  7880. # No cleanup needed here: once start is pressed the item is no
  7881. # longer staged, and whichever exit runs next overwrites the reason
  7882. # (`hold_item` on the fixed-printer branch, the assignment on the
  7883. # model-based one), as does dispatch.
  7884. return False
  7885. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  7886. held_by = item.printer_id
  7887. item.manual_start = True
  7888. # Human-readable: this renders on the queue row.
  7889. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  7890. if release_assignment:
  7891. # "Any P2S" means any, so the job returns to the pool rather than
  7892. # waiting on the printer that could not take it. The mapping goes
  7893. # with the assignment: its tray IDs were resolved against the
  7894. # printer being released and mean nothing on the next one (#2799),
  7895. # and keeping them would hold the job again even on a printer that
  7896. # has the filament, since an unresolved slot is deliberately not a
  7897. # conflict worth recomputing over.
  7898. item.printer_id = None
  7899. drop_printer_resolved(item)
  7900. await db.commit()
  7901. job_name = await self._get_job_name(db, item)
  7902. printer = await self._get_printer(db, held_by)
  7903. logger.info(
  7904. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  7905. item.id,
  7906. held_by,
  7907. wanted,
  7908. )
  7909. try:
  7910. await notification_service.on_queue_job_waiting(
  7911. job_name=job_name,
  7912. target_model=(printer.model if printer else "") or "",
  7913. waiting_reason=f"needs {wanted}",
  7914. db=db,
  7915. # Released to the pool: no printer holds it any more.
  7916. printer_id=None if release_assignment else held_by,
  7917. )
  7918. except Exception as e:
  7919. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  7920. return True
  7921. @staticmethod
  7922. async def _queue_owner_id(db: AsyncSession, item: PrintQueueItem) -> int | None:
  7923. """The queue item's owner as the row has it now.
  7924. item.created_by_id was read before preheat and upload, which can take
  7925. minutes; deleting the user clears the row, not this session's copy.
  7926. """
  7927. return await db.scalar(select(PrintQueueItem.created_by_id).where(PrintQueueItem.id == item.id))
  7928. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  7929. """Hand the queue item's owner to printer_manager so the
  7930. print-complete callback can credit the user in PrintLogEntry (#1670).
  7931. No-ops when the item has no `created_by_id` or the referenced user
  7932. row is missing (e.g. user deleted between queue-add and dispatch —
  7933. in that case the print log row falls back to the existing un-credited
  7934. behaviour rather than crashing the dispatch).
  7935. """
  7936. from backend.app.models.user import User
  7937. # Read from the row, not item.created_by_id or db.get: both can still
  7938. # hold a user deleted during the upload, after delete_user forgot them
  7939. # (on SQLite the id may be someone new's by the time the print ends).
  7940. # Joined with the printer too: one deleted during the upload was
  7941. # forgotten as well, and this would write the owner back under its id.
  7942. owner = (
  7943. await db.execute(
  7944. select(User.id, User.username)
  7945. .join(PrintQueueItem, PrintQueueItem.created_by_id == User.id)
  7946. .join(Printer, Printer.id == PrintQueueItem.printer_id)
  7947. .where(PrintQueueItem.id == item.id)
  7948. )
  7949. ).first()
  7950. if owner:
  7951. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username, queue_item_id=item.id)
  7952. if item.printer_id is not None:
  7953. self._unconfirmed_print_user[item.id] = item.printer_id
  7954. async def _fail_dispatch(self, db: AsyncSession, item: PrintQueueItem, message: str) -> bool:
  7955. """Mark a dispatching item failed, unless the user cancelled it meanwhile.
  7956. A cancel lands in another session while the upload runs (the edit route
  7957. even tells users to cancel a job that is being sent). An unconditional
  7958. write here would turn that cancellation into a failure, with a failure
  7959. notification, and block the next job that needs the previous print to
  7960. have succeeded. Returns whether the item was marked failed.
  7961. """
  7962. result = cast(
  7963. CursorResult,
  7964. await db.execute(
  7965. update(PrintQueueItem)
  7966. .where(PrintQueueItem.id == item.id)
  7967. .where(PrintQueueItem.status.in_(("pending", "printing")))
  7968. # Failed before the print started: no slot printed in any colour (#3279).
  7969. .values(
  7970. status="failed",
  7971. error_message=message,
  7972. completed_at=datetime.now(timezone.utc),
  7973. color_substitutions=None,
  7974. )
  7975. .execution_options(synchronize_session=False)
  7976. ),
  7977. )
  7978. await db.commit()
  7979. if result.rowcount == 0:
  7980. # Cancelled, or deleted, meanwhile: the row is not refreshed, it may be gone.
  7981. logger.info("Queue item %s: not marked failed (%s), it was cancelled meanwhile", item.id, message)
  7982. return False
  7983. await db.refresh(item)
  7984. from backend.app.services.print_batch import refresh_batches_after
  7985. await refresh_batches_after([item.id])
  7986. return True
  7987. @staticmethod
  7988. async def _defer_until_printer_idle(db: AsyncSession, item: PrintQueueItem) -> None:
  7989. """Put a job whose printer turned busy before the start back in the queue.
  7990. Only if it is still printing: a stop that landed meanwhile stands.
  7991. """
  7992. await db.execute(
  7993. update(PrintQueueItem)
  7994. .where(PrintQueueItem.id == item.id)
  7995. .where(PrintQueueItem.status == "printing")
  7996. .values(status="pending", started_at=None, color_substitutions=None)
  7997. .execution_options(synchronize_session=False)
  7998. )
  7999. await db.commit()
  8000. @staticmethod
  8001. async def _close_cancelled_dispatch_toast(item: PrintQueueItem, toast_uid: int | None) -> None:
  8002. """Close the dispatch toast of an item the user cancelled while it was sent."""
  8003. try:
  8004. await ws_manager.send_queue_item_failed(
  8005. user_id=toast_uid,
  8006. queue_item_id=item.id,
  8007. printer_id=item.printer_id,
  8008. reason="cancelled_mid_dispatch",
  8009. )
  8010. except Exception:
  8011. pass # toast is best-effort
  8012. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  8013. """Upload file and start print for a queue item.
  8014. Supports two sources:
  8015. - archive_id: Print from an existing archive
  8016. - library_file_id: Print from a library file (file manager)
  8017. """
  8018. logger.info("Starting queue item %s", item.id)
  8019. # Also covers a reservation left active by a process interruption
  8020. # during an earlier attempt. `_dispatch_one` releases this marker on
  8021. # every exit unless start_print() confirms that the command was sent.
  8022. self._unconfirmed_budget_reservations.add(item.id)
  8023. try:
  8024. from backend.app.models.user import User
  8025. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  8026. # Recompute at the final authorization boundary as well as enqueue
  8027. # time. This covers rows created before the server-side estimate
  8028. # migration and prevents any alternate write path from weakening
  8029. # the budget reservation.
  8030. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  8031. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  8032. item.estimated_cost = await estimate_queue_source_cost(
  8033. db,
  8034. archive=archive,
  8035. library_file=library_file,
  8036. plate_id=item.plate_id,
  8037. ams_mapping=item.ams_mapping,
  8038. printer_id=item.printer_id,
  8039. )
  8040. await validate_print_budget(
  8041. db,
  8042. cost_center_id=item.cost_center_id,
  8043. estimated_cost=item.estimated_cost,
  8044. current_user=queue_user,
  8045. exclude_queue_item_id=item.id,
  8046. exclude_reservation_source_type="print_queue",
  8047. exclude_reservation_source_id=item.id,
  8048. )
  8049. budget_reservation = await create_budget_reservation(
  8050. db,
  8051. cost_center_id=item.cost_center_id,
  8052. estimated_cost=item.estimated_cost,
  8053. current_user=queue_user,
  8054. source_type="print_queue",
  8055. source_id=item.id,
  8056. print_archive_id=item.archive_id,
  8057. exclude_queue_item_id=item.id,
  8058. )
  8059. await db.commit()
  8060. except HTTPException as exc:
  8061. if not await self._fail_dispatch(db, item, str(exc.detail)):
  8062. return
  8063. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  8064. await self._power_off_if_needed(db, item)
  8065. return
  8066. # Get printer first (needed for both paths)
  8067. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  8068. printer = result.scalar_one_or_none()
  8069. if not printer:
  8070. if not await self._fail_dispatch(db, item, "Printer not found"):
  8071. return
  8072. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  8073. await self._power_off_if_needed(db, item)
  8074. return
  8075. # Check printer is connected
  8076. if not printer_manager.is_connected(item.printer_id):
  8077. if not await self._fail_dispatch(db, item, "Printer not connected"):
  8078. return
  8079. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  8080. await self._power_off_if_needed(db, item)
  8081. return
  8082. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  8083. # `items` was taken at the top of check_queue, but the user can /cancel
  8084. # any pending row in the gap before we reach this point. Re-read the
  8085. # row and bail out cleanly instead of starting an FTP upload for a row
  8086. # that's already cancelled. The atomic CAS at the pending→printing
  8087. # transition (below, before start_print) is the load-bearing guard;
  8088. # this is the early-exit optimisation that avoids wasted FTP I/O.
  8089. await db.refresh(item)
  8090. if item.status != "pending":
  8091. logger.info(
  8092. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  8093. item.id,
  8094. item.status,
  8095. )
  8096. return
  8097. # Busy-printer guard (#2598). check_queue gates dispatch on
  8098. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  8099. # keep reporting FINISH for tens of seconds *after* it accepted a
  8100. # project_file (see the watchdog's phase-B note). A watchdog revert
  8101. # (#2555) also releases the dispatch hold, so a re-selected item can
  8102. # reach here while its printer has actually started printing. Uploading
  8103. # and dispatching then collides with the live job — the firmware answers
  8104. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  8105. # live state right before the expensive FTP upload: if the printer is
  8106. # busy, leave the item pending and let a later tick dispatch it once the
  8107. # printer is genuinely idle. No wasted upload, no collision.
  8108. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  8109. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  8110. logger.info(
  8111. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  8112. "leaving item pending for a later tick (#2598)",
  8113. item.id,
  8114. item.printer_id,
  8115. pre_dispatch_state,
  8116. )
  8117. return
  8118. # Determine source: archive or library file
  8119. archive = None
  8120. library_file = None
  8121. file_path = None
  8122. filename = None
  8123. cleanup_disk_paths: list[Path] = []
  8124. # Set when a dispatch consumes its library file, so the photos can be
  8125. # carried over after the commit that removes the row (#3077).
  8126. consumed_library_file_id: int | None = None
  8127. consumed_photos: list[str] = []
  8128. if item.archive_id:
  8129. # Print from archive
  8130. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  8131. archive = result.scalar_one_or_none()
  8132. if not archive:
  8133. if not await self._fail_dispatch(db, item, "Archive not found"):
  8134. return
  8135. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  8136. await self._power_off_if_needed(db, item)
  8137. return
  8138. # Persist the queue item's selected plate onto the archive so Print
  8139. # History can show the actual plate after cancel/fail/complete (#2603).
  8140. # The archive shows its latest run's plate; each run keeps its own
  8141. # on its print log entry.
  8142. if item.plate_id is not None:
  8143. archive.plate_id = item.plate_id
  8144. # Ask-for-outcome opt-in rides from the queue item to the archive
  8145. # the same way (#1898); never cleared here so a reprint of an
  8146. # archive that already asked keeps asking.
  8147. if item.confirm_outcome:
  8148. archive.confirm_requested = True
  8149. file_path = settings.base_dir / archive.file_path
  8150. filename = archive.filename
  8151. elif item.library_file_id:
  8152. # Print from library file (file manager)
  8153. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  8154. library_file = result.scalar_one_or_none()
  8155. if not library_file:
  8156. # "Not found" covers two different situations and only one of
  8157. # them is recoverable, so say which. A trashed file is still
  8158. # there and restoring it makes a re-queued job work; a file that
  8159. # is really gone needs a different one. Neither is knowable from
  8160. # the queue, which is the whole complaint about this message.
  8161. trashed = (
  8162. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  8163. ).scalar_one_or_none()
  8164. if not await self._fail_dispatch(
  8165. db,
  8166. item,
  8167. (
  8168. f"'{trashed}' is in the library trash — restore it and queue the print again"
  8169. if trashed
  8170. else "Library file not found — it was deleted after this job was queued"
  8171. ),
  8172. ):
  8173. return
  8174. logger.error(
  8175. "Queue item %s: library file %s is %s",
  8176. item.id,
  8177. item.library_file_id,
  8178. "in the trash" if trashed else "gone",
  8179. )
  8180. await self._power_off_if_needed(db, item)
  8181. return
  8182. # Library files store absolute paths
  8183. lib_path = Path(library_file.file_path)
  8184. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  8185. filename = library_file.filename
  8186. # Create archive from library file so usage tracking has access to the 3MF
  8187. queue_item_id = item.id
  8188. # Held separately: a cleanup dispatch clears item.library_file_id
  8189. # below, and the log line at the end of this block reported that
  8190. # cleared field -- so every consumed print logged "from library
  8191. # file None", which is the one case worth being able to trace.
  8192. source_library_file_id = item.library_file_id
  8193. reused_archive = False
  8194. try:
  8195. from backend.app.services.archive import ArchiveService
  8196. # The file printed before: this run joins its archive rather
  8197. # than archiving the same file a second time.
  8198. archive = await self._claim_reusable_archive(db, item, file_path)
  8199. if archive is not None:
  8200. reused_archive = True
  8201. if archive.library_file_id is None:
  8202. archive.library_file_id = item.library_file_id
  8203. # This run's, as a new archive would have them: the
  8204. # archive shows its latest run's plate, and billing falls
  8205. # back to the archive's cost centre.
  8206. if item.plate_id is not None:
  8207. archive.plate_id = item.plate_id
  8208. archive.cost_center_id = item.cost_center_id
  8209. else:
  8210. archive_service = ArchiveService(db)
  8211. archive = await archive_service.archive_print(
  8212. printer_id=item.printer_id,
  8213. source_file=file_path,
  8214. original_filename=filename,
  8215. created_by_id=item.created_by_id,
  8216. project_id=item.project_id,
  8217. cost_center_id=item.cost_center_id,
  8218. library_file_id=item.library_file_id, # per-file project progress (#1897)
  8219. plate_id=item.plate_id, # selected plate → Print History (#2603)
  8220. )
  8221. if archive:
  8222. item.archive_id = archive.id
  8223. if item.confirm_outcome:
  8224. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  8225. if budget_reservation is not None:
  8226. budget_reservation.print_archive_id = archive.id
  8227. if item.cleanup_library_after_dispatch and not library_file.is_external:
  8228. consumed_library_file_id = library_file.id
  8229. item.library_file_id = None
  8230. cleanup_disk_paths.append(file_path)
  8231. if library_file.thumbnail_path:
  8232. thumb_path = Path(library_file.thumbnail_path)
  8233. if not thumb_path.is_absolute():
  8234. thumb_path = settings.base_dir / library_file.thumbnail_path
  8235. cleanup_disk_paths.append(thumb_path)
  8236. # Before the delete, not after: on PostgreSQL the FK
  8237. # cascade would already have taken these rows (#2819).
  8238. await self._repoint_siblings_at_archive(
  8239. db,
  8240. consumed_library_file_id=consumed_library_file_id,
  8241. archive_id=archive.id,
  8242. dispatched_item_id=item.id,
  8243. )
  8244. # Read while the row is still here; the photos move
  8245. # below, once the delete has actually committed.
  8246. consumed_photos = list(library_file.photos or [])
  8247. # The delete clears the link on the earlier archives of
  8248. # this file (ON DELETE SET NULL; core/sqlite_fk on
  8249. # SQLite). This one is loaded, so set it here too, or it
  8250. # keeps the stale id in the session.
  8251. archive.library_file_id = None
  8252. await db.delete(library_file)
  8253. file_path = settings.base_dir / archive.file_path
  8254. filename = archive.filename
  8255. # Commit, not flush — flush opens the SQLite write
  8256. # transaction (item.archive_id update + library_file
  8257. # delete) and would hold the WAL writer lock through the
  8258. # FTP upload below, causing "database is locked" cascades
  8259. # for sensor history + concurrent cancels (#1853).
  8260. await db.commit()
  8261. logger.info(
  8262. "Queue item %s: %s archive %s from library file %s",
  8263. item.id,
  8264. "Reused" if reused_archive else "Created",
  8265. archive.id,
  8266. source_library_file_id,
  8267. )
  8268. except Exception as e:
  8269. logger.warning(
  8270. "Queue item %s: Failed to create archive from library file: %s",
  8271. queue_item_id,
  8272. e,
  8273. exc_info=True,
  8274. )
  8275. await db.rollback()
  8276. item = await db.get(PrintQueueItem, queue_item_id)
  8277. if item:
  8278. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8279. return
  8280. await self._power_off_if_needed(db, item)
  8281. return
  8282. if not archive:
  8283. if not await self._fail_dispatch(db, item, "Failed to create archive from library file"):
  8284. return
  8285. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  8286. await self._power_off_if_needed(db, item)
  8287. return
  8288. # The photos follow the file into the archive that replaces it, for
  8289. # the same reason the siblings do (#3077). After the commit above,
  8290. # never before it: that commit can fail ("database is locked",
  8291. # #1853) and roll the library row back, and photos already moved
  8292. # would leave it naming a directory that no longer exists. The
  8293. # file and thumbnail unlinks are deferred for the same reason.
  8294. if consumed_library_file_id is not None and consumed_photos:
  8295. # Held as a plain int, read here while the session is still
  8296. # healthy, because the handler below may not touch an ORM
  8297. # instance at all. The commit it exists for fails inside the
  8298. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  8299. # first DML statement, so a busy writer surfaces as "database
  8300. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  8301. # internally through safe_reraise before re-raising, which
  8302. # expires every loaded instance and leaves the session in
  8303. # pending-rollback state -- so `archive.id` inside the except
  8304. # would itself raise PendingRollbackError and the rollback
  8305. # below would never be reached.
  8306. archive_id = archive.id
  8307. try:
  8308. carried_photos = move_library_photos(
  8309. consumed_library_file_id,
  8310. consumed_photos,
  8311. archive_photos_dir(archive),
  8312. )
  8313. if carried_photos:
  8314. archive.photos = list(archive.photos or []) + carried_photos
  8315. await db.commit()
  8316. except Exception as e:
  8317. # The archive and the delete are already committed; the
  8318. # print goes ahead either way. Worst case the pictures sit
  8319. # unnamed in the archive's own directory.
  8320. #
  8321. # Ints only until the rollback has run, per the note above,
  8322. # which is why this logs queue_item_id and not item.id --
  8323. # the sibling handler forty lines up does the same.
  8324. logger.warning(
  8325. "Queue item %s: failed to carry library photos into archive %s: %s",
  8326. queue_item_id,
  8327. archive_id,
  8328. e,
  8329. )
  8330. await db.rollback()
  8331. # rollback() expires every loaded instance, and in async
  8332. # SQLAlchemy the next plain attribute read is lazy IO
  8333. # outside the greenlet -- MissingGreenlet, which would turn
  8334. # this cosmetic failure into a dispatch crash in exactly the
  8335. # "database is locked" case the block exists for (#1853).
  8336. # The nozzle guard, the upload and the start all keep
  8337. # reading item, archive and printer, so all three go back
  8338. # into the session before falling through.
  8339. item = await db.get(PrintQueueItem, queue_item_id)
  8340. archive = await db.get(PrintArchive, archive_id)
  8341. printer = await db.get(Printer, item.printer_id) if item else None
  8342. if not item or not archive or not printer:
  8343. logger.error(
  8344. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  8345. queue_item_id,
  8346. archive_id,
  8347. )
  8348. return
  8349. else:
  8350. # Neither archive nor library file specified
  8351. if not await self._fail_dispatch(db, item, "No source file specified"):
  8352. return
  8353. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  8354. await self._power_off_if_needed(db, item)
  8355. return
  8356. # Check file exists on disk
  8357. if not file_path.exists():
  8358. if not await self._fail_dispatch(db, item, "Source file not found on disk"):
  8359. return
  8360. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  8361. await self._power_off_if_needed(db, item)
  8362. return
  8363. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  8364. # size dispatched to a printer with a different nozzle installed is
  8365. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  8366. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  8367. # gives the user no idea what went wrong. Catch it here, before we spend
  8368. # time preheating and uploading, and fail with an actionable message.
  8369. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  8370. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  8371. # the printer hasn't reported its nozzles yet, we fall through and let the
  8372. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  8373. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  8374. # as one of the two hotends is a 0.6.
  8375. #
  8376. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  8377. # (#2885): the printer fetches one as part of starting the print, so the
  8378. # set to test against is "reachable", not "currently mounted". This runs
  8379. # well before the rack picker at the bottom of this method, so without
  8380. # the rack in scope here that picker never got the chance to run.
  8381. sliced_nozzle = archive.nozzle_diameter if archive else None
  8382. if sliced_nozzle:
  8383. nozzle_status = printer_manager.get_status(item.printer_id)
  8384. installed = _installed_nozzle_diameters(nozzle_status)
  8385. rack = _rack_nozzle_diameters(nozzle_status)
  8386. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  8387. if mismatch_msg:
  8388. if not await self._fail_dispatch(db, item, mismatch_msg):
  8389. return
  8390. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  8391. await notification_service.on_queue_job_failed(
  8392. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8393. printer_id=printer.id,
  8394. printer_name=printer.name,
  8395. reason=mismatch_msg,
  8396. db=db,
  8397. )
  8398. try:
  8399. await ws_manager.send_queue_item_failed(
  8400. user_id=item.created_by_id,
  8401. queue_item_id=item.id,
  8402. printer_id=item.printer_id,
  8403. reason="nozzle_mismatch",
  8404. )
  8405. except Exception:
  8406. pass
  8407. await self._power_off_if_needed(db, item)
  8408. return
  8409. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  8410. # bed (and chamber, if applicable) is at temperature when the firmware
  8411. # starts the actual print routine. Best-effort: any failure logs and
  8412. # falls through to the normal upload+start path rather than turning a
  8413. # configuration issue into a failed queue item.
  8414. # Returns False only when the item was cancelled or deleted while the
  8415. # stage was holding at temperature. Uploading and starting it anyway
  8416. # would print a job the user has already called off, so abandon the
  8417. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  8418. if not await self._preheat_and_soak(db, item, printer, archive):
  8419. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  8420. return
  8421. # See `_effective_plate_id` for why this is resolved once here rather
  8422. # than each site below repeating `item.plate_id or 1`.
  8423. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  8424. # G-code injection for auto-print systems (#422)
  8425. injected_path = None
  8426. # #2547: tracked separately from `injected_path`, which is also set when
  8427. # only a START snippet was injected. Only an END snippet changes what the
  8428. # camera sees at print completion.
  8429. end_gcode_injected = False
  8430. if item.gcode_injection:
  8431. try:
  8432. snippets_raw = await self._get_setting(db, "gcode_snippets")
  8433. if snippets_raw:
  8434. snippets = json.loads(snippets_raw)
  8435. model_snippets = snippets.get(printer.model, {})
  8436. start_gc = (model_snippets.get("start_gcode") or "").strip()
  8437. end_gc = (model_snippets.get("end_gcode") or "").strip()
  8438. if start_gc or end_gc:
  8439. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  8440. injected_path = inject_gcode_into_3mf(
  8441. file_path, effective_plate_id, start_gc or None, end_gc or None
  8442. )
  8443. if injected_path:
  8444. file_path = injected_path
  8445. end_gcode_injected = bool(end_gc)
  8446. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  8447. else:
  8448. logger.warning(
  8449. "Queue item %s: G-code injection returned no result, using original", item.id
  8450. )
  8451. except Exception as e:
  8452. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  8453. # #2547: the finish-photo path can't learn from telemetry that this print
  8454. # ends with user End G-code — which means the plate may be gone by the
  8455. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  8456. # the print once the printer confirms it running.
  8457. if end_gcode_injected:
  8458. print_dispatch_context.mark_pending(printer.id)
  8459. # Upload to root directory (not /cache/) - the start_print command references
  8460. # files by name only (ftp://{filename}), so they must be in the root
  8461. remote_filename = derive_remote_filename(filename)
  8462. remote_path = f"/{remote_filename}"
  8463. # Get FTP retry settings
  8464. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  8465. logger.info(
  8466. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  8467. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  8468. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  8469. )
  8470. # Release the pooled DB connection before the FTP delete/upload (#2572).
  8471. # Every read this method needs (printer, archive/library, preheat) is
  8472. # done, and the library-file branch already committed its archive
  8473. # creation. Without this the transaction opened by the first SELECT above
  8474. # stays "idle in transaction" for the entire upload — multiple seconds
  8475. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  8476. # a farm dispatching many jobs at once then exhausts the pool. This was
  8477. # correlated to an exact idle-in-transaction session on a 93-printer farm
  8478. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  8479. # readable; the status writes below (upload-failure path and the
  8480. # pending->printing CAS) transparently open a fresh transaction.
  8481. # The owner is read here, after preheat, so the commit releases this read too.
  8482. toast_uid = await self._queue_owner_id(db, item)
  8483. await db.commit()
  8484. # Delete existing file if present (avoids 553 error on overwrite)
  8485. try:
  8486. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  8487. delete_result = await delete_file_async(
  8488. printer.ip_address,
  8489. printer.access_code,
  8490. remote_path,
  8491. socket_timeout=ftp_timeout,
  8492. printer_model=printer.model,
  8493. # This delete and the upload below are one bounded, user-initiated
  8494. # unit -- at most nine connections -- so neither skips on the
  8495. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  8496. # trace this delete took the TLS failure and armed the cool-off,
  8497. # and the upload's four attempts were then spent against it
  8498. # without a socket being opened.
  8499. respect_handshake_cooloff=False,
  8500. )
  8501. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  8502. except Exception as e:
  8503. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  8504. # Dispatch toast — announce the upload start with the total byte
  8505. # count so the frontend can render an honest progress bar.
  8506. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  8507. try:
  8508. total_bytes = file_path.stat().st_size
  8509. except OSError:
  8510. total_bytes = 0
  8511. try:
  8512. await ws_manager.send_queue_item_uploading(
  8513. user_id=toast_uid,
  8514. queue_item_id=item.id,
  8515. printer_id=item.printer_id,
  8516. printer_name=printer.name,
  8517. file_name=toast_file_name,
  8518. total_bytes=total_bytes,
  8519. )
  8520. except Exception:
  8521. pass # toast is best-effort
  8522. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  8523. # A deadline expiry gets its own message: "check your SD card" is the
  8524. # wrong advice for a link that was simply too slow to finish (#2529).
  8525. upload_error: str | None = None
  8526. # Why the upload failed, straight from the client rather than inferred.
  8527. # Owned here, so a background fetch for another print cannot overwrite
  8528. # it between the failure and the sentence built from it (#2899).
  8529. upload_failure = FtpFailureReport()
  8530. try:
  8531. if ftp_retry_enabled:
  8532. uploaded = await with_ftp_retry(
  8533. upload_file_async,
  8534. printer.ip_address,
  8535. printer.access_code,
  8536. file_path,
  8537. remote_path,
  8538. socket_timeout=ftp_timeout,
  8539. printer_model=printer.model,
  8540. progress_callback=progress_bridge,
  8541. respect_handshake_cooloff=False,
  8542. failure=upload_failure,
  8543. max_retries=ftp_retry_count,
  8544. retry_delay=ftp_retry_delay,
  8545. operation_name=f"Upload print to {printer.name}",
  8546. )
  8547. else:
  8548. uploaded = await upload_file_async(
  8549. printer.ip_address,
  8550. printer.access_code,
  8551. file_path,
  8552. remote_path,
  8553. socket_timeout=ftp_timeout,
  8554. printer_model=printer.model,
  8555. progress_callback=progress_bridge,
  8556. respect_handshake_cooloff=False,
  8557. failure=upload_failure,
  8558. )
  8559. except UploadCancelled as e:
  8560. uploaded = False
  8561. upload_error = (
  8562. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  8563. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  8564. )
  8565. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  8566. except Exception as e:
  8567. uploaded = False
  8568. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  8569. # Clean up injected temp file after upload attempt
  8570. if injected_path and injected_path.exists():
  8571. injected_path.unlink(missing_ok=True)
  8572. # Again after the upload, which can take minutes: an owner deleted
  8573. # meanwhile gets no more toasts, and neither does whoever has their id.
  8574. toast_uid = await self._queue_owner_id(db, item)
  8575. # The printer's copy at this path was replaced (or deleted above): the
  8576. # file browser's previews must not show the old one.
  8577. from backend.app.services.printer_file_cache import printer_file_cache
  8578. printer_file_cache.forget(printer.id, remote_path)
  8579. if not uploaded:
  8580. # This used to be one string for every upload failure, telling
  8581. # everyone to check the SD card. The client knows which of seven
  8582. # things went wrong and logs each one differently; it just had no
  8583. # way to say so here, so the card got named even for a TLS
  8584. # handshake that never reached the printer's filesystem (#2899).
  8585. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  8586. failure = upload_failure.failure
  8587. if failure is not None and failure.kind is FtpFailureKind.STORAGE:
  8588. try:
  8589. validate_print_filename(remote_filename)
  8590. except InvalidFilenameError as e:
  8591. # This 553 is the file's name, which no card can hold, not
  8592. # the printer's storage: it would be refused on every retry
  8593. # and every printer, so this item fails and the queue goes on.
  8594. upload_error = f"The printer could not create the file {remote_filename!r}: {e}. Rename the file."
  8595. error_msg = upload_error
  8596. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  8597. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid, failure.kind)
  8598. return
  8599. if not await self._fail_dispatch(db, item, error_msg):
  8600. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8601. return
  8602. logger.error(
  8603. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  8604. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  8605. )
  8606. # Send failure notification
  8607. await notification_service.on_queue_job_failed(
  8608. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8609. printer_id=printer.id,
  8610. printer_name=printer.name,
  8611. # The same sentence the queue shows. A push notification saying
  8612. # something different from the UI is its own small bug (#2899).
  8613. reason=error_msg,
  8614. db=db,
  8615. )
  8616. try:
  8617. await ws_manager.send_queue_item_failed(
  8618. user_id=toast_uid,
  8619. queue_item_id=item.id,
  8620. printer_id=item.printer_id,
  8621. reason="upload_failed",
  8622. )
  8623. except Exception:
  8624. pass
  8625. await self._power_off_if_needed(db, item)
  8626. return
  8627. # The printer took a file, so any run of refused uploads is over: the
  8628. # next refusal starts again at the shortest backoff, and notifies (#3210).
  8629. self._upload_refusals.pop(printer.id, None)
  8630. self._upload_refusal_kind.pop(printer.id, None)
  8631. self._upload_refusal_notified.pop(printer.id, None)
  8632. # Parse AMS mapping if stored
  8633. ams_mapping = None
  8634. if item.ams_mapping:
  8635. try:
  8636. ams_mapping = json.loads(item.ams_mapping)
  8637. except json.JSONDecodeError:
  8638. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  8639. # Register as expected print so we don't create a duplicate archive
  8640. # Only applicable for archive-based prints
  8641. if archive:
  8642. from backend.app.main import register_expected_print
  8643. register_expected_print(
  8644. item.printer_id,
  8645. remote_filename,
  8646. archive.id,
  8647. ams_mapping=ams_mapping,
  8648. # Read after the upload (toast_uid): a user deleted meanwhile gets
  8649. # no print-start email, and neither does whoever has their id.
  8650. created_by_id=toast_uid,
  8651. cost_center_id=item.cost_center_id,
  8652. # The plate actually dispatched, not the queue item's raw
  8653. # column: on None, `register_expected_print` stores nothing,
  8654. # and `extract_filament_usage_from_3mf` then books every
  8655. # filament in the file rather than the one plate that printed.
  8656. plate_id=effective_plate_id,
  8657. )
  8658. # Registration happens before the print command by necessity (the
  8659. # printer can report the print before the send returns), so record
  8660. # what to undo if we never get as far as sending. `_dispatch_one`
  8661. # rolls back anything still pending here on every exit — exception,
  8662. # early return, or cancel winning the CAS below.
  8663. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  8664. # Propagate the queue item's owner into printer_manager so the
  8665. # print-complete callback can credit the user in the PrintLogEntry
  8666. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  8667. # items) or when the user clicks the manual-start button.
  8668. await self._propagate_owner_to_printer_manager(db, item)
  8669. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  8670. # This prevents phantom reprints if the backend crashes/restarts after the
  8671. # print command is sent but before the status update is committed.
  8672. # If we crash after this commit but before start_print(), the item will be
  8673. # in "printing" status without actually printing - but that's safer than
  8674. # accidentally reprinting the same file hours later.
  8675. #
  8676. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  8677. # initial pending read at the top of check_queue and this point) flips
  8678. # the row to "cancelled" in a separate session. Without the WHERE
  8679. # status='pending' clause, the unconditional update here would silently
  8680. # overwrite that cancellation and we'd ship the MQTT start_print below
  8681. # — printer obeys, user sees "I pressed cancel and the print started".
  8682. # rowcount==0 means the user won the race; bail out, best-effort delete
  8683. # the file we just uploaded, do NOT send start_print.
  8684. now_utc = datetime.now(timezone.utc)
  8685. billing_run_id = str(uuid.uuid4())
  8686. # Written with the move to printing, so a retried send replaces the
  8687. # last answer and a cancelled one leaves the row alone (#3279).
  8688. color_substitutions = await self._color_substitutions_for(db, item)
  8689. cas = await db.execute(
  8690. update(PrintQueueItem)
  8691. .where(PrintQueueItem.id == item.id)
  8692. .where(PrintQueueItem.status == "pending")
  8693. .values(
  8694. status="printing",
  8695. started_at=now_utc,
  8696. billing_run_id=billing_run_id,
  8697. color_substitutions=color_substitutions,
  8698. )
  8699. )
  8700. await db.commit()
  8701. if cas.rowcount == 0:
  8702. logger.info(
  8703. "Queue item %s no longer pending at print-command time "
  8704. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  8705. item.id,
  8706. )
  8707. try:
  8708. await delete_file_async(
  8709. printer.ip_address,
  8710. printer.access_code,
  8711. remote_path,
  8712. socket_timeout=ftp_timeout,
  8713. printer_model=printer.model,
  8714. )
  8715. except Exception as cleanup_err:
  8716. logger.debug(
  8717. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  8718. item.id,
  8719. cleanup_err,
  8720. )
  8721. try:
  8722. await ws_manager.send_queue_item_failed(
  8723. user_id=toast_uid,
  8724. queue_item_id=item.id,
  8725. printer_id=item.printer_id,
  8726. reason="cancelled_mid_dispatch",
  8727. )
  8728. except Exception:
  8729. pass
  8730. return
  8731. # Sync the in-memory item so subsequent code that reads item.status /
  8732. # item.started_at sees the values we just persisted.
  8733. item.status = "printing"
  8734. item.started_at = now_utc
  8735. item.billing_run_id = billing_run_id
  8736. if archive is not None:
  8737. archive.billing_run_id = billing_run_id
  8738. # Legacy transaction deletion used an archive-wide skip flag.
  8739. # A newly dispatched run has its own UUID/tombstone, so it must be
  8740. # billable independently of any older deleted run on this archive.
  8741. archive.wallet_charge_skipped = False
  8742. # Persist before MQTT send so completion and restart recovery can
  8743. # always recover the internal billing identity.
  8744. await db.commit()
  8745. for cleanup_path in cleanup_disk_paths:
  8746. try:
  8747. if cleanup_path.exists():
  8748. cleanup_path.unlink()
  8749. except OSError as cleanup_err:
  8750. logger.warning(
  8751. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  8752. json.dumps(
  8753. {
  8754. "queue_item_id": item.id,
  8755. "path": str(cleanup_path),
  8756. "error": str(cleanup_err),
  8757. },
  8758. sort_keys=True,
  8759. ),
  8760. )
  8761. # Clear the awaiting-plate-clear flag now that we're starting a new print
  8762. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  8763. # #1898: with the opt-in default-good setting, moving on to the next
  8764. # print resolves the previous print's unanswered outcome prompt as
  8765. # "good" — this path also covers the camera-based plate detection,
  8766. # which releases the gate by allowing dispatch rather than by an
  8767. # explicit acknowledgment. Rides on the dispatch transaction.
  8768. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  8769. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  8770. await resolve_pending_confirmation_as_good(db, item.printer_id)
  8771. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  8772. # Capture state before dispatch so the watchdog can detect whether the
  8773. # printer actually transitioned (#967). Also capture subtask_id so the
  8774. # watchdog can recognise "command landed but state hasn't flipped yet"
  8775. # on slow H2D transitions (#1078).
  8776. pre_status = printer_manager.get_status(item.printer_id)
  8777. pre_state = getattr(pre_status, "state", None) if pre_status else None
  8778. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  8779. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  8780. # #1721: respect the user's explicit timelapse choice. The #1397
  8781. # force-on at dispatch was removed because it caused per-layer nozzle
  8782. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  8783. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  8784. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  8785. # FINISH-state fallback — no need to force a video.
  8786. effective_timelapse = bool(item.timelapse)
  8787. # Nozzle-rack fallback (#2800). A job that never passed through the
  8788. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  8789. # dispatches with no nozzle field at all and chooses for itself — which
  8790. # is how a print levelled on one hotend and then printed on another,
  8791. # millimetres above the plate. Derive the per-slot extruder assignment
  8792. # from the file being dispatched.
  8793. #
  8794. # Done here rather than at queue time because this is the first point
  8795. # that knows both the actual printer and the actual file: an item can
  8796. # be created without a printer (model-based assignment), reassigned
  8797. # afterwards, or have its file swapped for a G-code-injected copy just
  8798. # above. Every queue-creation path — the print dialog, a bulk library
  8799. # add, the webhook, a pipeline run — is covered by the one call.
  8800. # Skipped when the item already carries a Bambu Studio capture: that
  8801. # one wins downstream anyway, so reading the 3MF again would be work
  8802. # thrown away on every dispatch.
  8803. # Rack position resolution (#1784), tried before the #2800 fallback
  8804. # below because it can express what that one cannot: a plate wanting a
  8805. # *different* hotend off the rack per filament group. The position per
  8806. # group is the operator's pick — the 3MF states it nowhere, proven by
  8807. # sending one plate twice with different picks and finding the two
  8808. # files identical bar float noise — so it is resolved here against the
  8809. # rack as it stands right now, after the upload, not at queue time.
  8810. resolved_nozzle_mapping = None
  8811. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  8812. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  8813. if rack_plan is not None:
  8814. try:
  8815. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  8816. except (json.JSONDecodeError, TypeError):
  8817. stored_choice = {}
  8818. logger.warning(
  8819. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  8820. item.id,
  8821. item.nozzle_rack_choice,
  8822. )
  8823. # JSON object keys are strings; the groups are ints.
  8824. choice: dict[int, int] = {}
  8825. for key, value in (stored_choice or {}).items():
  8826. try:
  8827. choice[int(key)] = int(value)
  8828. except (TypeError, ValueError):
  8829. continue
  8830. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  8831. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  8832. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  8833. )
  8834. if resolved_nozzle_mapping is None and choice:
  8835. # An explicit pick that no longer holds stops the print. The
  8836. # operator named a hotend; printing from a different one is
  8837. # how a plate gets levelled on one nozzle and drawn with
  8838. # another, millimetres above the bed. Nothing has been sent
  8839. # to the printer yet, so failing here costs only the upload.
  8840. # The file is already on the SD card by this point, and a
  8841. # 3MF left there is a phantom print waiting to be started
  8842. # from the touchscreen. Same cleanup the start_print
  8843. # failure path below does, for the same reason.
  8844. try:
  8845. await delete_file_async(
  8846. printer.ip_address,
  8847. printer.access_code,
  8848. remote_path,
  8849. printer_model=printer.model,
  8850. )
  8851. except Exception:
  8852. pass # Best-effort — don't fail the error handler
  8853. if not await self._fail_dispatch(
  8854. db,
  8855. item,
  8856. (
  8857. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  8858. "Edit the item to choose another position."
  8859. ),
  8860. ):
  8861. await self._close_cancelled_dispatch_toast(item, toast_uid)
  8862. return
  8863. logger.warning(
  8864. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  8865. item.id,
  8866. printer.name,
  8867. rack_error,
  8868. choice,
  8869. [slot.get("id") for slot in live_rack],
  8870. )
  8871. await notification_service.on_queue_job_failed(
  8872. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  8873. printer_id=printer.id,
  8874. printer_name=printer.name,
  8875. reason=item.error_message,
  8876. db=db,
  8877. )
  8878. try:
  8879. await ws_manager.send_queue_item_failed(
  8880. user_id=toast_uid,
  8881. queue_item_id=item.id,
  8882. printer_id=item.printer_id,
  8883. reason="nozzle_rack_pick_stale",
  8884. )
  8885. except Exception:
  8886. pass # Best-effort — don't fail the error handler
  8887. return
  8888. if resolved_nozzle_mapping is None:
  8889. # Nothing was picked and nothing could be assigned. Falls
  8890. # through to the #2800 path, which is what ran before this
  8891. # existed — strictly not worse than today.
  8892. logger.info(
  8893. "Queue item %s: no rack positions assignable (%s); falling back",
  8894. item.id,
  8895. rack_error,
  8896. )
  8897. else:
  8898. logger.info(
  8899. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  8900. item.id,
  8901. resolved_nozzle_mapping,
  8902. rack_plan.slot_groups,
  8903. choice or "auto",
  8904. )
  8905. nozzle_slot_extruders = None
  8906. if (
  8907. not item.nozzle_mapping
  8908. and resolved_nozzle_mapping is None
  8909. and file_path is not None
  8910. and is_nozzle_rack_model(printer.model)
  8911. ):
  8912. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  8913. if slot_extruders:
  8914. nozzle_slot_extruders = json.dumps(slot_extruders)
  8915. # Every filament this plate prints is on the external spool -> the print
  8916. # must go out with use_ams=False. The firmware answers use_ams=true plus
  8917. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  8918. # table", which is what held the reporter's P1S at Heatbed preheating
  8919. # for ten minutes before it gave up (#3087). The MQTT command builder
  8920. # already downgrades a mapping that is *only* external ([254]), but a
  8921. # multi-filament project pads the slots this plate does not print with
  8922. # -1 — BambuStudio's own convention — and down there a -1 is
  8923. # indistinguishable from a slot that never resolved, which must never be
  8924. # sent to the spool holder (#2589). Here the plate's filament list says
  8925. # which is which, so the answer is exact rather than a guess.
  8926. #
  8927. # Deliberately narrow: this fires only when every consumed slot is an
  8928. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  8929. # alone and the firmware still rejects the print, exactly as today. And
  8930. # only for single-nozzle printers, mirroring the builder's own reconcile
  8931. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  8932. # whether to use the AMS, so it is not ours to rewrite.
  8933. effective_use_ams = item.use_ams
  8934. plate_uses_only_external = False
  8935. if (
  8936. ams_mapping
  8937. and file_path is not None
  8938. # Cheap gate before opening the file: with nothing on the spool
  8939. # holder anywhere in the mapping, no subset of it can be all
  8940. # external, so most dispatches never pay for the parse. The
  8941. # isinstance also keeps a malformed stored mapping (a bare number
  8942. # from a hand-edited row) failing where it always failed, in the
  8943. # command builder, rather than here.
  8944. and isinstance(ams_mapping, list)
  8945. and any(_is_external_tray(t) for t in ams_mapping)
  8946. and not _might_be_dual_nozzle(printer.model, pre_status)
  8947. ):
  8948. from backend.app.services.filament_requirements import extract_filament_requirements
  8949. consumed = _consumed_mapping_entries(
  8950. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  8951. )
  8952. if consumed and all(_is_external_tray(t) for t in consumed):
  8953. # Exact for this plate: the command builder must not turn the
  8954. # AMS back on for a real tray another plate of the file uses,
  8955. # whether the job asked for the AMS or already had it off.
  8956. plate_uses_only_external = True
  8957. if plate_uses_only_external and effective_use_ams:
  8958. effective_use_ams = False
  8959. logger.info(
  8960. "Queue item %s: every filament plate %s prints is on the external spool "
  8961. "(mapping %s) — dispatching with use_ams=False (#3087)",
  8962. item.id,
  8963. effective_plate_id,
  8964. ams_mapping,
  8965. )
  8966. # A slot that lost its K-profile selection (a power cycle resets every
  8967. # slot to the default K) would print on the default. The idle check in
  8968. # the status handler normally restores it first, but nothing guarantees
  8969. # it ran before this dispatch (#3219). Unthrottled: once per job.
  8970. # Never allowed to stop the print it is protecting.
  8971. try:
  8972. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  8973. except Exception:
  8974. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  8975. # Start the print with AMS mapping, plate_id and print options.
  8976. # nozzle_mapping rides through verbatim — JSON string captured from
  8977. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  8978. # parses + injects it only for dual-nozzle models so a null on every
  8979. # other model is a transparent pass-through. The rack fallback is
  8980. # resolved down there too, where the live rack position is known.
  8981. started = printer_manager.start_print(
  8982. item.printer_id,
  8983. remote_filename,
  8984. plate_id=effective_plate_id,
  8985. ams_mapping=ams_mapping,
  8986. bed_levelling=item.bed_levelling,
  8987. flow_cali=item.flow_cali,
  8988. vibration_cali=item.vibration_cali,
  8989. layer_inspect=item.layer_inspect,
  8990. timelapse=effective_timelapse,
  8991. use_ams=effective_use_ams,
  8992. plate_uses_only_external=plate_uses_only_external,
  8993. nozzle_offset_cali=item.nozzle_offset_cali,
  8994. nozzle_mapping=item.nozzle_mapping
  8995. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  8996. nozzle_slot_extruders=nozzle_slot_extruders,
  8997. )
  8998. if started:
  8999. # The command is away, so the expectation is now legitimate and must
  9000. # survive. Anything still in this dict when _dispatch_one exits gets
  9001. # rolled back.
  9002. self._unconfirmed_expected_print.pop(item.id, None)
  9003. self._unconfirmed_budget_reservations.discard(item.id)
  9004. self._unconfirmed_print_user.pop(item.id, None)
  9005. if item.printer_id is not None:
  9006. self._sent_unstarted_print[item.id] = (
  9007. item.printer_id,
  9008. remote_filename if archive else None,
  9009. archive.id if archive else None,
  9010. )
  9011. # Handoff to the print's own gcode: keep whatever preheat set (bed
  9012. # target, chamber target, airduct heating) — the gcode owns
  9013. # heater/flap control from here. Clearing the pin prevents
  9014. # `_dispatch_one`'s finally from unwinding a live print.
  9015. self._preheat_pin.pop(item.printer_id, None)
  9016. self._preheat_pin_bed.pop(item.printer_id, None)
  9017. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  9018. # No dispatch-toast event here: the legacy bg-dispatch path kept
  9019. # status='processing' from upload start until the printer acked
  9020. # (or timed out). The frontend derives "Awaiting printer…" purely
  9021. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  9022. # event would push the status chip out of 'PROCESSING' prematurely
  9023. # — which is exactly what the screenshot at #1625-followup
  9024. # complained about.
  9025. # Register the local 3MF in the cover-cache so /cover skips FTP
  9026. # (#1166 follow-up). file_path was resolved earlier from either the
  9027. # archive or the library file row.
  9028. if file_path is not None:
  9029. cache_3mf_download(item.printer_id, remote_filename, file_path)
  9030. # Hold the printer against further dispatches until the watchdog
  9031. # confirms the printer transitioned (or until the hard timeout).
  9032. # Prevents multi-plate batches from triple-dispatching onto the
  9033. # same H2D Pro while it digests the first project_file (#1157).
  9034. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  9035. # Watchdog: if the printer never transitions out of pre_state AND
  9036. # never advances subtask_id, the MQTT publish was accepted locally but
  9037. # didn't reach the printer (half-broken session — same shape as
  9038. # #887/#936). Revert the queue item so the next dispatch can pick it
  9039. # up instead of leaving it stuck in "printing" (#967). subtask_id
  9040. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  9041. # that would otherwise cause the item to re-dispatch as a reprint
  9042. # of the just-finished job (#1078).
  9043. if pre_state:
  9044. spawn_background_task(
  9045. self._watchdog_print_start(
  9046. item.id,
  9047. item.printer_id,
  9048. pre_state,
  9049. pre_subtask_id,
  9050. pre_gcode_file,
  9051. created_by_id=toast_uid,
  9052. ),
  9053. name=f"watchdog-print-start-{item.id}",
  9054. )
  9055. # Get estimated time for notification.
  9056. #
  9057. # This used to fall back to `library_file.print_time_seconds`, a column
  9058. # LibraryFile does not have — the print time it knows about lives in
  9059. # `file_metadata`. So a library print whose archive carried no parseable
  9060. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  9061. # AttributeError right here, *after* the printer had already been sent
  9062. # the job: the started-notification never fired, and the exception
  9063. # unwound the whole queue pass, so every other printer still waiting to
  9064. # be dispatched on that tick silently missed its turn.
  9065. #
  9066. # The queue item caches the print time at creation ("Cached from
  9067. # archive/library"), which is the value this was reaching for.
  9068. estimated_time = None
  9069. if archive and archive.print_time_seconds:
  9070. estimated_time = archive.print_time_seconds
  9071. elif item.print_time_seconds:
  9072. estimated_time = item.print_time_seconds
  9073. # Send job started notification
  9074. await notification_service.on_queue_job_started(
  9075. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9076. printer_id=printer.id,
  9077. printer_name=printer.name,
  9078. db=db,
  9079. estimated_time=estimated_time,
  9080. )
  9081. # MQTT relay - publish queue job started
  9082. try:
  9083. await mqtt_relay.on_queue_job_started(
  9084. job_id=item.id,
  9085. filename=filename,
  9086. printer_id=printer.id,
  9087. printer_name=printer.name,
  9088. printer_serial=printer.serial_number,
  9089. )
  9090. except Exception:
  9091. pass # Don't fail if MQTT fails
  9092. else:
  9093. # Clean up uploaded file from SD card to prevent phantom prints
  9094. try:
  9095. await delete_file_async(
  9096. printer.ip_address,
  9097. printer.access_code,
  9098. remote_path,
  9099. printer_model=printer.model,
  9100. )
  9101. except Exception:
  9102. pass # Best-effort — don't fail the error handler
  9103. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  9104. # state can flip from idle to active in the window between the
  9105. # pre-dispatch check above and this publish (the FTP upload takes
  9106. # seconds); start_print() then refuses to send project_file to the
  9107. # now-busy printer and returns False. Failing the item here would be
  9108. # wrong — the printer is fine, it is simply busy — so revert to
  9109. # pending and let a later tick dispatch it once the printer is idle,
  9110. # exactly like the pre-dispatch guard. Only a start_print() False on
  9111. # an idle/unknown printer is a genuine command failure.
  9112. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  9113. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  9114. logger.info(
  9115. "Queue item %s: printer %s became busy (state=%s) before the start "
  9116. "command was sent — deferring, reverting item to pending (#2598)",
  9117. item.id,
  9118. item.printer_id,
  9119. post_dispatch_state,
  9120. )
  9121. await self._defer_until_printer_idle(db, item)
  9122. return
  9123. # Print command failed - revert status
  9124. if not await self._fail_dispatch(db, item, "Failed to send print command to printer"):
  9125. await self._close_cancelled_dispatch_toast(item, toast_uid)
  9126. return
  9127. logger.error(
  9128. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  9129. f"printer_manager.start_print() returned False. "
  9130. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  9131. f"Check printer status and backend logs for details."
  9132. )
  9133. # Send failure notification
  9134. await notification_service.on_queue_job_failed(
  9135. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  9136. printer_id=printer.id,
  9137. printer_name=printer.name,
  9138. reason="Failed to send print command to printer - check printer connection and status",
  9139. db=db,
  9140. )
  9141. try:
  9142. await ws_manager.send_queue_item_failed(
  9143. user_id=toast_uid,
  9144. queue_item_id=item.id,
  9145. printer_id=item.printer_id,
  9146. reason="start_command_failed",
  9147. )
  9148. except Exception:
  9149. pass
  9150. await self._power_off_if_needed(db, item)
  9151. @staticmethod
  9152. async def _watchdog_print_start(
  9153. queue_item_id: int,
  9154. printer_id: int,
  9155. pre_state: str,
  9156. pre_subtask_id: str | None = None,
  9157. pre_gcode_file: str | None = None,
  9158. timeout: float = 90.0,
  9159. phase_b_timeout: float = 180.0,
  9160. poll_interval: float = 3.0,
  9161. created_by_id: int | None = None,
  9162. ) -> None:
  9163. """Revert a queue item if the printer never acknowledges the start command.
  9164. Bambuddy optimistically marks the queue item as "printing" right after the
  9165. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  9166. Phase A (up to ``timeout``): wait for either an active-state transition
  9167. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  9168. primary signal; subtask_id advance handles the H2D case where state can
  9169. sit at FINISH for ~50 s after the printer accepted ``project_file``
  9170. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  9171. was lost on a half-broken session (#887/#936) — revert and force
  9172. reconnect (the #967 recovery path).
  9173. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  9174. alone): keep watching for the active-state transition. subtask_id alone
  9175. proves the file landed but not that the printer started — and a printer
  9176. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  9177. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  9178. used to leave the queue item stuck in 'printing' forever because the
  9179. old watchdog returned success as soon as subtask_id advanced. If Phase
  9180. B times out, revert the queue item so the user can retry without
  9181. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  9182. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9183. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  9184. transitions that also don't emit an early subtask_id tick.
  9185. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  9186. refuses to verify our commands will never start this job or any other,
  9187. so waiting out the full 270 s and re-uploading the 3MF twice more only
  9188. burns an upload slot the rest of the farm is queued behind — that path
  9189. is for a printer that might still come good, which this one cannot
  9190. (#2732). It fails the item on the spot with the actual reason instead.
  9191. """
  9192. last_status = None
  9193. landed_on_subtask = False
  9194. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  9195. # every push carrying an `hms` key, so the fault can come and go between
  9196. # 3-second polls. Seeing it once inside the dispatch window is enough.
  9197. command_rejected = False
  9198. # Latched for the same reason as command_rejected: drying can finish, or
  9199. # be stopped by the user, part-way through the dispatch window. Seeing it
  9200. # once is what matters — it is the state the printer was in when it
  9201. # declined to start (#2758).
  9202. drying_ams_ids: list[int] = []
  9203. # The printer answered the start with a refusal: nothing will start,
  9204. # and the command was not lost, so no reconnect either.
  9205. start_refusal: tuple[str, str | None] | None = None
  9206. deadline = time.monotonic() + timeout
  9207. while time.monotonic() < deadline:
  9208. await asyncio.sleep(poll_interval)
  9209. status = printer_manager.get_status(printer_id)
  9210. if not status:
  9211. # Printer disconnected — don't mess with the DB. Drop the
  9212. # in-memory dispatch hold too so a fresh dispatch can retry
  9213. # once the printer comes back; the hard timeout would
  9214. # otherwise hold the printer unnecessarily.
  9215. scheduler._release_dispatch_hold(printer_id)
  9216. return
  9217. last_status = status
  9218. if status.state in _ACTIVE_PRINT_STATES:
  9219. # Printer is actively processing the job — release the
  9220. # post-dispatch hold so the next pending item for this printer
  9221. # can be evaluated normally. We do NOT accept arbitrary state
  9222. # transitions: a printer going FINISH -> IDLE (user dismissed
  9223. # the post-print prompt without accepting our project_file)
  9224. # would otherwise look like "command landed" and leave the
  9225. # queue item stuck in 'printing' forever (#1370).
  9226. scheduler._release_dispatch_hold(printer_id)
  9227. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9228. try:
  9229. await ws_manager.send_queue_item_acked(
  9230. user_id=created_by_id,
  9231. queue_item_id=queue_item_id,
  9232. printer_id=printer_id,
  9233. )
  9234. except Exception:
  9235. pass
  9236. return
  9237. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9238. # Checked only after the active-state exit above: a stale HMS left
  9239. # over from an earlier job must never abort a print that is visibly
  9240. # running. An actually-refused command leaves the printer idle, so
  9241. # this ordering costs the detection nothing.
  9242. if _mqtt_commands_rejected(status):
  9243. command_rejected = True
  9244. break
  9245. refusal = getattr(printer_manager.get_client(printer_id), "last_start_refusal", None)
  9246. if isinstance(refusal, tuple):
  9247. start_refusal = refusal
  9248. break
  9249. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  9250. # Phase A exit — printer accepted the file (subtask_id flipped
  9251. # to our submission id). Don't return yet: the printer may
  9252. # have accepted the command but never actually start (e.g.
  9253. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  9254. # B watches for the active-state transition.
  9255. landed_on_subtask = True
  9256. break
  9257. if landed_on_subtask and not command_rejected:
  9258. phase_b_deadline = time.monotonic() + phase_b_timeout
  9259. while time.monotonic() < phase_b_deadline:
  9260. await asyncio.sleep(poll_interval)
  9261. status = printer_manager.get_status(printer_id)
  9262. if not status:
  9263. scheduler._release_dispatch_hold(printer_id)
  9264. return
  9265. last_status = status
  9266. if status.state in _ACTIVE_PRINT_STATES:
  9267. scheduler._release_dispatch_hold(printer_id)
  9268. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9269. try:
  9270. await ws_manager.send_queue_item_acked(
  9271. user_id=created_by_id,
  9272. queue_item_id=queue_item_id,
  9273. printer_id=printer_id,
  9274. )
  9275. except Exception:
  9276. pass
  9277. return
  9278. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  9279. # Same ordering rule as Phase A: a running print wins over a
  9280. # lingering HMS.
  9281. if _mqtt_commands_rejected(status):
  9282. command_rejected = True
  9283. break
  9284. # No active-state transition. Revert the item so the scheduler can retry.
  9285. # Drop the in-memory hold so the retry isn't blocked by it.
  9286. scheduler._release_dispatch_hold(printer_id)
  9287. # Logged on every failed dispatch window, not just the last one, so a
  9288. # support bundle shows the correlation from the first attempt rather than
  9289. # only after the retry budget is spent (#2758).
  9290. if drying_ams_ids:
  9291. logger.info(
  9292. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  9293. queue_item_id,
  9294. printer_id,
  9295. ", ".join(str(i) for i in drying_ams_ids),
  9296. )
  9297. # Four outcomes from the revert attempt, each routed differently:
  9298. # "reverted": row flipped from printing -> pending, run recovery
  9299. # "gave_up": same, but the retry budget is spent — row failed
  9300. # rather than pending, so it stops going round again
  9301. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  9302. # on_print_complete or user). Skip recovery entirely
  9303. # — the print clearly landed somewhere even if the
  9304. # watchdog didn't see the active-state transition.
  9305. # "revert_failed": SQLite contention exhausted retries. Still run
  9306. # recovery so the MQTT session gets a fresh client_id
  9307. # on the half-broken-session path.
  9308. #
  9309. # The retry budget (#2555): reverting to 'pending' hands the item straight
  9310. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  9311. # the watchdog again. For a printer that is genuinely wedged that loop never
  9312. # ends — the reporter had one printer "since this morning still not launch"
  9313. # — and each lap also consumes an upload slot that the other printers in the
  9314. # farm are waiting on. Retrying is right; retrying forever is not.
  9315. async def _do_revert(db):
  9316. item = await db.get(PrintQueueItem, queue_item_id)
  9317. if not item or item.status != "printing":
  9318. return "already_moved_on"
  9319. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  9320. item.started_at = None
  9321. # The print never started: no slot printed in any colour (#3279).
  9322. item.color_substitutions = None
  9323. # Charge the attempt to the candidate that was actually dispatched, so
  9324. # a cross-model item (#671) reaches for its other file next lap instead
  9325. # of retrying the printer that just failed to start. Matched by file
  9326. # because that is what the resolver copied onto the row.
  9327. if item.library_file_id is not None:
  9328. await db.execute(
  9329. update(PrintQueueVariant)
  9330. .where(PrintQueueVariant.queue_item_id == item.id)
  9331. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  9332. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  9333. )
  9334. if command_rejected:
  9335. # No retry budget for this one: the printer refused to verify the
  9336. # command, and re-uploading the same 3MF to the same printer will
  9337. # be refused the same way. Fail now with the fix rather than after
  9338. # three laps of a message about SD cards (#2732).
  9339. item.status = "failed"
  9340. item.error_message = (
  9341. "The printer rejected the print command: MQTT command verification failed "
  9342. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  9343. "then start the job again."
  9344. )
  9345. item.completed_at = datetime.now(timezone.utc)
  9346. await db.commit()
  9347. return "command_rejected"
  9348. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  9349. item.status = "failed"
  9350. if drying_ams_ids:
  9351. # #2758: the generic message below sent the reporter looking
  9352. # at the SD card while the actual obstacle — AMS units in a
  9353. # drying cycle — was on screen the whole time. Name what we
  9354. # observed and let the user judge it; Bambuddy does not stop
  9355. # the cycle itself, because on this hardware drying can run
  9356. # alongside a print and stopping it may not be the fix.
  9357. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  9358. item.error_message = (
  9359. f"The printer accepted the file but never started printing, after "
  9360. f"{item.dispatch_attempts} attempts. {units} "
  9361. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  9362. f"some printers refuse to begin a print while an AMS is in a drying "
  9363. f"cycle, and an AMS drying without its external power supply can also "
  9364. f"leave too little power for the start-of-print calibration. Stop the "
  9365. f"drying, or connect the AMS power supply, and start the job again."
  9366. )
  9367. else:
  9368. item.error_message = (
  9369. f"The printer accepted the file but never started printing, after "
  9370. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  9371. f"prompt or error, confirm its SD card is readable, and start the job again."
  9372. )
  9373. item.completed_at = datetime.now(timezone.utc)
  9374. await release_budget_reservation(
  9375. db,
  9376. source_type="print_queue",
  9377. source_id=item.id,
  9378. status="released",
  9379. )
  9380. await db.commit()
  9381. return "gave_up"
  9382. item.status = "pending"
  9383. await db.commit()
  9384. return "reverted"
  9385. try:
  9386. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  9387. except Exception as e:
  9388. logger.warning(
  9389. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  9390. "scheduler may keep treating this item as in-flight",
  9391. queue_item_id,
  9392. printer_id,
  9393. e,
  9394. )
  9395. revert_outcome = "revert_failed"
  9396. if revert_outcome in ("command_rejected", "gave_up"):
  9397. # The item is failed: its print user and expected print must not
  9398. # pass the printer's next print off as Bambuddy's.
  9399. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True)
  9400. from backend.app.services.print_batch import refresh_batches_after
  9401. await refresh_batches_after([queue_item_id])
  9402. elif revert_outcome == "reverted":
  9403. # Another try claims the printer again. Until then no print on it
  9404. # is vouched for as this item's, except a late start of its file.
  9405. scheduler._forget_unstarted_print(queue_item_id, unless_printing=True, keep_expected=True)
  9406. elif revert_outcome == "already_moved_on":
  9407. scheduler._sent_unstarted_print.pop(queue_item_id, None)
  9408. if revert_outcome == "already_moved_on":
  9409. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  9410. # other path) already moved the item past 'printing', don't run the
  9411. # MQTT session-recovery logic below — a forced reconnect on a healthy
  9412. # session breaks ongoing prints on the same printer.
  9413. return
  9414. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  9415. if revert_outcome == "command_rejected":
  9416. logger.error(
  9417. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  9418. "failed) — the print command was rejected, not lost. Failing the item "
  9419. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  9420. queue_item_id,
  9421. printer_id,
  9422. HMS_MQTT_VERIFY_FAILED,
  9423. )
  9424. await scheduler._notify_dispatch_gave_up(
  9425. queue_item_id,
  9426. printer_id,
  9427. created_by_id,
  9428. reason="Printer rejected the print command (MQTT command verification failed)",
  9429. )
  9430. # Same reasoning as the landed_on_subtask path below: the file is on
  9431. # the printer and a forced reconnect would only add 0500_4003 to a
  9432. # problem that has nothing to do with the MQTT session (#1150).
  9433. return
  9434. if revert_outcome == "gave_up":
  9435. logger.error(
  9436. "Queue item %s: printer %d never started the print after %d dispatch "
  9437. "attempts (last one waited %.0fs) — marking the item failed instead of "
  9438. "re-uploading it again (#2555)",
  9439. queue_item_id,
  9440. printer_id,
  9441. DISPATCH_MAX_ATTEMPTS,
  9442. total_timeout,
  9443. )
  9444. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  9445. elif revert_outcome == "reverted":
  9446. if start_refusal is not None:
  9447. logger.warning(
  9448. "Queue item %s: printer %d refused the print start (result=%s, reason=%s) — "
  9449. "reverted to 'pending' for retry",
  9450. queue_item_id,
  9451. printer_id,
  9452. start_refusal[0],
  9453. start_refusal[1],
  9454. )
  9455. elif landed_on_subtask:
  9456. logger.warning(
  9457. "Queue item %s: printer %d accepted project_file (subtask_id "
  9458. "advanced) but never transitioned to an active state within "
  9459. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  9460. "for retry (#1678)",
  9461. queue_item_id,
  9462. printer_id,
  9463. total_timeout,
  9464. )
  9465. else:
  9466. logger.warning(
  9467. "Queue item %s: printer %d did not respond to print command within "
  9468. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  9469. "for retry (#967)",
  9470. queue_item_id,
  9471. printer_id,
  9472. timeout,
  9473. pre_state,
  9474. pre_subtask_id,
  9475. )
  9476. # Phase B was entered iff subtask_id advanced, which means the
  9477. # project_file landed on the printer. A forced reconnect at this point
  9478. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  9479. # skip the recovery entirely.
  9480. if landed_on_subtask or start_refusal is not None:
  9481. return
  9482. # Phase A timeout path: if the printer's gcode_file changed since
  9483. # pre-dispatch, the project_file command landed and the printer is
  9484. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  9485. # If gcode_file is unchanged, the publish was silently swallowed
  9486. # (#887/#936) and force_reconnect recovery is what we want.
  9487. client = printer_manager.get_client(printer_id)
  9488. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  9489. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  9490. if publish_landed:
  9491. logger.warning(
  9492. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  9493. "received the command and is parsing slowly. Skipping forced "
  9494. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  9495. queue_item_id,
  9496. current_gcode_file,
  9497. pre_gcode_file,
  9498. )
  9499. elif client and hasattr(client, "force_reconnect_stale_session"):
  9500. client.force_reconnect_stale_session(
  9501. f"queue print command unacknowledged after {timeout:.0f}s "
  9502. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  9503. )
  9504. # Global scheduler instance
  9505. scheduler = PrintScheduler()