prod2u_p4_cli.py 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992
  1. #!/usr/bin/env python3
  2. """Normal-only host tooling for Prod2U Profile 4 binary921-v3."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import queue
  8. import re
  9. import subprocess
  10. import sys
  11. import threading
  12. import time
  13. from dataclasses import dataclass
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. from typing import Any, Callable, Mapping
  17. from prod2u_programmer import execute_program_sram
  18. from prod2u_p4_normal_v3_build import validate_build_info, verify_bitstream
  19. from prod2u_p4_normal_v3_receipts import replay_serial_transcript_events, validate_session_receipt
  20. from prod2u_p4_protocol import (
  21. CRC_LEN,
  22. HEADER_LEN,
  23. MAGIC,
  24. CAPABILITY_FLAGS,
  25. BootBuildId,
  26. CommandId,
  27. FrameType,
  28. HostAck,
  29. MotionStatus,
  30. P4Frame,
  31. P4FrameError,
  32. StatusCode,
  33. build_get_motor_status,
  34. build_host_command,
  35. build_mark_closed,
  36. build_motor_jog,
  37. build_output_snapshot,
  38. decode_boot_build_id,
  39. decode_frame,
  40. decode_host_ack,
  41. decode_motion_status,
  42. state_hash16,
  43. )
  44. from prod2u_p4_trace import (
  45. AxisStopReason,
  46. AxisTraceSource,
  47. CompletedCommand,
  48. EpochTraceEvidence,
  49. TraceEvent,
  50. TraceEventType,
  51. TraceHostPolicy,
  52. TracePolicyError,
  53. decode_axis_trace_event,
  54. decode_epoch_trace_event,
  55. decode_limit_trace_event,
  56. decode_overflow_trace_event,
  57. decode_trace_frame,
  58. encode_trace_frame,
  59. )
  60. PROFILE = "prod2u-p4-normal-actuator-trace-binary921-v3"
  61. PROFILE_ID = 4
  62. PROTOCOL_VERSION = 2
  63. PORT = "COM5"
  64. BAUD = 921600
  65. DEFAULT_TD_ROOT = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412")
  66. BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
  67. BOARD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
  68. COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
  69. SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
  70. HARDWARE_QUALIFIED_AXES = (0, 1)
  71. SAFE_STATE_HASH16 = state_hash16(
  72. ptc_percent=(0,) * 24,
  73. fan_percent=(30,) * 4,
  74. solenoid=0,
  75. )
  76. POST_FAULT_DRAIN_BYTE_LIMIT = 8192
  77. POST_FAULT_DRAIN_FRAME_LIMIT = 64
  78. POST_FAULT_DRAIN_SECONDS = 0.050
  79. @dataclass(frozen=True)
  80. class CommandResult:
  81. ack: HostAck
  82. raw_response: bytes
  83. frames: tuple[P4Frame, ...]
  84. command_result_trace: TraceEvent
  85. @dataclass(frozen=True)
  86. class MotorStatusResult:
  87. ack: HostAck
  88. status: MotionStatus
  89. raw_response: bytes
  90. class _PumpCall:
  91. def __init__(
  92. self,
  93. action: Callable[[], Any],
  94. *,
  95. pre_dispatch_quiet: bool,
  96. activate_parser: bool,
  97. ) -> None:
  98. self.action = action
  99. self.pre_dispatch_quiet = pre_dispatch_quiet
  100. self.activate_parser = activate_parser
  101. self.done = threading.Event()
  102. self.result: Any = None
  103. self.error: BaseException | None = None
  104. def open_com5(serial_factory: Callable[[], Any] | None = None) -> Any:
  105. if serial_factory is None:
  106. try:
  107. import serial # type: ignore
  108. except ImportError as exc:
  109. raise RuntimeError("pyserial is required for live Profile 4 operation") from exc
  110. serial_factory = serial.Serial
  111. endpoint = serial_factory()
  112. endpoint.port = PORT
  113. endpoint.baudrate = BAUD
  114. endpoint.bytesize = 8
  115. endpoint.parity = "N"
  116. endpoint.stopbits = 1
  117. endpoint.timeout = 0
  118. endpoint.write_timeout = 1
  119. endpoint.dtr = False
  120. endpoint.rts = False
  121. if not getattr(endpoint, "is_open", False):
  122. endpoint.open()
  123. endpoint.dtr = False
  124. endpoint.rts = False
  125. return endpoint
  126. class NormalSession:
  127. """One-outstanding-command COM5 session with one DISABLE fallback."""
  128. def __init__(
  129. self,
  130. endpoint: Any,
  131. *,
  132. timeout_seconds: float = 0.25,
  133. quiet_window_seconds: float = 0.010,
  134. max_quiet_drain_seconds: float = 0.050,
  135. monotonic: Callable[[], float] = time.monotonic,
  136. sleep: Callable[[float], None] = time.sleep,
  137. expected_build_id: int | None = None,
  138. expected_capability_flags: int | None = None,
  139. ) -> None:
  140. if timeout_seconds <= 0:
  141. raise ValueError("timeout_seconds must be positive")
  142. if quiet_window_seconds <= 0:
  143. raise ValueError("quiet_window_seconds must be positive")
  144. if max_quiet_drain_seconds < quiet_window_seconds:
  145. raise ValueError("max_quiet_drain_seconds must cover the quiet window")
  146. for name, value in (
  147. ("expected_build_id", expected_build_id),
  148. ("expected_capability_flags", expected_capability_flags),
  149. ):
  150. if value is not None and (
  151. isinstance(value, bool)
  152. or not isinstance(value, int)
  153. or not 0 <= value <= 0xFFFFFFFF
  154. ):
  155. raise ValueError(f"{name} must be a 32-bit integer or None")
  156. self.endpoint = endpoint
  157. self.timeout_seconds = timeout_seconds
  158. self.quiet_window_seconds = quiet_window_seconds
  159. self.max_quiet_drain_seconds = max_quiet_drain_seconds
  160. self.disable_attempted = False
  161. self._command_lock = threading.Lock()
  162. self._state_lock = threading.RLock()
  163. self._fail_lock = threading.Lock()
  164. self._rx_buffer = bytearray()
  165. self._rx_journal = bytearray()
  166. self._last_exchange: dict[str, Any] | None = None
  167. self._best_effort_disable_exchange: dict[str, Any] | None = None
  168. self._trace_policy = TraceHostPolicy()
  169. self._post_fault_trace_events: list[TraceEvent] = []
  170. self._post_fault_drain_attempted = False
  171. self._terminated = False
  172. self._startup_preamble_state = "inactive"
  173. self._startup_boot_seen = False
  174. self._startup_epoch_seen = False
  175. self.expected_build_id = expected_build_id
  176. self.expected_capability_flags = expected_capability_flags
  177. self.startup_boot_identity: BootBuildId | None = None
  178. self.startup_epoch: EpochTraceEvidence | None = None
  179. self._monotonic = monotonic
  180. self._sleep = sleep
  181. self._pump_calls: queue.Queue[_PumpCall | None] = queue.Queue(maxsize=1)
  182. self._pump_thread: threading.Thread | None = None
  183. self._pump_thread_id: int | None = None
  184. self._pump_stop = threading.Event()
  185. self._pump_started = threading.Event()
  186. self._pump_persistent = False
  187. self._pump_capture_only = False
  188. self._pump_error: BaseException | None = None
  189. self._idle_partial_since: float | None = None
  190. self._idle_frames: list[P4Frame] = []
  191. self._idle_raw = bytearray()
  192. @property
  193. def rx_journal(self) -> bytes:
  194. with self._state_lock:
  195. return bytes(self._rx_journal)
  196. @property
  197. def trace_events(self) -> list[TraceEvent]:
  198. with self._state_lock:
  199. return [
  200. *self._trace_policy.trace_events,
  201. *self._post_fault_trace_events,
  202. ]
  203. @property
  204. def last_exchange(self) -> dict[str, Any] | None:
  205. with self._state_lock:
  206. return None if self._last_exchange is None else dict(self._last_exchange)
  207. @property
  208. def best_effort_disable_exchange(self) -> dict[str, Any] | None:
  209. with self._state_lock:
  210. return (
  211. None
  212. if self._best_effort_disable_exchange is None
  213. else dict(self._best_effort_disable_exchange)
  214. )
  215. @property
  216. def reader_running(self) -> bool:
  217. thread = self._pump_thread
  218. return thread is not None and thread.is_alive()
  219. @property
  220. def reader_thread_id(self) -> int | None:
  221. return self._pump_thread_id
  222. @property
  223. def reader_error(self) -> BaseException | None:
  224. return self._pump_error
  225. def start_reader(
  226. self,
  227. *,
  228. persistent: bool = True,
  229. capture_only: bool = False,
  230. allow_startup_preamble: bool = False,
  231. ) -> None:
  232. if self.reader_running:
  233. if persistent:
  234. self._pump_persistent = True
  235. if capture_only:
  236. self._pump_capture_only = True
  237. return
  238. if allow_startup_preamble:
  239. self._begin_startup_preamble(
  240. expected_command=CommandId.DISABLE,
  241. allow_boot_preamble=True,
  242. )
  243. self._pump_stop.clear()
  244. self._pump_started.clear()
  245. self._pump_calls = queue.Queue(maxsize=1)
  246. self._pump_persistent = persistent
  247. self._pump_capture_only = capture_only
  248. self._pump_error = None
  249. self._idle_partial_since = None
  250. self._pump_thread = threading.Thread(
  251. target=self._pump_loop,
  252. name="prod2u-p4-uart-pump",
  253. daemon=True,
  254. )
  255. self._pump_thread.start()
  256. if not self._pump_started.wait(1.0):
  257. raise RuntimeError("UART pump did not start within its bound")
  258. def stop_reader(self) -> None:
  259. thread = self._pump_thread
  260. if thread is None:
  261. return
  262. self._pump_stop.set()
  263. thread.join(timeout=max(1.0, self.timeout_seconds + self.max_quiet_drain_seconds + 0.5))
  264. if thread.is_alive():
  265. raise RuntimeError("UART pump did not stop within its bounded join")
  266. self._pump_thread = None
  267. self._pump_thread_id = None
  268. self._pump_persistent = False
  269. self._pump_capture_only = False
  270. self._pump_started.clear()
  271. def _store_idle_frames(self, frames: tuple[P4Frame, ...]) -> None:
  272. with self._state_lock:
  273. self._idle_frames.extend(frames)
  274. for frame in frames:
  275. self._idle_raw.extend(frame.raw)
  276. def _pump_capture_once(self) -> None:
  277. chunk = self._read_endpoint(256)
  278. if chunk:
  279. self._rx_buffer.extend(chunk)
  280. return
  281. self._pump_stop.wait(0.0005)
  282. def _capture_available_on_pump(self) -> None:
  283. captured = 0
  284. while True:
  285. chunk = self._read_endpoint(256)
  286. if not chunk:
  287. return
  288. self._rx_buffer.extend(chunk)
  289. captured += len(chunk)
  290. if captured >= 8192:
  291. return
  292. def _pump_idle_once(self) -> None:
  293. chunk = self._read_endpoint(256)
  294. if chunk:
  295. self._rx_buffer.extend(chunk)
  296. if self._idle_partial_since is None:
  297. self._idle_partial_since = self._monotonic()
  298. frames: list[P4Frame] = []
  299. while True:
  300. frame = self._pop_frame()
  301. if frame is None:
  302. break
  303. frames.append(frame)
  304. self._consume_passive_trace_frame(frame, expected_command=-1)
  305. if frames:
  306. self._store_idle_frames(tuple(frames))
  307. if self._rx_buffer:
  308. if self._idle_partial_since is None:
  309. self._idle_partial_since = self._monotonic()
  310. elif self._monotonic() - self._idle_partial_since >= self.max_quiet_drain_seconds:
  311. self._fail(
  312. -1,
  313. "idle UART stream ended with a truncated frame",
  314. drain_overflow_evidence=False,
  315. )
  316. else:
  317. self._idle_partial_since = None
  318. if not chunk:
  319. self._pump_stop.wait(0.0005)
  320. def _record_background_failure(self, exc: BaseException, *, capture_only: bool) -> None:
  321. if capture_only:
  322. self._pump_error = exc
  323. return
  324. if self._terminated:
  325. self._pump_error = exc
  326. return
  327. try:
  328. self._fail(-1, f"UART pump failure: {type(exc).__name__}:{exc}")
  329. except BaseException as fatal:
  330. self._pump_error = fatal
  331. def _pump_loop(self) -> None:
  332. self._pump_thread_id = threading.get_ident()
  333. self._pump_started.set()
  334. try:
  335. while not self._pump_stop.is_set():
  336. try:
  337. call = self._pump_calls.get_nowait()
  338. except queue.Empty:
  339. call = None
  340. if call is not None:
  341. if self._terminated:
  342. call.error = RuntimeError("Profile 4 session is terminated")
  343. call.done.set()
  344. break
  345. try:
  346. if self._pump_capture_only and call.activate_parser:
  347. self._pump_capture_only = False
  348. if call.pre_dispatch_quiet:
  349. self._store_idle_frames(
  350. self._drain_trace_quiet_window(
  351. expected_command=-1,
  352. maximum_seconds=self.max_quiet_drain_seconds,
  353. )
  354. )
  355. call.result = call.action()
  356. except BaseException as exc:
  357. call.error = exc
  358. finally:
  359. call.done.set()
  360. if not self._pump_persistent or self._terminated:
  361. break
  362. continue
  363. if not self._pump_persistent:
  364. self._pump_stop.wait(0.0005)
  365. continue
  366. if self._terminated:
  367. break
  368. capture_only = self._pump_capture_only
  369. try:
  370. if capture_only:
  371. self._pump_capture_once()
  372. else:
  373. self._pump_idle_once()
  374. except BaseException as exc:
  375. self._record_background_failure(exc, capture_only=capture_only)
  376. break
  377. finally:
  378. self._pump_started.set()
  379. def _run_on_pump(
  380. self,
  381. action: Callable[[], Any],
  382. *,
  383. pre_dispatch_quiet: bool,
  384. activate_parser: bool = True,
  385. ) -> Any:
  386. started_here = not self.reader_running
  387. if started_here:
  388. self.start_reader(persistent=False)
  389. call = _PumpCall(
  390. action,
  391. pre_dispatch_quiet=pre_dispatch_quiet,
  392. activate_parser=activate_parser,
  393. )
  394. try:
  395. try:
  396. self._pump_calls.put_nowait(call)
  397. except queue.Full as exc:
  398. raise RuntimeError("UART pump already has a queued operation") from exc
  399. wait_seconds = max(
  400. 2.0,
  401. self.timeout_seconds + self.max_quiet_drain_seconds + 1.0,
  402. )
  403. if not call.done.wait(wait_seconds):
  404. raise TimeoutError("UART pump operation did not complete within its bound")
  405. if call.error is not None:
  406. raise call.error
  407. return call.result
  408. finally:
  409. if started_here:
  410. self.stop_reader()
  411. def close(self) -> None:
  412. try:
  413. self.stop_reader()
  414. finally:
  415. self.endpoint.close()
  416. def _finish_exchange(
  417. self,
  418. *,
  419. request: bytes,
  420. response_prefix: bytes,
  421. journal_start: int,
  422. command: object,
  423. ) -> None:
  424. with self._state_lock:
  425. response = response_prefix + bytes(self._rx_journal[journal_start:])
  426. self._last_exchange = {
  427. "request_hex": request.hex(),
  428. "response_hex": response.hex(),
  429. "command": command,
  430. }
  431. def _read_endpoint(self, size: int = 256) -> bytes:
  432. chunk = bytes(self.endpoint.read(size))
  433. if chunk:
  434. with self._state_lock:
  435. self._rx_journal.extend(chunk)
  436. return chunk
  437. def _write_once(self, frame: bytes) -> None:
  438. written = self.endpoint.write(frame)
  439. if written != len(frame):
  440. raise IOError(f"short serial write: {written}/{len(frame)}")
  441. def _attempt_disable(self) -> None:
  442. with self._fail_lock:
  443. if self.disable_attempted:
  444. return
  445. self.disable_attempted = True
  446. request = build_host_command(command=CommandId.DISABLE)
  447. with self._state_lock:
  448. self._best_effort_disable_exchange = {
  449. "request_hex": request.hex(),
  450. "response_hex": "",
  451. "command": "DISABLE",
  452. }
  453. try:
  454. self._write_once(request)
  455. except Exception:
  456. pass
  457. def _drain_post_fault_overflow_evidence(self, expected_event_seq: int) -> None:
  458. if self._post_fault_drain_attempted:
  459. return
  460. self._post_fault_drain_attempted = True
  461. with self._state_lock:
  462. existing = list(self._trace_policy.trace_events)
  463. if any(event.event_type == TraceEventType.OVERFLOW for event in existing):
  464. return
  465. hard_deadline = self._monotonic() + min(
  466. self.max_quiet_drain_seconds,
  467. POST_FAULT_DRAIN_SECONDS,
  468. )
  469. quiet_deadline = self._monotonic() + self.quiet_window_seconds
  470. bytes_seen = len(self._rx_buffer)
  471. frames_seen = 0
  472. while (
  473. self._monotonic() < hard_deadline
  474. and bytes_seen <= POST_FAULT_DRAIN_BYTE_LIMIT
  475. and frames_seen < POST_FAULT_DRAIN_FRAME_LIMIT
  476. ):
  477. try:
  478. frame = self._pop_frame()
  479. except P4FrameError:
  480. self._rx_buffer.clear()
  481. return
  482. if frame is not None:
  483. frames_seen += 1
  484. if frame.frame_type != FrameType.TRACE_EVENT:
  485. continue
  486. try:
  487. event = decode_trace_frame(frame.raw)
  488. overflow = decode_overflow_trace_event(event)
  489. except ValueError:
  490. continue
  491. if overflow.first_lost_event_seq != expected_event_seq:
  492. continue
  493. with self._state_lock:
  494. known_sequences = {
  495. item.event_seq
  496. for item in (
  497. *self._trace_policy.trace_events,
  498. *self._post_fault_trace_events,
  499. )
  500. }
  501. if event.event_seq not in known_sequences:
  502. self._post_fault_trace_events.append(event)
  503. return
  504. now = self._monotonic()
  505. if now >= quiet_deadline:
  506. return
  507. remaining = POST_FAULT_DRAIN_BYTE_LIMIT - bytes_seen
  508. if remaining <= 0:
  509. return
  510. chunk = self._read_endpoint(min(256, remaining))
  511. if chunk:
  512. bytes_seen += len(chunk)
  513. self._rx_buffer.extend(chunk)
  514. quiet_deadline = self._monotonic() + self.quiet_window_seconds
  515. continue
  516. self._sleep(0.0005)
  517. def _fail(
  518. self,
  519. expected_command: CommandId | int,
  520. message: str,
  521. *,
  522. drain_overflow_evidence: bool = True,
  523. ) -> None:
  524. with self._state_lock:
  525. expected_event_seq = self._trace_policy.expected_event_seq
  526. self._terminated = True
  527. if int(expected_command) == int(CommandId.DISABLE):
  528. self.disable_attempted = True
  529. else:
  530. self._attempt_disable()
  531. if drain_overflow_evidence:
  532. self._drain_post_fault_overflow_evidence(expected_event_seq)
  533. self._rx_buffer.clear()
  534. raise RuntimeError(message)
  535. def _pop_frame(self) -> P4Frame | None:
  536. if not self._rx_buffer:
  537. return None
  538. magic_at = self._rx_buffer.find(MAGIC)
  539. if magic_at < 0:
  540. if self._rx_buffer == MAGIC[:1]:
  541. return None
  542. raise P4FrameError("non-frame bytes before Profile 4 magic")
  543. if magic_at:
  544. raise P4FrameError("non-frame bytes before Profile 4 magic")
  545. if len(self._rx_buffer) < HEADER_LEN + CRC_LEN:
  546. return None
  547. frame_len = HEADER_LEN + self._rx_buffer[13] + CRC_LEN
  548. if len(self._rx_buffer) < frame_len:
  549. return None
  550. raw = bytes(self._rx_buffer[:frame_len])
  551. del self._rx_buffer[:frame_len]
  552. return decode_frame(raw)
  553. def collect_available(self) -> bytes:
  554. """Collect every byte currently available without parsing or discarding partial frames."""
  555. if self._pump_thread is not None:
  556. raise RuntimeError("UART pump owns serial reads while the reader is running")
  557. raw = bytearray()
  558. while True:
  559. chunk = self._read_endpoint(256)
  560. if not chunk:
  561. break
  562. raw.extend(chunk)
  563. self._rx_buffer.extend(chunk)
  564. return bytes(raw)
  565. def drain_unparsed(self, *, timeout_seconds: float) -> bytes:
  566. """Quarantine pre-session bytes while keeping the same physical UART reader."""
  567. if self._pump_thread is not None:
  568. raise RuntimeError("UART pump owns serial reads while the reader is running")
  569. deadline = self._monotonic() + timeout_seconds
  570. while self._monotonic() < deadline:
  571. if not self.collect_available():
  572. self._sleep(0.001)
  573. raw = bytes(self._rx_buffer)
  574. self._rx_buffer.clear()
  575. return raw
  576. @staticmethod
  577. def _trace_failure_message(exc: TracePolicyError) -> str:
  578. message = str(exc)
  579. if "HOST_ACK arrived before COMMAND_RESULT" in message:
  580. return "COMMAND_RESULT must arrive before HOST_ACK"
  581. if "COMMAND_RESULT request identity mismatch" in message:
  582. return "COMMAND_RESULT request frame type or CRC mismatch"
  583. return message
  584. def _consume_passive_trace_frame(
  585. self,
  586. frame: P4Frame,
  587. *,
  588. expected_command: CommandId | int,
  589. ) -> None:
  590. if frame.frame_type == FrameType.BOOT_BUILD_ID:
  591. if self._startup_preamble_state != "open":
  592. self._fail(expected_command, "BOOT_BUILD_ID outside startup preamble")
  593. self._observe_startup_boot(
  594. expected_command=expected_command,
  595. allow_boot_preamble=True,
  596. command_result_seen=False,
  597. frame=frame,
  598. )
  599. return
  600. if frame.frame_type != FrameType.TRACE_EVENT:
  601. self._fail(expected_command, "unexpected response frame after command completion")
  602. self._guard_startup_trace_frame(frame, expected_command=expected_command)
  603. try:
  604. with self._state_lock:
  605. observed = self._trace_policy.observe_wire(frame.raw)
  606. except TracePolicyError as exc:
  607. self._fail(expected_command, self._trace_failure_message(exc))
  608. event = decode_trace_frame(frame.raw)
  609. self._observe_startup_trace(event, expected_command=expected_command)
  610. if observed != event or event != self.trace_events[-1]:
  611. self._fail(expected_command, "Trace decoder and host policy disagree")
  612. def _drain_trace_quiet_window(
  613. self,
  614. *,
  615. expected_command: CommandId | int,
  616. maximum_seconds: float,
  617. ) -> tuple[P4Frame, ...]:
  618. if maximum_seconds <= 0:
  619. raise ValueError("maximum_seconds must be positive")
  620. started = self._monotonic()
  621. hard_deadline = started + maximum_seconds
  622. quiet_deadline = started + self.quiet_window_seconds
  623. frames: list[P4Frame] = []
  624. newly_read_bytes = 0
  625. while True:
  626. try:
  627. frame = self._pop_frame()
  628. except P4FrameError as exc:
  629. self._fail(expected_command, f"malformed Profile 4 frame: {exc}")
  630. if frame is not None:
  631. frames.append(frame)
  632. self._consume_passive_trace_frame(
  633. frame,
  634. expected_command=expected_command,
  635. )
  636. continue
  637. now = self._monotonic()
  638. if now >= hard_deadline:
  639. if self._rx_buffer:
  640. self._fail(
  641. expected_command,
  642. "quiet-window drain ended with a truncated frame",
  643. drain_overflow_evidence=False,
  644. )
  645. if quiet_deadline > now:
  646. self._fail(
  647. expected_command,
  648. "UART quiet window did not settle before its hard deadline",
  649. drain_overflow_evidence=False,
  650. )
  651. return tuple(frames)
  652. chunk = self._read_endpoint(256)
  653. if chunk:
  654. newly_read_bytes += len(chunk)
  655. if newly_read_bytes > 8192:
  656. self._fail(
  657. expected_command,
  658. "UART quiet-window byte budget exceeded",
  659. drain_overflow_evidence=False,
  660. )
  661. self._rx_buffer.extend(chunk)
  662. quiet_deadline = self._monotonic() + self.quiet_window_seconds
  663. continue
  664. if now >= quiet_deadline:
  665. if self._rx_buffer:
  666. self._sleep(0.0005)
  667. continue
  668. return tuple(frames)
  669. self._sleep(0.0005)
  670. def _begin_startup_preamble(
  671. self,
  672. *,
  673. expected_command: CommandId | int,
  674. allow_boot_preamble: bool,
  675. ) -> None:
  676. if not allow_boot_preamble:
  677. return
  678. if self._startup_preamble_state == "closed":
  679. self._fail(expected_command, "startup BOOT/EPOCH preamble may occur only once")
  680. if self._startup_preamble_state == "inactive":
  681. self._startup_preamble_state = "open"
  682. def _observe_startup_boot(
  683. self,
  684. *,
  685. expected_command: CommandId | int,
  686. allow_boot_preamble: bool,
  687. command_result_seen: bool,
  688. frame: P4Frame,
  689. ) -> bool:
  690. if not allow_boot_preamble and self._startup_preamble_state == "inactive":
  691. return False
  692. if not allow_boot_preamble or self._startup_preamble_state != "open":
  693. self._fail(expected_command, "BOOT_BUILD_ID outside startup preamble")
  694. if self._startup_boot_seen:
  695. self._fail(expected_command, "duplicate BOOT_BUILD_ID in startup preamble")
  696. if self._startup_epoch_seen or command_result_seen:
  697. self._fail(expected_command, "BOOT_BUILD_ID must precede EPOCH")
  698. try:
  699. identity = decode_boot_build_id(frame)
  700. except ValueError as exc:
  701. self._fail(expected_command, f"malformed BOOT_BUILD_ID: {exc}")
  702. self.startup_boot_identity = identity
  703. if (
  704. self.expected_build_id is not None
  705. and identity.build_id != self.expected_build_id
  706. ) or (
  707. self.expected_capability_flags is not None
  708. and identity.capability_flags != self.expected_capability_flags
  709. ):
  710. self._fail(expected_command, "startup BOOT identity mismatch")
  711. self._startup_boot_seen = True
  712. return True
  713. def _observe_startup_trace(
  714. self,
  715. event: TraceEvent,
  716. *,
  717. expected_command: CommandId | int,
  718. ) -> None:
  719. if (
  720. event.event_type == TraceEventType.EPOCH
  721. and self._startup_preamble_state != "open"
  722. ):
  723. self._fail(expected_command, "EPOCH outside startup preamble")
  724. if self._startup_preamble_state != "open":
  725. return
  726. if event.event_type == TraceEventType.EPOCH:
  727. if not self._startup_boot_seen:
  728. self._fail(expected_command, "BOOT_BUILD_ID must precede EPOCH")
  729. if self._startup_epoch_seen:
  730. self._fail(expected_command, "duplicate EPOCH in startup preamble")
  731. if event.event_seq != 1:
  732. self._fail(expected_command, "startup EPOCH must use event_seq 1")
  733. epoch = decode_epoch_trace_event(event)
  734. boot = self.startup_boot_identity
  735. if boot is None or (
  736. epoch.build_id != boot.build_id
  737. or epoch.capability_flags != boot.capability_flags
  738. ):
  739. self._fail(expected_command, "startup BOOT/EPOCH identity mismatch")
  740. if (
  741. self.expected_build_id is not None
  742. and epoch.build_id != self.expected_build_id
  743. ) or (
  744. self.expected_capability_flags is not None
  745. and epoch.capability_flags != self.expected_capability_flags
  746. ):
  747. self._fail(expected_command, "startup EPOCH identity mismatch")
  748. self.startup_epoch = epoch
  749. self._startup_epoch_seen = True
  750. return
  751. if not self._startup_epoch_seen:
  752. self._fail(expected_command, "EPOCH must precede startup Trace backlog")
  753. def _guard_startup_trace_frame(
  754. self,
  755. frame: P4Frame,
  756. *,
  757. expected_command: CommandId | int,
  758. ) -> None:
  759. if (
  760. frame.frame_type == FrameType.TRACE_EVENT
  761. and self._startup_preamble_state != "open"
  762. and len(frame.payload) >= 5
  763. and frame.payload[4] == int(TraceEventType.EPOCH)
  764. ):
  765. self._fail(expected_command, "EPOCH outside startup preamble")
  766. def _read_command_frames(
  767. self,
  768. *,
  769. expected_command: CommandId | int,
  770. expected_followup: FrameType | None,
  771. allow_boot_preamble: bool,
  772. ) -> tuple[tuple[P4Frame, ...], bytes, CompletedCommand]:
  773. deadline = self._monotonic() + self.timeout_seconds
  774. frames: list[P4Frame] = []
  775. completed: CompletedCommand | None = None
  776. command_result_seen = False
  777. self._begin_startup_preamble(
  778. expected_command=expected_command,
  779. allow_boot_preamble=allow_boot_preamble,
  780. )
  781. while self._monotonic() < deadline:
  782. frame = self._pop_frame()
  783. if frame is None:
  784. chunk = self._read_endpoint(256)
  785. if chunk:
  786. self._rx_buffer.extend(chunk)
  787. continue
  788. self._sleep(0.0005)
  789. continue
  790. frames.append(frame)
  791. if frame.frame_type == FrameType.BOOT_BUILD_ID:
  792. if self._observe_startup_boot(
  793. expected_command=expected_command,
  794. allow_boot_preamble=allow_boot_preamble,
  795. command_result_seen=command_result_seen,
  796. frame=frame,
  797. ):
  798. continue
  799. self._guard_startup_trace_frame(
  800. frame,
  801. expected_command=expected_command,
  802. )
  803. try:
  804. with self._state_lock:
  805. observed = self._trace_policy.observe_wire(frame.raw)
  806. except TracePolicyError as exc:
  807. self._fail(expected_command, self._trace_failure_message(exc))
  808. if frame.frame_type == FrameType.TRACE_EVENT:
  809. event = decode_trace_frame(frame.raw)
  810. self._observe_startup_trace(event, expected_command=expected_command)
  811. if event.event_type == TraceEventType.COMMAND_RESULT:
  812. if self._startup_preamble_state == "open" and not (
  813. self._startup_boot_seen and self._startup_epoch_seen
  814. ):
  815. self._fail(
  816. expected_command,
  817. "startup BOOT/EPOCH must precede first COMMAND_RESULT",
  818. )
  819. command_result_seen = True
  820. if event != self.trace_events[-1]:
  821. self._fail(expected_command, "Trace decoder and host policy disagree")
  822. if isinstance(observed, CompletedCommand):
  823. completed = observed
  824. followup_seen = expected_followup is None or any(
  825. item.frame_type == expected_followup for item in frames
  826. )
  827. if completed is not None and followup_seen:
  828. if self._startup_preamble_state == "open":
  829. if not (self._startup_boot_seen and self._startup_epoch_seen):
  830. self._fail(expected_command, "startup BOOT/EPOCH preamble incomplete")
  831. self._startup_preamble_state = "closed"
  832. frames.extend(
  833. self._drain_trace_quiet_window(
  834. expected_command=expected_command,
  835. maximum_seconds=self.max_quiet_drain_seconds,
  836. )
  837. )
  838. return tuple(frames), b"".join(item.raw for item in frames), completed
  839. raise TimeoutError("Profile 4 ACK timeout without automatic retry")
  840. def observe_passive_bytes(self, raw: bytes | bytearray) -> tuple[P4Frame, ...]:
  841. """Consume a complete BOOT/Trace epoch before the first host command."""
  842. if self._pump_thread is not None:
  843. raise RuntimeError("UART pump owns passive frame parsing while the reader is running")
  844. if self._terminated:
  845. raise RuntimeError("Profile 4 session is terminated")
  846. data = bytes(raw)
  847. frames: list[P4Frame] = []
  848. offset = 0
  849. while offset < len(data):
  850. if data[offset : offset + len(MAGIC)] != MAGIC:
  851. self._fail(-1, "passive UART epoch contains non-frame bytes")
  852. if len(data) - offset < HEADER_LEN + CRC_LEN:
  853. self._fail(-1, "passive UART epoch contains a truncated frame")
  854. end = offset + HEADER_LEN + data[offset + 13] + CRC_LEN
  855. if end > len(data):
  856. self._fail(-1, "passive UART epoch contains a truncated frame")
  857. try:
  858. frame = decode_frame(data[offset:end])
  859. except P4FrameError as exc:
  860. self._fail(-1, f"malformed passive Profile 4 frame: {exc}")
  861. offset = end
  862. frames.append(frame)
  863. if frame.frame_type == FrameType.BOOT_BUILD_ID:
  864. self._fail(-1, "BOOT_BUILD_ID outside startup preamble")
  865. if frame.frame_type != FrameType.TRACE_EVENT:
  866. self._fail(-1, "passive UART epoch contains a non-Trace response")
  867. self._guard_startup_trace_frame(frame, expected_command=-1)
  868. try:
  869. with self._state_lock:
  870. observed = self._trace_policy.observe_wire(frame.raw)
  871. except TracePolicyError as exc:
  872. self._fail(-1, self._trace_failure_message(exc))
  873. event = decode_trace_frame(frame.raw)
  874. self._observe_startup_trace(event, expected_command=-1)
  875. if observed != event or event != self.trace_events[-1]:
  876. self._fail(-1, "Trace decoder and host policy disagree")
  877. return tuple(frames)
  878. def read_passive_frames(self, *, timeout_seconds: float) -> tuple[tuple[P4Frame, ...], bytes]:
  879. """Drain a bounded quiet window, accepting only continuous asynchronous Trace."""
  880. if self._terminated:
  881. raise RuntimeError("Profile 4 session is terminated")
  882. if not self._command_lock.acquire(blocking=False):
  883. raise RuntimeError("one outstanding command is already active")
  884. try:
  885. return self._run_on_pump(
  886. lambda: self._read_passive_frames_on_pump(timeout_seconds=timeout_seconds),
  887. pre_dispatch_quiet=False,
  888. )
  889. finally:
  890. self._command_lock.release()
  891. def _read_passive_frames_on_pump(
  892. self,
  893. *,
  894. timeout_seconds: float,
  895. ) -> tuple[tuple[P4Frame, ...], bytes]:
  896. with self._state_lock:
  897. frames = list(self._idle_frames)
  898. raw = bytearray(self._idle_raw)
  899. self._idle_frames.clear()
  900. self._idle_raw.clear()
  901. self._last_exchange = None
  902. drained = self._drain_trace_quiet_window(
  903. expected_command=-1,
  904. maximum_seconds=timeout_seconds,
  905. )
  906. frames.extend(drained)
  907. for frame in drained:
  908. raw.extend(frame.raw)
  909. with self._state_lock:
  910. self._last_exchange = {
  911. "request_hex": "",
  912. "response_hex": bytes(raw).hex(),
  913. "command": "PASSIVE_RX_DRAIN",
  914. }
  915. return tuple(frames), bytes(raw)
  916. def _command_on_pump(
  917. self,
  918. request: bytes,
  919. *,
  920. expected_command: CommandId | int,
  921. expected_followup: FrameType | None,
  922. allowed_statuses: tuple[StatusCode, ...],
  923. expected_detail: int | None,
  924. expected_state_hash16: int | None,
  925. required_result_flags: int,
  926. allowed_result_flags: int,
  927. allow_boot_preamble: bool,
  928. followup_decoder: Callable[[P4Frame], Any] | None,
  929. followup_name: str,
  930. ) -> tuple[CommandResult, Any]:
  931. response_prefix = bytes(self._rx_buffer)
  932. with self._state_lock:
  933. journal_start = len(self._rx_journal)
  934. self._last_exchange = None
  935. try:
  936. try:
  937. with self._state_lock:
  938. self._trace_policy.begin_command(
  939. request,
  940. expected_followup=expected_followup,
  941. )
  942. except TracePolicyError as exc:
  943. self._fail(expected_command, self._trace_failure_message(exc))
  944. try:
  945. self._write_once(request)
  946. except Exception:
  947. self._terminated = True
  948. if int(expected_command) == int(CommandId.DISABLE):
  949. self.disable_attempted = True
  950. else:
  951. self._attempt_disable()
  952. raise
  953. try:
  954. frames, raw, completed = self._read_command_frames(
  955. expected_command=expected_command,
  956. expected_followup=expected_followup,
  957. allow_boot_preamble=allow_boot_preamble,
  958. )
  959. except TimeoutError:
  960. self._terminated = True
  961. if int(expected_command) == int(CommandId.DISABLE):
  962. self.disable_attempted = True
  963. else:
  964. self._attempt_disable()
  965. raise
  966. except P4FrameError as exc:
  967. self._fail(expected_command, f"malformed Profile 4 frame: {exc}")
  968. ack_frames = [frame for frame in frames if frame.frame_type == FrameType.HOST_ACK]
  969. if len(ack_frames) != 1:
  970. self._fail(expected_command, "expected exactly one HOST_ACK")
  971. try:
  972. ack = decode_host_ack(ack_frames[0])
  973. except ValueError as exc:
  974. self._fail(expected_command, f"malformed HOST_ACK: {exc}")
  975. if int(ack.command) != int(expected_command):
  976. self._fail(expected_command, "HOST_ACK command mismatch")
  977. if not ack.ok or ack.status not in allowed_statuses:
  978. self._fail(
  979. expected_command,
  980. f"HOST_ACK rejected command with status 0x{int(ack.status):02x}",
  981. )
  982. expected_response_type = int(expected_followup) if expected_followup is not None else 0
  983. if int(ack.response_type) != expected_response_type:
  984. self._fail(expected_command, "HOST_ACK response type mismatch")
  985. if expected_detail is not None and ack.detail != expected_detail:
  986. self._fail(expected_command, "HOST_ACK detail mismatch")
  987. if expected_state_hash16 is not None and ack.state_hash16 != expected_state_hash16:
  988. self._fail(expected_command, "HOST_ACK state hash mismatch")
  989. if ack.result_flags & ~allowed_result_flags:
  990. self._fail(expected_command, "HOST_ACK contains unexpected result flags")
  991. if (ack.result_flags & required_result_flags) != required_result_flags:
  992. self._fail(expected_command, "HOST_ACK is missing required result flags")
  993. decoded_followup: Any = None
  994. if expected_followup is not None:
  995. followups = [frame for frame in frames if frame.frame_type == expected_followup]
  996. if len(followups) != 1:
  997. self._fail(expected_command, "HOST_ACK follow-up type mismatch")
  998. if followup_decoder is not None:
  999. try:
  1000. decoded_followup = followup_decoder(followups[0])
  1001. except ValueError as exc:
  1002. self._fail(expected_command, f"malformed {followup_name}: {exc}")
  1003. result = CommandResult(
  1004. ack=ack,
  1005. raw_response=raw,
  1006. frames=frames,
  1007. command_result_trace=completed.command_result_trace,
  1008. )
  1009. return result, decoded_followup
  1010. finally:
  1011. self._finish_exchange(
  1012. request=bytes(request),
  1013. response_prefix=response_prefix,
  1014. journal_start=journal_start,
  1015. command=int(expected_command),
  1016. )
  1017. def _run_command_transaction(
  1018. self,
  1019. request: bytes,
  1020. *,
  1021. expected_command: CommandId | int,
  1022. expected_followup: FrameType | None,
  1023. allowed_statuses: tuple[StatusCode, ...],
  1024. expected_detail: int | None,
  1025. expected_state_hash16: int | None,
  1026. required_result_flags: int,
  1027. allowed_result_flags: int,
  1028. allow_boot_preamble: bool,
  1029. followup_decoder: Callable[[P4Frame], Any] | None = None,
  1030. followup_name: str = "follow-up",
  1031. ) -> tuple[CommandResult, Any]:
  1032. if self._terminated:
  1033. raise RuntimeError("Profile 4 session is terminated")
  1034. if not self._command_lock.acquire(blocking=False):
  1035. raise RuntimeError("one outstanding command is already active")
  1036. try:
  1037. return self._run_on_pump(
  1038. lambda: self._command_on_pump(
  1039. request,
  1040. expected_command=expected_command,
  1041. expected_followup=expected_followup,
  1042. allowed_statuses=allowed_statuses,
  1043. expected_detail=expected_detail,
  1044. expected_state_hash16=expected_state_hash16,
  1045. required_result_flags=required_result_flags,
  1046. allowed_result_flags=allowed_result_flags,
  1047. allow_boot_preamble=allow_boot_preamble,
  1048. followup_decoder=followup_decoder,
  1049. followup_name=followup_name,
  1050. ),
  1051. pre_dispatch_quiet=not allow_boot_preamble,
  1052. )
  1053. finally:
  1054. self._command_lock.release()
  1055. def command(
  1056. self,
  1057. request: bytes,
  1058. *,
  1059. expected_command: CommandId | int,
  1060. expected_followup: FrameType | None = None,
  1061. allowed_statuses: tuple[StatusCode, ...] = (StatusCode.OK, StatusCode.PARTIAL),
  1062. expected_detail: int | None = None,
  1063. expected_state_hash16: int | None = None,
  1064. required_result_flags: int = 0,
  1065. allowed_result_flags: int = 0,
  1066. allow_boot_preamble: bool = False,
  1067. ) -> CommandResult:
  1068. if required_result_flags & ~allowed_result_flags:
  1069. raise ValueError("required result flags must be included in allowed result flags")
  1070. result, _ = self._run_command_transaction(
  1071. request,
  1072. expected_command=expected_command,
  1073. expected_followup=expected_followup,
  1074. allowed_statuses=allowed_statuses,
  1075. expected_detail=expected_detail,
  1076. expected_state_hash16=expected_state_hash16,
  1077. required_result_flags=required_result_flags,
  1078. allowed_result_flags=allowed_result_flags,
  1079. allow_boot_preamble=allow_boot_preamble,
  1080. )
  1081. return result
  1082. def motor_status(self) -> MotorStatusResult:
  1083. result, status = self._run_command_transaction(
  1084. build_get_motor_status(),
  1085. expected_command=0x37,
  1086. expected_followup=FrameType.MOTION_STATUS,
  1087. allowed_statuses=(StatusCode.OK,),
  1088. expected_detail=0,
  1089. expected_state_hash16=None,
  1090. required_result_flags=0x08,
  1091. allowed_result_flags=0x08,
  1092. allow_boot_preamble=False,
  1093. followup_decoder=decode_motion_status,
  1094. followup_name="MOTION_STATUS",
  1095. )
  1096. return MotorStatusResult(
  1097. ack=result.ack,
  1098. status=status,
  1099. raw_response=result.raw_response,
  1100. )
  1101. def _bounded_int(minimum: int, maximum: int) -> Callable[[str], int]:
  1102. def parse(value: str) -> int:
  1103. try:
  1104. parsed = int(value, 10)
  1105. except ValueError as exc:
  1106. raise argparse.ArgumentTypeError("must be an integer") from exc
  1107. if not minimum <= parsed <= maximum:
  1108. raise argparse.ArgumentTypeError(f"must be from {minimum} to {maximum}")
  1109. return parsed
  1110. return parse
  1111. def build_parser() -> argparse.ArgumentParser:
  1112. parser = argparse.ArgumentParser(description=__doc__)
  1113. sub = parser.add_subparsers(dest="command", required=True)
  1114. sub.add_parser("selftest")
  1115. sub.add_parser("preflight")
  1116. snapshot = sub.add_parser(
  1117. "set-all-outputs",
  1118. description=(
  1119. "Sets synchronous outputs and always sends X/Y/Z motor targets; X/Y default 0 "
  1120. "requests CLOSED and may start motion, while Z 0/100 is an accepted no-op."
  1121. ),
  1122. )
  1123. snapshot.add_argument("--ptc", type=_bounded_int(0, 100), default=0)
  1124. snapshot.add_argument("--fan", type=_bounded_int(0, 100), default=30)
  1125. snapshot.add_argument("--solenoid", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  1126. snapshot.add_argument("--x", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  1127. snapshot.add_argument("--y", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  1128. snapshot.add_argument("--z", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  1129. jog = sub.add_parser("jog")
  1130. jog.add_argument("--axis", type=_bounded_int(0, 2), required=True)
  1131. jog.add_argument("--raw-dir", type=_bounded_int(0, 1), required=True)
  1132. jog.add_argument("--speed-code", type=_bounded_int(0, 3), required=True)
  1133. jog.add_argument("--steps", type=_bounded_int(1, 65535), required=True)
  1134. mark = sub.add_parser("mark-closed")
  1135. mark.add_argument("--axis", type=_bounded_int(0, 1), required=True)
  1136. mark.add_argument("--close-dir", type=_bounded_int(0, 1), required=True)
  1137. sub.add_parser("get-status")
  1138. sub.add_parser("motor-status")
  1139. sub.add_parser("disable")
  1140. gate = sub.add_parser("normal-actuator-trace-gate")
  1141. gate.add_argument("--bitstream", type=Path, required=True)
  1142. gate.add_argument("--build-info", type=Path, required=True)
  1143. gate.add_argument("--td-receipt", type=Path, required=True)
  1144. gate.add_argument("--package-info", type=Path, required=True)
  1145. gate.add_argument("--output-dir", type=Path, required=True)
  1146. gate.add_argument("--board-id", required=True)
  1147. gate.add_argument("--confirm-ptc-load-disabled", action="store_true")
  1148. gate.add_argument("--confirm-mechanical-travel-safe", action="store_true")
  1149. gate.add_argument("--confirm-p5-active-high-closes-intake", action="store_true")
  1150. gate.add_argument("--confirm-ls1-x-closed-high", action="store_true")
  1151. gate.add_argument("--confirm-ls2-y-closed-high", action="store_true")
  1152. gate.add_argument("--x-close-dir", type=_bounded_int(0, 1), required=True)
  1153. gate.add_argument("--y-close-dir", type=_bounded_int(0, 1), required=True)
  1154. gate.add_argument("--td-root", type=Path, default=DEFAULT_TD_ROOT)
  1155. gate.add_argument("--run-id", default="prod2u-p4-normal-v3-gate")
  1156. return parser
  1157. def _selftest() -> dict[str, Any]:
  1158. snapshot = build_output_snapshot(
  1159. ptc_percent=(0,) * 24,
  1160. fan_percent=(30,) * 4,
  1161. solenoid=0,
  1162. xyz=(0, 0, 0),
  1163. )
  1164. return {
  1165. "schema": "prod2u-p4-normal-v3-selftest-v1",
  1166. "status": "pass" if len(snapshot) == 50 else "fail",
  1167. "profile": PROFILE,
  1168. "profile_id": PROFILE_ID,
  1169. "protocol_version": PROTOCOL_VERSION,
  1170. "baud": BAUD,
  1171. "port": PORT,
  1172. "hardware_opened": False,
  1173. "program_sram_attempted": False,
  1174. }
  1175. def hardware_stage_plan() -> dict[str, Any]:
  1176. return {
  1177. "stages": [
  1178. "preflight",
  1179. "program_sram",
  1180. "initial_disable",
  1181. "boot_identity",
  1182. "baseline_status",
  1183. "direction_mapping",
  1184. "limit_jog",
  1185. "open_to_close",
  1186. "standard_motion",
  1187. "xy_partial",
  1188. "watchdog",
  1189. "trace_integrity",
  1190. "register_checkpoint",
  1191. "final_disable",
  1192. ]
  1193. }
  1194. def enumerate_hardware_candidates(
  1195. *,
  1196. runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
  1197. ) -> dict[str, Any]:
  1198. """Enumerate COM and AL-Link candidates without opening either interface."""
  1199. script = r"""
  1200. $ErrorActionPreference = 'Stop'
  1201. $cimSerialPorts = @()
  1202. try {
  1203. $cimSerialPorts = @(
  1204. Get-CimInstance Win32_SerialPort |
  1205. Sort-Object DeviceID |
  1206. ForEach-Object {
  1207. [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
  1208. }
  1209. )
  1210. } catch {}
  1211. $pnpSerialPorts = @()
  1212. try {
  1213. if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) {
  1214. $pnpSerialPorts = @(
  1215. Get-PnpDevice -Class Ports -PresentOnly -ErrorAction Stop |
  1216. Sort-Object InstanceId |
  1217. ForEach-Object {
  1218. [ordered]@{ name = [string]$_.FriendlyName; device_id = [string]$_.InstanceId }
  1219. }
  1220. )
  1221. }
  1222. } catch {}
  1223. $dotNetSerialPorts = @()
  1224. try {
  1225. $dotNetSerialPorts = @(
  1226. [System.IO.Ports.SerialPort]::GetPortNames() |
  1227. Sort-Object |
  1228. ForEach-Object {
  1229. [ordered]@{ name = [string]$_; device_id = [string]$_ }
  1230. }
  1231. )
  1232. } catch {}
  1233. $serialPorts = @($cimSerialPorts) + @($pnpSerialPorts) + @($dotNetSerialPorts)
  1234. $pnpDevices = @()
  1235. try {
  1236. $pnpDevices = @(
  1237. Get-CimInstance Win32_PnPEntity |
  1238. Where-Object { ([string]$_.Name) -match '(?i)AL[- ]?Link|Anlogic' } |
  1239. Sort-Object DeviceID |
  1240. ForEach-Object {
  1241. [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
  1242. }
  1243. )
  1244. } catch {}
  1245. [ordered]@{ serial_ports = @($serialPorts); pnp_devices = @($pnpDevices) } |
  1246. ConvertTo-Json -Compress -Depth 4
  1247. """.strip()
  1248. try:
  1249. completed = runner(
  1250. ["powershell.exe", "-NoProfile", "-Command", script],
  1251. capture_output=True,
  1252. text=True,
  1253. check=False,
  1254. timeout=20,
  1255. )
  1256. except (OSError, subprocess.TimeoutExpired) as exc:
  1257. return {
  1258. "status": "blocked_hardware_enumeration_failed",
  1259. "opened_com": False,
  1260. "opened_jtag": False,
  1261. "serial_ports": [],
  1262. "pnp_devices": [],
  1263. "error": str(exc),
  1264. }
  1265. if completed.returncode != 0:
  1266. return {
  1267. "status": "blocked_hardware_enumeration_failed",
  1268. "opened_com": False,
  1269. "opened_jtag": False,
  1270. "serial_ports": [],
  1271. "pnp_devices": [],
  1272. "error": f"PowerShell enumeration exited {completed.returncode}",
  1273. }
  1274. try:
  1275. payload = json.loads(completed.stdout)
  1276. except (TypeError, json.JSONDecodeError) as exc:
  1277. return {
  1278. "status": "blocked_hardware_enumeration_failed",
  1279. "opened_com": False,
  1280. "opened_jtag": False,
  1281. "serial_ports": [],
  1282. "pnp_devices": [],
  1283. "error": f"invalid enumeration JSON: {exc}",
  1284. }
  1285. def records(name: str) -> list[dict[str, str]]:
  1286. raw = payload.get(name, []) if isinstance(payload, dict) else []
  1287. if isinstance(raw, dict):
  1288. raw = [raw]
  1289. if not isinstance(raw, list):
  1290. return []
  1291. return [
  1292. {"name": str(item.get("name", "")), "device_id": str(item.get("device_id", ""))}
  1293. for item in raw
  1294. if isinstance(item, dict)
  1295. ]
  1296. serial_ports = records("serial_ports")
  1297. serial_key_order: list[tuple[str, ...]] = []
  1298. best_serial_record: dict[tuple[str, ...], dict[str, str]] = {}
  1299. def serial_record_score(record: dict[str, str]) -> tuple[int, int, int]:
  1300. name = record["name"].strip()
  1301. device_id = record["device_id"].strip()
  1302. generic_name = re.fullmatch(r"COM[0-9]+", name, re.IGNORECASE) is not None
  1303. generic_device = re.fullmatch(r"COM[0-9]+", device_id, re.IGNORECASE) is not None
  1304. return (
  1305. 0 if generic_device else 1,
  1306. 0 if generic_name else 1,
  1307. len(name) + len(device_id),
  1308. )
  1309. for record in serial_ports:
  1310. combined = f"{record['name']} {record['device_id']}"
  1311. match = re.search(r"(?<![A-Z0-9])COM([0-9]+)(?![0-9])", combined.upper())
  1312. key = ("com", str(int(match.group(1)))) if match else (
  1313. "record",
  1314. record["name"].casefold(),
  1315. record["device_id"].casefold(),
  1316. )
  1317. if key not in best_serial_record:
  1318. serial_key_order.append(key)
  1319. best_serial_record[key] = record
  1320. elif serial_record_score(record) > serial_record_score(best_serial_record[key]):
  1321. best_serial_record[key] = record
  1322. deduplicated_serial_ports = [best_serial_record[key] for key in serial_key_order]
  1323. return {
  1324. "status": "pass",
  1325. "opened_com": False,
  1326. "opened_jtag": False,
  1327. "dtr_rts_toggled": False,
  1328. "serial_ports": deduplicated_serial_ports,
  1329. "pnp_devices": records("pnp_devices"),
  1330. }
  1331. def _record_text(record: Any) -> str:
  1332. if not isinstance(record, dict):
  1333. return ""
  1334. return " ".join(str(record.get(field, "")) for field in ("name", "device_id"))
  1335. def run_preflight(
  1336. *,
  1337. enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
  1338. ) -> dict[str, Any]:
  1339. try:
  1340. enumeration = enumerator()
  1341. except Exception as exc:
  1342. enumeration = {
  1343. "status": "blocked_hardware_enumeration_failed",
  1344. "opened_com": False,
  1345. "opened_jtag": False,
  1346. "serial_ports": [],
  1347. "pnp_devices": [],
  1348. "error": str(exc),
  1349. }
  1350. serial_ports = enumeration.get("serial_ports", []) if isinstance(enumeration, dict) else []
  1351. pnp_devices = enumeration.get("pnp_devices", []) if isinstance(enumeration, dict) else []
  1352. if not isinstance(serial_ports, list):
  1353. serial_ports = []
  1354. if not isinstance(pnp_devices, list):
  1355. pnp_devices = []
  1356. com5_present = any(
  1357. re.search(r"(?<![A-Z0-9])COM5(?![0-9])", _record_text(record).upper())
  1358. for record in serial_ports
  1359. )
  1360. al_link_present = any(
  1361. any(
  1362. marker in re.sub(r"[^a-z0-9]", "", _record_text(record).casefold())
  1363. for marker in ("allink", "anlogic")
  1364. )
  1365. for record in pnp_devices
  1366. )
  1367. opened_com = enumeration.get("opened_com") is True
  1368. opened_jtag = enumeration.get("opened_jtag") is True
  1369. dtr_rts_toggled = enumeration.get("dtr_rts_toggled") is True
  1370. failures: list[str] = []
  1371. if enumeration.get("status") != "pass":
  1372. failures.append("hardware_enumeration_failed")
  1373. if opened_com:
  1374. failures.append("enumerator_opened_com")
  1375. if opened_jtag:
  1376. failures.append("enumerator_opened_jtag")
  1377. if dtr_rts_toggled:
  1378. failures.append("enumerator_toggled_dtr_rts")
  1379. if not com5_present:
  1380. failures.append("com5_not_found")
  1381. if not al_link_present:
  1382. failures.append("al_link_not_found")
  1383. return {
  1384. "schema": "prod2u-p4-normal-v3-preflight-v2",
  1385. "status": "pass" if not failures else "blocked_hardware_not_ready",
  1386. "serial": {
  1387. "port": PORT,
  1388. "baud": BAUD,
  1389. "format": "8N1",
  1390. "com5_present": com5_present,
  1391. "ports": serial_ports,
  1392. "opened": opened_com,
  1393. "dtr_rts_toggled": dtr_rts_toggled,
  1394. },
  1395. "jtag": {
  1396. "adapter": "AL-Link",
  1397. "speed_hz": 200000,
  1398. "al_link_present": al_link_present,
  1399. "devices": pnp_devices,
  1400. "opened": opened_jtag,
  1401. },
  1402. "hardware_opened": opened_com or opened_jtag,
  1403. "program_sram_attempted": False,
  1404. "failures": sorted(set(failures)),
  1405. }
  1406. def _program_input_failures(
  1407. args: argparse.Namespace,
  1408. ) -> tuple[list[str], dict[str, Any] | None]:
  1409. failures: list[str] = []
  1410. bitstream = Path(args.bitstream)
  1411. build_info_path = Path(args.build_info)
  1412. build_info: dict[str, Any] | None = None
  1413. try:
  1414. payload = json.loads(build_info_path.read_text(encoding="utf-8-sig"))
  1415. except (OSError, UnicodeError, json.JSONDecodeError):
  1416. failures.append("build_info_unreadable")
  1417. else:
  1418. if not isinstance(payload, dict):
  1419. failures.append("build_info_not_object")
  1420. else:
  1421. build_info = payload
  1422. failures.extend(validate_build_info(build_info)["failures"])
  1423. failures.extend(verify_bitstream(bitstream=bitstream, build_info=build_info)["failures"])
  1424. output_dir = Path(args.output_dir)
  1425. if output_dir.exists() and (not output_dir.is_dir() or any(output_dir.iterdir())):
  1426. failures.append("output_dir_not_empty")
  1427. if not str(getattr(args, "run_id", "")).strip():
  1428. failures.append("run_id_missing")
  1429. if not BOARD_ID_RE.fullmatch(str(getattr(args, "board_id", ""))):
  1430. failures.append("board_id_invalid")
  1431. return sorted(set(failures)), build_info
  1432. def _sha256_file(path: Path) -> str:
  1433. digest = hashlib.sha256()
  1434. with Path(path).open("rb") as handle:
  1435. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1436. digest.update(chunk)
  1437. return digest.hexdigest()
  1438. def _load_json_object(path: Path, *, label: str, failures: list[str]) -> dict[str, Any] | None:
  1439. try:
  1440. payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
  1441. except (OSError, UnicodeError, json.JSONDecodeError):
  1442. failures.append(f"{label}_unreadable")
  1443. return None
  1444. if not isinstance(payload, dict):
  1445. failures.append(f"{label}_not_object")
  1446. return None
  1447. return payload
  1448. def _gate_evidence_input_failures(
  1449. args: argparse.Namespace,
  1450. *,
  1451. build_info: Mapping[str, Any] | None,
  1452. ) -> tuple[list[str], dict[str, Any] | None, dict[str, Any] | None]:
  1453. failures: list[str] = []
  1454. td_path = Path(args.td_receipt)
  1455. package_path = Path(args.package_info)
  1456. td = _load_json_object(td_path, label="td_receipt", failures=failures)
  1457. package = _load_json_object(package_path, label="package_info", failures=failures)
  1458. if build_info is None or td is None or package is None:
  1459. return sorted(set(failures)), package, td
  1460. if set(package) != {
  1461. "schema",
  1462. "profile",
  1463. "commit",
  1464. "build_id",
  1465. "build_info_sha256",
  1466. "bitstream_sha256",
  1467. "td_receipt_sha256",
  1468. "file_sha256",
  1469. }:
  1470. failures.append("package_info_fields_mismatch")
  1471. if package.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v1":
  1472. failures.append("package_info_schema_mismatch")
  1473. if package.get("profile") != PROFILE:
  1474. failures.append("package_profile_mismatch")
  1475. commit = package.get("commit")
  1476. if not isinstance(commit, str) or not COMMIT_RE.fullmatch(commit):
  1477. failures.append("package_commit_invalid")
  1478. if package.get("build_id") != build_info.get("build_id"):
  1479. failures.append("package_build_id_mismatch")
  1480. if package.get("build_info_sha256") != _sha256_file(Path(args.build_info)):
  1481. failures.append("package_build_info_sha256_mismatch")
  1482. if package.get("bitstream_sha256") != build_info.get("bitstream_sha256"):
  1483. failures.append("package_bitstream_sha256_mismatch")
  1484. if package.get("td_receipt_sha256") != _sha256_file(td_path):
  1485. failures.append("package_td_receipt_sha256_mismatch")
  1486. if td.get("status") != "pass":
  1487. failures.append("td_receipt_not_pass")
  1488. if td.get("commit") != commit:
  1489. failures.append("td_receipt_commit_mismatch")
  1490. if td.get("build_id") != build_info.get("build_id"):
  1491. failures.append("td_receipt_build_id_mismatch")
  1492. if td.get("bitstream_sha256") != build_info.get("bitstream_sha256"):
  1493. failures.append("td_receipt_bitstream_sha256_mismatch")
  1494. file_sha256 = package.get("file_sha256")
  1495. if not isinstance(file_sha256, dict) or any(
  1496. not isinstance(relative, str)
  1497. or not isinstance(digest, str)
  1498. or not SHA256_RE.fullmatch(digest)
  1499. for relative, digest in (file_sha256.items() if isinstance(file_sha256, dict) else ())
  1500. ):
  1501. failures.append("package_file_sha256_invalid")
  1502. else:
  1503. root = package_path.resolve().parent
  1504. observed: dict[str, str] = {}
  1505. for path in sorted(candidate for candidate in root.rglob("*") if candidate.is_file()):
  1506. if path.resolve() == package_path.resolve():
  1507. continue
  1508. relative = path.resolve().relative_to(root).as_posix()
  1509. observed[relative] = _sha256_file(path)
  1510. if set(file_sha256) != set(observed):
  1511. failures.append("package_file_sha256_paths_mismatch")
  1512. for relative in sorted(set(file_sha256) & set(observed)):
  1513. if file_sha256[relative] != observed[relative]:
  1514. failures.append(f"package_file_sha256_mismatch:{relative}")
  1515. for label, path in (
  1516. ("bitstream", Path(args.bitstream)),
  1517. ("build_info", Path(args.build_info)),
  1518. ("td_receipt", td_path),
  1519. ):
  1520. if not path.is_file():
  1521. failures.append(f"package_{label}_missing")
  1522. continue
  1523. try:
  1524. relative = path.resolve().relative_to(root).as_posix()
  1525. except ValueError:
  1526. failures.append(f"package_{label}_outside_root")
  1527. else:
  1528. if file_sha256.get(relative) != _sha256_file(path):
  1529. failures.append(f"package_{label}_not_bound")
  1530. return sorted(set(failures)), package, td
  1531. def _program_receipt_failures(
  1532. receipt: Any,
  1533. *,
  1534. build_id: str,
  1535. expected_sha256: str,
  1536. ) -> list[str]:
  1537. if not isinstance(receipt, dict):
  1538. return ["programmer_receipt_not_object"]
  1539. failures: list[str] = []
  1540. request = receipt.get("request") if isinstance(receipt.get("request"), dict) else {}
  1541. execution = receipt.get("execution") if isinstance(receipt.get("execution"), dict) else {}
  1542. safety = receipt.get("safety") if isinstance(receipt.get("safety"), dict) else {}
  1543. bitstream = receipt.get("bitstream") if isinstance(receipt.get("bitstream"), dict) else {}
  1544. expected_request = {
  1545. "operation": "PROGRAM_SRAM",
  1546. "target_chip": "EF2L45",
  1547. "cable_index": 0,
  1548. "speed_code": 2,
  1549. "speed_hz": 200000,
  1550. "attempt_limit": 1,
  1551. "power_cycle_allowed": False,
  1552. }
  1553. for field, expected in expected_request.items():
  1554. if request.get(field) != expected:
  1555. failures.append(f"programmer_request_mismatch:{field}")
  1556. expected_execution = {
  1557. "attempt_count": 1,
  1558. "retry_count": 0,
  1559. "power_cycle_count": 0,
  1560. "command_execution_attempted": True,
  1561. }
  1562. for field, expected in expected_execution.items():
  1563. if execution.get(field) != expected:
  1564. failures.append(f"programmer_execution_mismatch:{field}")
  1565. for field in (
  1566. "flash_attempted",
  1567. "programs_nonvolatile",
  1568. "power_cycle_attempted",
  1569. "driver_install_attempted",
  1570. "toggles_dtr_rts",
  1571. ):
  1572. if safety.get(field) is not False:
  1573. failures.append(f"programmer_safety_not_false:{field}")
  1574. if str(bitstream.get("build_id", "")).upper() != build_id:
  1575. failures.append("programmer_build_id_mismatch")
  1576. if str(bitstream.get("sha256", "")).casefold() != expected_sha256:
  1577. failures.append("programmer_bitstream_sha256_mismatch")
  1578. if receipt.get("status") != "pass":
  1579. failures.append("programmer_receipt_not_pass")
  1580. return sorted(set(failures))
  1581. PROGRAMMER_METADATA_CONTRACT: dict[str, object] = {
  1582. "operation": "PROGRAM_SRAM",
  1583. "speed_hz": 200000,
  1584. "program_sram_attempted": True,
  1585. "attempt_count": 1,
  1586. "retry_count": 0,
  1587. "flash_attempted": False,
  1588. }
  1589. def _program_receipt_metadata(receipt: object) -> dict[str, object]:
  1590. if not isinstance(receipt, Mapping):
  1591. return {field: None for field in PROGRAMMER_METADATA_CONTRACT}
  1592. request = receipt.get("request") if isinstance(receipt.get("request"), Mapping) else {}
  1593. execution = receipt.get("execution") if isinstance(receipt.get("execution"), Mapping) else {}
  1594. safety = receipt.get("safety") if isinstance(receipt.get("safety"), Mapping) else {}
  1595. return {
  1596. "operation": request.get("operation"),
  1597. "speed_hz": request.get("speed_hz"),
  1598. "program_sram_attempted": execution.get("command_execution_attempted"),
  1599. "attempt_count": execution.get("attempt_count"),
  1600. "retry_count": execution.get("retry_count"),
  1601. "flash_attempted": safety.get("flash_attempted"),
  1602. }
  1603. def _programmer_metadata_failures(result: Mapping[str, Any]) -> list[str]:
  1604. failures: list[str] = []
  1605. for field, expected in PROGRAMMER_METADATA_CONTRACT.items():
  1606. observed = result.get(field)
  1607. if type(observed) is not type(expected) or observed != expected:
  1608. failures.append(f"programmer_metadata_mismatch:{field}")
  1609. return failures
  1610. def run_program_only(
  1611. args: argparse.Namespace,
  1612. *,
  1613. programmer: Callable[..., dict[str, Any]] = execute_program_sram,
  1614. ) -> dict[str, Any]:
  1615. """Validate build-info and invoke PROGRAM_SRAM exactly once without COM5."""
  1616. failures, build_info = _program_input_failures(args)
  1617. if failures:
  1618. return {
  1619. "schema": "prod2u-p4-normal-v3-program-only-v2",
  1620. "status": "fail_preflight",
  1621. "failures": failures,
  1622. "program_sram_attempted": False,
  1623. "attempt_count": 0,
  1624. "retry_count": 0,
  1625. "serial_opened": False,
  1626. "flash_attempted": False,
  1627. }
  1628. assert build_info is not None
  1629. build_id = str(build_info["build_id"])
  1630. expected_sha256 = str(build_info["bitstream_sha256"])
  1631. try:
  1632. receipt = programmer(
  1633. source_bitstream=Path(args.bitstream),
  1634. expected_bitstream_sha256=expected_sha256,
  1635. build_id=build_id,
  1636. output_dir=Path(args.output_dir),
  1637. td_root=Path(args.td_root),
  1638. run_id=str(args.run_id),
  1639. )
  1640. except Exception as exc:
  1641. return {
  1642. "schema": "prod2u-p4-normal-v3-program-only-v2",
  1643. "status": "fail_programmer_exception",
  1644. "error_type": type(exc).__name__,
  1645. "error": str(exc),
  1646. "failures": ["programmer_exception"],
  1647. "program_sram_attempted": True,
  1648. "attempt_count": 1,
  1649. "retry_count": 0,
  1650. "serial_opened": False,
  1651. "flash_attempted": False,
  1652. "build_id": build_id,
  1653. "bitstream_sha256": expected_sha256,
  1654. }
  1655. failures = _program_receipt_failures(
  1656. receipt,
  1657. build_id=build_id,
  1658. expected_sha256=expected_sha256,
  1659. )
  1660. safety = receipt.get("safety") if isinstance(receipt, dict) and isinstance(receipt.get("safety"), dict) else {}
  1661. metadata = _program_receipt_metadata(receipt)
  1662. failures = sorted(set(failures + _programmer_metadata_failures(metadata)))
  1663. return {
  1664. "schema": "prod2u-p4-normal-v3-program-only-v2",
  1665. "status": "pass" if not failures else "fail_programmer_contract",
  1666. "failures": failures,
  1667. **metadata,
  1668. "serial_opened": False,
  1669. "programs_nonvolatile": safety.get("programs_nonvolatile") is not False,
  1670. "build_id": build_id,
  1671. "bitstream_sha256": expected_sha256,
  1672. }
  1673. def _console_operator_observer(stage: str, context: dict[str, Any]) -> dict[str, Any]:
  1674. if not sys.stdin.isatty():
  1675. return {"status": "fail", "stage": stage, "reason": "operator_console_not_interactive"}
  1676. print(json.dumps({"operator_observation_required": stage, "context": context}, ensure_ascii=False))
  1677. answer = input(f"观察完成后输入 CONFIRM {stage}: ").strip()
  1678. confirmations: dict[str, bool] = {}
  1679. for field in context.get("required_confirmations", []):
  1680. field_answer = input(f"输入 CONFIRM {stage} {field}: ").strip()
  1681. confirmations[str(field)] = field_answer == f"CONFIRM {stage} {field}"
  1682. return {
  1683. "status": "pass" if answer == f"CONFIRM {stage}" else "fail",
  1684. "stage": stage,
  1685. "observed_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
  1686. "confirmations": confirmations,
  1687. }
  1688. def _confirm_operator_observation(
  1689. observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
  1690. observations: list[dict[str, Any]],
  1691. *,
  1692. stage: str,
  1693. context: dict[str, Any],
  1694. required_confirmations: tuple[str, ...] = (),
  1695. ) -> dict[str, Any]:
  1696. if observer is None:
  1697. raise RuntimeError(f"operator observer missing for {stage}")
  1698. observer_context = {**context, "required_confirmations": list(required_confirmations)}
  1699. response = observer(stage, observer_context)
  1700. if not isinstance(response, Mapping) or response.get("status") != "pass" or response.get("stage") != stage:
  1701. raise RuntimeError(f"operator observation rejected for {stage}")
  1702. observed_at = response.get("observed_at")
  1703. if not isinstance(observed_at, str) or not observed_at.endswith("Z"):
  1704. raise RuntimeError(f"operator observation timestamp invalid for {stage}")
  1705. confirmations = response.get("confirmations") if isinstance(response.get("confirmations"), Mapping) else {}
  1706. for field in required_confirmations:
  1707. if confirmations.get(field) is not True:
  1708. raise RuntimeError(f"operator confirmation missing for {stage}:{field}")
  1709. recorded = {
  1710. "stage": stage,
  1711. "context": observer_context,
  1712. "observed_at": observed_at,
  1713. "confirmations": {str(key): value is True for key, value in confirmations.items()},
  1714. }
  1715. observations.append(recorded)
  1716. return recorded
  1717. def _confirm_operator_observation_from_disabled(
  1718. session: NormalSession,
  1719. events: list[dict[str, Any]],
  1720. observations: list[dict[str, Any]],
  1721. *,
  1722. observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
  1723. stage: str,
  1724. context: dict[str, Any],
  1725. required_confirmations: tuple[str, ...] = (),
  1726. ) -> dict[str, Any]:
  1727. _gate_safe_disable(session, events, phase=f"{stage}-pre-observation-disable")
  1728. try:
  1729. return _confirm_operator_observation(
  1730. observer,
  1731. observations,
  1732. stage=stage,
  1733. context=context,
  1734. required_confirmations=required_confirmations,
  1735. )
  1736. except BaseException:
  1737. session.disable_attempted = True
  1738. raise
  1739. def _gate_result(
  1740. *,
  1741. status: str,
  1742. args: argparse.Namespace,
  1743. failures: list[str],
  1744. hardware_enumerated: bool,
  1745. serial_opened: bool,
  1746. program_sram_attempted: object,
  1747. attempt_count: object,
  1748. retry_count: object,
  1749. flash_attempted: object = False,
  1750. operation: object = None,
  1751. speed_hz: object = None,
  1752. ) -> dict[str, Any]:
  1753. return {
  1754. "schema": "prod2u-p4-normal-v3-gate-launch-v2",
  1755. "status": status,
  1756. "profile": PROFILE,
  1757. "bitstream": str(Path(args.bitstream)),
  1758. "output_dir": str(Path(args.output_dir)),
  1759. "failures": list(dict.fromkeys(failures)),
  1760. "hardware_enumerated": hardware_enumerated,
  1761. "serial_opened": serial_opened,
  1762. "program_sram_attempted": program_sram_attempted,
  1763. "operation": operation,
  1764. "speed_hz": speed_hz,
  1765. "attempt_count": attempt_count,
  1766. "retry_count": retry_count,
  1767. "flash_attempted": flash_attempted,
  1768. "authority_boundary": (
  1769. "The gate performs at most one PROGRAM_SRAM attempt and never programs flash. "
  1770. "Trace, motion, watchdog and final DISABLE evidence are required for acceptance."
  1771. ),
  1772. }
  1773. def _build_hardware_session_receipt(
  1774. *,
  1775. board_id: str,
  1776. commit: str,
  1777. build_id: str,
  1778. artifacts: Mapping[str, Any],
  1779. programmer_metadata: Mapping[str, Any],
  1780. trace: Mapping[str, Any],
  1781. wire_order: Mapping[str, Any],
  1782. axes: Mapping[str, Any],
  1783. partial: Mapping[str, Any],
  1784. watchdog: Mapping[str, Any],
  1785. stages: list[Mapping[str, Any]],
  1786. final_disable: Mapping[str, Any],
  1787. status: str = "pass",
  1788. failures: list[str] | None = None,
  1789. ) -> dict[str, Any]:
  1790. receipt = {
  1791. "schema": "prod2u-p4-normal-v3-actuator-trace-hardware-session-v1",
  1792. "status": status,
  1793. "profile": PROFILE,
  1794. "board_id": board_id,
  1795. "commit": commit,
  1796. "build_id": build_id,
  1797. "artifacts": dict(artifacts),
  1798. "serial": {"port": PORT, "baud": BAUD, "format": "8N1"},
  1799. "jtag": {
  1800. field: programmer_metadata[field]
  1801. for field in PROGRAMMER_METADATA_CONTRACT
  1802. },
  1803. "trace": dict(trace),
  1804. "wire_order": dict(wire_order),
  1805. "axes": {str(key): dict(value) for key, value in axes.items()},
  1806. "partial": dict(partial),
  1807. "watchdog": dict(watchdog),
  1808. "counterparty": {
  1809. "kind": "prod2u-p4-normal-v3-board",
  1810. "board_id": board_id,
  1811. "uart_endpoint": PORT,
  1812. "jtag_adapter": "AL-Link",
  1813. },
  1814. "stages": [dict(stage) for stage in stages],
  1815. "final_disable": dict(final_disable),
  1816. "prohibited_actions": {
  1817. "flash_attempted": programmer_metadata["flash_attempted"],
  1818. "driver_install_attempted": False,
  1819. "ptc_heating_attempted": False,
  1820. "retired_sensor_action_attempted": False,
  1821. "z_motion_attempted": False,
  1822. "limit_fault_injection_attempted": False,
  1823. "automatic_retry_attempted": False,
  1824. "second_program_sram_attempted": False,
  1825. },
  1826. "authority_boundary": (
  1827. "This receipt proves one controlled SRAM session and the observed Normal v3 digital control "
  1828. "path only; it does not prove mechanics, external wiring, thermal behavior, or service life."
  1829. ),
  1830. }
  1831. if status == "fail":
  1832. receipt["failures"] = list(dict.fromkeys(failures or ["unspecified_hardware_session_failure"]))
  1833. return receipt
  1834. def _write_json_artifact(path: Path, payload: Any) -> str:
  1835. Path(path).write_text(
  1836. json.dumps(payload, indent=2, ensure_ascii=False, default=lambda value: int(value)) + "\n",
  1837. encoding="utf-8",
  1838. newline="\n",
  1839. )
  1840. return _sha256_file(Path(path))
  1841. def _trace_event_row(event: TraceEvent) -> dict[str, Any]:
  1842. return {
  1843. "event_seq": event.event_seq,
  1844. "event_type": event.event_type.name,
  1845. "source": event.source,
  1846. "meta": event.meta,
  1847. "data": event.data,
  1848. "state_hash16": event.state_hash16,
  1849. }
  1850. def _trace_receipt_summary(events: list[TraceEvent]) -> dict[str, Any]:
  1851. continuous = bool(events)
  1852. for previous, current in zip(events, events[1:]):
  1853. expected = 1 if previous.event_seq == 0xFFFFFFFF else previous.event_seq + 1
  1854. if current.event_seq != expected:
  1855. continuous = False
  1856. break
  1857. overflow = any(event.event_type == TraceEventType.OVERFLOW for event in events)
  1858. epoch = any(event.event_type == TraceEventType.EPOCH for event in events)
  1859. command_result = any(event.event_type == TraceEventType.COMMAND_RESULT for event in events)
  1860. return {
  1861. "status": "pass" if continuous and not overflow and epoch and command_result else "fail",
  1862. "first_event_seq": events[0].event_seq if events else None,
  1863. "last_event_seq": events[-1].event_seq if events else None,
  1864. "event_count": len(events),
  1865. "continuous_event_seq": continuous,
  1866. "overflow_observed": overflow,
  1867. "command_result_before_ack": command_result,
  1868. "epoch_observed": epoch,
  1869. "layout_versions": {
  1870. "EPOCH": 1,
  1871. "CORE_STATE": 1,
  1872. "AXIS_STATE": 1,
  1873. "LIMIT_STATE": 1,
  1874. "SAFETY_STATE": 1,
  1875. "OVERFLOW": 1,
  1876. },
  1877. }
  1878. def _open_to_close_trace_pair(
  1879. events: list[TraceEvent],
  1880. *,
  1881. expected_source: AxisTraceSource,
  1882. close_dir: int,
  1883. ) -> list[tuple[TraceEvent, Any]]:
  1884. decoded = [
  1885. (event, decode_axis_trace_event(event))
  1886. for event in events
  1887. if event.event_type == TraceEventType.AXIS_STATE
  1888. and event.source == int(expected_source)
  1889. ]
  1890. reversals = [
  1891. (index, event, evidence)
  1892. for index, (event, evidence) in enumerate(decoded)
  1893. if evidence.stop_reason == AxisStopReason.REVERSED_TO_CLOSE
  1894. ]
  1895. if len(reversals) != 1:
  1896. raise ValueError(
  1897. f"{expected_source.name} open-to-close requires exactly one REVERSED_TO_CLOSE terminal"
  1898. )
  1899. reverse_index, reverse_event, reverse_evidence = reversals[0]
  1900. finals = [
  1901. (event, evidence)
  1902. for event, evidence in decoded[reverse_index + 1 :]
  1903. if evidence.stop_reason == AxisStopReason.LIMIT_CONFIRMED
  1904. and evidence.axis_state == 1
  1905. ]
  1906. if len(finals) != 1:
  1907. raise ValueError(
  1908. f"{expected_source.name} open-to-close requires exactly one final CLOSED/LIMIT_CONFIRMED terminal"
  1909. )
  1910. final_event, final_evidence = finals[0]
  1911. if (
  1912. reverse_evidence.axis_state != 4
  1913. or reverse_evidence.move_kind != 1
  1914. or not reverse_evidence.close_dir_valid
  1915. or reverse_evidence.close_dir != close_dir
  1916. or reverse_evidence.requested_dir == close_dir
  1917. ):
  1918. raise ValueError(f"{expected_source.name} REVERSED_TO_CLOSE direction/state evidence is invalid")
  1919. if (
  1920. final_evidence.move_kind != 1
  1921. or not final_evidence.close_dir_valid
  1922. or final_evidence.close_dir != close_dir
  1923. or final_evidence.requested_dir != close_dir
  1924. or final_evidence.live_dir != close_dir
  1925. ):
  1926. raise ValueError(f"{expected_source.name} final close direction/state evidence is invalid")
  1927. return [(reverse_event, reverse_evidence), (final_event, final_evidence)]
  1928. def _axis_evidence_from_trace(
  1929. events: list[TraceEvent],
  1930. *,
  1931. axis_label: str,
  1932. close_dir: int,
  1933. checks: Mapping[str, bool],
  1934. open_to_close_events: list[TraceEvent],
  1935. ) -> dict[str, Any]:
  1936. try:
  1937. expected_source = AxisTraceSource[axis_label]
  1938. except KeyError as exc:
  1939. raise ValueError(f"unsupported axis label: {axis_label}") from exc
  1940. if close_dir not in {0, 1}:
  1941. raise ValueError("close_dir must be 0 or 1")
  1942. expected_checks = {"mark_closed", "jog_away", "jog_to_limit", "standard_open_close"}
  1943. if set(checks) != expected_checks or any(not isinstance(value, bool) for value in checks.values()):
  1944. raise ValueError("axis checks must contain the four non-derived motion checks")
  1945. open_to_close = _open_to_close_trace_pair(
  1946. open_to_close_events,
  1947. expected_source=expected_source,
  1948. close_dir=close_dir,
  1949. )
  1950. decoded = [
  1951. (event, decode_axis_trace_event(event))
  1952. for event in events
  1953. if event.event_type == TraceEventType.AXIS_STATE and event.source == int(expected_source)
  1954. ]
  1955. final_index = next(
  1956. (
  1957. index
  1958. for index in range(len(decoded) - 1, -1, -1)
  1959. if decoded[index][1].axis_state == 1
  1960. and decoded[index][1].stop_reason == AxisStopReason.LIMIT_CONFIRMED
  1961. ),
  1962. None,
  1963. )
  1964. if final_index is None:
  1965. raise ValueError(f"{axis_label} has no terminal CLOSED/LIMIT_CONFIRMED Trace evidence")
  1966. selected = [decoded[final_index]]
  1967. final_evidence = selected[-1][1]
  1968. if final_evidence.recovery_segment:
  1969. primary_index = next(
  1970. (
  1971. index
  1972. for index in range(final_index - 1, -1, -1)
  1973. if not decoded[index][1].recovery_segment
  1974. ),
  1975. None,
  1976. )
  1977. if primary_index is None:
  1978. raise ValueError(f"{axis_label} recovery Trace is missing its primary segment")
  1979. selected.insert(0, decoded[primary_index])
  1980. final_evidence = selected[-1][1]
  1981. if any(
  1982. evidence.move_kind != 1
  1983. or not evidence.close_dir_valid
  1984. or evidence.close_dir != close_dir
  1985. or evidence.requested_dir != close_dir
  1986. or evidence.live_dir != close_dir
  1987. for _, evidence in selected
  1988. ):
  1989. raise ValueError(f"{axis_label} standard CLOSE terminal evidence is invalid")
  1990. if len(selected) == 1:
  1991. if final_evidence.recovery_segment:
  1992. raise ValueError(f"{axis_label} standard CLOSE recovery evidence is incomplete")
  1993. else:
  1994. primary_evidence = selected[0][1]
  1995. if (
  1996. len(selected) != 2
  1997. or primary_evidence.recovery_segment
  1998. or primary_evidence.stop_reason != AxisStopReason.REQUEST_COMPLETE
  1999. or primary_evidence.axis_state != 6
  2000. or not final_evidence.recovery_segment
  2001. ):
  2002. raise ValueError(f"{axis_label} standard CLOSE recovery evidence is invalid")
  2003. primary = next((evidence for _, evidence in selected if not evidence.recovery_segment), None)
  2004. requested_steps = primary.requested_steps if primary is not None else final_evidence.requested_steps
  2005. emitted_steps = sum(evidence.completed_steps for _, evidence in selected)
  2006. recovery_steps = sum(
  2007. evidence.completed_steps for _, evidence in selected if evidence.recovery_segment
  2008. )
  2009. axis_states = (
  2010. "UNCALIBRATED",
  2011. "CLOSED",
  2012. "OPENING",
  2013. "OPEN",
  2014. "CLOSING",
  2015. "INTERMEDIATE",
  2016. "RECOVERY",
  2017. "LOCKED_FAULT",
  2018. )
  2019. return {
  2020. "status": "pass",
  2021. "axis": axis_label,
  2022. "close_dir": close_dir,
  2023. "limit_open_volts": 0.0,
  2024. "limit_closed_volts": 3.3,
  2025. "limit_active_high": True,
  2026. "requested_steps": requested_steps,
  2027. "emitted_steps": emitted_steps,
  2028. "recovery_steps": recovery_steps,
  2029. "stop_reason": final_evidence.stop_reason.name.lower(),
  2030. "final_state": axis_states[final_evidence.axis_state],
  2031. "trace_event_seqs": [evidence.event_seq for _, evidence in selected],
  2032. "trace_frames_hex": [encode_trace_frame(event).hex() for event, _ in selected],
  2033. "distance_steps": final_evidence.distance_steps,
  2034. "distance_valid": final_evidence.distance_valid,
  2035. "distance_saturated": final_evidence.distance_saturated,
  2036. "layout_version": 1,
  2037. "open_to_close_trace_event_seqs": [
  2038. evidence.event_seq for _, evidence in open_to_close
  2039. ],
  2040. "open_to_close_trace_frames_hex": [
  2041. encode_trace_frame(event).hex() for event, _ in open_to_close
  2042. ],
  2043. "checks": {**dict(checks), "open_to_close": len(open_to_close) == 2},
  2044. }
  2045. def _finalize_hardware_session_receipt(
  2046. *,
  2047. output_dir: Path,
  2048. board_id: str,
  2049. commit: str,
  2050. build_id: str,
  2051. build_info_path: Path,
  2052. bitstream_path: Path,
  2053. td_receipt_path: Path,
  2054. programmer_metadata: Mapping[str, Any],
  2055. serial_events: list[Mapping[str, Any]],
  2056. trace_events: list[TraceEvent],
  2057. register_checkpoint: Mapping[str, Any],
  2058. axes: Mapping[str, Any],
  2059. partial: Mapping[str, Any],
  2060. watchdog: Mapping[str, Any],
  2061. stages: list[Mapping[str, Any]],
  2062. final_disable: Mapping[str, Any],
  2063. ) -> dict[str, Any]:
  2064. output_dir = Path(output_dir)
  2065. serial_path = output_dir / "serial-transcript.json"
  2066. trace_path = output_dir / "trace-events.json"
  2067. register_path = output_dir / "register-checkpoint.json"
  2068. serial_payload = {"events": [dict(row) for row in serial_events]}
  2069. serial_sha256 = _write_json_artifact(serial_path, serial_payload)
  2070. wire_replay = replay_serial_transcript_events(
  2071. serial_payload["events"],
  2072. require_startup_epoch=True,
  2073. )
  2074. if wire_replay.get("status") != "pass":
  2075. raise ValueError(f"serial transcript replay failed: {wire_replay.get('failures', [])}")
  2076. wire_order = {
  2077. key: wire_replay[key]
  2078. for key in (
  2079. "status",
  2080. "command_count",
  2081. "trace_event_count",
  2082. "first_event_seq",
  2083. "last_event_seq",
  2084. "commands",
  2085. )
  2086. }
  2087. wire_order["serial_transcript_sha256"] = serial_sha256
  2088. trace_sha256 = _write_json_artifact(
  2089. trace_path,
  2090. {"events": [_trace_event_row(event) for event in trace_events]},
  2091. )
  2092. register_sha256 = _write_json_artifact(register_path, dict(register_checkpoint))
  2093. trace_summary = _trace_receipt_summary(trace_events)
  2094. trace_summary["command_result_before_ack"] = wire_order["status"] == "pass"
  2095. receipt = _build_hardware_session_receipt(
  2096. board_id=board_id,
  2097. commit=commit,
  2098. build_id=build_id,
  2099. artifacts={
  2100. "build_info_sha256": _sha256_file(Path(build_info_path)),
  2101. "bitstream_sha256": _sha256_file(Path(bitstream_path)),
  2102. "td_receipt_sha256": _sha256_file(Path(td_receipt_path)),
  2103. "serial_transcript_sha256": serial_sha256,
  2104. "trace_sha256": trace_sha256,
  2105. "register_checkpoint_sha256": register_sha256,
  2106. },
  2107. programmer_metadata=programmer_metadata,
  2108. trace=trace_summary,
  2109. wire_order=wire_order,
  2110. axes=axes,
  2111. partial=partial,
  2112. watchdog=watchdog,
  2113. stages=stages,
  2114. final_disable=final_disable,
  2115. )
  2116. receipt_path = output_dir / "hardware-session-receipt.json"
  2117. candidate_path = output_dir / "hardware-session-receipt.candidate.json"
  2118. _write_json_artifact(candidate_path, receipt)
  2119. validation = validate_session_receipt(candidate_path)
  2120. if validation.get("status") != "pass":
  2121. candidate_path.unlink(missing_ok=True)
  2122. raise ValueError(f"hardware session receipt invalid: {validation.get('failures', [])}")
  2123. candidate_path.replace(receipt_path)
  2124. return receipt
  2125. def _not_run_axis_evidence(axis: str, close_dir: int | None) -> dict[str, Any]:
  2126. return {
  2127. "status": "not_run",
  2128. "axis": axis,
  2129. "close_dir": close_dir,
  2130. "limit_open_volts": None,
  2131. "limit_closed_volts": None,
  2132. "limit_active_high": True,
  2133. "requested_steps": 0,
  2134. "emitted_steps": 0,
  2135. "recovery_steps": 0,
  2136. "stop_reason": "not_run",
  2137. "final_state": "UNKNOWN",
  2138. "trace_event_seqs": [],
  2139. "trace_frames_hex": [],
  2140. "distance_steps": 0,
  2141. "distance_valid": False,
  2142. "distance_saturated": False,
  2143. "layout_version": 1,
  2144. "open_to_close_trace_event_seqs": [],
  2145. "open_to_close_trace_frames_hex": [],
  2146. "checks": {
  2147. "mark_closed": False,
  2148. "jog_away": False,
  2149. "jog_to_limit": False,
  2150. "standard_open_close": False,
  2151. "open_to_close": False,
  2152. },
  2153. }
  2154. def _append_last_exchange(
  2155. events: list[dict[str, Any]],
  2156. session: NormalSession,
  2157. *,
  2158. phase: str,
  2159. ) -> None:
  2160. exchange = session.last_exchange
  2161. if exchange is None or (
  2162. not exchange.get("request_hex") and not exchange.get("response_hex")
  2163. ):
  2164. return
  2165. if any(
  2166. row.get("request_hex") == exchange.get("request_hex")
  2167. and row.get("response_hex") == exchange.get("response_hex")
  2168. for row in events
  2169. ):
  2170. return
  2171. events.append({"phase": phase, **exchange})
  2172. def _append_best_effort_disable(
  2173. events: list[dict[str, Any]],
  2174. session: NormalSession,
  2175. *,
  2176. phase: str,
  2177. ) -> None:
  2178. exchange = session.best_effort_disable_exchange
  2179. if exchange is None:
  2180. return
  2181. if any(
  2182. row.get("request_hex") == exchange.get("request_hex")
  2183. and row.get("response_hex") == exchange.get("response_hex")
  2184. for row in events
  2185. ):
  2186. return
  2187. events.append({"phase": phase, **exchange})
  2188. def _complete_failure_stages(
  2189. stages: list[Mapping[str, Any]],
  2190. *,
  2191. reason: str,
  2192. ) -> list[dict[str, Any]]:
  2193. completed = [dict(stage) for stage in stages]
  2194. names = {str(stage.get("name")) for stage in completed}
  2195. failure_assigned = any(stage.get("status") == "fail" for stage in completed)
  2196. for name in hardware_stage_plan()["stages"]:
  2197. if name in names:
  2198. continue
  2199. if not failure_assigned:
  2200. completed.append(_stage(name, status="fail", reason=reason))
  2201. failure_assigned = True
  2202. else:
  2203. completed.append(_stage(name, status="not_run", reason="blocked_by_prior_failure"))
  2204. return completed
  2205. def _finalize_failed_hardware_session_receipt(
  2206. *,
  2207. output_dir: Path,
  2208. board_id: str,
  2209. commit: str,
  2210. build_id: str,
  2211. build_info_path: Path,
  2212. bitstream_path: Path,
  2213. td_receipt_path: Path,
  2214. programmer_metadata: Mapping[str, Any],
  2215. serial_events: list[Mapping[str, Any]],
  2216. rx_journal: bytes,
  2217. trace_events: list[TraceEvent],
  2218. stages: list[Mapping[str, Any]],
  2219. failure_reasons: list[str],
  2220. final_disable: Mapping[str, Any],
  2221. x_close_dir: int | None,
  2222. y_close_dir: int | None,
  2223. ) -> dict[str, Any]:
  2224. output_dir = Path(output_dir)
  2225. serial_path = output_dir / "serial-transcript.json"
  2226. trace_path = output_dir / "trace-events.json"
  2227. register_path = output_dir / "register-checkpoint.json"
  2228. serial_payload = {
  2229. "events": [dict(row) for row in serial_events],
  2230. "rx_journal_hex": bytes(rx_journal).hex(),
  2231. "rx_byte_count": len(rx_journal),
  2232. }
  2233. serial_sha256 = _write_json_artifact(serial_path, serial_payload)
  2234. wire_replay = replay_serial_transcript_events(
  2235. serial_payload["events"],
  2236. require_startup_epoch=True,
  2237. expected_build_id=int(build_id, 16),
  2238. expected_capability_flags=CAPABILITY_FLAGS,
  2239. )
  2240. declared_failures = list(
  2241. dict.fromkeys(
  2242. [*failure_reasons, *[str(value) for value in wire_replay.get("failures", [])]]
  2243. )
  2244. )
  2245. wire_order = {
  2246. key: wire_replay[key]
  2247. for key in (
  2248. "status",
  2249. "command_count",
  2250. "trace_event_count",
  2251. "first_event_seq",
  2252. "last_event_seq",
  2253. "commands",
  2254. )
  2255. }
  2256. wire_order["serial_transcript_sha256"] = serial_sha256
  2257. trace_sha256 = _write_json_artifact(
  2258. trace_path,
  2259. {"events": [_trace_event_row(event) for event in trace_events]},
  2260. )
  2261. register_sha256 = _write_json_artifact(
  2262. register_path,
  2263. {
  2264. "status": "not_run",
  2265. "reason": "host_uart_failure",
  2266. "last_rx_byte_count": len(rx_journal),
  2267. },
  2268. )
  2269. trace_summary = _trace_receipt_summary(trace_events)
  2270. trace_summary["command_result_before_ack"] = wire_replay.get("status") == "pass"
  2271. receipt = _build_hardware_session_receipt(
  2272. board_id=board_id,
  2273. commit=commit,
  2274. build_id=build_id,
  2275. artifacts={
  2276. "build_info_sha256": _sha256_file(Path(build_info_path)),
  2277. "bitstream_sha256": _sha256_file(Path(bitstream_path)),
  2278. "td_receipt_sha256": _sha256_file(Path(td_receipt_path)),
  2279. "serial_transcript_sha256": serial_sha256,
  2280. "trace_sha256": trace_sha256,
  2281. "register_checkpoint_sha256": register_sha256,
  2282. },
  2283. programmer_metadata=programmer_metadata,
  2284. trace=trace_summary,
  2285. wire_order=wire_order,
  2286. axes={
  2287. "x": _not_run_axis_evidence("X", x_close_dir),
  2288. "y": _not_run_axis_evidence("Y", y_close_dir),
  2289. },
  2290. partial={"status": "not_run", "scenarios": []},
  2291. watchdog={"status": "not_run", "timeout_ms": 5000, "timeline": []},
  2292. stages=stages,
  2293. final_disable=final_disable,
  2294. status="fail",
  2295. failures=declared_failures,
  2296. )
  2297. receipt_path = output_dir / "hardware-session-receipt.json"
  2298. candidate_path = output_dir / "hardware-session-receipt.candidate.json"
  2299. _write_json_artifact(candidate_path, receipt)
  2300. validation = validate_session_receipt(candidate_path)
  2301. if validation.get("status") != "pass":
  2302. candidate_path.unlink(missing_ok=True)
  2303. raise ValueError(
  2304. f"hardware session failure receipt invalid: {validation.get('failures', [])}"
  2305. )
  2306. candidate_path.replace(receipt_path)
  2307. return receipt
  2308. def _stage(name: str, *, status: str = "pass", **details: Any) -> dict[str, Any]:
  2309. row: dict[str, Any] = {"name": name, "status": status}
  2310. if details:
  2311. row["details"] = details
  2312. return row
  2313. def _gate_safe_disable(
  2314. session: NormalSession,
  2315. events: list[dict[str, Any]],
  2316. *,
  2317. phase: str,
  2318. allow_boot_preamble: bool = False,
  2319. ) -> CommandResult:
  2320. request = build_host_command(command=CommandId.DISABLE)
  2321. result = session.command(
  2322. request,
  2323. expected_command=CommandId.DISABLE,
  2324. allowed_statuses=(StatusCode.OK,),
  2325. expected_detail=0x01,
  2326. expected_state_hash16=SAFE_STATE_HASH16,
  2327. allow_boot_preamble=allow_boot_preamble,
  2328. )
  2329. events.append(
  2330. {
  2331. "phase": phase,
  2332. "request_hex": request.hex(),
  2333. "response_hex": result.raw_response.hex(),
  2334. "command": "DISABLE",
  2335. }
  2336. )
  2337. return result
  2338. def _gate_status(
  2339. session: NormalSession,
  2340. events: list[dict[str, Any]],
  2341. *,
  2342. phase: str,
  2343. ) -> CommandResult:
  2344. request = build_host_command(command=CommandId.GET_STATUS)
  2345. result = session.command(
  2346. request,
  2347. expected_command=CommandId.GET_STATUS,
  2348. allowed_statuses=(StatusCode.OK,),
  2349. allowed_result_flags=0,
  2350. )
  2351. if result.ack.detail & ~0x03:
  2352. session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
  2353. events.append(
  2354. {
  2355. "phase": phase,
  2356. "request_hex": request.hex(),
  2357. "response_hex": result.raw_response.hex(),
  2358. "command": "GET_STATUS",
  2359. "detail": result.ack.detail,
  2360. "state_hash16": result.ack.state_hash16,
  2361. }
  2362. )
  2363. return result
  2364. def _gate_motor_status(
  2365. session: NormalSession,
  2366. events: list[dict[str, Any]],
  2367. *,
  2368. phase: str,
  2369. ) -> MotorStatusResult:
  2370. result = session.motor_status()
  2371. events.append(
  2372. {
  2373. "phase": phase,
  2374. "request_hex": build_get_motor_status().hex(),
  2375. "response_hex": result.raw_response.hex(),
  2376. "command": "GET_MOTOR_STATUS",
  2377. "flags": result.status.flags,
  2378. "busy_mask": result.status.busy_mask,
  2379. "position_valid_mask": result.status.position_valid_mask,
  2380. "current_xyz": list(result.status.current_xyz),
  2381. "target_xyz": list(result.status.target_xyz),
  2382. "fault_mask": result.status.fault_mask,
  2383. }
  2384. )
  2385. return result
  2386. def _gate_snapshot(
  2387. session: NormalSession,
  2388. events: list[dict[str, Any]],
  2389. *,
  2390. phase: str,
  2391. solenoid: int,
  2392. xyz: tuple[int, int, int],
  2393. ) -> CommandResult:
  2394. request = build_output_snapshot(
  2395. ptc_percent=(0,) * 24,
  2396. fan_percent=(30,) * 4,
  2397. solenoid=solenoid,
  2398. xyz=xyz,
  2399. )
  2400. expected_hash = state_hash16(
  2401. ptc_percent=(0,) * 24,
  2402. fan_percent=(30,) * 4,
  2403. solenoid=solenoid,
  2404. )
  2405. result = session.command(
  2406. request,
  2407. expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
  2408. expected_state_hash16=expected_hash,
  2409. required_result_flags=0x01,
  2410. allowed_result_flags=0x0F,
  2411. )
  2412. if result.ack.detail & 0xC0:
  2413. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
  2414. busy_mask = result.ack.detail & 0x07
  2415. invalid_mask = (result.ack.detail >> 3) & 0x07
  2416. if busy_mask & invalid_mask:
  2417. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
  2418. if result.ack.status == StatusCode.OK and result.ack.detail != 0:
  2419. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
  2420. if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
  2421. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK missing skip detail")
  2422. accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
  2423. expected_flags = 0x01 | (accepted_or_noop_mask << 1)
  2424. if result.ack.result_flags != expected_flags:
  2425. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
  2426. events.append(
  2427. {
  2428. "phase": phase,
  2429. "request_hex": request.hex(),
  2430. "response_hex": result.raw_response.hex(),
  2431. "command": "SET_OUTPUT_SNAPSHOT",
  2432. "status": result.ack.status.name,
  2433. "detail": result.ack.detail,
  2434. "result_flags": result.ack.result_flags,
  2435. "state_hash16": result.ack.state_hash16,
  2436. }
  2437. )
  2438. return result
  2439. def _gate_jog(
  2440. session: NormalSession,
  2441. events: list[dict[str, Any]],
  2442. *,
  2443. phase: str,
  2444. axis: int,
  2445. raw_dir: int,
  2446. speed_code: int,
  2447. steps: int,
  2448. ) -> CommandResult:
  2449. request = build_motor_jog(
  2450. axis=axis,
  2451. raw_dir=raw_dir,
  2452. speed_code=speed_code,
  2453. steps=steps,
  2454. )
  2455. result = session.command(
  2456. request,
  2457. expected_command=0x35,
  2458. allowed_statuses=(StatusCode.OK,),
  2459. expected_detail=0,
  2460. )
  2461. events.append(
  2462. {
  2463. "phase": phase,
  2464. "request_hex": request.hex(),
  2465. "response_hex": result.raw_response.hex(),
  2466. "command": "JOG",
  2467. "axis": axis,
  2468. "raw_dir": raw_dir,
  2469. "speed_code": speed_code,
  2470. "steps": steps,
  2471. }
  2472. )
  2473. return result
  2474. def _gate_mark_closed(
  2475. session: NormalSession,
  2476. events: list[dict[str, Any]],
  2477. *,
  2478. axis: int,
  2479. close_dir: int,
  2480. ) -> CommandResult:
  2481. request = build_mark_closed(axis=axis, close_dir=close_dir)
  2482. result = session.command(
  2483. request,
  2484. expected_command=0x36,
  2485. allowed_statuses=(StatusCode.OK,),
  2486. expected_detail=0,
  2487. )
  2488. events.append(
  2489. {
  2490. "phase": f"mark-closed-{axis}",
  2491. "request_hex": request.hex(),
  2492. "response_hex": result.raw_response.hex(),
  2493. "command": "MARK_CLOSED",
  2494. "axis": axis,
  2495. "close_dir": close_dir,
  2496. }
  2497. )
  2498. return result
  2499. def _wait_for_idle(
  2500. session: NormalSession,
  2501. events: list[dict[str, Any]],
  2502. *,
  2503. phase: str,
  2504. sleep: Callable[[float], None],
  2505. max_polls: int = 100,
  2506. ) -> MotorStatusResult:
  2507. for index in range(max_polls):
  2508. result = _gate_motor_status(session, events, phase=f"{phase}-poll-{index}")
  2509. if result.status.busy_mask == 0:
  2510. return result
  2511. sleep(0.1)
  2512. raise TimeoutError(f"motor status remained busy during {phase}")
  2513. def _latest_axis_limit_state(events: list[TraceEvent], *, axis: int) -> dict[str, bool] | None:
  2514. if axis not in {0, 1}:
  2515. raise ValueError("limit Trace is available only for X/Y")
  2516. for event in reversed(events):
  2517. if event.event_type != TraceEventType.LIMIT_STATE:
  2518. continue
  2519. try:
  2520. decoded = decode_limit_trace_event(event)
  2521. except ValueError as exc:
  2522. raise RuntimeError(f"malformed combined LIMIT_STATE Trace: {exc}") from exc
  2523. return {
  2524. "fast": decoded.x_fast if axis == 0 else decoded.y_fast,
  2525. "active": decoded.x_active if axis == 0 else decoded.y_active,
  2526. "ready": decoded.x_ready if axis == 0 else decoded.y_ready,
  2527. }
  2528. return None
  2529. def _calibrate_axis_until_limit(
  2530. session: NormalSession,
  2531. events: list[dict[str, Any]],
  2532. *,
  2533. axis: int,
  2534. raw_dir: int,
  2535. sleep: Callable[[float], None],
  2536. confirm_startup_high: Callable[[int, int], None] | None = None,
  2537. ) -> MotorStatusResult:
  2538. _gate_motor_status(session, events, phase=f"calibrate-{axis}-startup")
  2539. limit_state = _latest_axis_limit_state(list(session.trace_events), axis=axis)
  2540. for poll in range(100):
  2541. if (
  2542. limit_state is not None
  2543. and limit_state["ready"]
  2544. and limit_state["fast"] == limit_state["active"]
  2545. ):
  2546. break
  2547. sleep(0.001)
  2548. _gate_motor_status(session, events, phase=f"calibrate-{axis}-limit-ready-{poll}")
  2549. limit_state = _latest_axis_limit_state(list(session.trace_events), axis=axis)
  2550. if (
  2551. limit_state is None
  2552. or not limit_state["ready"]
  2553. or limit_state["fast"] != limit_state["active"]
  2554. ):
  2555. raise RuntimeError(f"axis {axis} limit filter did not reach a stable confirmed level")
  2556. if limit_state["active"]:
  2557. if confirm_startup_high is None:
  2558. raise RuntimeError(f"axis {axis} startup-high requires operator confirmation")
  2559. confirm_startup_high(axis, raw_dir)
  2560. _gate_mark_closed(session, events, axis=axis, close_dir=raw_dir)
  2561. marked = _gate_motor_status(session, events, phase=f"calibrate-{axis}-startup-marked")
  2562. if (
  2563. marked.status.busy_mask != 0
  2564. or not (marked.status.position_valid_mask & (1 << axis))
  2565. or marked.status.current_xyz[axis] != 0
  2566. ):
  2567. raise RuntimeError(f"axis {axis} startup-high MARK_CLOSED did not establish CLOSED")
  2568. return marked
  2569. for segment in range(40):
  2570. _gate_jog(
  2571. session,
  2572. events,
  2573. phase=f"calibrate-{axis}-{segment}",
  2574. axis=axis,
  2575. raw_dir=raw_dir,
  2576. speed_code=0,
  2577. steps=80,
  2578. )
  2579. state = _wait_for_idle(
  2580. session,
  2581. events,
  2582. phase=f"calibrate-{axis}-{segment}",
  2583. sleep=sleep,
  2584. )
  2585. if state.status.position_valid_mask & (1 << axis):
  2586. _gate_mark_closed(session, events, axis=axis, close_dir=raw_dir)
  2587. marked = _gate_motor_status(session, events, phase=f"calibrate-{axis}-marked")
  2588. if marked.status.busy_mask != 0 or marked.status.current_xyz[axis] != 0:
  2589. raise RuntimeError(f"axis {axis} MARK_CLOSED did not preserve CLOSED")
  2590. return marked
  2591. raise RuntimeError(f"axis {axis} did not reach its limit within 3200 steps")
  2592. def _run_xy_calibration_then_jog(
  2593. session: NormalSession,
  2594. events: list[dict[str, Any]],
  2595. stages: list[dict[str, Any]],
  2596. observations: list[dict[str, Any]],
  2597. *,
  2598. x_close_dir: int,
  2599. y_close_dir: int,
  2600. sleep: Callable[[float], None],
  2601. operator_observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
  2602. ) -> None:
  2603. start = len(events)
  2604. def confirm_startup_high(axis: int, close_dir: int) -> None:
  2605. axis_label = "X" if axis == 0 else "Y"
  2606. _confirm_operator_observation_from_disabled(
  2607. session,
  2608. events,
  2609. observations,
  2610. observer=operator_observer,
  2611. stage=f"startup_high_mark_closed_{axis_label.lower()}",
  2612. context={
  2613. "axis": axis_label,
  2614. "close_dir": close_dir,
  2615. "limit_ready": True,
  2616. "limit_active": True,
  2617. "limit_closed_volts": 3.3,
  2618. },
  2619. required_confirmations=("limit_closed_high", "close_direction"),
  2620. )
  2621. _calibrate_axis_until_limit(
  2622. session,
  2623. events,
  2624. axis=0,
  2625. raw_dir=x_close_dir,
  2626. sleep=sleep,
  2627. confirm_startup_high=confirm_startup_high,
  2628. )
  2629. _calibrate_axis_until_limit(
  2630. session,
  2631. events,
  2632. axis=1,
  2633. raw_dir=y_close_dir,
  2634. sleep=sleep,
  2635. confirm_startup_high=confirm_startup_high,
  2636. )
  2637. calibrated = _gate_motor_status(session, events, phase="calibration-status")
  2638. if (
  2639. calibrated.status.position_valid_mask != 0x03
  2640. or calibrated.status.busy_mask != 0
  2641. or calibrated.status.current_xyz != (0, 0, 0xFF)
  2642. ):
  2643. raise RuntimeError("XY calibration did not establish both closed positions")
  2644. stages.append(_stage("direction_mapping", events=_events_since(events, start)))
  2645. start = len(events)
  2646. for axis, close_dir, name in (
  2647. (0, x_close_dir, "x_jog_motion"),
  2648. (1, y_close_dir, "y_jog_motion"),
  2649. ):
  2650. _gate_jog(
  2651. session,
  2652. events,
  2653. phase=f"jog-{axis}",
  2654. axis=axis,
  2655. raw_dir=1 - close_dir,
  2656. speed_code=2,
  2657. steps=20,
  2658. )
  2659. _wait_for_idle(session, events, phase=f"jog-{axis}", sleep=sleep)
  2660. _confirm_operator_observation_from_disabled(
  2661. session,
  2662. events,
  2663. observations,
  2664. observer=operator_observer,
  2665. stage=name,
  2666. context={"axis": axis, "speed_step_per_s": 100, "steps": 20},
  2667. )
  2668. _calibrate_axis_until_limit(
  2669. session,
  2670. events,
  2671. axis=axis,
  2672. raw_dir=close_dir,
  2673. sleep=sleep,
  2674. )
  2675. recalibrated = _gate_motor_status(session, events, phase="post-jog-calibration-status")
  2676. if (
  2677. recalibrated.status.position_valid_mask != 0x03
  2678. or recalibrated.status.busy_mask != 0
  2679. or recalibrated.status.current_xyz != (0, 0, 0xFF)
  2680. ):
  2681. raise RuntimeError("XY jog verification did not return both axes to closed positions")
  2682. stages.append(_stage("limit_jog", events=_events_since(events, start)))
  2683. def _run_xy_partial_scenarios(
  2684. session: NormalSession,
  2685. events: list[dict[str, Any]],
  2686. stages: list[dict[str, Any]],
  2687. *,
  2688. sleep: Callable[[float], None],
  2689. ) -> list[dict[str, str]]:
  2690. start = len(events)
  2691. def snapshot(
  2692. phase: str,
  2693. xyz: tuple[int, int, int],
  2694. expected_status: StatusCode,
  2695. expected_detail: int,
  2696. ) -> None:
  2697. result = _gate_snapshot(session, events, phase=phase, solenoid=0, xyz=xyz)
  2698. if result.ack.status != expected_status or result.ack.detail != expected_detail:
  2699. raise RuntimeError(f"{phase} did not return expected per-axis result")
  2700. snapshot("partial-y-open", (0, 100, 0), StatusCode.OK, 0x00)
  2701. y_open = _wait_for_idle(session, events, phase="partial-y-open", sleep=sleep)
  2702. if y_open.status.current_xyz != (0, 100, 0xFF):
  2703. raise RuntimeError("Y did not reach OPEN for X-accepted/Y-busy PARTIAL scenario")
  2704. snapshot("partial-y-close", (0, 0, 0), StatusCode.OK, 0x00)
  2705. snapshot("partial-accept-x-busy-y", (100, 100, 0), StatusCode.PARTIAL, 0x02)
  2706. first = _gate_motor_status(session, events, phase="partial-accept-x-busy-y-status")
  2707. if first.status.busy_mask != 0x03 or first.status.target_xyz != (100, 0, 0xFF):
  2708. raise RuntimeError("X-accepted/Y-busy PARTIAL changed the wrong targets")
  2709. first_idle = _wait_for_idle(
  2710. session,
  2711. events,
  2712. phase="partial-accept-x-busy-y",
  2713. sleep=sleep,
  2714. )
  2715. if first_idle.status.current_xyz != (100, 0, 0xFF):
  2716. raise RuntimeError("X-accepted/Y-busy PARTIAL did not finish at the expected endpoints")
  2717. snapshot("partial-x-close", (0, 0, 0), StatusCode.OK, 0x00)
  2718. snapshot("partial-accept-y-busy-x", (100, 100, 0), StatusCode.PARTIAL, 0x01)
  2719. second = _gate_motor_status(session, events, phase="partial-accept-y-busy-x-status")
  2720. if second.status.busy_mask != 0x03 or second.status.target_xyz != (0, 100, 0xFF):
  2721. raise RuntimeError("Y-accepted/X-busy PARTIAL changed the wrong targets")
  2722. second_idle = _wait_for_idle(
  2723. session,
  2724. events,
  2725. phase="partial-accept-y-busy-x",
  2726. sleep=sleep,
  2727. )
  2728. if second_idle.status.current_xyz != (0, 100, 0xFF):
  2729. raise RuntimeError("Y-accepted/X-busy PARTIAL did not finish at the expected endpoints")
  2730. snapshot("partial-restore-close", (0, 0, 0), StatusCode.OK, 0x00)
  2731. restored = _wait_for_idle(session, events, phase="partial-restore-close", sleep=sleep)
  2732. if restored.status.current_xyz != (0, 0, 0xFF):
  2733. raise RuntimeError("XY PARTIAL scenarios did not restore both axes to CLOSED")
  2734. scenarios = [
  2735. {"accepted_axis": "X", "busy_axis": "Y", "result": "PARTIAL"},
  2736. {"accepted_axis": "Y", "busy_axis": "X", "result": "PARTIAL"},
  2737. ]
  2738. stages.append(_stage("xy_partial", events=_events_since(events, start), scenarios=scenarios))
  2739. return scenarios
  2740. def _start_watchdog_motion(
  2741. session: NormalSession,
  2742. events: list[dict[str, Any]],
  2743. *,
  2744. y_close_dir: int,
  2745. ) -> MotorStatusResult:
  2746. _gate_jog(
  2747. session,
  2748. events,
  2749. phase="watchdog-start",
  2750. axis=1,
  2751. raw_dir=1 - int(y_close_dir),
  2752. speed_code=0,
  2753. steps=160,
  2754. )
  2755. started = _gate_motor_status(session, events, phase="watchdog-start-status")
  2756. if not (started.status.busy_mask & 0x02):
  2757. raise RuntimeError("watchdog Y motion did not enter busy state")
  2758. return started
  2759. def _run_solenoid_pulse(
  2760. session: NormalSession,
  2761. events: list[dict[str, Any]],
  2762. *,
  2763. sleep: Callable[[float], None],
  2764. ) -> list[CommandResult]:
  2765. results = [
  2766. _gate_snapshot(session, events, phase="solenoid-off-1", solenoid=0, xyz=(0, 0, 0))
  2767. ]
  2768. results.append(
  2769. _gate_snapshot(session, events, phase="solenoid-on", solenoid=100, xyz=(0, 0, 0))
  2770. )
  2771. try:
  2772. sleep(0.25)
  2773. finally:
  2774. results.append(
  2775. _gate_snapshot(session, events, phase="solenoid-off-2", solenoid=0, xyz=(0, 0, 0))
  2776. )
  2777. return results
  2778. def _run_program_with_uart_collection(
  2779. session: NormalSession,
  2780. *,
  2781. programmer: Callable[[argparse.Namespace], dict[str, Any]],
  2782. program_args: argparse.Namespace,
  2783. ) -> dict[str, Any]:
  2784. """Capture UART bytes with the session pump while PROGRAM_SRAM runs once."""
  2785. result: dict[str, Any] = {}
  2786. failure: list[BaseException] = []
  2787. session.start_reader(
  2788. persistent=True,
  2789. capture_only=True,
  2790. allow_startup_preamble=True,
  2791. )
  2792. def run_programmer() -> None:
  2793. try:
  2794. value = programmer(program_args)
  2795. if not isinstance(value, dict):
  2796. raise TypeError("PROGRAM_SRAM runner must return an object")
  2797. result.update(value)
  2798. except BaseException as exc: # Preserve the programmer's original exception in the caller.
  2799. failure.append(exc)
  2800. worker = threading.Thread(
  2801. target=run_programmer,
  2802. name="prod2u-program-sram",
  2803. daemon=True,
  2804. )
  2805. worker.start()
  2806. while worker.is_alive():
  2807. worker.join(timeout=0.001)
  2808. if failure:
  2809. raise failure[0]
  2810. if session.reader_error is not None:
  2811. raise RuntimeError(
  2812. f"UART capture reader failed: {type(session.reader_error).__name__}:"
  2813. f"{session.reader_error}"
  2814. )
  2815. session._run_on_pump(
  2816. session._capture_available_on_pump,
  2817. pre_dispatch_quiet=False,
  2818. activate_parser=False,
  2819. )
  2820. if session.reader_error is not None:
  2821. raise RuntimeError(
  2822. f"UART capture reader failed: {type(session.reader_error).__name__}:"
  2823. f"{session.reader_error}"
  2824. )
  2825. return result
  2826. def _program_failure_disable(session: NormalSession) -> dict[str, Any]:
  2827. events: list[dict[str, Any]] = []
  2828. try:
  2829. result = _gate_safe_disable(
  2830. session,
  2831. events,
  2832. phase="program-failure-disable",
  2833. allow_boot_preamble=True,
  2834. )
  2835. return {
  2836. "attempted": True,
  2837. "confirmed": True,
  2838. "state_hash16": result.ack.state_hash16,
  2839. "events": events,
  2840. }
  2841. except Exception as exc:
  2842. _append_last_exchange(events, session, phase="program-failure-disable")
  2843. _append_best_effort_disable(events, session, phase="program-failure-disable")
  2844. return {
  2845. "attempted": True,
  2846. "confirmed": False,
  2847. "error": f"{type(exc).__name__}:{exc}",
  2848. "events": events,
  2849. }
  2850. def _publish_program_failure_receipt(
  2851. *,
  2852. args: argparse.Namespace,
  2853. output_dir: Path,
  2854. commit: str,
  2855. build_id: str,
  2856. session: NormalSession,
  2857. stages: list[dict[str, Any]],
  2858. serial_events: list[dict[str, Any]],
  2859. programmer_metadata: Mapping[str, Any],
  2860. failure_disable: Mapping[str, Any],
  2861. failure_reasons: list[str],
  2862. ) -> dict[str, Any]:
  2863. for row in failure_disable.get("events", []):
  2864. if isinstance(row, Mapping):
  2865. serial_events.append(dict(row))
  2866. attempted = programmer_metadata.get("attempt_count") == 1
  2867. failure_stages = list(stages)
  2868. failure_stages.append(
  2869. _stage(
  2870. "program_sram",
  2871. status="fail" if attempted else "not_run",
  2872. **dict(programmer_metadata),
  2873. )
  2874. )
  2875. failure_stages.append(
  2876. _stage(
  2877. "initial_disable",
  2878. status="pass" if failure_disable.get("confirmed") is True else "fail",
  2879. events=[dict(row) for row in failure_disable.get("events", []) if isinstance(row, Mapping)],
  2880. )
  2881. )
  2882. failure_stages = _complete_failure_stages(
  2883. failure_stages,
  2884. reason=";".join(failure_reasons),
  2885. )
  2886. confirmed = failure_disable.get("confirmed") is True
  2887. state_hash = failure_disable.get("state_hash16")
  2888. final_disable = {
  2889. "attempted": failure_disable.get("attempted") is True,
  2890. "acknowledged": confirmed,
  2891. "state_hash16": f"{int(state_hash):04X}" if confirmed and isinstance(state_hash, int) else "0000",
  2892. "ptc_percent": 0,
  2893. "fan_percent": [30, 30, 30, 30],
  2894. "solenoid_percent": 0,
  2895. "step_all_low": False,
  2896. "en_n_high": False,
  2897. }
  2898. return _finalize_failed_hardware_session_receipt(
  2899. output_dir=output_dir,
  2900. board_id=str(args.board_id),
  2901. commit=commit,
  2902. build_id=build_id,
  2903. build_info_path=Path(args.build_info),
  2904. bitstream_path=Path(args.bitstream),
  2905. td_receipt_path=Path(args.td_receipt),
  2906. programmer_metadata=programmer_metadata,
  2907. serial_events=serial_events,
  2908. rx_journal=session.rx_journal,
  2909. trace_events=list(session.trace_events),
  2910. stages=failure_stages,
  2911. failure_reasons=failure_reasons,
  2912. final_disable=final_disable,
  2913. x_close_dir=int(args.x_close_dir),
  2914. y_close_dir=int(args.y_close_dir),
  2915. )
  2916. def _gate_preflight_failures(args: argparse.Namespace) -> list[str]:
  2917. required = {
  2918. "confirm_ptc_load_disabled": "ptc_load_not_disabled",
  2919. "confirm_mechanical_travel_safe": "mechanical_travel_not_confirmed",
  2920. "confirm_p5_active_high_closes_intake": "p5_polarity_not_confirmed",
  2921. "confirm_ls1_x_closed_high": "ls1_x_closed_high_not_confirmed",
  2922. "confirm_ls2_y_closed_high": "ls2_y_closed_high_not_confirmed",
  2923. }
  2924. failures = [failure for field, failure in required.items() if getattr(args, field, False) is not True]
  2925. for axis in ("x", "y"):
  2926. value = getattr(args, f"{axis}_close_dir", None)
  2927. if isinstance(value, bool) or value not in (0, 1):
  2928. failures.append(f"{axis}_close_dir_invalid")
  2929. return sorted(set(failures))
  2930. def _events_since(events: list[dict[str, Any]], start: int) -> list[dict[str, Any]]:
  2931. return [dict(event) for event in events[start:]]
  2932. def run_normal_actuator_trace_gate(
  2933. args: argparse.Namespace,
  2934. *,
  2935. enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
  2936. program_runner: Callable[..., dict[str, Any]] = run_program_only,
  2937. endpoint_factory: Callable[[], Any] = open_com5,
  2938. sleep: Callable[[float], None] = time.sleep,
  2939. monotonic: Callable[[], float] = time.monotonic,
  2940. operator_observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None = _console_operator_observer,
  2941. ) -> dict[str, Any]:
  2942. """Run one Normal v3 SRAM hardware session with strict Trace evidence."""
  2943. input_failures, build_info = _program_input_failures(args)
  2944. evidence_failures, package_info, _ = _gate_evidence_input_failures(
  2945. args,
  2946. build_info=build_info,
  2947. )
  2948. input_failures.extend(evidence_failures)
  2949. input_failures.extend(_gate_preflight_failures(args))
  2950. if operator_observer is None or (
  2951. operator_observer is _console_operator_observer and not sys.stdin.isatty()
  2952. ):
  2953. input_failures.append("operator_observer_unavailable")
  2954. input_failures = sorted(set(input_failures))
  2955. if input_failures:
  2956. return _gate_result(
  2957. status="fail_preflight",
  2958. args=args,
  2959. failures=input_failures,
  2960. hardware_enumerated=False,
  2961. serial_opened=False,
  2962. program_sram_attempted=False,
  2963. attempt_count=0,
  2964. retry_count=0,
  2965. )
  2966. assert build_info is not None
  2967. assert package_info is not None
  2968. build_id = str(build_info["build_id"])
  2969. bitstream_sha256 = str(build_info["bitstream_sha256"])
  2970. commit = str(package_info["commit"])
  2971. plan = hardware_stage_plan()
  2972. preflight = run_preflight(enumerator=enumerator)
  2973. if preflight.get("status") != "pass":
  2974. return _gate_result(
  2975. status="fail_preflight",
  2976. args=args,
  2977. failures=[str(value) for value in preflight.get("failures", ["hardware_preflight_failed"])],
  2978. hardware_enumerated=True,
  2979. serial_opened=False,
  2980. program_sram_attempted=False,
  2981. attempt_count=0,
  2982. retry_count=0,
  2983. )
  2984. output_dir = Path(args.output_dir)
  2985. output_dir.mkdir(parents=True, exist_ok=False)
  2986. stages: list[dict[str, Any]] = [
  2987. _stage(
  2988. "preflight",
  2989. com5_present=True,
  2990. al_link_present=True,
  2991. ptc_load_disabled=True,
  2992. mechanical_travel_safe=True,
  2993. p5_active_high_closes_intake=True,
  2994. ls1_x_closed_high=True,
  2995. ls2_y_closed_high=True,
  2996. z_hardware="not_connected_protocol_reserved",
  2997. planned_stages=plan["stages"],
  2998. )
  2999. ]
  3000. try:
  3001. endpoint = endpoint_factory()
  3002. except Exception as exc:
  3003. return _gate_result(
  3004. status="fail_com5_open",
  3005. args=args,
  3006. failures=[f"{type(exc).__name__}:{exc}"],
  3007. hardware_enumerated=True,
  3008. serial_opened=False,
  3009. program_sram_attempted=False,
  3010. attempt_count=0,
  3011. retry_count=0,
  3012. )
  3013. session = NormalSession(
  3014. endpoint,
  3015. monotonic=monotonic,
  3016. sleep=sleep,
  3017. expected_build_id=int(build_id, 16),
  3018. expected_capability_flags=CAPABILITY_FLAGS,
  3019. )
  3020. preprogram_uart_noise = session.drain_unparsed(timeout_seconds=0.1)
  3021. events: list[dict[str, Any]] = []
  3022. if preprogram_uart_noise:
  3023. events.append(
  3024. {
  3025. "phase": "preprogram-rx-drain",
  3026. "request_hex": "",
  3027. "response_hex": preprogram_uart_noise.hex(),
  3028. "command": "PASSIVE_RX_DRAIN",
  3029. }
  3030. )
  3031. program_args = argparse.Namespace(
  3032. bitstream=Path(args.bitstream),
  3033. build_info=Path(args.build_info),
  3034. output_dir=output_dir / "program-sram",
  3035. td_root=Path(getattr(args, "td_root", DEFAULT_TD_ROOT)),
  3036. run_id=str(getattr(args, "run_id", "prod2u-p4-normal-v3-gate")),
  3037. board_id=str(args.board_id),
  3038. )
  3039. try:
  3040. program_result = _run_program_with_uart_collection(
  3041. session,
  3042. programmer=program_runner,
  3043. program_args=program_args,
  3044. )
  3045. except Exception as exc:
  3046. failure_disable = _program_failure_disable(session)
  3047. programmer_metadata = {
  3048. "operation": "PROGRAM_SRAM",
  3049. "speed_hz": 200000,
  3050. "program_sram_attempted": True,
  3051. "attempt_count": 1,
  3052. "retry_count": 0,
  3053. "flash_attempted": False,
  3054. }
  3055. failure_text = f"{type(exc).__name__}:{exc}"
  3056. try:
  3057. failure_receipt = _publish_program_failure_receipt(
  3058. args=args,
  3059. output_dir=output_dir,
  3060. commit=commit,
  3061. build_id=build_id,
  3062. session=session,
  3063. stages=stages,
  3064. serial_events=events,
  3065. programmer_metadata=programmer_metadata,
  3066. failure_disable=failure_disable,
  3067. failure_reasons=[failure_text],
  3068. )
  3069. finally:
  3070. try:
  3071. session.close()
  3072. except Exception:
  3073. pass
  3074. return {
  3075. **_gate_result(
  3076. status="fail_program_sram",
  3077. args=args,
  3078. failures=[failure_text],
  3079. hardware_enumerated=True,
  3080. serial_opened=True,
  3081. program_sram_attempted=True,
  3082. attempt_count=1,
  3083. retry_count=0,
  3084. ),
  3085. "program_failure_disable": failure_disable,
  3086. "hardware_session_receipt": failure_receipt,
  3087. "receipt": str(output_dir / "hardware-session-receipt.json"),
  3088. }
  3089. program_status = str(program_result.get("status", "fail_programmer_contract"))
  3090. programmer_metadata = {
  3091. field: program_result.get(field)
  3092. for field in PROGRAMMER_METADATA_CONTRACT
  3093. }
  3094. operation = programmer_metadata["operation"]
  3095. speed_hz = programmer_metadata["speed_hz"]
  3096. attempt_count = programmer_metadata["attempt_count"]
  3097. retry_count = programmer_metadata["retry_count"]
  3098. attempted_value = program_result.get("program_sram_attempted")
  3099. attempted = attempted_value is True
  3100. may_have_attempted = attempted_value is not False or (
  3101. type(attempt_count) is int and attempt_count > 0
  3102. )
  3103. metadata_failures = (
  3104. _programmer_metadata_failures(program_result)
  3105. if program_status == "pass"
  3106. else []
  3107. )
  3108. if metadata_failures:
  3109. failure_disable = _program_failure_disable(session)
  3110. try:
  3111. session.close()
  3112. except Exception:
  3113. pass
  3114. return {
  3115. **_gate_result(
  3116. status="fail_programmer_contract",
  3117. args=args,
  3118. failures=metadata_failures,
  3119. hardware_enumerated=True,
  3120. serial_opened=True,
  3121. program_sram_attempted=programmer_metadata["program_sram_attempted"],
  3122. operation=operation,
  3123. speed_hz=speed_hz,
  3124. attempt_count=attempt_count,
  3125. retry_count=retry_count,
  3126. flash_attempted=programmer_metadata["flash_attempted"],
  3127. ),
  3128. "program_failure_disable": failure_disable,
  3129. }
  3130. if program_status != "pass":
  3131. failure_disable = (
  3132. _program_failure_disable(session)
  3133. if may_have_attempted
  3134. else {"attempted": False, "confirmed": False, "reason": "program_sram_not_attempted"}
  3135. )
  3136. try:
  3137. session.close()
  3138. except Exception:
  3139. pass
  3140. failures = [str(value) for value in program_result.get("failures", [])]
  3141. if not failures:
  3142. failures = [f"program_result_status:{program_status}"]
  3143. failure_receipt = None
  3144. if may_have_attempted:
  3145. failure_metadata = {
  3146. "operation": "PROGRAM_SRAM",
  3147. "speed_hz": 200000,
  3148. "program_sram_attempted": True,
  3149. "attempt_count": 1,
  3150. "retry_count": 0,
  3151. "flash_attempted": False,
  3152. }
  3153. failure_receipt = _publish_program_failure_receipt(
  3154. args=args,
  3155. output_dir=output_dir,
  3156. commit=commit,
  3157. build_id=build_id,
  3158. session=session,
  3159. stages=stages,
  3160. serial_events=events,
  3161. programmer_metadata=failure_metadata,
  3162. failure_disable=failure_disable,
  3163. failure_reasons=failures,
  3164. )
  3165. return {
  3166. **_gate_result(
  3167. status="fail_program_sram",
  3168. args=args,
  3169. failures=failures,
  3170. hardware_enumerated=True,
  3171. serial_opened=True,
  3172. program_sram_attempted=may_have_attempted,
  3173. operation=operation,
  3174. speed_hz=speed_hz,
  3175. attempt_count=attempt_count,
  3176. retry_count=retry_count,
  3177. flash_attempted=programmer_metadata["flash_attempted"],
  3178. ),
  3179. "program_failure_disable": failure_disable,
  3180. "hardware_session_receipt": failure_receipt,
  3181. **(
  3182. {"receipt": str(output_dir / "hardware-session-receipt.json")}
  3183. if failure_receipt is not None
  3184. else {}
  3185. ),
  3186. }
  3187. stages.append(
  3188. _stage(
  3189. "program_sram",
  3190. **programmer_metadata,
  3191. )
  3192. )
  3193. observations: list[dict[str, Any]] = []
  3194. final_disable_confirmed = False
  3195. watchdog_evidence: dict[str, Any] = {
  3196. "status": "not_run",
  3197. "timeout_ms": 5000,
  3198. "timeline": [],
  3199. }
  3200. partial_scenarios: list[dict[str, str]] = []
  3201. open_to_close_trace_events: list[TraceEvent] = []
  3202. try:
  3203. start = len(events)
  3204. initial_disable = _gate_safe_disable(
  3205. session,
  3206. events,
  3207. phase="initial-disable",
  3208. allow_boot_preamble=True,
  3209. )
  3210. stages.append(_stage("initial_disable", events=_events_since(events, start)))
  3211. boot_frames = [
  3212. frame for frame in initial_disable.frames if frame.frame_type == FrameType.BOOT_BUILD_ID
  3213. ]
  3214. if len(boot_frames) != 1:
  3215. raise RuntimeError("expected exactly one BOOT_BUILD_ID after PROGRAM_SRAM")
  3216. boot = decode_boot_build_id(boot_frames[0])
  3217. if boot.build_id != int(build_id, 16) or boot.capability_flags != CAPABILITY_FLAGS:
  3218. raise RuntimeError("BOOT_BUILD_ID identity mismatch")
  3219. stages.append(
  3220. _stage(
  3221. "boot_identity",
  3222. build_id=build_id,
  3223. capability=CAPABILITY_FLAGS,
  3224. announcement_count=1,
  3225. )
  3226. )
  3227. start = len(events)
  3228. baseline = _gate_status(session, events, phase="baseline-status")
  3229. if not (baseline.ack.detail & 0x01) or baseline.ack.detail & 0x02:
  3230. raise RuntimeError("baseline GET_STATUS did not report DISABLE safe state")
  3231. if baseline.ack.state_hash16 != SAFE_STATE_HASH16:
  3232. raise RuntimeError("baseline safe state hash mismatch")
  3233. stages.append(_stage("baseline_status", events=_events_since(events, start)))
  3234. _run_xy_calibration_then_jog(
  3235. session,
  3236. events,
  3237. stages,
  3238. observations,
  3239. x_close_dir=int(args.x_close_dir),
  3240. y_close_dir=int(args.y_close_dir),
  3241. sleep=sleep,
  3242. operator_observer=operator_observer,
  3243. )
  3244. start = len(events)
  3245. open_ack = _gate_snapshot(
  3246. session,
  3247. events,
  3248. phase="open-xy",
  3249. solenoid=0,
  3250. xyz=(100, 100, 0),
  3251. )
  3252. if open_ack.ack.status != StatusCode.OK or open_ack.ack.detail != 0:
  3253. raise RuntimeError("XY open did not accept protocol-reserved Z as a no-op")
  3254. busy_status = _gate_motor_status(session, events, phase="open-busy")
  3255. if (
  3256. busy_status.status.busy_mask != 0x03
  3257. or busy_status.status.position_valid_mask != 0x03
  3258. or busy_status.status.current_xyz[:2] != (0xFE, 0xFE)
  3259. or busy_status.status.target_xyz != (100, 100, 0xFF)
  3260. ):
  3261. raise RuntimeError("XY open did not start both connected axes")
  3262. partial_ack = _gate_snapshot(
  3263. session,
  3264. events,
  3265. phase="busy-idempotent-open",
  3266. solenoid=0,
  3267. xyz=(100, 100, 0),
  3268. )
  3269. if partial_ack.ack.status != StatusCode.OK or partial_ack.ack.detail != 0:
  3270. raise RuntimeError("idempotent XY OPEN did not keep Z as an accepted no-op")
  3271. after_partial = _gate_motor_status(session, events, phase="busy-idempotent-open-status")
  3272. if after_partial.status.busy_mask != 0x03 or after_partial.status.target_xyz != (100, 100, 0xFF):
  3273. raise RuntimeError("idempotent XY OPEN changed active motion")
  3274. stages.append(
  3275. _stage(
  3276. "idempotent_motion",
  3277. events=[event for event in _events_since(events, start) if event["phase"].startswith("busy-idempotent")],
  3278. )
  3279. )
  3280. reverse_start = len(events)
  3281. reverse_trace_start = len(session.trace_events)
  3282. reverse_ack = _gate_snapshot(
  3283. session,
  3284. events,
  3285. phase="opening-reverse-close",
  3286. solenoid=0,
  3287. xyz=(0, 0, 0),
  3288. )
  3289. if reverse_ack.ack.status != StatusCode.OK or reverse_ack.ack.detail != 0:
  3290. raise RuntimeError("OPENING-to-CLOSE did not accept both connected axes")
  3291. reversing = _gate_motor_status(session, events, phase="opening-reverse-close-status")
  3292. if reversing.status.busy_mask != 0x03 or reversing.status.target_xyz != (0, 0, 0xFF):
  3293. raise RuntimeError("OPENING-to-CLOSE did not preserve a closing target")
  3294. reversed_closed = _wait_for_idle(
  3295. session,
  3296. events,
  3297. phase="opening-reverse-close",
  3298. sleep=sleep,
  3299. )
  3300. if reversed_closed.status.current_xyz != (0, 0, 0xFF):
  3301. raise RuntimeError("OPENING-to-CLOSE did not return both axes to CLOSED")
  3302. open_to_close_trace_events = list(session.trace_events[reverse_trace_start:])
  3303. stages.append(_stage("open_to_close", events=_events_since(events, reverse_start)))
  3304. partial_scenarios = _run_xy_partial_scenarios(
  3305. session,
  3306. events,
  3307. stages,
  3308. sleep=sleep,
  3309. )
  3310. standard_start = len(events)
  3311. standard_open_ack = _gate_snapshot(
  3312. session,
  3313. events,
  3314. phase="standard-open-xy",
  3315. solenoid=0,
  3316. xyz=(100, 100, 0),
  3317. )
  3318. if standard_open_ack.ack.status != StatusCode.OK or standard_open_ack.ack.detail != 0:
  3319. raise RuntimeError("standard XY open did not keep Z as an accepted no-op")
  3320. opened = _wait_for_idle(session, events, phase="standard-open-xy", sleep=sleep)
  3321. if opened.status.current_xyz != (100, 100, 0xFF):
  3322. raise RuntimeError("XY open did not complete")
  3323. close_ack = _gate_snapshot(
  3324. session,
  3325. events,
  3326. phase="close-xy",
  3327. solenoid=0,
  3328. xyz=(0, 0, 0),
  3329. )
  3330. if close_ack.ack.status != StatusCode.OK or close_ack.ack.detail != 0:
  3331. raise RuntimeError("XY close did not keep Z as an accepted no-op")
  3332. rejected_open_ack = _gate_snapshot(
  3333. session,
  3334. events,
  3335. phase="closing-reject-open",
  3336. solenoid=0,
  3337. xyz=(100, 100, 0),
  3338. )
  3339. if rejected_open_ack.ack.status != StatusCode.PARTIAL or rejected_open_ack.ack.detail != 0x03:
  3340. raise RuntimeError("CLOSING-to-OPEN did not report both XY axes busy")
  3341. after_rejected_open = _gate_motor_status(session, events, phase="closing-reject-open-status")
  3342. if (
  3343. after_rejected_open.status.busy_mask != 0x03
  3344. or after_rejected_open.status.current_xyz[:2] != (0xFE, 0xFE)
  3345. or after_rejected_open.status.target_xyz != (0, 0, 0xFF)
  3346. ):
  3347. raise RuntimeError("rejected CLOSING-to-OPEN changed active XY close motion")
  3348. closed = _wait_for_idle(session, events, phase="close-xy", sleep=sleep)
  3349. if closed.status.current_xyz != (0, 0, 0xFF):
  3350. raise RuntimeError("XY close did not complete")
  3351. _confirm_operator_observation_from_disabled(
  3352. session,
  3353. events,
  3354. observations,
  3355. observer=operator_observer,
  3356. stage="xy_open_close",
  3357. context={"open_target": [100, 100, 0], "closed_position": [0, 0, 255]},
  3358. )
  3359. stages.append(_stage("standard_motion", events=_events_since(events, standard_start)))
  3360. start = len(events)
  3361. _start_watchdog_motion(
  3362. session,
  3363. events,
  3364. y_close_dir=int(args.y_close_dir),
  3365. )
  3366. for event in events[start:]:
  3367. if event.get("phase") in {"watchdog-start", "watchdog-start-status"}:
  3368. event["elapsed_ms"] = 0
  3369. before_watchdog = monotonic()
  3370. sleep(1.0)
  3371. refreshed = _gate_motor_status(session, events, phase="watchdog-refresh")
  3372. refresh_ms = int(round((monotonic() - before_watchdog) * 1000))
  3373. events[-1]["elapsed_ms"] = refresh_ms
  3374. if not (refreshed.status.busy_mask & 0x02):
  3375. raise RuntimeError("watchdog refresh did not observe active Y motion")
  3376. sleep(5.1)
  3377. elapsed_ms = int(round((monotonic() - before_watchdog) * 1000))
  3378. watchdog_motor = _gate_motor_status(session, events, phase="watchdog-status")
  3379. watchdog_ack = _gate_status(session, events, phase="watchdog-get-status")
  3380. for event in events[start:]:
  3381. if event.get("phase") in {"watchdog-status", "watchdog-get-status"}:
  3382. event["elapsed_ms"] = elapsed_ms
  3383. if (
  3384. elapsed_ms < 4900
  3385. or not (watchdog_motor.status.position_valid_mask & 0x02)
  3386. or watchdog_motor.status.current_xyz[1] != 0xFE
  3387. or (watchdog_motor.status.flags & 0x0E) != 0x0C
  3388. or not (watchdog_ack.ack.detail & 0x02)
  3389. or watchdog_ack.ack.state_hash16 != SAFE_STATE_HASH16
  3390. ):
  3391. raise RuntimeError("watchdog safe-state verification failed")
  3392. _confirm_operator_observation_from_disabled(
  3393. session,
  3394. events,
  3395. observations,
  3396. observer=operator_observer,
  3397. stage="watchdog_safe_state",
  3398. context={"observed_delay_ms": elapsed_ms},
  3399. required_confirmations=("step_all_low", "en_n_high"),
  3400. )
  3401. stages.append(
  3402. _stage("watchdog", events=_events_since(events, start), observed_delay_ms=elapsed_ms)
  3403. )
  3404. watchdog_evidence = {
  3405. "status": "pass",
  3406. "timeout_ms": 5000,
  3407. "timeline": [
  3408. {"event": "armed", "elapsed_ms": 0},
  3409. {"event": "motor_status_refresh", "elapsed_ms": refresh_ms},
  3410. {"event": "expired", "elapsed_ms": elapsed_ms},
  3411. {"event": "safe_state_confirmed", "elapsed_ms": elapsed_ms},
  3412. ],
  3413. }
  3414. start = len(events)
  3415. final_disable = _gate_safe_disable(session, events, phase="final-disable")
  3416. final_motor = _gate_motor_status(session, events, phase="final-motor-status")
  3417. if (
  3418. final_disable.ack.state_hash16 != SAFE_STATE_HASH16
  3419. or final_motor.status.busy_mask != 0
  3420. or not (final_motor.status.flags & 0x04)
  3421. ):
  3422. raise RuntimeError("final DISABLE safe state verification failed")
  3423. final_disable_confirmed = True
  3424. _confirm_operator_observation(
  3425. operator_observer,
  3426. observations,
  3427. stage="final_disable_safe_state",
  3428. context={"state_hash16": final_disable.ack.state_hash16},
  3429. required_confirmations=("step_all_low", "en_n_high"),
  3430. )
  3431. final_quiet_frames, final_quiet_raw = session.read_passive_frames(
  3432. timeout_seconds=session.max_quiet_drain_seconds
  3433. )
  3434. if final_quiet_raw:
  3435. events.append(
  3436. {
  3437. "phase": "final-quiet-drain",
  3438. "request_hex": "",
  3439. "response_hex": final_quiet_raw.hex(),
  3440. "command": "PASSIVE_TRACE_DRAIN",
  3441. }
  3442. )
  3443. stages.append(
  3444. _stage(
  3445. "final_disable",
  3446. events=_events_since(events, start),
  3447. operator_observations=observations,
  3448. )
  3449. )
  3450. except BaseException as exc:
  3451. exchange = session.last_exchange or {}
  3452. if not exchange.get("request_hex"):
  3453. failed_phase = "final-quiet-drain"
  3454. elif not any(row.get("request_hex") for row in events) and int(
  3455. exchange.get("command", -1)
  3456. ) == int(CommandId.DISABLE):
  3457. failed_phase = "initial-disable"
  3458. else:
  3459. failed_phase = "failed-command"
  3460. _append_last_exchange(events, session, phase=failed_phase)
  3461. _append_best_effort_disable(events, session, phase="exception-disable")
  3462. if not final_disable_confirmed and not session.disable_attempted:
  3463. try:
  3464. _gate_safe_disable(session, events, phase="exception-disable")
  3465. except Exception as disable_exc:
  3466. _append_last_exchange(events, session, phase="exception-disable")
  3467. events.append(
  3468. {
  3469. "phase": "exception-disable",
  3470. "error": f"{type(disable_exc).__name__}:{disable_exc}",
  3471. }
  3472. )
  3473. failure_text = f"{type(exc).__name__}:{exc}"
  3474. failure_stages = _complete_failure_stages(stages, reason=failure_text)
  3475. failure_receipt: dict[str, Any] | None = None
  3476. try:
  3477. failure_receipt = _finalize_failed_hardware_session_receipt(
  3478. output_dir=output_dir,
  3479. board_id=str(args.board_id),
  3480. commit=commit,
  3481. build_id=build_id,
  3482. build_info_path=Path(args.build_info),
  3483. bitstream_path=Path(args.bitstream),
  3484. td_receipt_path=Path(args.td_receipt),
  3485. programmer_metadata=programmer_metadata,
  3486. serial_events=events,
  3487. rx_journal=session.rx_journal,
  3488. trace_events=list(session.trace_events),
  3489. stages=failure_stages,
  3490. failure_reasons=[failure_text],
  3491. final_disable={
  3492. "attempted": True,
  3493. "acknowledged": False,
  3494. "state_hash16": "0000",
  3495. "ptc_percent": 0,
  3496. "fan_percent": [30, 30, 30, 30],
  3497. "solenoid_percent": 0,
  3498. "step_all_low": False,
  3499. "en_n_high": False,
  3500. },
  3501. x_close_dir=int(args.x_close_dir),
  3502. y_close_dir=int(args.y_close_dir),
  3503. )
  3504. except Exception as receipt_exc:
  3505. failure_text = (
  3506. f"{failure_text};failure_receipt:{type(receipt_exc).__name__}:{receipt_exc}"
  3507. )
  3508. try:
  3509. session.close()
  3510. except Exception:
  3511. pass
  3512. return {
  3513. **_gate_result(
  3514. status="fail_host_uart_gate",
  3515. args=args,
  3516. failures=[failure_text],
  3517. hardware_enumerated=True,
  3518. serial_opened=True,
  3519. program_sram_attempted=attempted,
  3520. operation=operation,
  3521. speed_hz=speed_hz,
  3522. attempt_count=attempt_count,
  3523. retry_count=retry_count,
  3524. flash_attempted=programmer_metadata["flash_attempted"],
  3525. ),
  3526. "stages": failure_stages,
  3527. "serial_events": events,
  3528. "hardware_session_receipt": failure_receipt,
  3529. }
  3530. finally:
  3531. try:
  3532. session.close()
  3533. except Exception:
  3534. pass
  3535. trace_summary = _trace_receipt_summary(list(session.trace_events))
  3536. stages.append(
  3537. _stage(
  3538. "trace_integrity",
  3539. status=str(trace_summary["status"]),
  3540. **{key: value for key, value in trace_summary.items() if key != "status"},
  3541. )
  3542. )
  3543. register_checkpoint = {
  3544. "baseline": {
  3545. "detail": baseline.ack.detail,
  3546. "state_hash16": f"{baseline.ack.state_hash16:04X}",
  3547. },
  3548. "final_disable": {
  3549. "detail": final_disable.ack.detail,
  3550. "state_hash16": f"{final_disable.ack.state_hash16:04X}",
  3551. },
  3552. "final_motor": {
  3553. "flags": final_motor.status.flags,
  3554. "position_valid_mask": final_motor.status.position_valid_mask,
  3555. "busy_mask": final_motor.status.busy_mask,
  3556. "current_xyz": list(final_motor.status.current_xyz),
  3557. "target_xyz": list(final_motor.status.target_xyz),
  3558. "fault_mask": final_motor.status.fault_mask,
  3559. },
  3560. }
  3561. stages.append(_stage("register_checkpoint", checkpoint=register_checkpoint))
  3562. partial = {
  3563. "status": "pass",
  3564. "scenarios": partial_scenarios,
  3565. }
  3566. final_disable_evidence = {
  3567. "attempted": True,
  3568. "acknowledged": final_disable_confirmed,
  3569. "state_hash16": f"{final_disable.ack.state_hash16:04X}",
  3570. "ptc_percent": 0,
  3571. "fan_percent": [30, 30, 30, 30],
  3572. "solenoid_percent": 0,
  3573. "step_all_low": True,
  3574. "en_n_high": True,
  3575. }
  3576. try:
  3577. axis_checks = {
  3578. "mark_closed": True,
  3579. "jog_away": True,
  3580. "jog_to_limit": True,
  3581. "standard_open_close": True,
  3582. }
  3583. axes = {
  3584. "x": _axis_evidence_from_trace(
  3585. list(session.trace_events),
  3586. axis_label="X",
  3587. close_dir=int(args.x_close_dir),
  3588. checks=axis_checks,
  3589. open_to_close_events=open_to_close_trace_events,
  3590. ),
  3591. "y": _axis_evidence_from_trace(
  3592. list(session.trace_events),
  3593. axis_label="Y",
  3594. close_dir=int(args.y_close_dir),
  3595. checks=axis_checks,
  3596. open_to_close_events=open_to_close_trace_events,
  3597. ),
  3598. }
  3599. receipt = _finalize_hardware_session_receipt(
  3600. output_dir=output_dir,
  3601. board_id=str(args.board_id),
  3602. commit=commit,
  3603. build_id=build_id,
  3604. build_info_path=Path(args.build_info),
  3605. bitstream_path=Path(args.bitstream),
  3606. td_receipt_path=Path(args.td_receipt),
  3607. programmer_metadata=programmer_metadata,
  3608. serial_events=events,
  3609. trace_events=list(session.trace_events),
  3610. register_checkpoint=register_checkpoint,
  3611. axes=axes,
  3612. partial=partial,
  3613. watchdog=watchdog_evidence,
  3614. stages=stages,
  3615. final_disable=final_disable_evidence,
  3616. )
  3617. except (OSError, TypeError, ValueError) as exc:
  3618. return {
  3619. **_gate_result(
  3620. status="fail_gate_receipt",
  3621. args=args,
  3622. failures=[f"{type(exc).__name__}:{exc}"],
  3623. hardware_enumerated=True,
  3624. serial_opened=True,
  3625. program_sram_attempted=programmer_metadata["program_sram_attempted"],
  3626. operation=operation,
  3627. speed_hz=speed_hz,
  3628. attempt_count=attempt_count,
  3629. retry_count=retry_count,
  3630. flash_attempted=programmer_metadata["flash_attempted"],
  3631. ),
  3632. "stages": stages,
  3633. }
  3634. receipt_path = output_dir / "hardware-session-receipt.json"
  3635. return {
  3636. **_gate_result(
  3637. status="pass",
  3638. args=args,
  3639. failures=[],
  3640. hardware_enumerated=True,
  3641. serial_opened=True,
  3642. program_sram_attempted=programmer_metadata["program_sram_attempted"],
  3643. operation=operation,
  3644. speed_hz=speed_hz,
  3645. attempt_count=attempt_count,
  3646. retry_count=retry_count,
  3647. flash_attempted=programmer_metadata["flash_attempted"],
  3648. ),
  3649. "commit": commit,
  3650. "build_id": build_id,
  3651. "bitstream_sha256": bitstream_sha256,
  3652. "artifacts": dict(receipt["artifacts"]),
  3653. "receipt": str(receipt_path),
  3654. }
  3655. def _live_request(args: argparse.Namespace, endpoint: Any) -> dict[str, Any]:
  3656. session = NormalSession(endpoint)
  3657. if args.command == "set-all-outputs":
  3658. request = build_output_snapshot(
  3659. ptc_percent=(args.ptc,) * 24,
  3660. fan_percent=(args.fan,) * 4,
  3661. solenoid=args.solenoid,
  3662. xyz=(args.x, args.y, args.z),
  3663. )
  3664. expected_hash = state_hash16(
  3665. ptc_percent=(args.ptc,) * 24,
  3666. fan_percent=(args.fan,) * 4,
  3667. solenoid=args.solenoid,
  3668. )
  3669. result = session.command(
  3670. request,
  3671. expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
  3672. expected_state_hash16=expected_hash,
  3673. required_result_flags=0x01,
  3674. allowed_result_flags=0x0F,
  3675. )
  3676. if result.ack.detail & 0xC0:
  3677. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
  3678. if result.ack.status == StatusCode.OK and result.ack.detail != 0:
  3679. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
  3680. if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
  3681. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK is missing skip detail")
  3682. busy_mask = result.ack.detail & 0x07
  3683. invalid_mask = (result.ack.detail >> 3) & 0x07
  3684. if busy_mask & invalid_mask:
  3685. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
  3686. accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
  3687. expected_result_flags = 0x01 | (accepted_or_noop_mask << 1)
  3688. if result.ack.result_flags != expected_result_flags:
  3689. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
  3690. return {"status": "pass", "ack": result.ack.__dict__}
  3691. if args.command == "jog":
  3692. request = build_motor_jog(
  3693. axis=args.axis,
  3694. raw_dir=args.raw_dir,
  3695. speed_code=args.speed_code,
  3696. steps=args.steps,
  3697. )
  3698. result = session.command(
  3699. request,
  3700. expected_command=0x35,
  3701. allowed_statuses=(StatusCode.OK,),
  3702. expected_detail=0,
  3703. )
  3704. return {"status": "pass", "ack": result.ack.__dict__}
  3705. if args.command == "mark-closed":
  3706. result = session.command(
  3707. build_mark_closed(axis=args.axis, close_dir=args.close_dir),
  3708. expected_command=0x36,
  3709. allowed_statuses=(StatusCode.OK,),
  3710. expected_detail=0,
  3711. )
  3712. return {"status": "pass", "ack": result.ack.__dict__}
  3713. if args.command == "get-status":
  3714. result = session.command(
  3715. build_host_command(command=CommandId.GET_STATUS),
  3716. expected_command=CommandId.GET_STATUS,
  3717. allowed_statuses=(StatusCode.OK,),
  3718. allowed_result_flags=0,
  3719. )
  3720. if result.ack.detail & ~0x03:
  3721. session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
  3722. return {
  3723. "status": "pass",
  3724. "ack": result.ack.__dict__,
  3725. "disabled": bool(result.ack.detail & 0x01),
  3726. "watchdog_timeout": bool(result.ack.detail & 0x02),
  3727. }
  3728. if args.command == "motor-status":
  3729. result = session.motor_status()
  3730. return {
  3731. "status": "pass",
  3732. "ack": result.ack.__dict__,
  3733. "motor_status": result.status.__dict__,
  3734. }
  3735. if args.command == "disable":
  3736. result = session.command(
  3737. build_host_command(command=CommandId.DISABLE),
  3738. expected_command=CommandId.DISABLE,
  3739. allowed_statuses=(StatusCode.OK,),
  3740. expected_detail=0x01,
  3741. expected_state_hash16=SAFE_STATE_HASH16,
  3742. )
  3743. return {"status": "pass", "ack": result.ack.__dict__}
  3744. raise RuntimeError(f"unsupported live command: {args.command}")
  3745. def main(argv: list[str] | None = None) -> int:
  3746. args = build_parser().parse_args(argv)
  3747. if args.command == "selftest":
  3748. result = _selftest()
  3749. elif args.command == "preflight":
  3750. result = run_preflight()
  3751. elif args.command == "normal-actuator-trace-gate":
  3752. result = run_normal_actuator_trace_gate(args)
  3753. elif args.command in {
  3754. "set-all-outputs",
  3755. "jog",
  3756. "mark-closed",
  3757. "get-status",
  3758. "motor-status",
  3759. "disable",
  3760. }:
  3761. result = {
  3762. "status": "fail_unsafe_trace_reattach",
  3763. "reason": (
  3764. "one-shot live commands cannot safely reattach to the continuous Trace "
  3765. "event sequence; use normal-actuator-trace-gate"
  3766. ),
  3767. }
  3768. else:
  3769. raise AssertionError(f"unhandled command: {args.command}")
  3770. print(json.dumps(result, indent=2, default=lambda value: int(value), ensure_ascii=False))
  3771. return 0 if result.get("status") == "pass" else 1
  3772. if __name__ == "__main__":
  3773. raise SystemExit(main())