print_scheduler.py 190 KB

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