print_scheduler.py 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. from dataclasses import dataclass
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. from fastapi import HTTPException
  10. from sqlalchemy import func, select, update
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from sqlalchemy.orm import selectinload
  13. from backend.app.core.config import settings
  14. from backend.app.core.database import async_session, run_with_retry
  15. from backend.app.core.tasks import spawn_background_task
  16. from backend.app.core.websocket import ws_manager
  17. from backend.app.models.archive import PrintArchive
  18. from backend.app.models.library import LibraryFile
  19. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  20. from backend.app.models.printer import Printer
  21. from backend.app.models.settings import Settings
  22. from backend.app.models.smart_plug import SmartPlug
  23. from backend.app.models.spool_assignment import SpoolAssignment
  24. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  25. from backend.app.services import print_dispatch_context
  26. from backend.app.services.bambu_ftp import (
  27. UploadCancelled,
  28. cache_3mf_download,
  29. delete_file_async,
  30. get_ftp_retry_settings,
  31. upload_file_async,
  32. with_ftp_retry,
  33. )
  34. from backend.app.services.bambu_mqtt import HMS_MQTT_VERIFY_FAILED
  35. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  36. from backend.app.services.finance_budget import (
  37. create_budget_reservation,
  38. release_budget_reservation,
  39. validate_print_budget,
  40. )
  41. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  42. from backend.app.services.notification_service import notification_service
  43. from backend.app.services.printer_manager import (
  44. printer_manager,
  45. supports_airduct,
  46. supports_chamber_heater,
  47. supports_chamber_temp,
  48. supports_drying,
  49. supports_drying_while_printing,
  50. )
  51. from backend.app.services.smart_plug_manager import smart_plug_manager
  52. from backend.app.utils.filename import derive_remote_filename
  53. from backend.app.utils.printer_models import is_gcode_compatible, normalize_printer_model
  54. logger = logging.getLogger(__name__)
  55. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  56. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  57. # byte gate) from before the scheduler unification. Time gate keeps small
  58. # files from going silent (a single 8 KB chunk fires once and that's it);
  59. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  60. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  61. # sub-200 ms files.
  62. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  63. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  64. class _UploadProgressBridge:
  65. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  66. ``upload_file_async`` runs the FTP transfer in an executor thread and
  67. invokes its ``progress_callback`` from that thread, so the callback
  68. body cannot ``await`` directly. This bridge captures the asyncio loop
  69. at construction (on the scheduler thread) and uses
  70. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  71. matches the legacy background_dispatch.py path 1:1 so the toast feels
  72. identical to the pre-#1625 experience.
  73. Failures inside the emit are swallowed — progress is a UX nicety, the
  74. upload itself must not fail because of a WS hiccup.
  75. """
  76. def __init__(self, user_id: int | None, queue_item_id: int):
  77. self._user_id = user_id
  78. self._queue_item_id = queue_item_id
  79. try:
  80. self._loop = asyncio.get_running_loop()
  81. except RuntimeError:
  82. self._loop = None
  83. self._last_emit_bytes = 0
  84. self._last_emit_monotonic = 0.0
  85. self._has_emitted = False
  86. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  87. if self._loop is None or total_bytes <= 0:
  88. return
  89. now = time.monotonic()
  90. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  91. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  92. # the four matter most: first-call so the user sees something even
  93. # for sub-chunk-size files; uploaded >= total so the bar locks at
  94. # 100% even when the throttle would otherwise eat it.
  95. should_emit = (
  96. not self._has_emitted
  97. or bytes_transferred >= total_bytes
  98. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  99. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  100. )
  101. if not should_emit:
  102. return
  103. self._has_emitted = True
  104. self._last_emit_bytes = bytes_transferred
  105. self._last_emit_monotonic = now
  106. try:
  107. asyncio.run_coroutine_threadsafe(
  108. ws_manager.send_queue_item_upload_progress(
  109. user_id=self._user_id,
  110. queue_item_id=self._queue_item_id,
  111. bytes_transferred=bytes_transferred,
  112. total_bytes=total_bytes,
  113. ),
  114. self._loop,
  115. )
  116. except Exception:
  117. pass # progress is best-effort, never block the upload
  118. # Bambu firmware states that mean the project_file has actually been accepted
  119. # and the printer is now processing / running / paused mid-print. Used by the
  120. # dispatch watchdog (#1370): a transition into one of these states means the
  121. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  122. # a post-print prompt) is NOT a valid "command landed" signal even though the
  123. # state value did change. SLICING is included because some firmwares park
  124. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  125. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  126. # How many times the start-watchdog may revert an item to 'pending' before it
  127. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  128. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  129. # both never recovers and starves the other printers of dispatch slots. Three
  130. # is chosen to clear the transient causes the watchdog already recovers from —
  131. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  132. # force-reconnect on the very next attempt — while still bounding the loop.
  133. DISPATCH_MAX_ATTEMPTS = 3
  134. # Filament type equivalence groups — types within the same group are
  135. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  136. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  137. ["PA-CF", "PA12-CF", "PAHT-CF"],
  138. ]
  139. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  140. for _group in _FILAMENT_TYPE_GROUPS:
  141. _canonical = _group[0].upper()
  142. for _t in _group:
  143. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  144. def _canonical_filament_type(ftype: str) -> str:
  145. """Return canonical type for equivalence matching."""
  146. upper = ftype.upper()
  147. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  148. @dataclass(slots=True)
  149. class _ModelCandidate:
  150. """One (file, printer model) pair the model-based matcher may try.
  151. Model-based assignment used to have exactly one of these per item, held
  152. directly in the item's own columns. Cross-model queue items (#671) have
  153. several, held in ``print_queue_variants``. Both shapes are normalised into
  154. this so the matching, the cross-model gate and the waiting-reason handling
  155. are written once and an item without variants provably takes the same path
  156. it took before variants existed.
  157. ``variant`` is None for the item's own columns and set for a real variant
  158. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  159. item once that candidate wins.
  160. """
  161. target_model: str | None
  162. sliced_for: str | None
  163. required_filament_types: str | None
  164. filament_overrides: str | None
  165. variant: "PrintQueueVariant | None" = None
  166. def _sliced_for_model(archive, library_file) -> str | None:
  167. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  168. if archive is not None:
  169. return archive.sliced_for_model
  170. if library_file is not None and library_file.file_metadata:
  171. return library_file.file_metadata.get("sliced_for_model")
  172. return None
  173. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  174. """Candidate files for ``item``, best first.
  175. An item with no variant rows yields exactly one candidate built from its own
  176. columns — the pre-#671 behaviour, unchanged.
  177. Variants come back least-attempted first, ties broken by the user's
  178. ``position``. On the first pass every count is zero, so this is purely the
  179. user's priority order. After a start-watchdog bounce the printer that failed
  180. drops behind, so the next lap tries the other machine rather than spending the
  181. item's whole retry budget on the one that is wedged. Once every candidate has
  182. been tried equally often they cycle again, which keeps the item-level
  183. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  184. still gives up, it just does not give up without trying them.
  185. """
  186. if not item.variants:
  187. if not item.archive_id and not item.library_file_id:
  188. # Nothing to print at all. Dispatching would fail deep in the upload
  189. # on "No archive_id or library_file_id"; the caller holds the item
  190. # with an explanation instead.
  191. return []
  192. return [
  193. _ModelCandidate(
  194. target_model=item.target_model,
  195. sliced_for=_sliced_for_model(item.archive, item.library_file),
  196. required_filament_types=item.required_filament_types,
  197. filament_overrides=item.filament_overrides,
  198. )
  199. ]
  200. # Drop candidates whose file is gone or in the trash. Both are reachable and
  201. # neither is covered by the schema: library deletes are soft (the row lives
  202. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  203. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  204. # fires there and a hard delete leaves the variant row pointing at nothing.
  205. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  206. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  207. return [
  208. _ModelCandidate(
  209. target_model=v.target_model,
  210. sliced_for=_sliced_for_model(None, v.library_file),
  211. required_filament_types=v.required_filament_types,
  212. filament_overrides=v.filament_overrides,
  213. variant=v,
  214. )
  215. for v in ordered
  216. ]
  217. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  218. """Fold one waiting reason per candidate into a single line for the item.
  219. A cross-model item produces a reason per candidate, and pasting them
  220. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  221. — on which machine?). Each reason is prefixed with its model, except in the
  222. single-candidate case where the item already displays its target model and
  223. the prefix would be noise.
  224. Identical reasons collapse rather than repeat, so three idle-less models
  225. read as one clause.
  226. When *every* candidate is merely busy the parts are joined with the ``" | "``
  227. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  228. unprefixed. That case must keep testing busy-only: a fleet that is simply
  229. printing needs no user action, and labelling the clauses would turn each pass
  230. over a two-model item into a "job waiting" notification.
  231. """
  232. reasons = [(model, reason) for model, reason in per_model if reason]
  233. if not reasons:
  234. return None
  235. if len(reasons) == 1:
  236. return reasons[0][1]
  237. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  238. if len(distinct) == 1:
  239. return distinct[0]
  240. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  241. return " | ".join(distinct)
  242. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  243. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  244. """Human label for the models an item is waiting on ("H2S or H2C").
  245. Notifications take a single target model. For a cross-model item the item's
  246. own ``target_model`` is whichever variant happens to be first, which reads as
  247. a lie once it is the H2C that actually runs — so name all of them.
  248. """
  249. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  250. if not models:
  251. return None
  252. return " or ".join(models)
  253. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  254. """True if ``mapping`` is a non-empty list whose every entry is the
  255. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  256. Such a mapping is a bug artifact: a frontend status-load race can serialize
  257. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  258. recomputed from live status at dispatch rather than trusted, otherwise it
  259. reaches the print command and is silently downgraded to external-spool mode.
  260. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  261. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  262. explicit external selection (``>= 254``) is NOT unresolved either — those
  263. keep their meaning.
  264. """
  265. if not isinstance(mapping, list) or not mapping:
  266. return False
  267. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  268. def _mqtt_commands_rejected(status) -> bool:
  269. """True when the printer is currently reporting that it refused a command.
  270. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  271. a control command it could not verify. Queries still answer, so the printer
  272. looks connected and idle while project_file, gcode_line and
  273. ams_change_filament are all dropped — no amount of waiting or re-uploading
  274. changes that (#2732).
  275. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  276. ``print_error`` path builds HMSError differently), so this is safe to call on
  277. every watchdog poll.
  278. """
  279. for err in getattr(status, "hms_errors", None) or []:
  280. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  281. return True
  282. return False
  283. def _drying_ams_ids(status) -> list[int]:
  284. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  285. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  286. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  287. started (#2758) — it is a diagnostic, not a gate.
  288. Deliberately not used to block or stop drying before dispatch. This printer
  289. class supports drying concurrently with an active print
  290. (``supports_drying_while_printing``), so drying is not incompatible with
  291. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  292. while two AMS units were drying, one of them without its external PSU. Until
  293. it is known whether the blocker is drying itself or the power budget
  294. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  295. hardware is perfectly happy to continue.
  296. """
  297. ids: list[int] = []
  298. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  299. if not isinstance(unit, dict):
  300. continue
  301. try:
  302. if int(unit.get("dry_time") or 0) > 0:
  303. ids.append(int(unit.get("id", 0)))
  304. except (TypeError, ValueError):
  305. continue
  306. return ids
  307. def _installed_nozzle_diameters(status) -> list[float]:
  308. """Parse the installed nozzle diameters from a PrinterState (#1899).
  309. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  310. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  311. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  312. told us its nozzle hardware" — callers must treat that as unknown, not as a
  313. mismatch, so we never block a print on missing data.
  314. """
  315. diameters: list[float] = []
  316. for nozzle in getattr(status, "nozzles", None) or []:
  317. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  318. try:
  319. value = float(raw)
  320. except (TypeError, ValueError):
  321. continue
  322. if value > 0:
  323. diameters.append(value)
  324. return diameters
  325. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  326. """Return an actionable error message when the sliced nozzle can't be
  327. printed on any installed nozzle, else None (#1899).
  328. Fail-safe: returns None whenever we lack the data to judge — no sliced
  329. diameter, or the printer reported no nozzles — so a print is only ever
  330. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  331. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  332. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  333. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  334. """
  335. if not sliced_nozzle or not installed:
  336. return None
  337. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  338. return None
  339. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  340. return (
  341. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  342. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  343. f"install the matching nozzle before printing."
  344. )
  345. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  346. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  347. Shared by the required and loaded sides, which name their extruder
  348. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  349. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  350. 1 the left/deputy — and both are absent on single-nozzle printers, where
  351. naming a nozzle would be noise.
  352. """
  353. parts = [(entry.get("type") or "filament").upper()]
  354. if entry.get("color"):
  355. parts.append(str(entry["color"]))
  356. nozzle = entry.get(nozzle_key)
  357. if nozzle == 0:
  358. parts.append("(right nozzle)")
  359. elif nozzle == 1:
  360. parts.append("(left nozzle)")
  361. return " ".join(parts)
  362. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  363. """Explain that nothing loaded matches what the file needs (#2771).
  364. Only ever built for a printer with no AMS, where the loaded list is short
  365. enough to quote in full and there is no "load another spool and hit Resume"
  366. recovery — the external spool holder is all there is, so the user needs to
  367. be told which filament to put on it.
  368. """
  369. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  370. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  371. return (
  372. f"No filament loaded on this printer matches the file. It needs {want}; "
  373. f"the printer has {have} and no AMS. Load the required filament on the "
  374. f"external spool holder, or send this job to a printer that has it."
  375. )
  376. class PrintScheduler:
  377. """Background scheduler that processes the print queue."""
  378. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  379. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  380. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  381. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  382. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  383. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  384. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  385. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  386. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  387. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  388. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  389. }
  390. def __init__(self):
  391. self._running = False
  392. self._check_interval = 30 # seconds
  393. # After a pass that actually dispatched something, loop again almost
  394. # immediately instead of sleeping the full interval (#2555). A dispatch
  395. # changes printer state — a batch launch fans out over several passes as
  396. # printers free up, a wedged head-of-line job reverts to pending, an
  397. # upload slot opens — and the next batch of ready work should not have to
  398. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  399. # pending items are behind printers that are genuinely busy printing),
  400. # there is nothing to react to, so we fall back to the normal interval;
  401. # that also means this can never tight-loop, since fast ticks only
  402. # continue while dispatches keep happening and the queue is draining.
  403. self._fast_check_interval = 3 # seconds
  404. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  405. self._power_on_check_interval = 10 # seconds between connection checks
  406. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  407. self._drying_in_progress: dict[int, float] = {}
  408. # Defensive in-memory dispatch hold (#1157): a printer that just received
  409. # a project_file command must not get a second dispatch until either it
  410. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  411. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  412. # during that window the DB busy_printers seed is empirically unreliable
  413. # (multi-plate batches double-/triple-dispatched onto the same printer
  414. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  415. # or revert.
  416. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  417. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  418. # Minimum cooldown between dispatches to the same printer (covers the
  419. # H2D's project_file digestion window).
  420. self._dispatch_min_cooldown = 60.0
  421. # Hard timeout — drop the hold even if we never observed a transition,
  422. # so a lost MQTT session can't lock a printer out of the queue forever.
  423. # Matches the watchdog timeout (90 s) plus a safety margin so the
  424. # watchdog runs first on the unhappy path.
  425. self._dispatch_max_hold = 180.0
  426. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  427. # an earlier pass and is still running. `_start_print` flips the row
  428. # pending -> printing only *after* the upload completes, so until then
  429. # the row stays `pending`: each tick, check_queue excludes these
  430. # item_ids from re-selection and their printers from new dispatch /
  431. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  432. # freed slots refill on the next fast tick. check_queue is the sole,
  433. # sequential caller and the prune done-callbacks run in the same
  434. # event-loop thread, so this dict needs no lock.
  435. # item_id -> (task, printer_id)
  436. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  437. # Expected prints registered by `_start_print` that have not yet had a
  438. # print command sent. Populated at registration, dropped once
  439. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  440. # other exit. Same threading argument as `_inflight` above: one
  441. # sequential caller, callbacks on the same loop, so no lock.
  442. # item_id -> (printer_id, remote_filename, archive_id)
  443. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  444. # Budget reservations created for a dispatch whose print command has
  445. # not been confirmed yet. `_dispatch_one` releases these on every
  446. # unsuccessful exit; a successful start removes the item id and leaves
  447. # the reservation for finance_billing to consume with the archive.
  448. self._unconfirmed_budget_reservations: set[int] = set()
  449. async def run(self):
  450. """Main loop - check queue every interval."""
  451. self._running = True
  452. logger.info("Print scheduler started")
  453. await self._clear_stale_dispatch_claims(at_startup=True)
  454. while self._running:
  455. dispatched = False
  456. try:
  457. # No-op while any upload is in flight; on a quiet tick it releases
  458. # a claim whose best-effort clear failed (e.g. the database was
  459. # briefly unreachable), instead of leaving the row wedged until
  460. # the next restart.
  461. await self._clear_stale_dispatch_claims()
  462. dispatched = await self.check_queue()
  463. except Exception as e:
  464. logger.error("Scheduler error: %s", e)
  465. # Re-check quickly after a productive pass so a draining batch does
  466. # not stall behind the idle interval; otherwise sleep normally (#2555).
  467. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  468. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  469. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  470. A claim is only ever held by a live dispatch coroutine, so when this
  471. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  472. is stale. At startup that is trivially true — no coroutine survives a
  473. restart. It is equally true on any later tick where no upload is running,
  474. which is what makes this safe to repeat rather than only run once.
  475. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  476. the database is briefly unreachable at exactly the moment dispatch ends,
  477. the claim survives and the row is wedged out of the selection query. That
  478. used to last until the next restart (#2702 follow-up, seen when
  479. PostgreSQL refused a connection mid-dispatch).
  480. ``_inflight`` is populated when the task is spawned, before the coroutine
  481. claims its row, and pruned by a done-callback that cannot run before the
  482. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  483. race window and needs no age threshold. A size-derived upload deadline
  484. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  485. """
  486. if self._inflight:
  487. return
  488. try:
  489. async with async_session() as db:
  490. res = await db.execute(
  491. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  492. )
  493. await db.commit()
  494. if res.rowcount:
  495. logger.info(
  496. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  497. res.rowcount,
  498. " at startup" if at_startup else "",
  499. )
  500. except Exception as exc:
  501. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  502. def stop(self):
  503. """Stop the scheduler."""
  504. self._running = False
  505. logger.info("Print scheduler stopped")
  506. async def check_queue(self) -> bool:
  507. """Check for prints ready to start.
  508. Returns True if this pass dispatched at least one item, so the caller
  509. can loop again quickly instead of sleeping the full interval (#2555).
  510. """
  511. async with async_session() as db:
  512. # Check if shortest-job-first scheduling is enabled
  513. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  514. # Get all pending items, ordered by printer and position (or SJF order)
  515. if sjf_enabled:
  516. # SJF: group by printer (and target_model for model-based jobs),
  517. # then items already jumped get top priority (starvation guard),
  518. # then sort by print_time ascending. Items with no print time go last.
  519. result = await db.execute(
  520. select(PrintQueueItem)
  521. .where(PrintQueueItem.status == "pending")
  522. # Never re-select a row a dispatch worker has already claimed
  523. # (#2615) — belt-and-suspenders with the _inflight exclusion
  524. # below, and the guard that lets an orphaned claim be ignored
  525. # until startup reconciliation clears it.
  526. .where(PrintQueueItem.dispatching_at.is_(None))
  527. # archive/library_file are read by the cross-model gate
  528. # (#2578); eager-load once per pass instead of a lazy-load
  529. # (which would raise in async) per item.
  530. .options(
  531. selectinload(PrintQueueItem.archive),
  532. selectinload(PrintQueueItem.library_file),
  533. # Cross-model candidates (#671), plus each candidate's file
  534. # for the same cross-model gate. Lazy-loading either would
  535. # raise in async.
  536. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  537. )
  538. .order_by(
  539. PrintQueueItem.printer_id,
  540. PrintQueueItem.target_model,
  541. PrintQueueItem.been_jumped.desc(),
  542. PrintQueueItem.print_time_seconds.asc().nullslast(),
  543. PrintQueueItem.position,
  544. )
  545. )
  546. else:
  547. result = await db.execute(
  548. select(PrintQueueItem)
  549. .where(PrintQueueItem.status == "pending")
  550. # Skip rows already claimed by a dispatch worker (#2615).
  551. .where(PrintQueueItem.dispatching_at.is_(None))
  552. .options(
  553. selectinload(PrintQueueItem.archive),
  554. selectinload(PrintQueueItem.library_file),
  555. # Cross-model candidates (#671), plus each candidate's file
  556. # for the same cross-model gate. Lazy-loading either would
  557. # raise in async.
  558. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  559. )
  560. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  561. )
  562. items = list(result.scalars().all())
  563. # Drop rows whose upload is still in flight from an earlier pass
  564. # (#2602). They stay `pending` until the upload finishes, so without
  565. # this a fast tick would re-select and re-dispatch the same row.
  566. # Belt-and-suspenders with the printer exclusion below.
  567. if self._inflight:
  568. inflight_ids = set(self._inflight)
  569. items = [it for it in items if it.id not in inflight_ids]
  570. # Read plate-clear setting once per queue check. Default MUST be
  571. # False to match the schema (SettingsSchema.require_plate_clear
  572. # defaults False) and the frontend (toggle + card badge both treat a
  573. # missing value as off). When no settings row exists, a True default
  574. # here re-enabled the plate-clear gate the UI showed as disabled,
  575. # blocking dispatch to FINISH-state printers forever with no UI path
  576. # to clear it (#1865).
  577. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  578. if not items:
  579. # No dispatchable pending items — still check auto-drying on idle
  580. # printers, but keep any printer with an upload still in flight
  581. # from an earlier pass out of it (#2602): its print is imminent,
  582. # so it must not be auto-dried in the gap before the row flips to
  583. # printing. Report the pass as productive while uploads run so the
  584. # loop stays on the fast interval.
  585. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  586. await self._check_auto_drying(db, [], inflight_printers, require_plate_clear=require_plate_clear)
  587. return bool(self._inflight)
  588. logger.info(
  589. "Queue check: found %d pending items: %s",
  590. len(items),
  591. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  592. )
  593. # Seed busy_printers with printers that already have an item in 'printing'
  594. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  595. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  596. # lag several seconds behind the print command, so the next check_queue
  597. # tick still sees IDLE and would double-dispatch onto the same printer.
  598. # Without this guard, two pending items targeting the same printer
  599. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  600. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  601. busy_result = await db.execute(
  602. select(PrintQueueItem.printer_id)
  603. .where(PrintQueueItem.status == "printing")
  604. .where(PrintQueueItem.printer_id.is_not(None))
  605. )
  606. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  607. # Defense-in-depth (#1157): augment busy_printers with any printer
  608. # still in its post-dispatch hold window. Empirically, the DB seed
  609. # above can miss in-flight items in a multi-plate batch — same-file
  610. # plates were being dispatched 30 s apart while the H2D was still
  611. # digesting the first project_file. The hold is keyed in-memory and
  612. # released by the watchdog on the success path, so it adds a layer
  613. # that doesn't depend on DB row visibility or completion-callback
  614. # timing.
  615. for held_printer_id in list(self._dispatch_holds.keys()):
  616. if self._printer_in_dispatch_hold(held_printer_id):
  617. busy_printers.add(held_printer_id)
  618. # Exclude printers whose upload is still in flight from an earlier
  619. # pass (#2602). The row is `pending` until the upload finishes and
  620. # the printing-state seed / dispatch hold above only arm once the
  621. # upload completes, so this is what holds the printer (and, via
  622. # busy_printers, its auto-drying) out of the pass during the upload.
  623. for _task, inflight_pid in self._inflight.values():
  624. if inflight_pid is not None:
  625. busy_printers.add(inflight_pid)
  626. # Printers held by a Home Assistant sensor interlock (#1148) — an
  627. # enclosure door left open, say. The fixed-printer branch turns
  628. # this into a waiting_reason the user can act on; the model-based
  629. # branch hides these printers from the matcher so an "Any <model>"
  630. # job runs on a sibling instead of queueing behind the held one.
  631. #
  632. # Deliberately NOT merged into busy_printers, even though that set
  633. # already means "unavailable this pass". _check_auto_drying reads
  634. # it as "is currently printing" and would put an idle-but-held
  635. # printer down the mid-print drying path, which caps the drying
  636. # temperature and skips the queue-only gating. A held printer is
  637. # idle; it should dry exactly as it did before.
  638. #
  639. # Only sensors we actually read and found alerting appear here; see
  640. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  641. # holds nothing.
  642. interlocked: dict[int, str] = {}
  643. try:
  644. interlocked = await ha_sensor_manager.blocked_printers(db)
  645. except Exception as e:
  646. # Never let the interlock stop the queue running. A broken
  647. # lookup means no holds, not no dispatches.
  648. logger.warning("Home Assistant interlock check failed: %s", e)
  649. interlocked = {}
  650. # Log skip reasons once per queue check (not per item)
  651. skip_reasons: dict[str, int] = {}
  652. # Items selected for dispatch in this pass, one per printer. The
  653. # loop below only *decides* — the uploads happen afterwards, in
  654. # parallel (#2555). See _dispatch_selected().
  655. dispatch_ids: list[int] = []
  656. # Library rows queued with `cleanup_library_after_dispatch` (the
  657. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  658. # that prints them: the row is deleted and the 3MF is unlinked from
  659. # disk. That was safe only because dispatch was serial. Run two of
  660. # them against the same row at once and the second DELETE matches no
  661. # row (StaleDataError), and the winner's unlink can pull the file out
  662. # from under the loser's in-flight upload.
  663. #
  664. # Only the cleanup flag mutates the row. An ordinary library print
  665. # just reads it, so the common fan-out — one file, many printers,
  666. # which is exactly the reporter's workload — still goes out fully in
  667. # parallel. Narrow the guard to the mutating case; do not serialise
  668. # the case the whole fix exists for.
  669. dispatch_libs: set[int] = set()
  670. consumed_libs: set[int] = set()
  671. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  672. """True if dispatching `candidate` now would race another item's cleanup."""
  673. lib_id = candidate.library_file_id
  674. if lib_id is None:
  675. return False
  676. if candidate.cleanup_library_after_dispatch:
  677. # We would delete a row someone else in this pass is reading.
  678. return lib_id in dispatch_libs
  679. # Someone else in this pass will delete the row out from under us.
  680. return lib_id in consumed_libs
  681. def _claim_library_row(candidate: PrintQueueItem) -> None:
  682. lib_id = candidate.library_file_id
  683. if lib_id is None:
  684. return
  685. dispatch_libs.add(lib_id)
  686. if candidate.cleanup_library_after_dispatch:
  687. consumed_libs.add(lib_id)
  688. for item in items:
  689. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  690. if item.scheduled_time:
  691. sched = item.scheduled_time
  692. if sched.tzinfo is None:
  693. sched = sched.replace(tzinfo=timezone.utc)
  694. if sched > datetime.now(timezone.utc):
  695. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  696. continue
  697. # Skip items that require manual start
  698. if item.manual_start:
  699. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  700. continue
  701. if item.printer_id:
  702. # Held by a sensor interlock (#1148). Checked before the
  703. # busy_printers test that would otherwise swallow it
  704. # silently — "waiting for a printer" and "waiting for you
  705. # to shut the enclosure" need to read differently, and only
  706. # one of them is something the user can fix.
  707. #
  708. # The interlock is the only thing that writes a
  709. # waiting_reason on this branch — the model-based branch
  710. # nulls it at the moment it assigns a printer — so any
  711. # reason still standing once the hold lifts is stale and is
  712. # cleared here. Doing it at dispatch instead would leave a
  713. # shut door reading "Waiting on Enclosure Door" for as long
  714. # as the printer stayed busy with something else.
  715. interlock_reason = interlocked.get(item.printer_id)
  716. reason = f"Waiting on {interlock_reason}" if interlock_reason else None
  717. if item.waiting_reason != reason:
  718. item.waiting_reason = reason
  719. await db.commit()
  720. if interlock_reason:
  721. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  722. continue
  723. # Specific printer assignment (existing behavior)
  724. if item.printer_id in busy_printers:
  725. continue
  726. # Check if printer is idle
  727. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  728. printer_connected = printer_manager.is_connected(item.printer_id)
  729. # If printer not connected, try to power on via smart plug
  730. if not printer_connected:
  731. plugs = await self._get_smart_plugs(db, item.printer_id)
  732. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  733. if auto_on_plugs:
  734. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  735. # Power on using the plug that actually feeds the printer, and
  736. # wait for it to boot on that one only (#2629).
  737. primary_plug = self._pick_power_plug(auto_on_plugs)
  738. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  739. if powered_on:
  740. # Also turn on any remaining auto_on plugs (e.g., filter)
  741. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  742. try:
  743. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  744. await service.turn_on(extra_plug)
  745. logger.info(
  746. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  747. )
  748. except Exception as e:
  749. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  750. printer_connected = True
  751. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  752. else:
  753. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  754. busy_printers.add(item.printer_id)
  755. continue
  756. else:
  757. # No plug or auto_on disabled
  758. busy_printers.add(item.printer_id)
  759. continue
  760. # Check if printer is idle (busy with another print)
  761. if not printer_idle:
  762. # If printer is drying (not truly busy), handle based on queue_drying_block
  763. if self._drying_in_progress.get(item.printer_id):
  764. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  765. if block_for_drying:
  766. # Drying blocks queue — skip this printer
  767. busy_printers.add(item.printer_id)
  768. continue
  769. else:
  770. # Print takes priority — stop drying
  771. await self._stop_drying(item.printer_id)
  772. # Re-check idle after stopping drying
  773. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  774. if not printer_idle:
  775. busy_printers.add(item.printer_id)
  776. continue
  777. else:
  778. busy_printers.add(item.printer_id)
  779. continue
  780. # Check condition (previous print success)
  781. if item.require_previous_success:
  782. if not await self._check_previous_success(db, item):
  783. item.status = "skipped"
  784. item.error_message = "Previous print failed or was aborted"
  785. item.completed_at = datetime.now(timezone.utc)
  786. await db.commit()
  787. logger.info("Skipped queue item %s - previous print failed", item.id)
  788. # Send notification
  789. job_name = await self._get_job_name(db, item)
  790. printer = await self._get_printer(db, item.printer_id)
  791. await notification_service.on_queue_job_skipped(
  792. job_name=job_name,
  793. printer_id=item.printer_id,
  794. printer_name=printer.name if printer else "Unknown",
  795. reason="Previous print failed or was aborted",
  796. db=db,
  797. )
  798. continue
  799. # Resolve the AMS mapping when it's missing OR unresolved
  800. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  801. # frontend status-load race can persist [-1] (#2589) — and
  802. # must be recomputed from live trays rather than trusted.
  803. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  804. if unmappable:
  805. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  806. continue
  807. # Filament-deficit pre-dispatch check (#1496). If the
  808. # assigned spool can't satisfy any required slot grams,
  809. # promote the item to manual_start so the user must
  810. # acknowledge via the ▶ button (which re-checks live).
  811. if await self._block_on_filament_deficit(db, item):
  812. continue
  813. # Hold this item back for the next pass rather than racing
  814. # another dispatch over the same transient library row. The
  815. # printer is still marked busy so a later item does not jump
  816. # its place in this printer's queue.
  817. if _library_row_conflict(item):
  818. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  819. busy_printers.add(item.printer_id)
  820. continue
  821. # Queue the dispatch instead of running it here — see
  822. # _dispatch_selected(). busy_printers still gets the printer
  823. # immediately, so nothing else in this pass can target it.
  824. _claim_library_row(item)
  825. dispatch_ids.append(item.id)
  826. busy_printers.add(item.printer_id)
  827. # SJF starvation guard: mark items that were jumped
  828. if sjf_enabled and item.print_time_seconds is not None:
  829. for other in items:
  830. if (
  831. other.id != item.id
  832. and other.status == "pending"
  833. and other.printer_id == item.printer_id
  834. and not other.been_jumped
  835. and other.position < item.position
  836. and (
  837. other.print_time_seconds is None
  838. or other.print_time_seconds > item.print_time_seconds
  839. )
  840. ):
  841. other.been_jumped = True
  842. await db.commit()
  843. elif item.target_model or item.variants:
  844. # Model-based assignment - find any idle printer of matching model.
  845. # A plain model-based item has exactly one candidate, built from
  846. # its own columns. A cross-model item (#671) has one per sliced
  847. # variant and takes the first that matches, walking them in the
  848. # user's priority order so the pick is reproducible when more
  849. # than one printer is free in the same pass.
  850. candidates = _candidates_for(item)
  851. printer_id = None
  852. chosen: _ModelCandidate | None = None
  853. per_model_reasons: list[tuple[str | None, str]] = []
  854. if not candidates:
  855. # Every candidate file has been deleted or trashed out from
  856. # under this item. Hold it with something the user can act
  857. # on rather than letting it look dispatchable forever.
  858. per_model_reasons.append(
  859. (
  860. item.target_model,
  861. "Every file for this job has been deleted — add a file back or remove the item",
  862. )
  863. )
  864. for candidate in candidates:
  865. # Parse required filament types if present
  866. required_types = None
  867. if candidate.required_filament_types:
  868. try:
  869. required_types = json.loads(candidate.required_filament_types)
  870. except json.JSONDecodeError:
  871. pass # Ignore malformed filament types; treat as no constraint
  872. # Parse filament overrides if present
  873. filament_overrides = None
  874. if candidate.filament_overrides:
  875. try:
  876. filament_overrides = json.loads(candidate.filament_overrides)
  877. except json.JSONDecodeError:
  878. pass
  879. # If overrides exist, use override types for validation instead
  880. effective_types = required_types
  881. if filament_overrides:
  882. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  883. if override_types:
  884. # Merge: keep original types for non-overridden slots, add override types
  885. effective_types = sorted(set(required_types or []) | set(override_types))
  886. # Cross-model safety gate (#2578): never hand a 3MF sliced
  887. # for an incompatible model to a printer, no matter how the
  888. # row got into the DB (old rows, direct API writes). Held
  889. # as pending with an actionable waiting_reason — the user
  890. # fixes it by editing the item's target model.
  891. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  892. per_model_reasons.append(
  893. (
  894. candidate.target_model,
  895. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  896. f"{candidate.target_model} — edit the item and fix its target model",
  897. )
  898. )
  899. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  900. continue
  901. match_id, match_reason = await self._find_idle_printer_for_model(
  902. db,
  903. candidate.target_model,
  904. # Sensor-held printers are unavailable to the
  905. # matcher but stay out of busy_printers itself
  906. # (#1148) — see where `interlocked` is built.
  907. busy_printers | interlocked.keys(),
  908. effective_types,
  909. item.target_location,
  910. filament_overrides=filament_overrides,
  911. require_plate_clear=require_plate_clear,
  912. )
  913. if match_id:
  914. printer_id = match_id
  915. chosen = candidate
  916. break
  917. per_model_reasons.append((candidate.target_model, match_reason or ""))
  918. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  919. # Fold the winning variant's file and settings onto the item
  920. # before anything else looks at them — the guards below and
  921. # every step of the dispatch read the item's own columns.
  922. if chosen is not None:
  923. self._resolve_variant(item, chosen)
  924. # Update waiting_reason if changed and send notification when first waiting
  925. if item.waiting_reason != waiting_reason:
  926. was_waiting = item.waiting_reason is not None
  927. item.waiting_reason = waiting_reason
  928. await db.commit()
  929. # Send waiting notification only when transitioning to waiting state
  930. # and the reason requires user action (not just "all printers busy")
  931. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  932. job_name = await self._get_job_name(db, item)
  933. await notification_service.on_queue_job_waiting(
  934. job_name=job_name,
  935. target_model=_candidate_model_label(candidates) or item.target_model,
  936. waiting_reason=waiting_reason,
  937. db=db,
  938. )
  939. if printer_id:
  940. # Before claiming the printer: hold back rather than race
  941. # another dispatch over the same transient library row.
  942. # Checked here so a held item does not get a printer
  943. # assigned and then sit on it. See _library_row_conflict().
  944. #
  945. # No busy_printers.add() here, unlike the fixed-printer
  946. # branch above: that one protects its printer's own queue
  947. # ordering, but this item was never assigned to `printer_id`
  948. # — the matcher merely offered it. Marking it busy would
  949. # strand an idle printer for the rest of the pass.
  950. if _library_row_conflict(item):
  951. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  952. continue
  953. # Check condition (previous print success) before assigning
  954. if item.require_previous_success:
  955. if not await self._check_previous_success(db, item):
  956. item.status = "skipped"
  957. item.error_message = "Previous print failed or was aborted"
  958. item.completed_at = datetime.now(timezone.utc)
  959. await db.commit()
  960. logger.info("Skipped queue item %s - previous print failed", item.id)
  961. # Send notification
  962. job_name = await self._get_job_name(db, item)
  963. printer = await self._get_printer(db, printer_id)
  964. await notification_service.on_queue_job_skipped(
  965. job_name=job_name,
  966. printer_id=printer_id,
  967. printer_name=printer.name if printer else "Unknown",
  968. reason="Previous print failed or was aborted",
  969. db=db,
  970. )
  971. continue
  972. # Assign printer and start - clear waiting reason
  973. item.printer_id = printer_id
  974. item.waiting_reason = None
  975. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  976. # Send assignment notification
  977. job_name = await self._get_job_name(db, item)
  978. printer = await self._get_printer(db, printer_id)
  979. await notification_service.on_queue_job_assigned(
  980. job_name=job_name,
  981. printer_id=printer_id,
  982. printer_name=printer.name if printer else "Unknown",
  983. target_model=item.target_model,
  984. db=db,
  985. )
  986. # Resolve the AMS mapping for the assigned printer when it's
  987. # missing OR unresolved (all -1). Critical for model-based
  988. # jobs where mapping wasn't computed upfront, and it also
  989. # self-heals a bogus stored [-1] (#2589).
  990. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  991. if unmappable:
  992. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  993. continue
  994. # Filament-deficit pre-dispatch check (#1496).
  995. if await self._block_on_filament_deficit(db, item):
  996. continue
  997. _claim_library_row(item)
  998. dispatch_ids.append(item.id)
  999. busy_printers.add(printer_id)
  1000. # SJF starvation guard: mark model-based items that were jumped
  1001. if sjf_enabled and item.print_time_seconds is not None:
  1002. for other in items:
  1003. if (
  1004. other.id != item.id
  1005. and other.status == "pending"
  1006. and other.printer_id is None
  1007. and other.target_model
  1008. and other.target_model.upper() == item.target_model.upper()
  1009. and not other.been_jumped
  1010. and other.position < item.position
  1011. and (
  1012. other.print_time_seconds is None
  1013. or other.print_time_seconds > item.print_time_seconds
  1014. )
  1015. ):
  1016. other.been_jumped = True
  1017. await db.commit()
  1018. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  1019. # as long as the slowest upload takes (minutes on a big 3MF), and a
  1020. # skip summary that only lands after the transfers have finished is
  1021. # useless for working out why an item did not go out.
  1022. if skip_reasons:
  1023. logger.info("Queue skip summary: %s", skip_reasons)
  1024. if busy_printers:
  1025. # Log why each printer was busy (first time it was checked)
  1026. for pid in busy_printers:
  1027. state = printer_manager.get_status(pid)
  1028. connected = printer_manager.is_connected(pid)
  1029. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  1030. state_name = state.state if state else "NO_STATUS"
  1031. logger.info(
  1032. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  1033. pid,
  1034. connected,
  1035. state_name,
  1036. awaiting,
  1037. )
  1038. # Read the concurrency limit BEFORE the commit below, not inside
  1039. # _dispatch_selected(). A SELECT on this session after the commit
  1040. # implicitly opens a fresh transaction that nothing then closes, and
  1041. # it would stay open for the whole dispatch — minutes of "idle in
  1042. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  1043. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  1044. # checkpointed while every dispatch is writing to it.
  1045. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  1046. # Selection is done; every decision above is recorded on `db`
  1047. # (model-based printer assignment, computed ams_mapping). Flush it
  1048. # before the dispatch tasks open their own sessions, or they will
  1049. # read a row that still says printer_id=None. This also releases the
  1050. # connection back to the pool for the duration of the dispatch.
  1051. await db.commit()
  1052. if dispatch_ids:
  1053. item_printers = {it.id: it.printer_id for it in items}
  1054. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  1055. # Auto-drying: start drying on idle printers that have no pending queue items
  1056. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  1057. # Keep the loop on the fast interval while any upload is in flight so
  1058. # a slot freed mid-tick refills within seconds rather than after the
  1059. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  1060. # deferred because the pool was full) also counts as productive.
  1061. return bool(dispatch_ids) or bool(self._inflight)
  1062. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  1063. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  1064. Dispatch used to happen inline in the selection loop: ``await
  1065. _start_print(db, item)`` per item in turn. Since ``_start_print``
  1066. performs the FTP upload, that serialized every printer behind every
  1067. other printer's transfer even though the printers are independent
  1068. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  1069. gather was awaited before ``check_queue`` returned, so the run loop
  1070. stayed blocked until the *slowest* upload in the batch finished — a
  1071. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  1072. 93-printer farm even as other printers came free (#2602).
  1073. Each upload now runs as an independent background task tracked in
  1074. ``self._inflight``. check_queue excludes in-flight item_ids (still
  1075. `pending` until their upload completes) and their printers from the
  1076. next pass's selection, and this method launches at most
  1077. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  1078. the next fast tick instead of waiting out the whole batch. The bound
  1079. exists because the printers are independent but the host is not: each
  1080. in-flight upload holds a thread in the FTP pool, a TLS session and a
  1081. file handle.
  1082. The no-overlapping-dispatch invariant the batch-await used to provide
  1083. is now carried by the in-flight exclusion in check_queue. Everything
  1084. else — the pending->printing CAS, the busy-printer guard (#2598), the
  1085. per-printer hold, and each item's independent failure handling — still
  1086. lives in ``_start_print`` and runs per task exactly as before.
  1087. Synchronous on purpose: it registers every launched task into
  1088. ``self._inflight`` before returning, so the next (sequential) tick sees
  1089. an accurate in-flight count with no interleaving await.
  1090. """
  1091. free = limit - len(self._inflight)
  1092. if free <= 0:
  1093. logger.info(
  1094. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  1095. len(self._inflight),
  1096. limit,
  1097. len(item_ids),
  1098. item_ids,
  1099. )
  1100. return
  1101. to_launch = item_ids[:free]
  1102. deferred = item_ids[free:]
  1103. logger.info(
  1104. "Launching %d upload(s) (pool %d/%d in flight)%s",
  1105. len(to_launch),
  1106. len(self._inflight),
  1107. limit,
  1108. f" — deferring {deferred} to a later tick" if deferred else "",
  1109. )
  1110. for item_id in to_launch:
  1111. task = spawn_background_task(self._dispatch_one(item_id), name=f"queue-upload-{item_id}")
  1112. self._inflight[item_id] = (task, item_printers.get(item_id))
  1113. # Prune on completion so the freed slot is refillable next tick.
  1114. # spawn_background_task already logs any uncaught exception; this
  1115. # only reclaims the pool slot (fires on success, failure, or cancel).
  1116. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  1117. async def _dispatch_one(self, item_id: int) -> None:
  1118. """Upload + start one queue item in its own session (pool worker, #2602).
  1119. Its own session: pool workers run concurrently and an AsyncSession is
  1120. not safe to share across tasks; it also keeps a slow upload from pinning
  1121. the scheduler's session (and, on SQLite, its transaction) open for the
  1122. transfer's duration.
  1123. """
  1124. async with async_session() as item_db:
  1125. # Claim the row for dispatch BEFORE reading the printer snapshot or
  1126. # touching any slow I/O (#2615). The claim is an atomic CAS on
  1127. # (status='pending', dispatching_at IS NULL); while it's held the edit
  1128. # routes reject reassignment (409), so printer_id can't change out from
  1129. # under the in-flight upload and split the queue row from the
  1130. # archive/expected-print/physical command.
  1131. if not await self._claim_for_dispatch(item_db, item_id):
  1132. logger.info(
  1133. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  1134. item_id,
  1135. )
  1136. return
  1137. try:
  1138. item = await item_db.get(PrintQueueItem, item_id)
  1139. if not item:
  1140. logger.info("Queue item %s vanished after claim — skipping", item_id)
  1141. return
  1142. await self._start_print(item_db, item)
  1143. finally:
  1144. # Undo an expected-print registration whose print command never
  1145. # went out. One choke point covers every way `_start_print` can
  1146. # end without sending: a raised exception (a DB failure mid-
  1147. # dispatch is the reported case), an early return, a cancel
  1148. # winning the #1853 CAS, or `start_print()` returning False.
  1149. # A confirmed send removes the entry itself, so this is a no-op
  1150. # on the happy path.
  1151. self._rollback_unconfirmed_expected_print(item_id)
  1152. # Mirror the pre-#1625 background-dispatch lifecycle: a
  1153. # reservation survives only after start_print() accepted the
  1154. # command. Failure, cancellation, deferral, and exceptions all
  1155. # release it here.
  1156. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_db, item_id))
  1157. # Release the claim on every exit. Once dispatch has finished the
  1158. # row's status carries the lock (printing/failed/cancelled are all
  1159. # != pending), so the token is only needed for the duration of the
  1160. # upload. A row left pending (e.g. busy-printer deferral) becomes
  1161. # dispatchable again on the next tick.
  1162. await self._clear_dispatch_claim(item_db, item_id)
  1163. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  1164. """Drop an expectation for a print command that was never sent.
  1165. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  1166. where the interesting exception is usually the one already propagating.
  1167. """
  1168. pending = self._unconfirmed_expected_print.pop(item_id, None)
  1169. if pending is None:
  1170. return
  1171. printer_id, remote_filename, archive_id = pending
  1172. try:
  1173. from backend.app.main import unregister_expected_print
  1174. unregister_expected_print(printer_id, remote_filename, archive_id)
  1175. except Exception:
  1176. logger.warning(
  1177. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  1178. item_id,
  1179. printer_id,
  1180. remote_filename,
  1181. archive_id,
  1182. exc_info=True,
  1183. )
  1184. async def _release_unconfirmed_budget_reservation(self, db: AsyncSession, item_id: int) -> None:
  1185. """Release a queue reservation when dispatch ended before MQTT send."""
  1186. if item_id not in self._unconfirmed_budget_reservations:
  1187. return
  1188. for attempt in range(1, 4):
  1189. try:
  1190. await db.rollback()
  1191. await release_budget_reservation(
  1192. db,
  1193. source_type="print_queue",
  1194. source_id=item_id,
  1195. status="released",
  1196. )
  1197. await db.commit()
  1198. self._unconfirmed_budget_reservations.discard(item_id)
  1199. return
  1200. except Exception as exc:
  1201. try:
  1202. await db.rollback()
  1203. except Exception:
  1204. pass
  1205. if attempt == 3:
  1206. logger.error(
  1207. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  1208. item_id,
  1209. attempt,
  1210. exc,
  1211. )
  1212. return
  1213. await asyncio.sleep(0.5 * attempt)
  1214. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  1215. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  1216. Returns True if this call won the claim, False if the row was already
  1217. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  1218. the load-bearing guard against reassign-during-dispatch (#2615)."""
  1219. res = await db.execute(
  1220. update(PrintQueueItem)
  1221. .where(PrintQueueItem.id == item_id)
  1222. .where(PrintQueueItem.status == "pending")
  1223. .where(PrintQueueItem.dispatching_at.is_(None))
  1224. .values(dispatching_at=datetime.now(timezone.utc))
  1225. )
  1226. await db.commit()
  1227. return res.rowcount > 0
  1228. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  1229. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  1230. mask the dispatch outcome.
  1231. Retried, because the failure mode in practice is transient and narrow: a
  1232. database that is momentarily unreachable — PostgreSQL out of connection
  1233. slots is the observed case — refuses this write for a second or two while
  1234. the dispatch that just ended is still holding the row out of the selection
  1235. query. One attempt was enough to wedge the item; a couple of spaced
  1236. attempts clear it. Each attempt rolls back first, since a failed write
  1237. leaves the session needing it before it can be reused.
  1238. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  1239. on the next quiet tick.
  1240. """
  1241. for attempt in range(1, 4):
  1242. try:
  1243. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  1244. await db.commit()
  1245. return
  1246. except Exception as exc:
  1247. try:
  1248. await db.rollback()
  1249. except Exception:
  1250. pass
  1251. if attempt == 3:
  1252. logger.warning(
  1253. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  1254. "— a later quiet tick will release it",
  1255. item_id,
  1256. attempt,
  1257. exc,
  1258. )
  1259. return
  1260. await asyncio.sleep(0.5 * attempt)
  1261. async def _find_idle_printer_for_model(
  1262. self,
  1263. db: AsyncSession,
  1264. model: str,
  1265. exclude_ids: set[int],
  1266. required_filament_types: list[str] | None = None,
  1267. target_location: str | None = None,
  1268. filament_overrides: list[dict] | None = None,
  1269. require_plate_clear: bool = True,
  1270. ) -> tuple[int | None, str | None]:
  1271. """Find an idle, connected printer matching the model with compatible filaments.
  1272. Args:
  1273. db: Database session
  1274. model: Printer model to match (e.g., "X1C", "P1S")
  1275. exclude_ids: Printer IDs to exclude (already busy)
  1276. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1277. If provided, only printers with all required types loaded will match.
  1278. target_location: Optional location filter. If provided, only printers in this location are considered.
  1279. filament_overrides: Optional list of override dicts. Each entry may include
  1280. ``force_color_match: true`` to require an exact type+color match
  1281. on the printer for that slot. Without the flag the existing
  1282. colour-preference logic applies.
  1283. Returns:
  1284. Tuple of (printer_id, waiting_reason):
  1285. - (printer_id, None) if a matching printer was found
  1286. - (None, reason) if no printer is available, with explanation
  1287. """
  1288. # Normalize model name and use case-insensitive matching
  1289. normalized_model = normalize_printer_model(model) or model
  1290. query = (
  1291. select(Printer)
  1292. .where(func.lower(Printer.model) == normalized_model.lower())
  1293. .where(Printer.is_active == True) # noqa: E712
  1294. )
  1295. # Add location filter if specified
  1296. if target_location:
  1297. query = query.where(Printer.location == target_location)
  1298. result = await db.execute(query)
  1299. printers = list(result.scalars().all())
  1300. location_suffix = f" in {target_location}" if target_location else ""
  1301. if not printers:
  1302. return None, f"No active {normalized_model} printers{location_suffix} configured"
  1303. # Separate force-matched overrides from preference-only overrides
  1304. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  1305. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  1306. # Track reasons for skipping printers
  1307. printers_busy = []
  1308. printers_offline = []
  1309. printers_missing_filament: list[tuple[str, list[str]]] = []
  1310. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  1311. for printer in printers:
  1312. if printer.id in exclude_ids:
  1313. # Printer is already claimed by another job in this scheduling run.
  1314. # For force-color jobs, still check if the color would match — if not,
  1315. # report it as a color mismatch rather than plain "Busy" so the user
  1316. # knows the job needs a filament change, not just to wait for availability.
  1317. if force_overrides and not pref_overrides:
  1318. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1319. if missing_colors:
  1320. printers_missing_filament.append((printer.name, missing_colors))
  1321. continue
  1322. printers_busy.append(printer.name)
  1323. continue
  1324. is_connected = printer_manager.is_connected(printer.id)
  1325. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  1326. if not is_connected:
  1327. printers_offline.append(printer.name)
  1328. continue
  1329. if not is_idle:
  1330. # Printer is currently printing. For force-color jobs, check whether the
  1331. # loaded color would satisfy the requirement — if not, surface it as a
  1332. # color-mismatch reason rather than plain "Busy" so the user understands
  1333. # that the job is waiting for a filament change, not just printer availability.
  1334. if force_overrides and not pref_overrides:
  1335. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1336. if missing_colors:
  1337. printers_missing_filament.append((printer.name, missing_colors))
  1338. logger.debug(
  1339. "Printer %s (%s) is busy but also has wrong force-color: %s",
  1340. printer.id,
  1341. printer.name,
  1342. missing_colors,
  1343. )
  1344. continue
  1345. printers_busy.append(printer.name)
  1346. continue
  1347. # Validate filament compatibility if required types are specified
  1348. if required_filament_types:
  1349. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  1350. if missing:
  1351. # When force_overrides are present, enrich missing entries with color info
  1352. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  1353. if force_overrides:
  1354. force_color_map = {
  1355. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  1356. for o in force_overrides
  1357. }
  1358. missing_enriched = [
  1359. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  1360. for t in missing
  1361. ]
  1362. printers_missing_filament.append((printer.name, missing_enriched))
  1363. else:
  1364. printers_missing_filament.append((printer.name, missing))
  1365. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  1366. continue
  1367. # Force color match: ALL flagged slots must have an exact type+color match
  1368. if force_overrides:
  1369. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1370. if missing_colors:
  1371. printers_missing_filament.append((printer.name, missing_colors))
  1372. logger.debug(
  1373. "Skipping printer %s (%s) - missing force-matched colors: %s",
  1374. printer.id,
  1375. printer.name,
  1376. missing_colors,
  1377. )
  1378. continue
  1379. # If preference-only overrides exist, rank by color matches (existing behaviour)
  1380. if pref_overrides:
  1381. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  1382. if color_matches > 0:
  1383. candidates.append((printer.id, color_matches))
  1384. else:
  1385. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  1386. printers_missing_filament.append((printer.name, override_colors))
  1387. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  1388. continue
  1389. elif force_overrides:
  1390. # Passed all force checks — immediately eligible (no preference ordering needed)
  1391. return printer.id, None
  1392. else:
  1393. # No overrides at all - take first available (existing behavior)
  1394. return printer.id, None
  1395. # If we have candidates from preference override matching, pick the one with most color matches
  1396. if candidates:
  1397. candidates.sort(key=lambda c: c[1], reverse=True)
  1398. return candidates[0][0], None
  1399. # Build waiting reason from what we found
  1400. reasons = []
  1401. if printers_missing_filament:
  1402. # Filament/color mismatch is most actionable - show first
  1403. if force_overrides and not pref_overrides:
  1404. # All mismatches are force-color failures — use descriptive message only;
  1405. # but only if there are no busy printers that DO have the matching color.
  1406. # If a printer has the right color but is busy, surface "Busy" instead so
  1407. # the user knows the job will start automatically once that printer is free.
  1408. if not printers_busy:
  1409. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  1410. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  1411. # else: fall through — printers_busy will be appended below
  1412. else:
  1413. names_and_missing = [
  1414. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  1415. ]
  1416. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  1417. if printers_busy:
  1418. reasons.append(f"Busy: {', '.join(printers_busy)}")
  1419. if printers_offline:
  1420. reasons.append(f"Offline: {', '.join(printers_offline)}")
  1421. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  1422. @staticmethod
  1423. def _is_busy_only(waiting_reason: str) -> bool:
  1424. """Check if the waiting reason only contains 'Busy' entries.
  1425. When all matching printers are simply busy printing, the queued job
  1426. will start automatically once a printer finishes — no user action
  1427. is required, so we skip the notification.
  1428. """
  1429. parts = [p.strip() for p in waiting_reason.split(" | ")]
  1430. return all(p.startswith("Busy:") for p in parts)
  1431. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  1432. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  1433. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  1434. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  1435. with an exact type+color match.
  1436. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  1437. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  1438. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  1439. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  1440. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  1441. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  1442. setups are unaffected.
  1443. Returns:
  1444. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  1445. """
  1446. status = printer_manager.get_status(printer_id)
  1447. if not status:
  1448. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  1449. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  1450. loaded: list[tuple[str, str, str]] = []
  1451. for ams_unit in status.raw_data.get("ams", []):
  1452. for tray in ams_unit.get("tray", []):
  1453. tray_type = tray.get("tray_type")
  1454. if tray_type:
  1455. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1456. loaded.append(
  1457. (_canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or "")
  1458. )
  1459. for vt in status.raw_data.get("vt_tray") or []:
  1460. vt_type = vt.get("tray_type")
  1461. if vt_type:
  1462. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1463. loaded.append((_canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  1464. missing = []
  1465. for o in force_overrides:
  1466. o_type = _canonical_filament_type(o.get("type") or "")
  1467. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1468. o_idx = o.get("tray_info_idx") or ""
  1469. satisfied = any(
  1470. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  1471. for t_type, t_color, t_idx in loaded
  1472. )
  1473. if not satisfied:
  1474. color_label = o.get("color_name") or o.get("color", "?")
  1475. missing.append(f"{o_type} ({color_label})")
  1476. return missing
  1477. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  1478. """Get the list of required filament types that are not loaded on the printer.
  1479. Args:
  1480. printer_id: The printer ID
  1481. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  1482. Returns:
  1483. List of missing filament types (empty if all are loaded)
  1484. """
  1485. status = printer_manager.get_status(printer_id)
  1486. if not status:
  1487. return required_types # Can't determine, assume all missing
  1488. # Collect all filament types loaded on this printer (AMS units + external spool)
  1489. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  1490. loaded_types: set[str] = set()
  1491. # Check AMS units (stored in raw_data["ams"])
  1492. ams_data = status.raw_data.get("ams", [])
  1493. if ams_data:
  1494. for ams_unit in ams_data:
  1495. for tray in ams_unit.get("tray", []):
  1496. tray_type = tray.get("tray_type")
  1497. if tray_type:
  1498. loaded_types.add(_canonical_filament_type(tray_type))
  1499. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  1500. for vt in status.raw_data.get("vt_tray") or []:
  1501. vt_type = vt.get("tray_type")
  1502. if vt_type:
  1503. loaded_types.add(_canonical_filament_type(vt_type))
  1504. # Find which required types are missing (using canonical type for equivalence)
  1505. missing = []
  1506. for req_type in required_types:
  1507. if _canonical_filament_type(req_type) not in loaded_types:
  1508. missing.append(req_type)
  1509. return missing
  1510. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  1511. """Count how many filament overrides have an exact color match on the printer.
  1512. Used to prefer printers that already have the desired override colors loaded.
  1513. """
  1514. status = printer_manager.get_status(printer_id)
  1515. if not status:
  1516. return 0
  1517. # Collect loaded filaments' type+color pairs
  1518. loaded: set[tuple[str, str]] = set()
  1519. for ams_unit in status.raw_data.get("ams", []):
  1520. for tray in ams_unit.get("tray", []):
  1521. tray_type = tray.get("tray_type")
  1522. tray_color = tray.get("tray_color", "")
  1523. if tray_type:
  1524. color_norm = tray_color.replace("#", "").lower()[:6]
  1525. loaded.add((tray_type.upper(), color_norm))
  1526. for vt in status.raw_data.get("vt_tray") or []:
  1527. vt_type = vt.get("tray_type")
  1528. if vt_type:
  1529. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1530. loaded.add((vt_type.upper(), color_norm))
  1531. matches = 0
  1532. for o in overrides:
  1533. o_type = (o.get("type") or "").upper()
  1534. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1535. if (o_type, o_color) in loaded:
  1536. matches += 1
  1537. return matches
  1538. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  1539. """Fold the winning candidate's file and settings onto the queue row (#671).
  1540. This is the whole trick that keeps cross-model items cheap: the many-to-many
  1541. never escapes the selection loop. By the time the pass commits, the row
  1542. looks exactly like an ordinary single-file model-based item, so the upload,
  1543. archive creation, expected-print registration, print history and reprint
  1544. paths need no knowledge that variants exist.
  1545. No-ops for a non-variant candidate, which is already the item's own columns.
  1546. Safe to run and re-run: the item's file columns are only ever *read* when it
  1547. has no variants, so an item that gets resolved and then skipped (library-row
  1548. conflict, previous-print gate) is simply resolved again on the next pass.
  1549. """
  1550. variant = candidate.variant
  1551. if variant is None:
  1552. return
  1553. item.library_file_id = variant.library_file_id
  1554. item.library_file = variant.library_file
  1555. # The dispatcher checks archive_id first and would print that instead of
  1556. # the file we just picked. Creation refuses to combine the two, so this
  1557. # only ever fires on a hand-written row — clear it rather than silently
  1558. # dispatch something the matcher never considered.
  1559. item.archive_id = None
  1560. item.archive = None
  1561. item.target_model = variant.target_model
  1562. item.plate_id = variant.plate_id
  1563. item.ams_mapping = variant.ams_mapping
  1564. item.nozzle_mapping = variant.nozzle_mapping
  1565. item.filament_overrides = variant.filament_overrides
  1566. item.required_filament_types = variant.required_filament_types
  1567. if variant.print_time_seconds is not None:
  1568. # The row carried the shortest candidate's estimate so SJF could order
  1569. # it before a printer was known; now that one is chosen, record what is
  1570. # actually going to run so history and the ETA agree with reality.
  1571. item.print_time_seconds = variant.print_time_seconds
  1572. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  1573. """Ensure the queue item carries a usable AMS mapping before dispatch.
  1574. Recomputes from live printer status when the stored mapping is missing OR
  1575. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  1576. frontend status-load race can serialize [-1] before the printer's AMS
  1577. trays are known (#2589) — and must not be trusted: downstream it would be
  1578. silently downgraded to external-spool mode and print against an empty
  1579. feed. A resolved mapping (including manual overrides, or a partially
  1580. padded one) is left untouched.
  1581. When recompute cannot resolve it either (no compatible tray loaded), the
  1582. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  1583. external selection; the print command then keeps use_ams=True and the
  1584. firmware surfaces a clear AMS-mapping error instead of silently printing
  1585. to the empty external feed.
  1586. Returns an actionable message when that firmware error is the only
  1587. possible outcome — the matcher ran, matched nothing, and the printer has
  1588. no AMS to load a different spool into (#2771). The caller fails the item
  1589. on it instead of spending an upload on a print that cannot start.
  1590. Returns None everywhere else, including every case where we simply lack
  1591. the data to judge, so dispatch is only ever blocked on a positive
  1592. finding.
  1593. """
  1594. stored_mapping: list | None = None
  1595. if item.ams_mapping:
  1596. try:
  1597. stored_mapping = json.loads(item.ams_mapping)
  1598. except (json.JSONDecodeError, TypeError):
  1599. stored_mapping = None
  1600. # Already resolved (present and not all-unresolved) — keep as-is so a
  1601. # user's manual mapping is never overwritten.
  1602. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  1603. return None
  1604. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  1605. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  1606. item.ams_mapping = json.dumps(computed_mapping)
  1607. logger.info(
  1608. "Queue item %s: Computed AMS mapping for printer %s: %s",
  1609. item.id,
  1610. printer_id,
  1611. computed_mapping,
  1612. )
  1613. await db.commit()
  1614. return None
  1615. if _mapping_is_all_unresolved(stored_mapping):
  1616. logger.warning(
  1617. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  1618. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  1619. item.id,
  1620. stored_mapping,
  1621. printer_id,
  1622. )
  1623. item.ams_mapping = None
  1624. await db.commit()
  1625. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  1626. async def _unmappable_without_ams_message(
  1627. self,
  1628. db: AsyncSession,
  1629. printer_id: int,
  1630. item: PrintQueueItem,
  1631. computed_mapping: list[int] | None,
  1632. ) -> str | None:
  1633. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  1634. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  1635. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  1636. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  1637. uploaded several megabytes and burned its dispatch retries. With an AMS
  1638. attached that error is worth reaching: the user can load the right spool
  1639. and press Resume, so this returns None and today's behaviour stands. With
  1640. no AMS there is nothing to resume into — the external spool holder is the
  1641. whole inventory — so the useful answer is to say which filament is
  1642. missing and stop.
  1643. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  1644. every branch that lacks the evidence to be sure returns None.
  1645. """
  1646. # None means the matcher never ran (no requirements parsed from the 3MF,
  1647. # or nothing loaded at all) rather than "ran and matched nothing". Those
  1648. # dispatch as they always have.
  1649. if not _mapping_is_all_unresolved(computed_mapping):
  1650. return None
  1651. status = printer_manager.get_status(printer_id)
  1652. if status is None:
  1653. return None
  1654. # "No AMS" has to be a fact the printer stated, not the absence of a
  1655. # statement. `raw_data["ams"]` is written only once an AMS push has been
  1656. # handled and is preserved across partial pushes thereafter, so a missing
  1657. # key means we have not heard yet — most likely a reconnect, where the
  1658. # trays of a fully loaded AMS would be invisible for a few seconds. An
  1659. # empty list is the positive report of a printer with no AMS.
  1660. ams_units = status.raw_data.get("ams")
  1661. if not isinstance(ams_units, list) or ams_units:
  1662. return None
  1663. required = await self._get_filament_requirements(db, item)
  1664. loaded = self._build_loaded_filaments(status)
  1665. if not required or not loaded:
  1666. # Both were non-empty moments ago or the matcher could not have run.
  1667. # If the picture changed under us, say nothing rather than fail an
  1668. # item on stale evidence.
  1669. return None
  1670. self._apply_filament_overrides(item, required)
  1671. return _unmatched_filament_message(required, loaded)
  1672. async def _fail_unmappable_item(
  1673. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  1674. ) -> None:
  1675. """Fail a queue item whose filament mapping cannot resolve (#2771).
  1676. This replaces a failure, not a success: without it the item is uploaded,
  1677. rejected by the firmware with 0700_8012, retried twice more and failed
  1678. anyway with "never started the print after N dispatch attempts". So this
  1679. applies on the model-based path too, even though it means an "Any <model>"
  1680. job stops at the first printer offered rather than trying its siblings —
  1681. deferring instead would need the check to move inside
  1682. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  1683. re-assigns the same printer on the next tick.
  1684. """
  1685. item.status = "failed"
  1686. item.error_message = message
  1687. item.completed_at = datetime.now(timezone.utc)
  1688. item.waiting_reason = None
  1689. await db.commit()
  1690. logger.warning(
  1691. "Queue item %s: no usable AMS mapping on printer %s — %s",
  1692. item.id,
  1693. printer_id,
  1694. message,
  1695. )
  1696. job_name = await self._get_job_name(db, item)
  1697. printer = await self._get_printer(db, printer_id)
  1698. await notification_service.on_queue_job_failed(
  1699. job_name=job_name,
  1700. printer_id=printer_id,
  1701. printer_name=printer.name if printer else "Unknown",
  1702. reason=message,
  1703. db=db,
  1704. )
  1705. try:
  1706. await ws_manager.send_queue_item_failed(
  1707. user_id=item.created_by_id,
  1708. queue_item_id=item.id,
  1709. printer_id=printer_id,
  1710. reason="filament_unmappable",
  1711. )
  1712. except Exception:
  1713. pass
  1714. async def _compute_ams_mapping_for_printer(
  1715. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  1716. ) -> list[int] | None:
  1717. """Compute AMS mapping for a printer based on filament requirements.
  1718. Called when a queue item has no ams_mapping set — either for model-based
  1719. items after printer assignment, or printer-specific items (e.g. from VP).
  1720. Args:
  1721. db: Database session
  1722. printer_id: The assigned printer ID
  1723. item: The queue item (contains archive_id or library_file_id)
  1724. Returns:
  1725. AMS mapping array or None if no mapping needed/possible
  1726. """
  1727. # Get printer status
  1728. status = printer_manager.get_status(printer_id)
  1729. if not status:
  1730. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  1731. return None
  1732. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  1733. # either extruder, so the per-nozzle hard filter below must NOT apply.
  1734. # Otherwise a print on one nozzle can't use a spool physically loaded in
  1735. # an AMS on the *other* nozzle, and the matcher falls through to a
  1736. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  1737. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  1738. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  1739. # Get filament requirements from source file
  1740. filament_reqs = await self._get_filament_requirements(db, item)
  1741. if not filament_reqs:
  1742. # When the 3MF can't be read but force-color overrides are present, build a
  1743. # direct mapping from the overrides so the printer uses the correct AMS slot.
  1744. if item.filament_overrides:
  1745. try:
  1746. overrides = json.loads(item.filament_overrides)
  1747. force_overrides = [o for o in overrides if o.get("force_color_match")]
  1748. if force_overrides:
  1749. logger.info(
  1750. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  1751. "force-color override(s)",
  1752. item.id,
  1753. len(force_overrides),
  1754. )
  1755. return self._build_override_direct_mapping(force_overrides, status)
  1756. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1757. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  1758. logger.debug("No filament requirements found for queue item %s", item.id)
  1759. return None
  1760. self._apply_filament_overrides(item, filament_reqs)
  1761. # Build loaded filaments from printer status
  1762. loaded_filaments = self._build_loaded_filaments(status)
  1763. if not loaded_filaments:
  1764. logger.debug("No filaments loaded on printer %s", printer_id)
  1765. return None
  1766. # Check if user prefers lowest remaining filament when multiple spools match
  1767. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  1768. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  1769. # Without backup, the printer will not switch to a second spool when the
  1770. # picked one runs out — so sorting toward the lowest leaves the print
  1771. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  1772. # today's behaviour intentionally.
  1773. if prefer_lowest and status.ams_filament_backup is False:
  1774. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  1775. prefer_lowest = False
  1776. # When the preference is on, surface Bambuddy's inventory-side
  1777. # remaining for each slot that's bound to a tracked spool, so the
  1778. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  1779. # entirely when the preference is off — no behaviour change for
  1780. # users who haven't opted in.
  1781. inventory_remain_overrides: dict[int, float] | None = None
  1782. if prefer_lowest:
  1783. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  1784. # Compute mapping: match required filaments to available slots
  1785. return self._match_filaments_to_slots(
  1786. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  1787. )
  1788. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  1789. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  1790. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  1791. diagnosis (#2771) describes the filament the matcher actually looked
  1792. for, not the one the 3MF was sliced with — naming the pre-override
  1793. filament in a user-facing error would send the user to load the wrong
  1794. spool.
  1795. """
  1796. if not item.filament_overrides:
  1797. return
  1798. try:
  1799. overrides = json.loads(item.filament_overrides)
  1800. override_map = {o["slot_id"]: o for o in overrides}
  1801. for req in filament_reqs:
  1802. if req["slot_id"] in override_map:
  1803. override = override_map[req["slot_id"]]
  1804. req["type"] = override["type"]
  1805. req["color"] = override["color"]
  1806. # A manual/preference override SWAPS the slot's filament, so the
  1807. # 3MF's original tray_info_idx now points at the old spool and must
  1808. # be cleared — matching then falls back to type+colour. A
  1809. # force_color_match override is not a swap: it carries the 3MF's
  1810. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  1811. # it here too, letting the matcher pin the correct variant slot on a
  1812. # printer holding two same-colour spools of different variants (#2650).
  1813. # If that variant isn't loaded the matcher falls back to type+colour,
  1814. # so an eligible printer never fails to map.
  1815. req["tray_info_idx"] = (
  1816. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  1817. )
  1818. logger.debug(
  1819. "Queue item %s: Override slot %d -> %s %s",
  1820. item.id,
  1821. req["slot_id"],
  1822. override["type"],
  1823. override["color"],
  1824. )
  1825. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1826. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  1827. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  1828. """Build an AMS mapping directly from force-color overrides without a 3MF.
  1829. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  1830. slice_info is missing or unreadable) but ``force_color_match`` overrides
  1831. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  1832. treated as the filament requirement for that slot and matched against the
  1833. current AMS state of the printer.
  1834. Returns the same format as ``_match_filaments_to_slots``, or None when
  1835. the AMS has no loaded filaments.
  1836. """
  1837. loaded = self._build_loaded_filaments(status)
  1838. if not loaded:
  1839. return None
  1840. reqs = [
  1841. {
  1842. "slot_id": o["slot_id"],
  1843. "type": o.get("type", ""),
  1844. "color": o.get("color", ""),
  1845. # These are all force_color_match overrides, so the idx (when the
  1846. # 3MF carried one) is the intended variant, not a stale swap —
  1847. # keep it so the matcher pins the right variant slot, falling back
  1848. # to type+colour when it isn't loaded (#2650).
  1849. "tray_info_idx": o.get("tray_info_idx", ""),
  1850. }
  1851. for o in force_overrides
  1852. ]
  1853. return self._match_filaments_to_slots(reqs, loaded)
  1854. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  1855. """Resolve the queue item's source 3MF and parse the per-slot
  1856. filament requirements out of it. Thin DB-resolver wrapper around
  1857. ``filament_requirements.extract_filament_requirements`` so the VP
  1858. queue-mode write path (#1188) can reuse the same parser at upload
  1859. time.
  1860. """
  1861. from backend.app.services.filament_requirements import extract_filament_requirements
  1862. file_path: Path | None = None
  1863. if item.archive_id:
  1864. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1865. archive = result.scalar_one_or_none()
  1866. if archive:
  1867. file_path = settings.base_dir / archive.file_path
  1868. elif item.library_file_id:
  1869. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1870. library_file = result.scalar_one_or_none()
  1871. if library_file:
  1872. lib_path = Path(library_file.file_path)
  1873. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1874. if not file_path or not file_path.exists():
  1875. return None
  1876. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  1877. return filaments if filaments else None
  1878. def _build_loaded_filaments(self, status) -> list[dict]:
  1879. """Build list of loaded filaments from printer status.
  1880. Args:
  1881. status: PrinterState from printer_manager
  1882. Returns:
  1883. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  1884. """
  1885. filaments = []
  1886. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  1887. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  1888. # Dual-nozzle detection, used below to route external spools to an
  1889. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  1890. # which was corrected for #1257 while this copy kept the old signal.
  1891. #
  1892. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  1893. # printer with zero AMS units reports an empty map — and every external
  1894. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  1895. # `_match_filaments_to_slots` rejects outright because `None` equals
  1896. # neither 0 nor 1. On an X2D feeding from external spools only that left
  1897. # nothing to match, the mapping came back all -1, and the print went out
  1898. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  1899. # "Failed to get AMS mapping table".
  1900. #
  1901. # `nozzles` is always a two-entry list (the state seeds it with two empty
  1902. # NozzleInfo stubs), so its length proves nothing; only a populated
  1903. # diameter on the second entry means real hardware. The other two signals
  1904. # are fallbacks for firmware revisions that surface one but not the
  1905. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  1906. # and so is more than one `vt_tray` entry, since single-nozzle printers
  1907. # expose exactly one external feed.
  1908. nozzles = getattr(status, "nozzles", None) or []
  1909. vt_trays = status.raw_data.get("vt_tray") or []
  1910. is_dual_nozzle = bool(
  1911. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  1912. or ams_extruder_map
  1913. # isinstance, because a dict here would count its ~30 keys as trays.
  1914. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  1915. # so this is unreachable — but the loop below would raise on a dict
  1916. # and that is the pre-existing behaviour to keep, not to paper over.
  1917. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  1918. )
  1919. # Parse AMS units from raw_data
  1920. ams_data = status.raw_data.get("ams", [])
  1921. for ams_unit in ams_data:
  1922. ams_id = int(ams_unit.get("id", 0))
  1923. trays = ams_unit.get("tray", [])
  1924. is_ht = len(trays) == 1 # AMS-HT has single tray
  1925. for tray in trays:
  1926. tray_type = tray.get("tray_type")
  1927. if tray_type:
  1928. tray_id = int(tray.get("id", 0))
  1929. tray_color = tray.get("tray_color", "")
  1930. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  1931. tray_info_idx = tray.get("tray_info_idx", "")
  1932. # Normalize color: remove alpha, add hash
  1933. color = self._normalize_color(tray_color)
  1934. # Calculate global tray ID
  1935. # AMS-HT units have IDs starting at 128 with a single tray
  1936. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  1937. filaments.append(
  1938. {
  1939. "type": tray_type,
  1940. "color": color,
  1941. "tray_info_idx": tray_info_idx,
  1942. "ams_id": ams_id,
  1943. "tray_id": tray_id,
  1944. "is_ht": is_ht,
  1945. "is_external": False,
  1946. "global_tray_id": global_tray_id,
  1947. "extruder_id": ams_extruder_map.get(str(ams_id)),
  1948. "remain": tray.get("remain", -1),
  1949. }
  1950. )
  1951. # Check external spool(s) (vt_tray is a list)
  1952. for idx, vt in enumerate(vt_trays):
  1953. if vt.get("tray_type"):
  1954. color = self._normalize_color(vt.get("tray_color", ""))
  1955. tray_id = int(vt.get("id", 254))
  1956. filaments.append(
  1957. {
  1958. "type": vt["tray_type"],
  1959. "color": color,
  1960. "tray_info_idx": vt.get("tray_info_idx", ""),
  1961. "ams_id": -1,
  1962. "tray_id": idx,
  1963. "is_ht": False,
  1964. "is_external": True,
  1965. "global_tray_id": tray_id,
  1966. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  1967. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  1968. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  1969. "remain": vt.get("remain", -1),
  1970. }
  1971. )
  1972. return filaments
  1973. def _normalize_color(self, color: str | None) -> str:
  1974. """Normalize color to #RRGGBB format."""
  1975. if not color:
  1976. return "#808080"
  1977. hex_color = color.replace("#", "")[:6]
  1978. return f"#{hex_color}"
  1979. def _normalize_color_for_compare(self, color: str | None) -> str:
  1980. """Normalize color for comparison (lowercase, no hash)."""
  1981. if not color:
  1982. return ""
  1983. return color.replace("#", "").lower()[:6]
  1984. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  1985. """Check if two colors are visually similar within a threshold."""
  1986. hex1 = self._normalize_color_for_compare(color1)
  1987. hex2 = self._normalize_color_for_compare(color2)
  1988. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  1989. return False
  1990. try:
  1991. r1 = int(hex1[0:2], 16)
  1992. g1 = int(hex1[2:4], 16)
  1993. b1 = int(hex1[4:6], 16)
  1994. r2 = int(hex2[0:2], 16)
  1995. g2 = int(hex2[2:4], 16)
  1996. b2 = int(hex2[4:6], 16)
  1997. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  1998. except ValueError:
  1999. return False
  2000. async def _build_inventory_remain_overrides(
  2001. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  2002. ) -> dict[int, float]:
  2003. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  2004. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  2005. The MQTT ``remain`` field on a tray is the printer firmware's
  2006. RFID-decremented value, which has two limitations the "Prefer Lowest
  2007. Remaining Filament" feature has been ignoring (#1508):
  2008. - it's only meaningful for Bambu RFID spools; everything else reports
  2009. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  2010. compare equal and the sort collapses to AMS-slot order — the user
  2011. who's curating inventory weights gets the lower-slot pick instead
  2012. of the lower-remaining pick;
  2013. - even when set, it's the *printer's* counter, not Bambuddy's
  2014. ``label_weight - weight_used`` (internal mode) or Spoolman's
  2015. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  2016. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  2017. When the user has bound a spool to a slot, their own inventory
  2018. tracking is authoritative; this helper surfaces that value so the
  2019. sort can prefer it. Slots without a binding are absent from the
  2020. returned map — the caller then falls back to MQTT ``remain`` for
  2021. those, preserving the pre-#1508 behaviour for un-tracked spools.
  2022. Returns an empty map on any failure (no inventory bindings, DB
  2023. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  2024. is a preference, not a guarantee.
  2025. """
  2026. if not loaded:
  2027. return {}
  2028. # External / virtual-tray slots are tracked separately from AMS — skip
  2029. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  2030. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  2031. # match is fiddly and out of scope for this fix).
  2032. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  2033. if not tracked_slots:
  2034. return {}
  2035. is_spoolman = await self._is_spoolman_mode(db)
  2036. overrides: dict[int, float] = {}
  2037. if is_spoolman:
  2038. result = await db.execute(
  2039. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2040. )
  2041. assignments = list(result.scalars().all())
  2042. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  2043. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  2044. for ams_id, tray_id, gtid in tracked_slots:
  2045. spoolman_id = by_slot.get((ams_id, tray_id))
  2046. if spoolman_id is None:
  2047. continue
  2048. grams = await _spoolman_remaining_grams(spoolman_id)
  2049. if grams is not None:
  2050. overrides[gtid] = grams
  2051. return overrides
  2052. # Internal inventory mode (default). selectinload matches the pattern
  2053. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  2054. # plus an eager-loaded relationship rather than an explicit join, so
  2055. # the row-attribute shape is exactly what those routes already rely on.
  2056. result = await db.execute(
  2057. select(SpoolAssignment)
  2058. .options(selectinload(SpoolAssignment.spool))
  2059. .where(SpoolAssignment.printer_id == printer_id)
  2060. )
  2061. assignments = list(result.scalars().all())
  2062. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  2063. for ams_id, tray_id, gtid in tracked_slots:
  2064. spool = by_slot.get((ams_id, tray_id))
  2065. if spool is None:
  2066. continue
  2067. label = float(spool.label_weight or 0)
  2068. used = float(spool.weight_used or 0)
  2069. overrides[gtid] = max(0.0, label - used)
  2070. return overrides
  2071. @staticmethod
  2072. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  2073. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  2074. here to avoid making this module import-dependent on that private
  2075. helper's signature."""
  2076. try:
  2077. from backend.app.api.routes.settings import get_setting
  2078. v = await get_setting(db, "spoolman_enabled")
  2079. return bool(v) and v.lower() == "true"
  2080. except Exception:
  2081. return False
  2082. @staticmethod
  2083. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  2084. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  2085. Three bands, matched to the emission order in ``_build_loaded_filaments``
  2086. so a tied sort produces the same physical-position order the pre-#1508
  2087. stable sort did (preserves the regression-free baseline):
  2088. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  2089. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  2090. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  2091. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  2092. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  2093. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  2094. """
  2095. if ams_id is None or ams_id < 0:
  2096. return 10_000
  2097. if ams_id >= 128:
  2098. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  2099. return ams_id * 4 + (tray_id or 0)
  2100. @staticmethod
  2101. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  2102. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  2103. Two-tier ordering: inventory-tracked spools always sort BEFORE
  2104. non-tracked spools (the user has told us they care about these
  2105. specifically), then ascending by remaining within each tier, then
  2106. ascending by AMS slot position as the deterministic tie-breaker.
  2107. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  2108. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  2109. because the tier flag dominates — which is what lets us mix grams
  2110. (inventory) and percent (MQTT) without a unit conversion.
  2111. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  2112. spools the printer DOES know something about sort ahead of those
  2113. it knows nothing about — preserves pre-#1508 behaviour for the
  2114. no-inventory-binding case.
  2115. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  2116. external on ties, matching the legacy emission-order stable sort.
  2117. """
  2118. gtid = f.get("global_tray_id")
  2119. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  2120. if overrides and gtid in overrides:
  2121. return (0, overrides[gtid], slot_order)
  2122. remain = f.get("remain", -1)
  2123. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  2124. def _match_filaments_to_slots(
  2125. self,
  2126. required: list[dict],
  2127. loaded: list[dict],
  2128. prefer_lowest: bool = False,
  2129. inventory_remain_overrides: dict[int, float] | None = None,
  2130. fts_installed: bool = False,
  2131. ) -> list[int] | None:
  2132. """Match required filaments to loaded filaments and build AMS mapping.
  2133. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  2134. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  2135. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  2136. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  2137. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  2138. matching among those trays.
  2139. Args:
  2140. required: List of required filaments with slot_id, type, color, tray_info_idx
  2141. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  2142. Returns:
  2143. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  2144. """
  2145. if not required:
  2146. return None
  2147. # Track used trays to avoid duplicate assignment
  2148. used_tray_ids: set[int] = set()
  2149. comparisons = []
  2150. for req in required:
  2151. req_type = (req.get("type") or "").upper()
  2152. req_color = req.get("color", "")
  2153. req_tray_info_idx = req.get("tray_info_idx", "")
  2154. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  2155. idx_match = None
  2156. exact_match = None
  2157. similar_match = None
  2158. type_only_match = None
  2159. # Get available trays (not already used)
  2160. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  2161. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  2162. # Hard filter — cross-nozzle assignment causes print failures
  2163. # ("position of left hotend is abnormal"), so never fall back.
  2164. # Skipped when an FTS is installed: it routes any AMS slot to either
  2165. # extruder, so restricting to one nozzle would wrongly exclude the
  2166. # correct spool sitting in the other nozzle's AMS (#2186).
  2167. req_nozzle_id = req.get("nozzle_id")
  2168. if req_nozzle_id is not None and not fts_installed:
  2169. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  2170. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  2171. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  2172. # _prefer_lowest_sort_key for the full rationale.
  2173. if prefer_lowest:
  2174. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2175. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  2176. # One line per filament req so a bug report can be diagnosed
  2177. # without enabling debug logging: shows what the matcher saw
  2178. # (req shape + sorted candidate trays with their remain values
  2179. # and any inventory override that was applied). Mirrored by
  2180. # the picked-match log at the bottom of the loop.
  2181. logger.info(
  2182. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  2183. req.get("slot_id"),
  2184. req_type,
  2185. req_color,
  2186. req_tray_info_idx,
  2187. req_nozzle_id,
  2188. [
  2189. {
  2190. "gtid": f.get("global_tray_id"),
  2191. "type": f.get("type"),
  2192. "color": f.get("color"),
  2193. "tii": f.get("tray_info_idx"),
  2194. "remain": f.get("remain"),
  2195. "inv_g": (
  2196. inventory_remain_overrides.get(f.get("global_tray_id"))
  2197. if inventory_remain_overrides
  2198. else None
  2199. ),
  2200. }
  2201. for f in available
  2202. ],
  2203. )
  2204. # Check if tray_info_idx is unique among available trays
  2205. if req_tray_info_idx:
  2206. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  2207. if len(idx_matches) == 1:
  2208. # Unique tray_info_idx - use it as definitive match
  2209. idx_match = idx_matches[0]
  2210. logger.debug(
  2211. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  2212. f"-> tray {idx_match['global_tray_id']}"
  2213. )
  2214. elif len(idx_matches) > 1:
  2215. # Multiple trays with same tray_info_idx - use color matching among them
  2216. logger.debug(
  2217. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  2218. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  2219. )
  2220. if prefer_lowest:
  2221. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2222. # Use color matching within this subset
  2223. for f in idx_matches:
  2224. f_color = f.get("color", "")
  2225. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2226. if not exact_match:
  2227. exact_match = f
  2228. elif self._colors_are_similar(f_color, req_color):
  2229. if not similar_match:
  2230. similar_match = f
  2231. elif not type_only_match:
  2232. type_only_match = f
  2233. # If no idx_match yet, do standard type/color matching on all available trays
  2234. if not idx_match and not exact_match and not similar_match and not type_only_match:
  2235. for f in available:
  2236. f_type = (f.get("type") or "").upper()
  2237. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  2238. continue
  2239. # Type matches - check color
  2240. f_color = f.get("color", "")
  2241. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2242. if not exact_match:
  2243. exact_match = f
  2244. elif self._colors_are_similar(f_color, req_color):
  2245. if not similar_match:
  2246. similar_match = f
  2247. elif not type_only_match:
  2248. type_only_match = f
  2249. match = idx_match or exact_match or similar_match or type_only_match
  2250. if match:
  2251. used_tray_ids.add(match["global_tray_id"])
  2252. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  2253. else:
  2254. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  2255. if prefer_lowest:
  2256. # Pair with the "available (sorted)" log above so the reporter
  2257. # bundle shows BOTH what the matcher saw AND which match bucket
  2258. # won — fast triage when "Prefer Lowest Filament" picks the
  2259. # wrong slot (#1766).
  2260. if match:
  2261. bucket = (
  2262. "idx"
  2263. if idx_match is not None
  2264. else "exact_color"
  2265. if exact_match is not None
  2266. else "similar_color"
  2267. if similar_match is not None
  2268. else "type_only"
  2269. )
  2270. logger.info(
  2271. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  2272. match["global_tray_id"],
  2273. bucket,
  2274. req.get("slot_id"),
  2275. )
  2276. else:
  2277. logger.info(
  2278. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  2279. req.get("slot_id"),
  2280. req_type,
  2281. req_color,
  2282. req_tray_info_idx,
  2283. )
  2284. # Build mapping array
  2285. if not comparisons:
  2286. return None
  2287. max_slot_id = max(c["slot_id"] for c in comparisons)
  2288. if max_slot_id <= 0:
  2289. return None
  2290. mapping = [-1] * max_slot_id
  2291. for c in comparisons:
  2292. slot_id = c["slot_id"]
  2293. if slot_id and slot_id > 0:
  2294. mapping[slot_id - 1] = c["global_tray_id"]
  2295. return mapping
  2296. def _mark_printer_dispatched(
  2297. self,
  2298. printer_id: int,
  2299. pre_state: str | None,
  2300. pre_subtask_id: str | None,
  2301. ) -> None:
  2302. """Record that a print command was just sent to ``printer_id``.
  2303. Held until either the watchdog observes a state/subtask transition
  2304. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  2305. """
  2306. if not pre_state:
  2307. # No pre_state means we can't detect a transition — fall back to a
  2308. # pure time-based hold using empty string as a sentinel that won't
  2309. # match any real printer state.
  2310. pre_state = ""
  2311. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  2312. def _release_dispatch_hold(self, printer_id: int) -> None:
  2313. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  2314. self._dispatch_holds.pop(printer_id, None)
  2315. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  2316. """True if ``printer_id`` is still inside its post-dispatch hold window.
  2317. Returns False (and clears the hold) once any of these are true:
  2318. - hard timeout (``_dispatch_max_hold``) has elapsed
  2319. - the printer has transitioned out of pre_state and we're past the
  2320. minimum cooldown
  2321. - the printer's subtask_id has advanced past pre_subtask_id and we're
  2322. past the minimum cooldown
  2323. Otherwise the printer is held — caller should treat it as busy.
  2324. """
  2325. entry = self._dispatch_holds.get(printer_id)
  2326. if not entry:
  2327. return False
  2328. started_at, pre_state, pre_subtask_id = entry
  2329. elapsed = time.monotonic() - started_at
  2330. if elapsed >= self._dispatch_max_hold:
  2331. self._dispatch_holds.pop(printer_id, None)
  2332. return False
  2333. # Without a pre_state we can't detect a transition — fall back to the
  2334. # min cooldown alone, then drop the hold.
  2335. if not pre_state:
  2336. if elapsed >= self._dispatch_min_cooldown:
  2337. self._dispatch_holds.pop(printer_id, None)
  2338. return False
  2339. return True
  2340. status = printer_manager.get_status(printer_id)
  2341. current_state = getattr(status, "state", None) if status else None
  2342. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  2343. transitioned = (current_state is not None and current_state != pre_state) or (
  2344. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  2345. )
  2346. if transitioned and elapsed >= self._dispatch_min_cooldown:
  2347. self._dispatch_holds.pop(printer_id, None)
  2348. return False
  2349. return True
  2350. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  2351. """Check if a printer is connected and idle."""
  2352. if not printer_manager.is_connected(printer_id):
  2353. logger.debug("Printer %d: not connected", printer_id)
  2354. return False
  2355. state = printer_manager.get_status(printer_id)
  2356. if not state:
  2357. logger.debug("Printer %d: no status available", printer_id)
  2358. return False
  2359. # Plate-clear gate: if the printer finished/failed a previous print and the user
  2360. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  2361. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  2362. # printer, it boots back into IDLE with no memory of the previous finish; without
  2363. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  2364. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  2365. logger.debug(
  2366. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  2367. printer_id,
  2368. state.state,
  2369. )
  2370. return False
  2371. idle = state.state in ("IDLE", "FINISH", "FAILED")
  2372. if not idle:
  2373. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  2374. return idle
  2375. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  2376. """Read a setting value from the database."""
  2377. result = await db.execute(select(Settings).where(Settings.key == key))
  2378. setting = result.scalar_one_or_none()
  2379. return setting.value if setting else None
  2380. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  2381. """Read a boolean setting from the database."""
  2382. result = await db.execute(select(Settings).where(Settings.key == key))
  2383. setting = result.scalar_one_or_none()
  2384. if setting:
  2385. return setting.value.lower() == "true"
  2386. return default
  2387. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  2388. """Read an int setting; falls back to default on missing/unparseable rows."""
  2389. result = await db.execute(select(Settings).where(Settings.key == key))
  2390. setting = result.scalar_one_or_none()
  2391. if setting and setting.value:
  2392. try:
  2393. return int(setting.value)
  2394. except ValueError:
  2395. pass
  2396. return default
  2397. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  2398. """Get drying presets (user-configured or built-in defaults)."""
  2399. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  2400. setting = result.scalar_one_or_none()
  2401. if setting and setting.value:
  2402. try:
  2403. presets = json.loads(setting.value)
  2404. if isinstance(presets, dict) and presets:
  2405. return presets
  2406. except json.JSONDecodeError:
  2407. pass
  2408. return self.DEFAULT_DRYING_PRESETS
  2409. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  2410. """Per-filament humidity thresholds (#1605).
  2411. Returns the user-configured overrides map keyed by normalized filament
  2412. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  2413. unknown / unmapped types. Empty / unset → empty dict, in which case
  2414. callers fall back to ``ams_humidity_fair``.
  2415. """
  2416. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  2417. setting = result.scalar_one_or_none()
  2418. if not setting or not setting.value:
  2419. return {}
  2420. try:
  2421. data = json.loads(setting.value)
  2422. except json.JSONDecodeError:
  2423. return {}
  2424. if not isinstance(data, dict):
  2425. return {}
  2426. out: dict[str, int] = {}
  2427. for key, value in data.items():
  2428. try:
  2429. out[str(key).upper() if key != "default" else "default"] = int(value)
  2430. except (TypeError, ValueError):
  2431. continue
  2432. return out
  2433. @staticmethod
  2434. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  2435. """Resolve the effective humidity threshold for an AMS unit (#1605).
  2436. For mixed filament types loaded into one AMS, returns the most
  2437. restrictive (lowest) threshold across all loaded tray types — matches
  2438. the conservative-params strategy already used for drying temp/hours.
  2439. Empty / unloaded trays contribute no constraint. Unknown types use the
  2440. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  2441. when no per-type map is configured at all.
  2442. """
  2443. default = thresholds.get("default", fallback)
  2444. if not thresholds:
  2445. return fallback
  2446. candidates: list[int] = []
  2447. for tray in trays:
  2448. tray_type = str(tray.get("tray_type") or "").strip()
  2449. if not tray_type:
  2450. continue
  2451. base_type = tray_type.split()[0].upper()
  2452. candidates.append(thresholds.get(base_type, default))
  2453. if not candidates:
  2454. return default
  2455. return min(candidates)
  2456. def _get_conservative_drying_params(
  2457. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  2458. ) -> tuple[int, int, str] | None:
  2459. """Get the most conservative drying params for mixed filament types in an AMS unit.
  2460. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  2461. """
  2462. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  2463. hours_key = f"{temp_key}_hours"
  2464. min_temp = None
  2465. max_hours = None
  2466. filament_type = ""
  2467. for tray in trays:
  2468. tray_type = tray.get("tray_type", "")
  2469. if not tray_type:
  2470. continue
  2471. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  2472. base_type = tray_type.split()[0].upper()
  2473. preset = presets.get(base_type)
  2474. if not preset:
  2475. continue
  2476. temp = preset.get(temp_key, 55)
  2477. hours = preset.get(hours_key, 12)
  2478. # Conservative: lowest temp, longest duration
  2479. if min_temp is None or temp < min_temp:
  2480. min_temp = temp
  2481. if max_hours is None or hours > max_hours:
  2482. max_hours = hours
  2483. if not filament_type:
  2484. filament_type = base_type
  2485. if min_temp is None:
  2486. return None
  2487. return (min_temp, max_hours or 12, filament_type)
  2488. async def _check_auto_drying(
  2489. self,
  2490. db: AsyncSession,
  2491. queue_items: list[PrintQueueItem],
  2492. busy_printers: set[int],
  2493. *,
  2494. require_plate_clear: bool = True,
  2495. ):
  2496. """Start drying on idle printers based on humidity.
  2497. Three modes (can all be enabled independently):
  2498. - queue_drying_enabled: Dry between scheduled queue prints
  2499. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  2500. - print_drying_enabled: Also evaluate printers that are currently printing,
  2501. when model+firmware supports "Print While Drying" (gated by
  2502. supports_drying_while_printing). Drying temperature is capped at
  2503. max(40, preset_temp - 5) to protect spools mid-print.
  2504. """
  2505. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  2506. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  2507. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  2508. if not queue_drying_enabled and not ambient_drying_enabled:
  2509. # Stop active drying on all printers if both features disabled
  2510. if self._drying_in_progress:
  2511. for pid in list(self._drying_in_progress):
  2512. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  2513. await self._stop_drying(pid)
  2514. return
  2515. # Update drying state from printer status (handles backend restart)
  2516. self._sync_drying_state()
  2517. # Find printers with scheduled items (for queue drying mode)
  2518. printers_with_scheduled: set[int] = set()
  2519. printers_with_items: set[int] = set()
  2520. for item in queue_items:
  2521. if item.printer_id:
  2522. printers_with_items.add(item.printer_id)
  2523. if item.scheduled_time and not item.manual_start:
  2524. printers_with_scheduled.add(item.printer_id)
  2525. # If only queue mode is on and no printers have scheduled items, stop drying
  2526. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  2527. # may still be eligible for mid-print drying regardless of queue state).
  2528. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  2529. for pid in list(self._drying_in_progress):
  2530. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  2531. await self._stop_drying(pid)
  2532. return
  2533. # Get humidity threshold (global fallback)
  2534. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2535. setting = result.scalar_one_or_none()
  2536. global_humidity_threshold = int(setting.value) if setting else 60
  2537. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  2538. # to the global threshold for every AMS unit.
  2539. per_type_thresholds = await self._get_humidity_thresholds(db)
  2540. # Get drying presets
  2541. presets = await self._get_drying_presets(db)
  2542. # Determine if drying should be skipped for printers with pending items
  2543. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  2544. # Get all active printers
  2545. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2546. for printer in all_printers.scalars():
  2547. pid = printer.id
  2548. # Resolve model+firmware up front — needed to decide whether this printer
  2549. # qualifies for mid-print drying (busy printer on capable hardware).
  2550. state = printer_manager.get_status(pid)
  2551. if not state:
  2552. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  2553. continue
  2554. model = printer_manager.get_model(pid)
  2555. firmware = state.firmware_version
  2556. mid_print = (
  2557. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  2558. )
  2559. if pid in busy_printers and not mid_print:
  2560. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  2561. continue
  2562. if not mid_print:
  2563. # In queue-only mode, only dry printers that have scheduled prints
  2564. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  2565. if self._drying_in_progress.get(pid):
  2566. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  2567. await self._stop_drying(pid)
  2568. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  2569. continue
  2570. # When block mode is on, don't START new drying on printers with pending items.
  2571. # But allow already-drying printers through so humidity auto-stop logic still runs.
  2572. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  2573. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  2574. continue
  2575. if not printer_manager.is_connected(pid):
  2576. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  2577. continue
  2578. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  2579. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  2580. continue
  2581. # Check drying capability. For mid-print path, supports_drying_while_printing
  2582. # was already verified when computing mid_print above.
  2583. if not mid_print and not supports_drying(model, firmware):
  2584. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  2585. continue
  2586. # Check each AMS unit from raw_data
  2587. ams_list = state.raw_data.get("ams", [])
  2588. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  2589. for ams_data in ams_list:
  2590. module_type = str(ams_data.get("module_type") or "")
  2591. ams_id = int(ams_data.get("id", 0))
  2592. # Only n3f/n3s support drying
  2593. if module_type not in ("n3f", "n3s"):
  2594. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  2595. continue
  2596. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  2597. # Most-restrictive of all loaded tray types; falls back to the
  2598. # global threshold when no overrides are configured.
  2599. trays = ams_data.get("tray", []) or []
  2600. humidity_threshold = self.resolve_humidity_threshold(
  2601. trays, per_type_thresholds, global_humidity_threshold
  2602. )
  2603. dry_time = int(ams_data.get("dry_time") or 0)
  2604. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  2605. humidity = None
  2606. h_raw = ams_data.get("humidity_raw")
  2607. if h_raw is not None:
  2608. try:
  2609. humidity = int(h_raw)
  2610. except (ValueError, TypeError):
  2611. pass
  2612. if humidity is None:
  2613. h_idx = ams_data.get("humidity")
  2614. if h_idx is not None:
  2615. try:
  2616. humidity = int(h_idx)
  2617. except (ValueError, TypeError):
  2618. pass
  2619. # Already drying — let it run to its configured duration (#1892).
  2620. #
  2621. # We deliberately do NOT stop drying from a humidity re-check here.
  2622. # Relative humidity drops steeply in heated air, so the AMS sensor
  2623. # reads ~15-20% within minutes of the dryer starting even while the
  2624. # filament is still saturated. A humidity-based early-stop therefore
  2625. # always fires at the minimum-time floor, truncating both user-started
  2626. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  2627. # The firmware stops when the configured duration elapses; scheduling
  2628. # stops (print takes priority, queue no longer needs drying) are
  2629. # handled separately via _stop_drying().
  2630. if dry_time > 0:
  2631. if pid not in self._drying_in_progress:
  2632. # Drying we didn't start (manual or from before restart) —
  2633. # track it so scheduling stops still apply; never auto-stop it.
  2634. self._drying_in_progress[pid] = time.monotonic()
  2635. logger.debug(
  2636. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  2637. pid,
  2638. ams_id,
  2639. dry_time,
  2640. humidity,
  2641. )
  2642. continue
  2643. # Humidity below threshold — no need to start drying
  2644. if humidity is None or humidity <= humidity_threshold:
  2645. logger.debug(
  2646. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  2647. pid,
  2648. ams_id,
  2649. humidity,
  2650. humidity_threshold,
  2651. )
  2652. continue
  2653. # Check cannot-dry reasons (power constraints etc.)
  2654. sf_reasons = ams_data.get("dry_sf_reason", [])
  2655. if sf_reasons:
  2656. logger.debug(
  2657. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  2658. pid,
  2659. ams_id,
  2660. sf_reasons,
  2661. )
  2662. continue
  2663. # Get conservative drying params for mixed filaments
  2664. params = self._get_conservative_drying_params(trays, module_type, presets)
  2665. if not params:
  2666. logger.debug(
  2667. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  2668. )
  2669. continue
  2670. temp, duration_hours, filament_type = params
  2671. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  2672. # "drying temperature must not exceed the filament's softening temperature"
  2673. # for Print While Drying). Floor at 40 degC — below that the dryer is
  2674. # ineffective and firmware will reject anyway.
  2675. if mid_print:
  2676. temp = max(40, temp - 5)
  2677. # Start drying
  2678. logger.info(
  2679. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  2680. "starting %s drying at %d°C for %dh%s",
  2681. pid,
  2682. ams_id,
  2683. humidity,
  2684. humidity_threshold,
  2685. filament_type,
  2686. temp,
  2687. duration_hours,
  2688. " (mid-print)" if mid_print else "",
  2689. )
  2690. success = printer_manager.send_drying_command(
  2691. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  2692. )
  2693. if success:
  2694. self._drying_in_progress[pid] = time.monotonic()
  2695. def _sync_drying_state(self):
  2696. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  2697. One direction only: it prunes, it never adds. A printer drying without an
  2698. entry here — because the user started the cycle from Studio, the printer's
  2699. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  2700. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  2701. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  2702. That is deliberate for now rather than an oversight: populating this from
  2703. telemetry would hand the scheduler authority to stop drying a user started
  2704. by hand. It also means the backend-restart case this used to claim to
  2705. handle is not handled.
  2706. """
  2707. to_remove = []
  2708. for pid in self._drying_in_progress:
  2709. state = printer_manager.get_status(pid)
  2710. if not state:
  2711. to_remove.append(pid)
  2712. continue
  2713. # Check if any AMS unit is still drying
  2714. ams_list = state.raw_data.get("ams", [])
  2715. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  2716. if not any_drying:
  2717. to_remove.append(pid)
  2718. for pid in to_remove:
  2719. self._drying_in_progress.pop(pid, None)
  2720. async def _stop_drying(self, printer_id: int):
  2721. """Stop all active drying on a printer (print takes priority)."""
  2722. state = printer_manager.get_status(printer_id)
  2723. if not state:
  2724. self._drying_in_progress.pop(printer_id, None)
  2725. return
  2726. ams_list = state.raw_data.get("ams", [])
  2727. for ams_data in ams_list:
  2728. dry_time = int(ams_data.get("dry_time") or 0)
  2729. if dry_time > 0:
  2730. ams_id = int(ams_data.get("id", 0))
  2731. logger.info(
  2732. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  2733. printer_id,
  2734. ams_id,
  2735. )
  2736. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  2737. self._drying_in_progress.pop(printer_id, None)
  2738. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  2739. """Get all smart plugs associated with a printer."""
  2740. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2741. return list(result.scalars().all())
  2742. @staticmethod
  2743. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  2744. """Pick the plug to power-cycle a printer back online with (#2629).
  2745. Only a plug flagged ``controls_printer_power`` can actually bring the
  2746. printer back; waiting for a boot on an accessory (filter fan, lights)
  2747. just burns the power-on timeout and fails the dispatch. Falls back to
  2748. the first plug when none is flagged, which is the pre-#2629 behaviour.
  2749. Callers must pass a non-empty list.
  2750. """
  2751. for plug in auto_on_plugs:
  2752. if plug.controls_printer_power:
  2753. return plug
  2754. return auto_on_plugs[0]
  2755. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  2756. # chamber-temperature recommendations BambuStudio ships for the matching
  2757. # filament profile; users can override via Settings → Workflow → Preheat
  2758. # card. "default" applies when a loaded tray's normalised type isn't in
  2759. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  2760. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  2761. "PLA": 0,
  2762. "PETG": 0,
  2763. "PETG-CF": 40,
  2764. "ABS": 45,
  2765. "ASA": 45,
  2766. "PA": 50,
  2767. "PA-CF": 55,
  2768. "PC": 50,
  2769. "PC-FR": 50,
  2770. "TPU": 0,
  2771. "PVA": 0,
  2772. "default": 0,
  2773. }
  2774. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  2775. """Parse the user-configured filament→chamber-target map, falling back
  2776. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  2777. are uppercased and the 'default' fallback is always present in the
  2778. returned dict so the resolution loop can index it unconditionally."""
  2779. raw = await self._get_setting(db, "preheat_filament_targets")
  2780. if not raw:
  2781. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2782. try:
  2783. parsed = json.loads(raw)
  2784. if not isinstance(parsed, dict):
  2785. raise ValueError("not an object")
  2786. except (json.JSONDecodeError, ValueError) as exc:
  2787. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  2788. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2789. # Coerce values to int; drop unparseable rows so a stray string
  2790. # doesn't crash the loop.
  2791. out: dict[str, int] = {}
  2792. for key, value in parsed.items():
  2793. try:
  2794. out[str(key).upper()] = int(value)
  2795. except (TypeError, ValueError):
  2796. continue
  2797. if "DEFAULT" not in out:
  2798. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  2799. return out
  2800. @staticmethod
  2801. def _normalize_filament_type(tray_type: str) -> str:
  2802. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  2803. existing drying-preset normalisation (split-at-space, upper-case) so
  2804. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  2805. "PA-CF" (no space to split on)."""
  2806. return tray_type.split()[0].upper() if tray_type else ""
  2807. def _derive_chamber_target(
  2808. self,
  2809. printer: Printer,
  2810. targets: dict[str, int],
  2811. ) -> int:
  2812. """Look up the chamber target for each loaded AMS tray and return the
  2813. max. Returns 0 when no AMS data is available (e.g. external-spool
  2814. prints) or when every loaded slot maps to 0 — the chamber phase then
  2815. short-circuits in the main loop.
  2816. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  2817. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  2818. less slots have empty `tray_type` and contribute nothing."""
  2819. state = printer_manager.get_status(printer.id)
  2820. if state is None:
  2821. return 0
  2822. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  2823. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  2824. if isinstance(ams_list, dict):
  2825. ams_list = ams_list.get("ams") or []
  2826. if not isinstance(ams_list, list):
  2827. return 0
  2828. best = 0
  2829. for ams in ams_list:
  2830. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  2831. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  2832. if not normalised:
  2833. continue
  2834. target = targets.get(normalised, targets.get("DEFAULT", 0))
  2835. if target > best:
  2836. best = target
  2837. return best
  2838. async def _preheat_and_soak(
  2839. self,
  2840. db: AsyncSession,
  2841. item: PrintQueueItem,
  2842. printer: Printer,
  2843. archive: PrintArchive | None,
  2844. ) -> None:
  2845. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  2846. Resolution order:
  2847. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  2848. to the global `preheat_enabled` setting; 'on' forces the stage on
  2849. even if the global is off.
  2850. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  2851. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  2852. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  2853. phase + soak timer).
  2854. 3. Three hardware tiers branch the wait loop:
  2855. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  2856. send M141 to the resolved target, then wait for the chamber sensor
  2857. to reach it (or the max-wait timeout to elapse).
  2858. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  2859. no M141; the bed is the only heat source, so we wait for the chamber
  2860. sensor to rise via bed radiation OR fall through on timeout.
  2861. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  2862. temperature; the function just heats the bed and holds for the
  2863. configured soak duration.
  2864. The bed target comes from the archive's parsed metadata
  2865. (`bed_temperature`); if missing the preheat stage logs and returns
  2866. without dispatching anything, rather than guessing at a default that
  2867. might wreck filament setup.
  2868. Failures are logged but never re-raised — preheat is best-effort. A
  2869. printer that goes offline mid-soak, a refused gcode command, or a
  2870. missing temperature reading must not turn into a failed queue item; the
  2871. normal upload + start path runs immediately after this method returns.
  2872. """
  2873. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  2874. if override == "off":
  2875. return
  2876. if override == "inherit":
  2877. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  2878. if not enabled:
  2879. return
  2880. # override == "on" forces the stage on regardless of the global setting.
  2881. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  2882. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  2883. # Chamber target resolution:
  2884. # 1. Explicit per-item override beats everything (user knows best).
  2885. # 2. Otherwise derive from loaded AMS filament types via the per-
  2886. # filament target map. PLA-only print derives 0 → chamber phase
  2887. # auto-skips without the user touching anything.
  2888. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  2889. if explicit_target is not None and explicit_target > 0:
  2890. chamber_target = int(explicit_target)
  2891. chamber_source = "item-override"
  2892. elif explicit_target == 0:
  2893. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  2894. chamber_source = "item-override-zero"
  2895. else:
  2896. targets = await self._get_preheat_filament_targets(db)
  2897. chamber_target = self._derive_chamber_target(printer, targets)
  2898. chamber_source = "filament-map"
  2899. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  2900. if bed_target <= 0:
  2901. logger.info(
  2902. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  2903. item.id,
  2904. )
  2905. return
  2906. client = printer_manager.get_client(printer.id)
  2907. if client is None:
  2908. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  2909. return
  2910. model = printer.model or ""
  2911. has_heater = supports_chamber_heater(model)
  2912. has_sensor = supports_chamber_temp(model)
  2913. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  2914. logger.info(
  2915. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  2916. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  2917. item.id,
  2918. bed_target,
  2919. chamber_target if do_chamber else 0,
  2920. chamber_source,
  2921. override,
  2922. model,
  2923. has_heater,
  2924. has_sensor,
  2925. max_wait,
  2926. soak_seconds,
  2927. )
  2928. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  2929. # cache the target locally so the polling reads below see consistent
  2930. # state (firmware MQTT echoes lag by ~1s).
  2931. try:
  2932. client.set_bed_temperature(bed_target)
  2933. except Exception as exc:
  2934. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  2935. return
  2936. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  2937. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  2938. # left it on, regardless of M141. Default cooling actively vents the
  2939. # chamber, so a `chamber_target > 0` print with the flap stuck in
  2940. # cooling never converges — the heater fights the open exhaust. We
  2941. # flip the flap BEFORE M141 to "heating" when the preheat wants
  2942. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  2943. # on an H2D that was previously running ABS would otherwise stay in
  2944. # heating mode and overheat PLA). The current-state read keeps the
  2945. # command idempotent — no MQTT chatter when the flap is already where
  2946. # we want it.
  2947. if supports_airduct(model):
  2948. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  2949. desired_id = 1 if desired_airduct == "heating" else 0
  2950. current_state = printer_manager.get_status(printer.id)
  2951. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  2952. if current_airduct != desired_id:
  2953. try:
  2954. client.set_airduct_mode(desired_airduct)
  2955. except Exception as exc:
  2956. logger.warning(
  2957. "Queue item %s: preheat airduct %s mode failed: %s",
  2958. item.id,
  2959. desired_airduct,
  2960. exc,
  2961. )
  2962. if do_chamber and has_heater:
  2963. try:
  2964. client.set_chamber_temperature(chamber_target)
  2965. except Exception as exc:
  2966. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  2967. # Release the pooled DB connection before the (potentially many-minute)
  2968. # heat-soak wait below (#2572). Every setting this method needs is read
  2969. # above; the wait/soak loop only polls printer_manager state and sleeps —
  2970. # it never touches the DB. Without this the caller's transaction sat
  2971. # "idle in transaction" for the whole soak, pinning one pooled connection
  2972. # per preheating printer. expire_on_commit=False keeps item/printer
  2973. # readable afterwards; there are no pending writes to lose here.
  2974. await db.commit()
  2975. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  2976. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  2977. # Poll every 3s — frequent enough for responsive logging without
  2978. # spamming the MQTT state stream. The "converged" predicate is:
  2979. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  2980. # AND
  2981. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  2982. BED_TOLERANCE = 2.0
  2983. CHAMBER_TOLERANCE = 2.0
  2984. POLL_INTERVAL = 3.0
  2985. deadline = asyncio.get_event_loop().time() + max_wait
  2986. while True:
  2987. state = printer_manager.get_status(printer.id)
  2988. if state is None:
  2989. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  2990. break
  2991. temps = state.temperatures or {}
  2992. bed_now = float(temps.get("bed", 0) or 0)
  2993. chamber_now = float(temps.get("chamber", 0) or 0)
  2994. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  2995. if not do_chamber:
  2996. chamber_ok = True # phase disabled or model has neither sensor nor heater
  2997. elif not has_sensor:
  2998. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  2999. else:
  3000. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  3001. if bed_ok and chamber_ok:
  3002. logger.info(
  3003. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  3004. item.id,
  3005. bed_now,
  3006. chamber_now,
  3007. )
  3008. break
  3009. if asyncio.get_event_loop().time() >= deadline:
  3010. logger.info(
  3011. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  3012. item.id,
  3013. bed_now,
  3014. bed_target,
  3015. chamber_now,
  3016. chamber_target if do_chamber else 0,
  3017. )
  3018. break
  3019. await asyncio.sleep(POLL_INTERVAL)
  3020. if soak_seconds > 0:
  3021. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  3022. await asyncio.sleep(soak_seconds)
  3023. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  3024. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  3025. """Turn on smart plug and wait for printer to connect.
  3026. Returns True if printer connected successfully within timeout.
  3027. """
  3028. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  3029. service = await smart_plug_manager.get_service_for_plug(plug, db)
  3030. # Check current plug state
  3031. status = await service.get_status(plug)
  3032. if not status.get("reachable"):
  3033. logger.warning("Smart plug '%s' is not reachable", plug.name)
  3034. return False
  3035. # Turn on if not already on
  3036. if status.get("state") != "ON":
  3037. success = await service.turn_on(plug)
  3038. if not success:
  3039. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  3040. return False
  3041. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  3042. # Get printer from database for connection
  3043. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3044. printer = result.scalar_one_or_none()
  3045. if not printer:
  3046. logger.error("Printer %s not found in database", printer_id)
  3047. return False
  3048. # Wait for printer to boot (give it some time before trying to connect)
  3049. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  3050. await asyncio.sleep(30)
  3051. # Try to connect to the printer periodically
  3052. elapsed = 30 # Already waited 30s
  3053. while elapsed < self._power_on_wait_time:
  3054. # Try to connect
  3055. logger.info("Attempting to connect to printer %s...", printer_id)
  3056. try:
  3057. connected = await printer_manager.connect_printer(printer)
  3058. if connected:
  3059. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  3060. # Give it a moment to stabilize and get status
  3061. await asyncio.sleep(5)
  3062. return True
  3063. except Exception as e:
  3064. logger.debug("Connection attempt failed: %s", e)
  3065. await asyncio.sleep(self._power_on_check_interval)
  3066. elapsed += self._power_on_check_interval
  3067. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  3068. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  3069. return False
  3070. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  3071. """Check if the previous print on this printer succeeded.
  3072. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  3073. deliberate action, not a failure, so subsequent items should still
  3074. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  3075. a skip isn't an actual print attempt, so it must not gate downstream
  3076. items — counting it as a failed predecessor was the cascade bug that
  3077. let a single cancellation block 18 items over 3 days for the reporter.
  3078. Only `failed` and `aborted` — real print-attempt failures — block.
  3079. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  3080. action — #1818) are also excluded from the lookback so the user can
  3081. clear the gate after fixing the physical issue without having to
  3082. re-queue every downstream job.
  3083. """
  3084. result = await db.execute(
  3085. select(PrintQueueItem)
  3086. .where(PrintQueueItem.printer_id == item.printer_id)
  3087. .where(PrintQueueItem.id != item.id)
  3088. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  3089. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  3090. .order_by(PrintQueueItem.completed_at.desc())
  3091. .limit(1)
  3092. )
  3093. prev_item = result.scalar_one_or_none()
  3094. # If no previous item, assume success (first in queue)
  3095. if not prev_item:
  3096. return True
  3097. return prev_item.status in ("completed", "cancelled")
  3098. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  3099. """Schedule power-off if the queue item enabled auto_off_after.
  3100. Delegates to the smart-plug manager so the off honours each plug's
  3101. configured strategy (time delay or temperature threshold), is cancelled
  3102. if the printer starts printing again, and never cuts power on a loaded
  3103. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  3104. powered off on the timeout regardless of print state.
  3105. """
  3106. if not item.auto_off_after:
  3107. return
  3108. try:
  3109. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  3110. except Exception as e:
  3111. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  3112. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  3113. """Get a human-readable name for a queue item."""
  3114. if item.archive_id:
  3115. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3116. archive = result.scalar_one_or_none()
  3117. if archive:
  3118. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3119. if item.library_file_id:
  3120. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3121. library_file = result.scalar_one_or_none()
  3122. if library_file:
  3123. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3124. # A cross-model item (#671) holds no file of its own until a printer is
  3125. # picked, so name it after its first candidate — otherwise every waiting
  3126. # notification for one reads "Job #12". Queried rather than read off
  3127. # item.variants because callers outside the selection loop have not
  3128. # eager-loaded them, and a lazy load raises in async.
  3129. first_variant_name = (
  3130. await db.execute(
  3131. select(LibraryFile.filename)
  3132. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  3133. .where(PrintQueueVariant.queue_item_id == item.id)
  3134. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  3135. .limit(1)
  3136. )
  3137. ).scalar_one_or_none()
  3138. if first_variant_name:
  3139. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  3140. return f"Job #{item.id}"
  3141. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  3142. """Get printer by ID."""
  3143. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3144. return result.scalar_one_or_none()
  3145. async def _notify_dispatch_gave_up(
  3146. self,
  3147. queue_item_id: int,
  3148. printer_id: int,
  3149. created_by_id: int | None,
  3150. reason: str = "Printer accepted the file but never started printing",
  3151. ) -> None:
  3152. """Tell the user the queue item was failed after exhausting its dispatch retries.
  3153. Called from the watchdog, which is a background task with no session of
  3154. its own — hence the fresh one here. Best-effort throughout: the row is
  3155. already marked failed and that is the load-bearing part; a notification
  3156. provider being down must not resurrect the retry loop we just stopped.
  3157. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  3158. path passes its own, because "accepted the file but never started" is the
  3159. opposite of what happened there — the printer refused it outright (#2732).
  3160. """
  3161. try:
  3162. async with async_session() as db:
  3163. item = await db.get(PrintQueueItem, queue_item_id)
  3164. if not item:
  3165. return
  3166. job_name = await self._get_job_name(db, item)
  3167. printer = await self._get_printer(db, printer_id)
  3168. await notification_service.on_queue_job_failed(
  3169. job_name=job_name,
  3170. printer_id=printer_id,
  3171. printer_name=printer.name if printer else "Unknown",
  3172. reason=reason,
  3173. db=db,
  3174. )
  3175. except Exception as e:
  3176. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  3177. try:
  3178. await ws_manager.send_queue_item_failed(
  3179. user_id=created_by_id,
  3180. queue_item_id=queue_item_id,
  3181. printer_id=printer_id,
  3182. reason="never_started",
  3183. )
  3184. except Exception:
  3185. pass # toast is best-effort
  3186. async def _block_on_filament_deficit(
  3187. self,
  3188. db: AsyncSession,
  3189. item: PrintQueueItem,
  3190. ) -> bool:
  3191. """Promote the item to manual_start when the assigned spool is short (#1496).
  3192. Returns True when this dispatch attempt was blocked, False when the
  3193. item is clear to start. A previously-flagged item whose spool has
  3194. since been swapped to one with enough material clears the flag here
  3195. so the next scheduler tick dispatches it.
  3196. """
  3197. # User has explicitly acknowledged the deficit ("Print Anyway") —
  3198. # don't re-flag, don't even compute. Without this short-circuit the
  3199. # scheduler bounces between "user said anyway" (route clears
  3200. # manual_start) and "scheduler re-blocked" (this method re-flags it
  3201. # on identical spool state) (#1698-followup).
  3202. if item.skip_filament_check:
  3203. # #1762 diagnostic: surface the short-circuit at INFO so a
  3204. # future "Print Anyway didn't work" report (e.g. issue #1762
  3205. # comment 3) has actionable evidence in the support bundle
  3206. # without needing DEBUG enabled.
  3207. logger.info(
  3208. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  3209. item.id,
  3210. )
  3211. return False
  3212. try:
  3213. deficit = await compute_deficit_for_queue_item(db, item)
  3214. except Exception as e:
  3215. # Never let a flaky deficit check wedge the queue — log and let
  3216. # dispatch proceed. The PrintModal-side check still runs on the
  3217. # manual paths.
  3218. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  3219. return False
  3220. if deficit:
  3221. item.filament_short = True
  3222. item.manual_start = True
  3223. await db.commit()
  3224. job_name = await self._get_job_name(db, item)
  3225. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  3226. logger.info(
  3227. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  3228. item.id,
  3229. len(deficit),
  3230. )
  3231. try:
  3232. await notification_service.on_queue_job_waiting(
  3233. job_name=job_name,
  3234. target_model=(printer.model if printer else "") or "",
  3235. waiting_reason="filament_short",
  3236. db=db,
  3237. )
  3238. except Exception as e:
  3239. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  3240. return True
  3241. # No deficit — clear any stale flag from a previous tick.
  3242. if item.filament_short:
  3243. item.filament_short = False
  3244. await db.commit()
  3245. return False
  3246. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  3247. """Hand the queue item's owner to printer_manager so the
  3248. print-complete callback can credit the user in PrintLogEntry (#1670).
  3249. No-ops when the item has no `created_by_id` or the referenced user
  3250. row is missing (e.g. user deleted between queue-add and dispatch —
  3251. in that case the print log row falls back to the existing un-credited
  3252. behaviour rather than crashing the dispatch).
  3253. """
  3254. if not item.created_by_id:
  3255. return
  3256. from backend.app.models.user import User
  3257. owner = await db.get(User, item.created_by_id)
  3258. if owner:
  3259. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  3260. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  3261. """Upload file and start print for a queue item.
  3262. Supports two sources:
  3263. - archive_id: Print from an existing archive
  3264. - library_file_id: Print from a library file (file manager)
  3265. """
  3266. logger.info("Starting queue item %s", item.id)
  3267. # Also covers a reservation left active by a process interruption
  3268. # during an earlier attempt. `_dispatch_one` releases this marker on
  3269. # every exit unless start_print() confirms that the command was sent.
  3270. self._unconfirmed_budget_reservations.add(item.id)
  3271. try:
  3272. from backend.app.models.user import User
  3273. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  3274. await validate_print_budget(
  3275. db,
  3276. cost_center_id=item.cost_center_id,
  3277. estimated_cost=item.estimated_cost,
  3278. current_user=queue_user,
  3279. exclude_queue_item_id=item.id,
  3280. exclude_reservation_source_type="print_queue",
  3281. exclude_reservation_source_id=item.id,
  3282. )
  3283. budget_reservation = await create_budget_reservation(
  3284. db,
  3285. cost_center_id=item.cost_center_id,
  3286. estimated_cost=item.estimated_cost,
  3287. current_user=queue_user,
  3288. source_type="print_queue",
  3289. source_id=item.id,
  3290. print_archive_id=item.archive_id,
  3291. exclude_queue_item_id=item.id,
  3292. )
  3293. await db.commit()
  3294. except HTTPException as exc:
  3295. item.status = "failed"
  3296. item.error_message = str(exc.detail)
  3297. item.completed_at = datetime.now(timezone.utc)
  3298. await db.commit()
  3299. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  3300. await self._power_off_if_needed(db, item)
  3301. return
  3302. # Get printer first (needed for both paths)
  3303. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  3304. printer = result.scalar_one_or_none()
  3305. if not printer:
  3306. item.status = "failed"
  3307. item.error_message = "Printer not found"
  3308. item.completed_at = datetime.now(timezone.utc)
  3309. await db.commit()
  3310. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  3311. await self._power_off_if_needed(db, item)
  3312. return
  3313. # Check printer is connected
  3314. if not printer_manager.is_connected(item.printer_id):
  3315. item.status = "failed"
  3316. item.error_message = "Printer not connected"
  3317. item.completed_at = datetime.now(timezone.utc)
  3318. await db.commit()
  3319. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  3320. await self._power_off_if_needed(db, item)
  3321. return
  3322. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  3323. # `items` was taken at the top of check_queue, but the user can /cancel
  3324. # any pending row in the gap before we reach this point. Re-read the
  3325. # row and bail out cleanly instead of starting an FTP upload for a row
  3326. # that's already cancelled. The atomic CAS at the pending→printing
  3327. # transition (below, before start_print) is the load-bearing guard;
  3328. # this is the early-exit optimisation that avoids wasted FTP I/O.
  3329. await db.refresh(item)
  3330. if item.status != "pending":
  3331. logger.info(
  3332. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  3333. item.id,
  3334. item.status,
  3335. )
  3336. return
  3337. # Busy-printer guard (#2598). check_queue gates dispatch on
  3338. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  3339. # keep reporting FINISH for tens of seconds *after* it accepted a
  3340. # project_file (see the watchdog's phase-B note). A watchdog revert
  3341. # (#2555) also releases the dispatch hold, so a re-selected item can
  3342. # reach here while its printer has actually started printing. Uploading
  3343. # and dispatching then collides with the live job — the firmware answers
  3344. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  3345. # live state right before the expensive FTP upload: if the printer is
  3346. # busy, leave the item pending and let a later tick dispatch it once the
  3347. # printer is genuinely idle. No wasted upload, no collision.
  3348. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3349. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  3350. logger.info(
  3351. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  3352. "leaving item pending for a later tick (#2598)",
  3353. item.id,
  3354. item.printer_id,
  3355. pre_dispatch_state,
  3356. )
  3357. return
  3358. # Determine source: archive or library file
  3359. archive = None
  3360. library_file = None
  3361. file_path = None
  3362. filename = None
  3363. cleanup_disk_paths: list[Path] = []
  3364. if item.archive_id:
  3365. # Print from archive
  3366. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3367. archive = result.scalar_one_or_none()
  3368. if not archive:
  3369. item.status = "failed"
  3370. item.error_message = "Archive not found"
  3371. item.completed_at = datetime.now(timezone.utc)
  3372. await db.commit()
  3373. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  3374. await self._power_off_if_needed(db, item)
  3375. return
  3376. # Persist the queue item's selected plate onto the archive so Print
  3377. # History can show the actual plate after cancel/fail/complete (#2603).
  3378. # Only when the archive doesn't already carry one, so a reprint of a
  3379. # plate-specific archive isn't relabelled by a differently-plated
  3380. # queue row.
  3381. if archive.plate_id is None and item.plate_id is not None:
  3382. archive.plate_id = item.plate_id
  3383. file_path = settings.base_dir / archive.file_path
  3384. filename = archive.filename
  3385. elif item.library_file_id:
  3386. # Print from library file (file manager)
  3387. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3388. library_file = result.scalar_one_or_none()
  3389. if not library_file:
  3390. item.status = "failed"
  3391. item.error_message = "Library file not found"
  3392. item.completed_at = datetime.now(timezone.utc)
  3393. await db.commit()
  3394. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  3395. await self._power_off_if_needed(db, item)
  3396. return
  3397. # Library files store absolute paths
  3398. lib_path = Path(library_file.file_path)
  3399. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3400. filename = library_file.filename
  3401. # Create archive from library file so usage tracking has access to the 3MF
  3402. queue_item_id = item.id
  3403. try:
  3404. from backend.app.services.archive import ArchiveService
  3405. archive_service = ArchiveService(db)
  3406. archive = await archive_service.archive_print(
  3407. printer_id=item.printer_id,
  3408. source_file=file_path,
  3409. original_filename=filename,
  3410. created_by_id=item.created_by_id,
  3411. project_id=item.project_id,
  3412. cost_center_id=item.cost_center_id,
  3413. library_file_id=item.library_file_id, # per-file project progress (#1897)
  3414. plate_id=item.plate_id, # selected plate → Print History (#2603)
  3415. )
  3416. if archive:
  3417. item.archive_id = archive.id
  3418. if budget_reservation is not None:
  3419. budget_reservation.print_archive_id = archive.id
  3420. if item.cleanup_library_after_dispatch and not library_file.is_external:
  3421. item.library_file_id = None
  3422. cleanup_disk_paths.append(file_path)
  3423. if library_file.thumbnail_path:
  3424. thumb_path = Path(library_file.thumbnail_path)
  3425. if not thumb_path.is_absolute():
  3426. thumb_path = settings.base_dir / library_file.thumbnail_path
  3427. cleanup_disk_paths.append(thumb_path)
  3428. await db.delete(library_file)
  3429. file_path = settings.base_dir / archive.file_path
  3430. filename = archive.filename
  3431. # Commit, not flush — flush opens the SQLite write
  3432. # transaction (item.archive_id update + library_file
  3433. # delete) and would hold the WAL writer lock through the
  3434. # FTP upload below, causing "database is locked" cascades
  3435. # for sensor history + concurrent cancels (#1853).
  3436. await db.commit()
  3437. logger.info(
  3438. "Queue item %s: Created archive %s from library file %s",
  3439. item.id,
  3440. archive.id,
  3441. item.library_file_id,
  3442. )
  3443. except Exception as e:
  3444. logger.warning(
  3445. "Queue item %s: Failed to create archive from library file: %s",
  3446. queue_item_id,
  3447. e,
  3448. exc_info=True,
  3449. )
  3450. await db.rollback()
  3451. item = await db.get(PrintQueueItem, queue_item_id)
  3452. if item:
  3453. item.status = "failed"
  3454. item.error_message = "Failed to create archive from library file"
  3455. item.completed_at = datetime.now(timezone.utc)
  3456. await db.commit()
  3457. await self._power_off_if_needed(db, item)
  3458. return
  3459. if not archive:
  3460. item.status = "failed"
  3461. item.error_message = "Failed to create archive from library file"
  3462. item.completed_at = datetime.now(timezone.utc)
  3463. await db.commit()
  3464. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  3465. await self._power_off_if_needed(db, item)
  3466. return
  3467. else:
  3468. # Neither archive nor library file specified
  3469. item.status = "failed"
  3470. item.error_message = "No source file specified"
  3471. item.completed_at = datetime.now(timezone.utc)
  3472. await db.commit()
  3473. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  3474. await self._power_off_if_needed(db, item)
  3475. return
  3476. # Check file exists on disk
  3477. if not file_path.exists():
  3478. item.status = "failed"
  3479. item.error_message = "Source file not found on disk"
  3480. item.completed_at = datetime.now(timezone.utc)
  3481. await db.commit()
  3482. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  3483. await self._power_off_if_needed(db, item)
  3484. return
  3485. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  3486. # size dispatched to a printer with a different nozzle installed is
  3487. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  3488. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  3489. # gives the user no idea what went wrong. Catch it here, before we spend
  3490. # time preheating and uploading, and fail with an actionable message.
  3491. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  3492. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  3493. # the printer hasn't reported its nozzles yet, we fall through and let the
  3494. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  3495. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  3496. # as one of the two hotends is a 0.6.
  3497. sliced_nozzle = archive.nozzle_diameter if archive else None
  3498. if sliced_nozzle:
  3499. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  3500. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  3501. if mismatch_msg:
  3502. item.status = "failed"
  3503. item.error_message = mismatch_msg
  3504. item.completed_at = datetime.now(timezone.utc)
  3505. await db.commit()
  3506. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  3507. await notification_service.on_queue_job_failed(
  3508. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3509. printer_id=printer.id,
  3510. printer_name=printer.name,
  3511. reason=mismatch_msg,
  3512. db=db,
  3513. )
  3514. try:
  3515. await ws_manager.send_queue_item_failed(
  3516. user_id=item.created_by_id,
  3517. queue_item_id=item.id,
  3518. printer_id=item.printer_id,
  3519. reason="nozzle_mismatch",
  3520. )
  3521. except Exception:
  3522. pass
  3523. await self._power_off_if_needed(db, item)
  3524. return
  3525. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  3526. # bed (and chamber, if applicable) is at temperature when the firmware
  3527. # starts the actual print routine. Best-effort: any failure logs and
  3528. # falls through to the normal upload+start path rather than turning a
  3529. # configuration issue into a failed queue item.
  3530. await self._preheat_and_soak(db, item, printer, archive)
  3531. # G-code injection for auto-print systems (#422)
  3532. injected_path = None
  3533. # #2547: tracked separately from `injected_path`, which is also set when
  3534. # only a START snippet was injected. Only an END snippet changes what the
  3535. # camera sees at print completion.
  3536. end_gcode_injected = False
  3537. if item.gcode_injection:
  3538. try:
  3539. snippets_raw = await self._get_setting(db, "gcode_snippets")
  3540. if snippets_raw:
  3541. snippets = json.loads(snippets_raw)
  3542. model_snippets = snippets.get(printer.model, {})
  3543. start_gc = (model_snippets.get("start_gcode") or "").strip()
  3544. end_gc = (model_snippets.get("end_gcode") or "").strip()
  3545. if start_gc or end_gc:
  3546. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  3547. injected_path = inject_gcode_into_3mf(
  3548. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  3549. )
  3550. if injected_path:
  3551. file_path = injected_path
  3552. end_gcode_injected = bool(end_gc)
  3553. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  3554. else:
  3555. logger.warning(
  3556. "Queue item %s: G-code injection returned no result, using original", item.id
  3557. )
  3558. except Exception as e:
  3559. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  3560. # #2547: the finish-photo path can't learn from telemetry that this print
  3561. # ends with user End G-code — which means the plate may be gone by the
  3562. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  3563. # the print once the printer confirms it running.
  3564. if end_gcode_injected:
  3565. print_dispatch_context.mark_pending(printer.id)
  3566. # Upload to root directory (not /cache/) - the start_print command references
  3567. # files by name only (ftp://{filename}), so they must be in the root
  3568. remote_filename = derive_remote_filename(filename)
  3569. remote_path = f"/{remote_filename}"
  3570. # Get FTP retry settings
  3571. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3572. logger.info(
  3573. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  3574. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  3575. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  3576. )
  3577. # Release the pooled DB connection before the FTP delete/upload (#2572).
  3578. # Every read this method needs (printer, archive/library, preheat) is
  3579. # done, and the library-file branch already committed its archive
  3580. # creation. Without this the transaction opened by the first SELECT above
  3581. # stays "idle in transaction" for the entire upload — multiple seconds
  3582. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  3583. # a farm dispatching many jobs at once then exhausts the pool. This was
  3584. # correlated to an exact idle-in-transaction session on a 93-printer farm
  3585. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  3586. # readable; the status writes below (upload-failure path and the
  3587. # pending->printing CAS) transparently open a fresh transaction.
  3588. await db.commit()
  3589. # Delete existing file if present (avoids 553 error on overwrite)
  3590. try:
  3591. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  3592. delete_result = await delete_file_async(
  3593. printer.ip_address,
  3594. printer.access_code,
  3595. remote_path,
  3596. socket_timeout=ftp_timeout,
  3597. printer_model=printer.model,
  3598. )
  3599. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  3600. except Exception as e:
  3601. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  3602. # Dispatch toast — announce the upload start with the total byte
  3603. # count so the frontend can render an honest progress bar.
  3604. toast_uid = item.created_by_id
  3605. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3606. try:
  3607. total_bytes = file_path.stat().st_size
  3608. except OSError:
  3609. total_bytes = 0
  3610. try:
  3611. await ws_manager.send_queue_item_uploading(
  3612. user_id=toast_uid,
  3613. queue_item_id=item.id,
  3614. printer_id=item.printer_id,
  3615. printer_name=printer.name,
  3616. file_name=toast_file_name,
  3617. total_bytes=total_bytes,
  3618. )
  3619. except Exception:
  3620. pass # toast is best-effort
  3621. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  3622. # A deadline expiry gets its own message: "check your SD card" is the
  3623. # wrong advice for a link that was simply too slow to finish (#2529).
  3624. upload_error: str | None = None
  3625. try:
  3626. if ftp_retry_enabled:
  3627. uploaded = await with_ftp_retry(
  3628. upload_file_async,
  3629. printer.ip_address,
  3630. printer.access_code,
  3631. file_path,
  3632. remote_path,
  3633. socket_timeout=ftp_timeout,
  3634. printer_model=printer.model,
  3635. progress_callback=progress_bridge,
  3636. max_retries=ftp_retry_count,
  3637. retry_delay=ftp_retry_delay,
  3638. operation_name=f"Upload print to {printer.name}",
  3639. )
  3640. else:
  3641. uploaded = await upload_file_async(
  3642. printer.ip_address,
  3643. printer.access_code,
  3644. file_path,
  3645. remote_path,
  3646. socket_timeout=ftp_timeout,
  3647. printer_model=printer.model,
  3648. progress_callback=progress_bridge,
  3649. )
  3650. except UploadCancelled as e:
  3651. uploaded = False
  3652. upload_error = (
  3653. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  3654. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  3655. )
  3656. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  3657. except Exception as e:
  3658. uploaded = False
  3659. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  3660. # Clean up injected temp file after upload attempt
  3661. if injected_path and injected_path.exists():
  3662. injected_path.unlink(missing_ok=True)
  3663. if not uploaded:
  3664. error_msg = upload_error or (
  3665. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  3666. "See server logs for detailed diagnostics."
  3667. )
  3668. item.status = "failed"
  3669. item.error_message = error_msg
  3670. item.completed_at = datetime.now(timezone.utc)
  3671. await db.commit()
  3672. logger.error(
  3673. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  3674. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  3675. )
  3676. # Send failure notification
  3677. await notification_service.on_queue_job_failed(
  3678. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3679. printer_id=printer.id,
  3680. printer_name=printer.name,
  3681. reason="Failed to upload file to printer",
  3682. db=db,
  3683. )
  3684. try:
  3685. await ws_manager.send_queue_item_failed(
  3686. user_id=toast_uid,
  3687. queue_item_id=item.id,
  3688. printer_id=item.printer_id,
  3689. reason="upload_failed",
  3690. )
  3691. except Exception:
  3692. pass
  3693. await self._power_off_if_needed(db, item)
  3694. return
  3695. # Parse AMS mapping if stored
  3696. ams_mapping = None
  3697. if item.ams_mapping:
  3698. try:
  3699. ams_mapping = json.loads(item.ams_mapping)
  3700. except json.JSONDecodeError:
  3701. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  3702. # Register as expected print so we don't create a duplicate archive
  3703. # Only applicable for archive-based prints
  3704. if archive:
  3705. from backend.app.main import register_expected_print
  3706. register_expected_print(
  3707. item.printer_id,
  3708. remote_filename,
  3709. archive.id,
  3710. ams_mapping=ams_mapping,
  3711. created_by_id=item.created_by_id,
  3712. cost_center_id=item.cost_center_id,
  3713. plate_id=item.plate_id,
  3714. )
  3715. # Registration happens before the print command by necessity (the
  3716. # printer can report the print before the send returns), so record
  3717. # what to undo if we never get as far as sending. `_dispatch_one`
  3718. # rolls back anything still pending here on every exit — exception,
  3719. # early return, or cancel winning the CAS below.
  3720. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  3721. # Propagate the queue item's owner into printer_manager so the
  3722. # print-complete callback can credit the user in the PrintLogEntry
  3723. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  3724. # items) or when the user clicks the manual-start button.
  3725. await self._propagate_owner_to_printer_manager(db, item)
  3726. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  3727. # This prevents phantom reprints if the backend crashes/restarts after the
  3728. # print command is sent but before the status update is committed.
  3729. # If we crash after this commit but before start_print(), the item will be
  3730. # in "printing" status without actually printing - but that's safer than
  3731. # accidentally reprinting the same file hours later.
  3732. #
  3733. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  3734. # initial pending read at the top of check_queue and this point) flips
  3735. # the row to "cancelled" in a separate session. Without the WHERE
  3736. # status='pending' clause, the unconditional update here would silently
  3737. # overwrite that cancellation and we'd ship the MQTT start_print below
  3738. # — printer obeys, user sees "I pressed cancel and the print started".
  3739. # rowcount==0 means the user won the race; bail out, best-effort delete
  3740. # the file we just uploaded, do NOT send start_print.
  3741. now_utc = datetime.now(timezone.utc)
  3742. cas = await db.execute(
  3743. update(PrintQueueItem)
  3744. .where(PrintQueueItem.id == item.id)
  3745. .where(PrintQueueItem.status == "pending")
  3746. .values(status="printing", started_at=now_utc)
  3747. )
  3748. await db.commit()
  3749. if cas.rowcount == 0:
  3750. logger.info(
  3751. "Queue item %s no longer pending at print-command time "
  3752. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  3753. item.id,
  3754. )
  3755. try:
  3756. await delete_file_async(
  3757. printer.ip_address,
  3758. printer.access_code,
  3759. remote_path,
  3760. socket_timeout=ftp_timeout,
  3761. printer_model=printer.model,
  3762. )
  3763. except Exception as cleanup_err:
  3764. logger.debug(
  3765. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  3766. item.id,
  3767. cleanup_err,
  3768. )
  3769. try:
  3770. await ws_manager.send_queue_item_failed(
  3771. user_id=toast_uid,
  3772. queue_item_id=item.id,
  3773. printer_id=item.printer_id,
  3774. reason="cancelled_mid_dispatch",
  3775. )
  3776. except Exception:
  3777. pass
  3778. return
  3779. # Sync the in-memory item so subsequent code that reads item.status /
  3780. # item.started_at sees the values we just persisted.
  3781. item.status = "printing"
  3782. item.started_at = now_utc
  3783. for cleanup_path in cleanup_disk_paths:
  3784. try:
  3785. if cleanup_path.exists():
  3786. cleanup_path.unlink()
  3787. except OSError as cleanup_err:
  3788. logger.warning(
  3789. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  3790. json.dumps(
  3791. {
  3792. "queue_item_id": item.id,
  3793. "path": str(cleanup_path),
  3794. "error": str(cleanup_err),
  3795. },
  3796. sort_keys=True,
  3797. ),
  3798. )
  3799. # Clear the awaiting-plate-clear flag now that we're starting a new print
  3800. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  3801. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  3802. # Capture state before dispatch so the watchdog can detect whether the
  3803. # printer actually transitioned (#967). Also capture subtask_id so the
  3804. # watchdog can recognise "command landed but state hasn't flipped yet"
  3805. # on slow H2D transitions (#1078).
  3806. pre_status = printer_manager.get_status(item.printer_id)
  3807. pre_state = getattr(pre_status, "state", None) if pre_status else None
  3808. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  3809. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  3810. # #1721: respect the user's explicit timelapse choice. The #1397
  3811. # force-on at dispatch was removed because it caused per-layer nozzle
  3812. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  3813. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  3814. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  3815. # FINISH-state fallback — no need to force a video.
  3816. effective_timelapse = bool(item.timelapse)
  3817. # Start the print with AMS mapping, plate_id and print options.
  3818. # nozzle_mapping rides through verbatim — JSON string captured from
  3819. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  3820. # parses + injects it only for dual-nozzle models so a null on every
  3821. # other model is a transparent pass-through.
  3822. started = printer_manager.start_print(
  3823. item.printer_id,
  3824. remote_filename,
  3825. plate_id=item.plate_id or 1,
  3826. ams_mapping=ams_mapping,
  3827. bed_levelling=item.bed_levelling,
  3828. flow_cali=item.flow_cali,
  3829. vibration_cali=item.vibration_cali,
  3830. layer_inspect=item.layer_inspect,
  3831. timelapse=effective_timelapse,
  3832. use_ams=item.use_ams,
  3833. nozzle_offset_cali=item.nozzle_offset_cali,
  3834. nozzle_mapping=item.nozzle_mapping,
  3835. )
  3836. if started:
  3837. # The command is away, so the expectation is now legitimate and must
  3838. # survive. Anything still in this dict when _dispatch_one exits gets
  3839. # rolled back.
  3840. self._unconfirmed_expected_print.pop(item.id, None)
  3841. self._unconfirmed_budget_reservations.discard(item.id)
  3842. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  3843. # No dispatch-toast event here: the legacy bg-dispatch path kept
  3844. # status='processing' from upload start until the printer acked
  3845. # (or timed out). The frontend derives "Awaiting printer…" purely
  3846. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  3847. # event would push the status chip out of 'PROCESSING' prematurely
  3848. # — which is exactly what the screenshot at #1625-followup
  3849. # complained about.
  3850. # Register the local 3MF in the cover-cache so /cover skips FTP
  3851. # (#1166 follow-up). file_path was resolved earlier from either the
  3852. # archive or the library file row.
  3853. if file_path is not None:
  3854. cache_3mf_download(item.printer_id, remote_filename, file_path)
  3855. # Hold the printer against further dispatches until the watchdog
  3856. # confirms the printer transitioned (or until the hard timeout).
  3857. # Prevents multi-plate batches from triple-dispatching onto the
  3858. # same H2D Pro while it digests the first project_file (#1157).
  3859. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  3860. # Watchdog: if the printer never transitions out of pre_state AND
  3861. # never advances subtask_id, the MQTT publish was accepted locally but
  3862. # didn't reach the printer (half-broken session — same shape as
  3863. # #887/#936). Revert the queue item so the next dispatch can pick it
  3864. # up instead of leaving it stuck in "printing" (#967). subtask_id
  3865. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  3866. # that would otherwise cause the item to re-dispatch as a reprint
  3867. # of the just-finished job (#1078).
  3868. if pre_state:
  3869. spawn_background_task(
  3870. self._watchdog_print_start(
  3871. item.id,
  3872. item.printer_id,
  3873. pre_state,
  3874. pre_subtask_id,
  3875. pre_gcode_file,
  3876. created_by_id=toast_uid,
  3877. ),
  3878. name=f"watchdog-print-start-{item.id}",
  3879. )
  3880. # Get estimated time for notification.
  3881. #
  3882. # This used to fall back to `library_file.print_time_seconds`, a column
  3883. # LibraryFile does not have — the print time it knows about lives in
  3884. # `file_metadata`. So a library print whose archive carried no parseable
  3885. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  3886. # AttributeError right here, *after* the printer had already been sent
  3887. # the job: the started-notification never fired, and the exception
  3888. # unwound the whole queue pass, so every other printer still waiting to
  3889. # be dispatched on that tick silently missed its turn.
  3890. #
  3891. # The queue item caches the print time at creation ("Cached from
  3892. # archive/library"), which is the value this was reaching for.
  3893. estimated_time = None
  3894. if archive and archive.print_time_seconds:
  3895. estimated_time = archive.print_time_seconds
  3896. elif item.print_time_seconds:
  3897. estimated_time = item.print_time_seconds
  3898. # Send job started notification
  3899. await notification_service.on_queue_job_started(
  3900. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3901. printer_id=printer.id,
  3902. printer_name=printer.name,
  3903. db=db,
  3904. estimated_time=estimated_time,
  3905. )
  3906. # MQTT relay - publish queue job started
  3907. try:
  3908. from backend.app.services.mqtt_relay import mqtt_relay
  3909. await mqtt_relay.on_queue_job_started(
  3910. job_id=item.id,
  3911. filename=filename,
  3912. printer_id=printer.id,
  3913. printer_name=printer.name,
  3914. printer_serial=printer.serial_number,
  3915. )
  3916. except Exception:
  3917. pass # Don't fail if MQTT fails
  3918. else:
  3919. # Clean up uploaded file from SD card to prevent phantom prints
  3920. try:
  3921. await delete_file_async(
  3922. printer.ip_address,
  3923. printer.access_code,
  3924. remote_path,
  3925. printer_model=printer.model,
  3926. )
  3927. except Exception:
  3928. pass # Best-effort — don't fail the error handler
  3929. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  3930. # state can flip from idle to active in the window between the
  3931. # pre-dispatch check above and this publish (the FTP upload takes
  3932. # seconds); start_print() then refuses to send project_file to the
  3933. # now-busy printer and returns False. Failing the item here would be
  3934. # wrong — the printer is fine, it is simply busy — so revert to
  3935. # pending and let a later tick dispatch it once the printer is idle,
  3936. # exactly like the pre-dispatch guard. Only a start_print() False on
  3937. # an idle/unknown printer is a genuine command failure.
  3938. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3939. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  3940. logger.info(
  3941. "Queue item %s: printer %s became busy (state=%s) before the start "
  3942. "command was sent — deferring, reverting item to pending (#2598)",
  3943. item.id,
  3944. item.printer_id,
  3945. post_dispatch_state,
  3946. )
  3947. item.status = "pending"
  3948. item.started_at = None
  3949. await db.commit()
  3950. return
  3951. # Print command failed - revert status
  3952. item.status = "failed"
  3953. item.error_message = "Failed to send print command to printer"
  3954. item.completed_at = datetime.now(timezone.utc)
  3955. await db.commit()
  3956. logger.error(
  3957. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  3958. f"printer_manager.start_print() returned False. "
  3959. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  3960. f"Check printer status and backend logs for details."
  3961. )
  3962. # Send failure notification
  3963. await notification_service.on_queue_job_failed(
  3964. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3965. printer_id=printer.id,
  3966. printer_name=printer.name,
  3967. reason="Failed to send print command to printer - check printer connection and status",
  3968. db=db,
  3969. )
  3970. try:
  3971. await ws_manager.send_queue_item_failed(
  3972. user_id=toast_uid,
  3973. queue_item_id=item.id,
  3974. printer_id=item.printer_id,
  3975. reason="start_command_failed",
  3976. )
  3977. except Exception:
  3978. pass
  3979. await self._power_off_if_needed(db, item)
  3980. @staticmethod
  3981. async def _watchdog_print_start(
  3982. queue_item_id: int,
  3983. printer_id: int,
  3984. pre_state: str,
  3985. pre_subtask_id: str | None = None,
  3986. pre_gcode_file: str | None = None,
  3987. timeout: float = 90.0,
  3988. phase_b_timeout: float = 180.0,
  3989. poll_interval: float = 3.0,
  3990. created_by_id: int | None = None,
  3991. ) -> None:
  3992. """Revert a queue item if the printer never acknowledges the start command.
  3993. Bambuddy optimistically marks the queue item as "printing" right after the
  3994. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  3995. Phase A (up to ``timeout``): wait for either an active-state transition
  3996. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  3997. primary signal; subtask_id advance handles the H2D case where state can
  3998. sit at FINISH for ~50 s after the printer accepted ``project_file``
  3999. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  4000. was lost on a half-broken session (#887/#936) — revert and force
  4001. reconnect (the #967 recovery path).
  4002. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  4003. alone): keep watching for the active-state transition. subtask_id alone
  4004. proves the file landed but not that the printer started — and a printer
  4005. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  4006. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  4007. used to leave the queue item stuck in 'printing' forever because the
  4008. old watchdog returned success as soon as subtask_id advanced. If Phase
  4009. B times out, revert the queue item so the user can retry without
  4010. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  4011. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  4012. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  4013. transitions that also don't emit an early subtask_id tick.
  4014. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  4015. refuses to verify our commands will never start this job or any other,
  4016. so waiting out the full 270 s and re-uploading the 3MF twice more only
  4017. burns an upload slot the rest of the farm is queued behind — that path
  4018. is for a printer that might still come good, which this one cannot
  4019. (#2732). It fails the item on the spot with the actual reason instead.
  4020. """
  4021. last_status = None
  4022. landed_on_subtask = False
  4023. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  4024. # every push carrying an `hms` key, so the fault can come and go between
  4025. # 3-second polls. Seeing it once inside the dispatch window is enough.
  4026. command_rejected = False
  4027. # Latched for the same reason as command_rejected: drying can finish, or
  4028. # be stopped by the user, part-way through the dispatch window. Seeing it
  4029. # once is what matters — it is the state the printer was in when it
  4030. # declined to start (#2758).
  4031. drying_ams_ids: list[int] = []
  4032. deadline = time.monotonic() + timeout
  4033. while time.monotonic() < deadline:
  4034. await asyncio.sleep(poll_interval)
  4035. status = printer_manager.get_status(printer_id)
  4036. if not status:
  4037. # Printer disconnected — don't mess with the DB. Drop the
  4038. # in-memory dispatch hold too so a fresh dispatch can retry
  4039. # once the printer comes back; the hard timeout would
  4040. # otherwise hold the printer unnecessarily.
  4041. scheduler._release_dispatch_hold(printer_id)
  4042. return
  4043. last_status = status
  4044. if status.state in _ACTIVE_PRINT_STATES:
  4045. # Printer is actively processing the job — release the
  4046. # post-dispatch hold so the next pending item for this printer
  4047. # can be evaluated normally. We do NOT accept arbitrary state
  4048. # transitions: a printer going FINISH -> IDLE (user dismissed
  4049. # the post-print prompt without accepting our project_file)
  4050. # would otherwise look like "command landed" and leave the
  4051. # queue item stuck in 'printing' forever (#1370).
  4052. scheduler._release_dispatch_hold(printer_id)
  4053. try:
  4054. await ws_manager.send_queue_item_acked(
  4055. user_id=created_by_id,
  4056. queue_item_id=queue_item_id,
  4057. printer_id=printer_id,
  4058. )
  4059. except Exception:
  4060. pass
  4061. return
  4062. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  4063. # Checked only after the active-state exit above: a stale HMS left
  4064. # over from an earlier job must never abort a print that is visibly
  4065. # running. An actually-refused command leaves the printer idle, so
  4066. # this ordering costs the detection nothing.
  4067. if _mqtt_commands_rejected(status):
  4068. command_rejected = True
  4069. break
  4070. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  4071. # Phase A exit — printer accepted the file (subtask_id flipped
  4072. # to our submission id). Don't return yet: the printer may
  4073. # have accepted the command but never actually start (e.g.
  4074. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  4075. # B watches for the active-state transition.
  4076. landed_on_subtask = True
  4077. break
  4078. if landed_on_subtask and not command_rejected:
  4079. phase_b_deadline = time.monotonic() + phase_b_timeout
  4080. while time.monotonic() < phase_b_deadline:
  4081. await asyncio.sleep(poll_interval)
  4082. status = printer_manager.get_status(printer_id)
  4083. if not status:
  4084. scheduler._release_dispatch_hold(printer_id)
  4085. return
  4086. last_status = status
  4087. if status.state in _ACTIVE_PRINT_STATES:
  4088. scheduler._release_dispatch_hold(printer_id)
  4089. try:
  4090. await ws_manager.send_queue_item_acked(
  4091. user_id=created_by_id,
  4092. queue_item_id=queue_item_id,
  4093. printer_id=printer_id,
  4094. )
  4095. except Exception:
  4096. pass
  4097. return
  4098. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  4099. # Same ordering rule as Phase A: a running print wins over a
  4100. # lingering HMS.
  4101. if _mqtt_commands_rejected(status):
  4102. command_rejected = True
  4103. break
  4104. # No active-state transition. Revert the item so the scheduler can retry.
  4105. # Drop the in-memory hold so the retry isn't blocked by it.
  4106. scheduler._release_dispatch_hold(printer_id)
  4107. # Logged on every failed dispatch window, not just the last one, so a
  4108. # support bundle shows the correlation from the first attempt rather than
  4109. # only after the retry budget is spent (#2758).
  4110. if drying_ams_ids:
  4111. logger.info(
  4112. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  4113. queue_item_id,
  4114. printer_id,
  4115. ", ".join(str(i) for i in drying_ams_ids),
  4116. )
  4117. # Four outcomes from the revert attempt, each routed differently:
  4118. # "reverted": row flipped from printing -> pending, run recovery
  4119. # "gave_up": same, but the retry budget is spent — row failed
  4120. # rather than pending, so it stops going round again
  4121. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  4122. # on_print_complete or user). Skip recovery entirely
  4123. # — the print clearly landed somewhere even if the
  4124. # watchdog didn't see the active-state transition.
  4125. # "revert_failed": SQLite contention exhausted retries. Still run
  4126. # recovery so the MQTT session gets a fresh client_id
  4127. # on the half-broken-session path.
  4128. #
  4129. # The retry budget (#2555): reverting to 'pending' hands the item straight
  4130. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  4131. # the watchdog again. For a printer that is genuinely wedged that loop never
  4132. # ends — the reporter had one printer "since this morning still not launch"
  4133. # — and each lap also consumes an upload slot that the other printers in the
  4134. # farm are waiting on. Retrying is right; retrying forever is not.
  4135. async def _do_revert(db):
  4136. item = await db.get(PrintQueueItem, queue_item_id)
  4137. if not item or item.status != "printing":
  4138. return "already_moved_on"
  4139. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  4140. item.started_at = None
  4141. # Charge the attempt to the candidate that was actually dispatched, so
  4142. # a cross-model item (#671) reaches for its other file next lap instead
  4143. # of retrying the printer that just failed to start. Matched by file
  4144. # because that is what the resolver copied onto the row.
  4145. if item.library_file_id is not None:
  4146. await db.execute(
  4147. update(PrintQueueVariant)
  4148. .where(PrintQueueVariant.queue_item_id == item.id)
  4149. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  4150. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  4151. )
  4152. if command_rejected:
  4153. # No retry budget for this one: the printer refused to verify the
  4154. # command, and re-uploading the same 3MF to the same printer will
  4155. # be refused the same way. Fail now with the fix rather than after
  4156. # three laps of a message about SD cards (#2732).
  4157. item.status = "failed"
  4158. item.error_message = (
  4159. "The printer rejected the print command: MQTT command verification failed "
  4160. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  4161. "then start the job again."
  4162. )
  4163. item.completed_at = datetime.now(timezone.utc)
  4164. await db.commit()
  4165. return "command_rejected"
  4166. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  4167. item.status = "failed"
  4168. if drying_ams_ids:
  4169. # #2758: the generic message below sent the reporter looking
  4170. # at the SD card while the actual obstacle — AMS units in a
  4171. # drying cycle — was on screen the whole time. Name what we
  4172. # observed and let the user judge it; Bambuddy does not stop
  4173. # the cycle itself, because on this hardware drying can run
  4174. # alongside a print and stopping it may not be the fix.
  4175. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  4176. item.error_message = (
  4177. f"The printer accepted the file but never started printing, after "
  4178. f"{item.dispatch_attempts} attempts. {units} "
  4179. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  4180. f"some printers refuse to begin a print while an AMS is in a drying "
  4181. f"cycle, and an AMS drying without its external power supply can also "
  4182. f"leave too little power for the start-of-print calibration. Stop the "
  4183. f"drying, or connect the AMS power supply, and start the job again."
  4184. )
  4185. else:
  4186. item.error_message = (
  4187. f"The printer accepted the file but never started printing, after "
  4188. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  4189. f"prompt or error, confirm its SD card is readable, and start the job again."
  4190. )
  4191. item.completed_at = datetime.now(timezone.utc)
  4192. await release_budget_reservation(
  4193. db,
  4194. source_type="print_queue",
  4195. source_id=item.id,
  4196. status="released",
  4197. )
  4198. await db.commit()
  4199. return "gave_up"
  4200. item.status = "pending"
  4201. await db.commit()
  4202. return "reverted"
  4203. try:
  4204. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  4205. except Exception as e:
  4206. logger.warning(
  4207. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  4208. "scheduler may keep treating this item as in-flight",
  4209. queue_item_id,
  4210. printer_id,
  4211. e,
  4212. )
  4213. revert_outcome = "revert_failed"
  4214. if revert_outcome == "already_moved_on":
  4215. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  4216. # other path) already moved the item past 'printing', don't run the
  4217. # MQTT session-recovery logic below — a forced reconnect on a healthy
  4218. # session breaks ongoing prints on the same printer.
  4219. return
  4220. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  4221. if revert_outcome == "command_rejected":
  4222. logger.error(
  4223. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  4224. "failed) — the print command was rejected, not lost. Failing the item "
  4225. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  4226. queue_item_id,
  4227. printer_id,
  4228. HMS_MQTT_VERIFY_FAILED,
  4229. )
  4230. await scheduler._notify_dispatch_gave_up(
  4231. queue_item_id,
  4232. printer_id,
  4233. created_by_id,
  4234. reason="Printer rejected the print command (MQTT command verification failed)",
  4235. )
  4236. # Same reasoning as the landed_on_subtask path below: the file is on
  4237. # the printer and a forced reconnect would only add 0500_4003 to a
  4238. # problem that has nothing to do with the MQTT session (#1150).
  4239. return
  4240. if revert_outcome == "gave_up":
  4241. logger.error(
  4242. "Queue item %s: printer %d never started the print after %d dispatch "
  4243. "attempts (last one waited %.0fs) — marking the item failed instead of "
  4244. "re-uploading it again (#2555)",
  4245. queue_item_id,
  4246. printer_id,
  4247. DISPATCH_MAX_ATTEMPTS,
  4248. total_timeout,
  4249. )
  4250. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  4251. elif revert_outcome == "reverted":
  4252. if landed_on_subtask:
  4253. logger.warning(
  4254. "Queue item %s: printer %d accepted project_file (subtask_id "
  4255. "advanced) but never transitioned to an active state within "
  4256. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  4257. "for retry (#1678)",
  4258. queue_item_id,
  4259. printer_id,
  4260. total_timeout,
  4261. )
  4262. else:
  4263. logger.warning(
  4264. "Queue item %s: printer %d did not respond to print command within "
  4265. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  4266. "for retry (#967)",
  4267. queue_item_id,
  4268. printer_id,
  4269. timeout,
  4270. pre_state,
  4271. pre_subtask_id,
  4272. )
  4273. # Phase B was entered iff subtask_id advanced, which means the
  4274. # project_file landed on the printer. A forced reconnect at this point
  4275. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  4276. # skip the recovery entirely.
  4277. if landed_on_subtask:
  4278. return
  4279. # Phase A timeout path: if the printer's gcode_file changed since
  4280. # pre-dispatch, the project_file command landed and the printer is
  4281. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  4282. # If gcode_file is unchanged, the publish was silently swallowed
  4283. # (#887/#936) and force_reconnect recovery is what we want.
  4284. client = printer_manager.get_client(printer_id)
  4285. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  4286. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  4287. if publish_landed:
  4288. logger.warning(
  4289. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  4290. "received the command and is parsing slowly. Skipping forced "
  4291. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  4292. queue_item_id,
  4293. current_gcode_file,
  4294. pre_gcode_file,
  4295. )
  4296. elif client and hasattr(client, "force_reconnect_stale_session"):
  4297. client.force_reconnect_stale_session(
  4298. f"queue print command unacknowledged after {timeout:.0f}s "
  4299. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  4300. )
  4301. # Global scheduler instance
  4302. scheduler = PrintScheduler()