prod2u_p4_normal_v3_model.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. #!/usr/bin/env python3
  2. """Independent binary921-v3 model, replay, fuzz, and source detector.
  3. This verification-only oracle intentionally does not import the production
  4. protocol helper or any RTL-derived implementation. It models externally
  5. visible Profile 4 Normal behavior from the wire contract.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import ast
  10. import json
  11. import random
  12. import re
  13. from dataclasses import asdict, dataclass
  14. from pathlib import Path
  15. from typing import Iterable, Sequence
  16. ROOT = Path(__file__).resolve().parents[1]
  17. PROFILE_ID = "prod2u-p4-normal-actuator-binary921-v3"
  18. RAW_STEP_POLICY = "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP"
  19. FAST_PATH_POLICY = "RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT"
  20. SAME_AXIS_HOST_RULE = "HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION"
  21. SAME_AXIS_VIOLATION_POLICY = "LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED"
  22. COMPLETION_POLICY = "NONE_HOST_TRACKS_TIME"
  23. PARALLEL_POLICY = "TWO_INDEPENDENT_PARALLEL_EXECUTORS"
  24. MAGIC = b"\xA5\x5A"
  25. VERSION = 0x02
  26. PROFILE = 0x04
  27. FRAME_HOST_CMD = 0x05
  28. FRAME_HOST_BATCH = 0x07
  29. FRAME_TEMPERATURE_SHORT = 0x10
  30. FRAME_MOTION_CMD = 0x11
  31. FRAME_MOTION_STATUS = 0x12
  32. CMD_GET_STATUS = 0x24
  33. CMD_DISABLE = 0x26
  34. CMD_GET_TEMPERATURES = 0x28
  35. CMD_SET_SNAPSHOT = 0x2A
  36. MOTION_JOG = 0x35
  37. MOTION_MARK_CLOSED = 0x36
  38. MOTION_GET_STATUS = 0x37
  39. STATUS_OK = 0x00
  40. STATUS_UNSUPPORTED = 0x01
  41. STATUS_BAD_FLAGS = 0x02
  42. STATUS_BAD_LENGTH = 0x03
  43. STATUS_BAD_VALUE = 0x05
  44. STATUS_TEMPERATURE_BUS_ERROR = 0x0A
  45. STATUS_PARTIAL = 0x16
  46. PTC_COUNT = 24
  47. FAN_COUNT = 4
  48. AXIS_COUNT = 3
  49. UNKNOWN_POSITION = 0xFF
  50. WATCHDOG_TIMEOUT_MS = 5000
  51. DIR_SETUP_MS = 1
  52. SPEED_STEP_MS = (1, 1, 1, 1)
  53. SAFE_PTC = (0,) * PTC_COUNT
  54. SAFE_FAN = (30,) * FAN_COUNT
  55. SAFE_SOLENOID = 0
  56. TEMPERATURE_COUNT = 27
  57. DEFAULT_TEMPERATURE_VALUES = (0xFF,) * TEMPERATURE_COUNT
  58. AXIS_UNCALIBRATED = "uncalibrated"
  59. AXIS_CLOSED = "closed"
  60. AXIS_OPENING = "opening"
  61. AXIS_OPEN = "open"
  62. AXIS_CLOSING = "closing"
  63. AXIS_INTERMEDIATE = "intermediate"
  64. LEGACY_P4_ASSET_PATHS = (
  65. "src/rtl/prod2u_p4_host_rx.v",
  66. "src/rtl/prod2u_p4_tx_scheduler.v",
  67. "src/rtl/prod2u_fan_tach_capture8.v",
  68. "src/rtl/prod2u_fan_pwm_bank.v",
  69. "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
  70. "src/top/prod2u_fan_tach_binary921_v2_normal_top.v",
  71. "src/top/prod2u_fan_tach_binary921_v2_trace_top.v",
  72. "tests/sim/prod2u_p4_host_rx_tb.v",
  73. "tests/sim/prod2u_p4_tx_scheduler_tb.v",
  74. "tests/sim/prod2u_fan_tach_capture8_tb.v",
  75. "tests/sim/prod2u_fan_pwm_bank_tb.v",
  76. "tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v",
  77. "tests/formal/prod2u_fan_data_path.sby",
  78. "tests/formal/prod2u_fan_data_path_formal.v",
  79. "constraints/prod2u_fan_tach_binary921_v2.adc",
  80. "td/prod2u_fan_tach_binary921_v2_normal.prj",
  81. "td/prod2u_fan_tach_binary921_v2_trace.prj",
  82. "td/syn/prod2u_fan_tach_binary921_v2_normal.tcl",
  83. "td/syn/prod2u_fan_tach_binary921_v2_trace.tcl",
  84. "td/phy/prod2u_fan_tach_binary921_v2_normal.tcl",
  85. "td/phy/prod2u_fan_tach_binary921_v2_trace.tcl",
  86. "tools/package_prod2u_p4.ps1",
  87. "tools/prod2u_p4_collector.py",
  88. "tools/prod2u_p4_campaign.py",
  89. "tools/prod2u_p4_validate.py",
  90. "docs/prod2u-p4-start-here.zh-CN.md",
  91. "docs/prod2u-p4-program-sram-runbook.zh-CN.md",
  92. "schemas/prod2u_p4_campaign.schema.json",
  93. "schemas/prod2u_p4_evidence.schema.json",
  94. "schemas/prod2u_p4_final_gate.schema.json",
  95. "schemas/prod2u_p4_qualification.schema.json",
  96. "schemas/prod2u_p4_td_build_receipt.schema.json",
  97. "tests/unit/test_prod2u_p4_cli_campaign.py",
  98. "tests/unit/test_prod2u_p4_cli_identity.py",
  99. "tests/unit/test_prod2u_p4_evidence_binding.py",
  100. "tests/unit/test_prod2u_p4_integration.py",
  101. "tests/unit/test_prod2u_p4_package.py",
  102. "tests/unit/test_prod2u_p4_protocol.py",
  103. "tests/unit/test_prod2u_p4_qualification.py",
  104. "tests/unit/test_prod2u_p4_validate_contract.py",
  105. )
  106. class ModelFrameError(ValueError):
  107. def __init__(self, message: str, *, status: int = STATUS_BAD_VALUE) -> None:
  108. super().__init__(message)
  109. self.status = status
  110. class HostContractViolation(ValueError):
  111. """Input excluded by the trusted-host contract, not a modeled device reply."""
  112. @dataclass(frozen=True)
  113. class PinSample:
  114. time_us: int
  115. en_n: int
  116. direction: tuple[int, int, int]
  117. step: tuple[int, int, int]
  118. @dataclass(frozen=True)
  119. class TraceViolation:
  120. kind: str
  121. axis: int
  122. time_us: int
  123. @dataclass(frozen=True)
  124. class MechanicalTraceReport:
  125. positions: tuple[int, int, int]
  126. step_counts: tuple[int, int, int]
  127. lost_step_counts: tuple[int, int, int]
  128. uncertain_step_counts: tuple[int, int, int]
  129. limit_raw_mask: int
  130. violations: tuple[TraceViolation, ...]
  131. @dataclass(frozen=True)
  132. class MechanicalDifference:
  133. matches: bool
  134. mismatches: tuple[str, ...]
  135. class MechanicalPlant:
  136. """Pin-level plant independent of controller or RTL internal state.
  137. The plant owns the hidden mechanical close direction and physical position.
  138. Its only motion inputs are the externally visible shared EN_N plus per-axis
  139. DIR and STEP pins.
  140. """
  141. def __init__(
  142. self,
  143. *,
  144. positions: Sequence[int],
  145. close_dirs: Sequence[int],
  146. dir_setup_us: int = 1000,
  147. min_step_high_us: int = 0,
  148. min_step_low_us: int = 0,
  149. limit_modes: Sequence[str] = ("normal", "normal"),
  150. limit_assert_delay_us: Sequence[int] = (0, 0),
  151. limit_bounce_us: Sequence[int] = (0, 0),
  152. limit_bounce_period_us: int = 100,
  153. swap_xy_limits: bool = False,
  154. lost_step_every: Sequence[int] = (0, 0, 0),
  155. ) -> None:
  156. if len(positions) != AXIS_COUNT or len(close_dirs) != AXIS_COUNT:
  157. raise ValueError("positions and close_dirs require exactly three axes")
  158. if any(value < 0 for value in positions):
  159. raise ValueError("positions must be non-negative")
  160. if any(value not in (0, 1) for value in close_dirs):
  161. raise ValueError("close_dirs must contain only zero or one")
  162. if len(limit_modes) != 2 or any(
  163. mode not in ("normal", "stuck_low", "stuck_high") for mode in limit_modes
  164. ):
  165. raise ValueError("limit_modes must contain two supported modes")
  166. if len(limit_assert_delay_us) != 2 or len(limit_bounce_us) != 2:
  167. raise ValueError("limit timing values require X and Y entries")
  168. if len(lost_step_every) != AXIS_COUNT or any(value < 0 for value in lost_step_every):
  169. raise ValueError("lost_step_every requires three non-negative values")
  170. if min(dir_setup_us, min_step_high_us, min_step_low_us, limit_bounce_period_us) < 0:
  171. raise ValueError("timing values must be non-negative")
  172. if limit_bounce_period_us == 0:
  173. raise ValueError("limit_bounce_period_us must be positive")
  174. self._positions = list(positions)
  175. self._close_dirs = tuple(close_dirs)
  176. self._dir_setup_us = dir_setup_us
  177. self._min_step_high_us = min_step_high_us
  178. self._min_step_low_us = min_step_low_us
  179. self._limit_modes = tuple(limit_modes)
  180. self._limit_assert_delay_us = tuple(limit_assert_delay_us)
  181. self._limit_bounce_us = tuple(limit_bounce_us)
  182. self._limit_bounce_period_us = limit_bounce_period_us
  183. self._swap_xy_limits = swap_xy_limits
  184. self._lost_step_every = tuple(lost_step_every)
  185. self._step_counts = [0, 0, 0]
  186. self._lost_step_counts = [0, 0, 0]
  187. self._uncertain_step_counts = [0, 0, 0]
  188. self._violations: list[TraceViolation] = []
  189. self._last_sample: PinSample | None = None
  190. self._last_dir_change_us = [0, 0, 0]
  191. self._step_rise_us: list[int | None] = [None, None, None]
  192. self._pending_step_valid = [False, False, False]
  193. self._pending_step_dir = [0, 0, 0]
  194. self._last_step_fall_us: list[int | None] = [None, None, None]
  195. self._contact_time_us: list[int | None] = [
  196. 0 if self._positions[index] == 0 else None for index in range(2)
  197. ]
  198. self._last_time_us = 0
  199. @property
  200. def positions(self) -> tuple[int, int, int]:
  201. return tuple(self._positions) # type: ignore[return-value]
  202. @property
  203. def step_counts(self) -> tuple[int, int, int]:
  204. return tuple(self._step_counts) # type: ignore[return-value]
  205. @property
  206. def uncertain_step_counts(self) -> tuple[int, int, int]:
  207. return tuple(self._uncertain_step_counts) # type: ignore[return-value]
  208. @property
  209. def lost_step_counts(self) -> tuple[int, int, int]:
  210. return tuple(self._lost_step_counts) # type: ignore[return-value]
  211. @property
  212. def violations(self) -> tuple[TraceViolation, ...]:
  213. return tuple(self._violations)
  214. def _record(self, kind: str, axis: int, time_us: int) -> None:
  215. item = TraceViolation(kind=kind, axis=axis, time_us=time_us)
  216. if item not in self._violations:
  217. self._violations.append(item)
  218. def observe(self, sample: PinSample) -> int:
  219. if sample.time_us < self._last_time_us:
  220. raise ValueError("pin samples must be monotonic")
  221. if sample.en_n not in (0, 1):
  222. raise ValueError("en_n must be zero or one")
  223. if len(sample.direction) != AXIS_COUNT or len(sample.step) != AXIS_COUNT:
  224. raise ValueError("direction and step require exactly three axes")
  225. if any(value not in (0, 1) for value in (*sample.direction, *sample.step)):
  226. raise ValueError("direction and step values must be binary")
  227. previous = self._last_sample
  228. if previous is None:
  229. self._last_dir_change_us = [sample.time_us] * AXIS_COUNT
  230. previous_direction = sample.direction
  231. previous_step = (0, 0, 0)
  232. previous_en_n = 1
  233. else:
  234. previous_direction = previous.direction
  235. previous_step = previous.step
  236. previous_en_n = previous.en_n
  237. for axis in range(AXIS_COUNT):
  238. if sample.direction[axis] != previous_direction[axis]:
  239. if previous_step[axis] or sample.step[axis]:
  240. self._record("dir_changed_while_step_high", axis, sample.time_us)
  241. self._pending_step_valid[axis] = False
  242. self._last_dir_change_us[axis] = sample.time_us
  243. rising = not previous_step[axis] and bool(sample.step[axis])
  244. falling = bool(previous_step[axis]) and not sample.step[axis]
  245. truncated = (
  246. not previous_en_n
  247. and sample.en_n
  248. and bool(previous_step[axis] or sample.step[axis])
  249. )
  250. if truncated:
  251. self._record("step_truncated", axis, sample.time_us)
  252. self._pending_step_valid[axis] = False
  253. if rising:
  254. valid = True
  255. if sample.en_n:
  256. self._record("step_while_disabled", axis, sample.time_us)
  257. valid = False
  258. if sample.time_us - self._last_dir_change_us[axis] < self._dir_setup_us:
  259. self._record("dir_setup", axis, sample.time_us)
  260. valid = False
  261. last_fall = self._last_step_fall_us[axis]
  262. if last_fall is not None and sample.time_us - last_fall < self._min_step_low_us:
  263. self._record("step_low_width", axis, sample.time_us)
  264. valid = False
  265. self._step_rise_us[axis] = sample.time_us
  266. self._pending_step_valid[axis] = valid
  267. self._pending_step_dir[axis] = sample.direction[axis]
  268. if falling:
  269. rise = self._step_rise_us[axis]
  270. if rise is not None and sample.time_us - rise < self._min_step_high_us:
  271. self._record("step_high_width", axis, sample.time_us)
  272. self._pending_step_valid[axis] = False
  273. if rise is not None and self._pending_step_valid[axis]:
  274. self._step_counts[axis] += 1
  275. drop_every = self._lost_step_every[axis]
  276. if drop_every and self._step_counts[axis] % drop_every == 0:
  277. self._lost_step_counts[axis] += 1
  278. else:
  279. if self._pending_step_dir[axis] == self._close_dirs[axis]:
  280. self._positions[axis] = max(0, self._positions[axis] - 1)
  281. else:
  282. self._positions[axis] += 1
  283. if axis < 2:
  284. if self._positions[axis] == 0 and self._contact_time_us[axis] is None:
  285. self._contact_time_us[axis] = sample.time_us
  286. elif self._positions[axis] > 0:
  287. self._contact_time_us[axis] = None
  288. elif rise is not None:
  289. self._uncertain_step_counts[axis] += 1
  290. self._step_rise_us[axis] = None
  291. self._pending_step_valid[axis] = False
  292. self._last_step_fall_us[axis] = sample.time_us
  293. self._last_sample = sample
  294. self._last_time_us = sample.time_us
  295. return self.read_limit_raw_mask(sample.time_us)
  296. def _limit_value(self, axis: int, time_us: int) -> int:
  297. mode = self._limit_modes[axis]
  298. if mode == "stuck_low":
  299. return 0
  300. if mode == "stuck_high":
  301. return 1
  302. if self._positions[axis] != 0:
  303. return 0
  304. contact = self._contact_time_us[axis]
  305. if contact is None:
  306. return 0
  307. elapsed = max(0, time_us - contact)
  308. delay = self._limit_assert_delay_us[axis]
  309. if elapsed < delay:
  310. return 0
  311. bounce_elapsed = elapsed - delay
  312. bounce_window = self._limit_bounce_us[axis]
  313. if bounce_elapsed < bounce_window:
  314. return int((bounce_elapsed // self._limit_bounce_period_us) % 2 == 0)
  315. return 1
  316. def read_limit_raw_mask(self, time_us: int | None = None) -> int:
  317. now = self._last_time_us if time_us is None else time_us
  318. values = [self._limit_value(0, now), self._limit_value(1, now)]
  319. if self._swap_xy_limits:
  320. values.reverse()
  321. return values[0] | (values[1] << 1)
  322. def replay_mechanical_trace(
  323. plant: MechanicalPlant,
  324. samples: Iterable[PinSample],
  325. ) -> MechanicalTraceReport:
  326. limit_raw_mask = plant.read_limit_raw_mask(0)
  327. for sample in samples:
  328. limit_raw_mask = plant.observe(sample)
  329. return MechanicalTraceReport(
  330. positions=plant.positions,
  331. step_counts=plant.step_counts,
  332. lost_step_counts=plant.lost_step_counts,
  333. uncertain_step_counts=plant.uncertain_step_counts,
  334. limit_raw_mask=limit_raw_mask,
  335. violations=plant.violations,
  336. )
  337. def compare_mechanical_reports(
  338. reference: MechanicalTraceReport,
  339. candidate: MechanicalTraceReport,
  340. ) -> MechanicalDifference:
  341. mismatches = tuple(
  342. name
  343. for name in (
  344. "positions",
  345. "step_counts",
  346. "lost_step_counts",
  347. "uncertain_step_counts",
  348. "limit_raw_mask",
  349. "violations",
  350. )
  351. if getattr(reference, name) != getattr(candidate, name)
  352. )
  353. return MechanicalDifference(matches=not mismatches, mismatches=mismatches)
  354. def compare_pin_traces(
  355. *,
  356. reference_plant: MechanicalPlant,
  357. candidate_plant: MechanicalPlant,
  358. reference_samples: Iterable[PinSample],
  359. candidate_samples: Iterable[PinSample],
  360. ) -> MechanicalDifference:
  361. return compare_mechanical_reports(
  362. replay_mechanical_trace(reference_plant, reference_samples),
  363. replay_mechanical_trace(candidate_plant, candidate_samples),
  364. )
  365. @dataclass
  366. class AxisState:
  367. state: str = AXIS_UNCALIBRATED
  368. position_valid: bool = False
  369. busy: bool = False
  370. current: int = UNKNOWN_POSITION
  371. target: int = UNKNOWN_POSITION
  372. fault: bool = False
  373. move_kind: str = "idle"
  374. raw_dir: int | None = None
  375. speed_code: int | None = None
  376. remaining_steps: int = 0
  377. drive_active: bool = False
  378. step_phase: str = "idle"
  379. pending_jog: tuple[int, int, int] | None = None
  380. steps_executed: int = 0
  381. step_elapsed_ms: int = 0
  382. dir_setup_remaining_ms: int = 0
  383. @dataclass(frozen=True)
  384. class ModelResult:
  385. accepted: bool
  386. command: int
  387. status: int
  388. detail: int
  389. state_hash16: int
  390. response_type: int = 0
  391. result_flags: int = 0
  392. response: bytes | None = None
  393. reason: str = ""
  394. def crc16_ccitt_false(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
  395. crc = initial & 0xFFFF
  396. for byte in bytes(data):
  397. crc ^= byte << 8
  398. for _ in range(8):
  399. if crc & 0x8000:
  400. crc = ((crc << 1) ^ 0x1021) & 0xFFFF
  401. else:
  402. crc = (crc << 1) & 0xFFFF
  403. return crc
  404. def _byte_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  405. result = tuple(values)
  406. if len(result) != count:
  407. raise ValueError(f"{label} requires exactly {count} values")
  408. for index, value in enumerate(result):
  409. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
  410. raise ValueError(f"{label}[{index}] must fit in one byte")
  411. return result
  412. def _percent_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  413. result = _byte_values(values, count=count, label=label)
  414. for index, value in enumerate(result):
  415. if value > 100:
  416. raise ValueError(f"{label}[{index}] must be from 0 to 100")
  417. return result
  418. def _binary_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  419. result = _byte_values(values, count=count, label=label)
  420. for index, value in enumerate(result):
  421. if value not in (0, 100):
  422. raise ValueError(f"{label}[{index}] must be 0 or 100")
  423. return result
  424. def state_hash16(ptc_percent: Iterable[int], fan_percent: Iterable[int], solenoid: int) -> int:
  425. ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
  426. fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
  427. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  428. return crc16_ccitt_false(bytes(ptc + fan + (checked_solenoid,)))
  429. def _freeze_state(value: object) -> object:
  430. if isinstance(value, dict):
  431. return tuple(
  432. (key, _freeze_state(item))
  433. for key, item in sorted(value.items())
  434. )
  435. if isinstance(value, (list, tuple)):
  436. return tuple(_freeze_state(item) for item in value)
  437. return value
  438. def encode_standard_frame(frame_type: int, payload: bytes | bytearray | Iterable[int]) -> bytes:
  439. payload_bytes = bytes(payload)
  440. if not 0 <= frame_type <= 0xFF:
  441. raise ValueError("frame_type must fit in one byte")
  442. if len(payload_bytes) > 0xFF:
  443. raise ValueError("payload is too long")
  444. body = bytes((VERSION, PROFILE, frame_type))
  445. body += b"\x00" * 8
  446. body += bytes((len(payload_bytes),)) + payload_bytes
  447. return MAGIC + body + crc16_ccitt_false(body).to_bytes(2, "little")
  448. def encode_temperature_response(values: bytes | bytearray | Iterable[int]) -> bytes:
  449. payload = bytes(
  450. _byte_values(values, count=TEMPERATURE_COUNT, label="temperature")
  451. )
  452. body = bytes(
  453. (VERSION, PROFILE, FRAME_TEMPERATURE_SHORT, TEMPERATURE_COUNT)
  454. ) + payload
  455. return MAGIC + body + crc16_ccitt_false(body).to_bytes(2, "little")
  456. def encode_snapshot_frame(
  457. *,
  458. ptc_percent: Iterable[int],
  459. fan_percent: Iterable[int],
  460. solenoid: int,
  461. xyz: Iterable[int],
  462. ) -> bytes:
  463. ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
  464. fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
  465. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  466. checked_xyz = _byte_values(xyz, count=AXIS_COUNT, label="XYZ")
  467. payload = bytes((CMD_SET_SNAPSHOT, 0, *ptc, *fan, checked_solenoid, *checked_xyz))
  468. return encode_standard_frame(FRAME_HOST_BATCH, payload)
  469. def encode_motion_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
  470. payload_bytes = bytes(payload)
  471. if len(payload_bytes) != 8:
  472. raise ValueError("motion payload must contain exactly eight bytes")
  473. return encode_standard_frame(FRAME_MOTION_CMD, payload_bytes)
  474. def encode_host_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
  475. payload_bytes = bytes(payload)
  476. if len(payload_bytes) != 4:
  477. raise ValueError("host command payload must contain exactly four bytes")
  478. return encode_standard_frame(FRAME_HOST_CMD, payload_bytes)
  479. def _decode_standard_frame(frame: bytes | bytearray) -> tuple[int, bytes]:
  480. raw = bytes(frame)
  481. if len(raw) < 16:
  482. raise ModelFrameError("frame is truncated", status=STATUS_BAD_LENGTH)
  483. if raw[:2] != MAGIC:
  484. raise ModelFrameError("bad frame magic")
  485. if raw[2] != VERSION or raw[3] != PROFILE:
  486. raise ModelFrameError("bad frame identity")
  487. if raw[5:13] != b"\x00" * 8:
  488. raise ModelFrameError("seq and timestamp must be zero")
  489. payload_length = raw[13]
  490. expected_length = 16 + payload_length
  491. if len(raw) != expected_length:
  492. raise ModelFrameError("frame length mismatch", status=STATUS_BAD_LENGTH)
  493. expected_crc = crc16_ccitt_false(raw[2:-2])
  494. actual_crc = int.from_bytes(raw[-2:], "little")
  495. if actual_crc != expected_crc:
  496. raise ModelFrameError("frame CRC mismatch")
  497. return raw[4], raw[14:-2]
  498. GOLDEN_VECTORS = {
  499. "enable": bytes.fromhex(
  500. "a55a0204070000000000000000222a00"
  501. "000000000000000000000000000000000000000000000000"
  502. "1e1e1e1e00000000d6df"
  503. ),
  504. "jog_x": bytes.fromhex("a55a020411000000000000000008350001000100000086c3"),
  505. "jog_y": bytes.fromhex("a55a0204110000000000000000083501000001000000473e"),
  506. "mark_x": bytes.fromhex("a55a0204110000000000000000083600010000000000477d"),
  507. "mark_y": bytes.fromhex("a55a02041100000000000000000836010000000000008680"),
  508. "open": bytes.fromhex(
  509. "a55a0204070000000000000000222a00"
  510. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  511. "46464646646464642c75"
  512. ),
  513. "close": bytes.fromhex(
  514. "a55a0204070000000000000000222a00"
  515. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  516. "4646464600000000684a"
  517. ),
  518. "disable": bytes.fromhex("a55a02040500000000000000000426000000c4ae"),
  519. }
  520. class NormalV3Model:
  521. def __init__(
  522. self,
  523. *,
  524. temperature_values: Iterable[int] = DEFAULT_TEMPERATURE_VALUES,
  525. powerup_ready: bool = True,
  526. temperature_bus_error: bool = False,
  527. ) -> None:
  528. self.ptc_percent = SAFE_PTC
  529. self.fan_percent = SAFE_FAN
  530. self.solenoid = SAFE_SOLENOID
  531. self.axes = [AxisState() for _ in range(AXIS_COUNT)]
  532. self.disabled = True
  533. self.watchdog_timeout = False
  534. self.watchdog_armed = False
  535. self.watchdog_elapsed_ms = 0
  536. self.temperature_values = _byte_values(
  537. temperature_values,
  538. count=TEMPERATURE_COUNT,
  539. label="temperature",
  540. )
  541. self.powerup_ready = bool(powerup_ready)
  542. self.temperature_bus_error = bool(temperature_bus_error)
  543. @property
  544. def state_hash16(self) -> int:
  545. return state_hash16(self.ptc_percent, self.fan_percent, self.solenoid)
  546. @property
  547. def busy_mask(self) -> int:
  548. return 0
  549. @property
  550. def active_mask(self) -> int:
  551. return sum(
  552. (1 << index)
  553. for index, axis in enumerate(self.axes[:2])
  554. if axis.drive_active
  555. )
  556. @property
  557. def position_valid_mask(self) -> int:
  558. return 0
  559. @property
  560. def fault_mask(self) -> int:
  561. return 0
  562. def state_fingerprint(self) -> tuple[object, ...]:
  563. frozen = _freeze_state(self.state_payload())
  564. if not isinstance(frozen, tuple):
  565. raise AssertionError("state payload did not freeze to a tuple")
  566. return frozen
  567. def state_payload(self) -> dict[str, object]:
  568. return {
  569. "ptc_percent": list(self.ptc_percent),
  570. "fan_percent": list(self.fan_percent),
  571. "solenoid": self.solenoid,
  572. "state_hash16": self.state_hash16,
  573. "disabled": self.disabled,
  574. "watchdog_timeout": self.watchdog_timeout,
  575. "watchdog_armed": self.watchdog_armed,
  576. "watchdog_elapsed_ms": self.watchdog_elapsed_ms,
  577. "position_valid_mask": self.position_valid_mask,
  578. "busy_mask": self.busy_mask,
  579. "active_mask": self.active_mask,
  580. "fault_mask": self.fault_mask,
  581. "axes": [asdict(axis) for axis in self.axes],
  582. }
  583. @staticmethod
  584. def _set_xy_state(axis: AxisState, state: str) -> None:
  585. axis.state = state
  586. axis.fault = False
  587. axis.position_valid = False
  588. axis.current = UNKNOWN_POSITION
  589. axis.target = UNKNOWN_POSITION
  590. if state not in (
  591. AXIS_UNCALIBRATED,
  592. AXIS_CLOSED,
  593. AXIS_OPENING,
  594. AXIS_OPEN,
  595. AXIS_CLOSING,
  596. AXIS_INTERMEDIATE,
  597. ):
  598. raise ValueError(f"unsupported XY axis state: {state}")
  599. @staticmethod
  600. def _clear_motion(axis: AxisState) -> None:
  601. axis.busy = False
  602. axis.drive_active = False
  603. axis.step_phase = "idle"
  604. axis.pending_jog = None
  605. axis.move_kind = "idle"
  606. axis.remaining_steps = 0
  607. axis.steps_executed = 0
  608. axis.step_elapsed_ms = 0
  609. axis.dir_setup_remaining_ms = 0
  610. def _result(
  611. self,
  612. *,
  613. accepted: bool,
  614. command: int,
  615. status: int,
  616. detail: int = 0,
  617. response_type: int = 0,
  618. result_flags: int = 0,
  619. response: bytes | None = None,
  620. reason: str = "",
  621. ) -> ModelResult:
  622. return ModelResult(
  623. accepted=accepted,
  624. command=command,
  625. status=status,
  626. detail=detail,
  627. state_hash16=self.state_hash16,
  628. response_type=response_type,
  629. result_flags=result_flags,
  630. response=response,
  631. reason=reason,
  632. )
  633. def _arm_watchdog(self) -> None:
  634. self.disabled = False
  635. self.watchdog_timeout = False
  636. self.watchdog_armed = True
  637. self.watchdog_elapsed_ms = 0
  638. def _refresh_watchdog(self) -> None:
  639. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  640. self.watchdog_elapsed_ms = 0
  641. def advance_time(self, elapsed_ms: int) -> None:
  642. """Advance wall-clock time, including complete modeled STEP cycles."""
  643. if elapsed_ms < 0:
  644. raise ValueError("elapsed_ms must be non-negative")
  645. remaining_ms = elapsed_ms
  646. while remaining_ms > 0:
  647. delta_ms = remaining_ms
  648. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  649. delta_ms = min(
  650. delta_ms,
  651. WATCHDOG_TIMEOUT_MS - self.watchdog_elapsed_ms,
  652. )
  653. accumulating_axes: list[int] = []
  654. for axis_index, axis in enumerate(self.axes[:2]):
  655. if not axis.drive_active or axis.remaining_steps <= 0:
  656. continue
  657. if axis.dir_setup_remaining_ms > 0:
  658. delta_ms = min(delta_ms, axis.dir_setup_remaining_ms)
  659. continue
  660. accumulating_axes.append(axis_index)
  661. speed_code = axis.speed_code if axis.speed_code is not None else 3
  662. step_due_ms = SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms
  663. delta_ms = min(delta_ms, step_due_ms)
  664. self._advance_control_time(delta_ms)
  665. remaining_ms -= delta_ms
  666. for axis_index in accumulating_axes:
  667. axis = self.axes[axis_index]
  668. if axis.drive_active and axis.dir_setup_remaining_ms == 0:
  669. axis.step_elapsed_ms += delta_ms
  670. for axis_index, axis in enumerate(self.axes[:2]):
  671. if (
  672. not axis.drive_active
  673. or axis.dir_setup_remaining_ms > 0
  674. or axis.remaining_steps <= 0
  675. ):
  676. continue
  677. speed_code = axis.speed_code if axis.speed_code is not None else 3
  678. if axis.step_elapsed_ms < SPEED_STEP_MS[speed_code]:
  679. continue
  680. if axis.step_phase == "idle":
  681. self._commit_axis_step(axis_index)
  682. else:
  683. self.finish_axis_step(axis_index)
  684. def _advance_control_time(self, elapsed_ms: int) -> None:
  685. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  686. if self.watchdog_elapsed_ms + elapsed_ms >= WATCHDOG_TIMEOUT_MS:
  687. self.watchdog_expire()
  688. else:
  689. self.watchdog_elapsed_ms += elapsed_ms
  690. for axis_index, axis in enumerate(self.axes[:2]):
  691. if axis.dir_setup_remaining_ms <= 0:
  692. continue
  693. axis.dir_setup_remaining_ms = max(
  694. 0,
  695. axis.dir_setup_remaining_ms - elapsed_ms,
  696. )
  697. if axis.dir_setup_remaining_ms == 0 and axis.drive_active:
  698. self._complete_dir_setup(axis_index)
  699. def _complete_dir_setup(self, axis_index: int) -> None:
  700. axis = self.axes[axis_index]
  701. if not axis.drive_active:
  702. return
  703. axis.drive_active = True
  704. def _safe_outputs(self) -> None:
  705. self.ptc_percent = SAFE_PTC
  706. self.fan_percent = SAFE_FAN
  707. self.solenoid = SAFE_SOLENOID
  708. def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
  709. self._safe_outputs()
  710. self.disabled = disabled
  711. self.watchdog_timeout = watchdog_timeout
  712. self.watchdog_armed = False
  713. self.watchdog_elapsed_ms = 0
  714. def disable(self) -> None:
  715. self._force_safe(disabled=True, watchdog_timeout=False)
  716. def watchdog_expire(self) -> None:
  717. if self.watchdog_armed and not self.disabled:
  718. self._force_safe(disabled=True, watchdog_timeout=True)
  719. def apply_frame(
  720. self,
  721. frame: bytes | bytearray,
  722. ) -> ModelResult:
  723. before = self.state_fingerprint()
  724. try:
  725. frame_type, payload = _decode_standard_frame(frame)
  726. if frame_type == FRAME_HOST_BATCH:
  727. result = self._apply_snapshot(payload)
  728. elif frame_type == FRAME_HOST_CMD:
  729. result = self._apply_host(payload)
  730. elif frame_type == FRAME_MOTION_CMD:
  731. result = self._apply_motion(payload)
  732. else:
  733. result = self._result(
  734. accepted=False,
  735. command=payload[0] if payload else 0,
  736. status=STATUS_UNSUPPORTED,
  737. reason="unsupported input frame type",
  738. )
  739. except ModelFrameError as exc:
  740. result = self._result(
  741. accepted=False,
  742. command=0,
  743. status=exc.status,
  744. reason=str(exc),
  745. )
  746. except HostContractViolation:
  747. raise
  748. except ValueError as exc:
  749. result = self._result(
  750. accepted=False,
  751. command=0,
  752. status=STATUS_BAD_VALUE,
  753. reason=str(exc),
  754. )
  755. if not result.accepted and self.state_fingerprint() != before:
  756. raise AssertionError("rejected frame changed modeled state")
  757. return result
  758. def _apply_snapshot(
  759. self,
  760. payload: bytes,
  761. ) -> ModelResult:
  762. command = payload[0] if payload else 0
  763. if len(payload) != 34:
  764. raise ModelFrameError("snapshot payload length must be 34", status=STATUS_BAD_LENGTH)
  765. if payload[0] != CMD_SET_SNAPSHOT:
  766. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  767. if payload[1] != 0:
  768. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  769. ptc = tuple(payload[2:26])
  770. fan = tuple(payload[26:30])
  771. solenoid = payload[30]
  772. xyz = tuple(payload[31:34])
  773. try:
  774. checked_ptc = _percent_values(ptc, count=PTC_COUNT, label="PTC")
  775. checked_fan = _percent_values(fan, count=FAN_COUNT, label="FAN")
  776. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  777. except ValueError as exc:
  778. return self._result(
  779. accepted=False,
  780. command=command,
  781. status=STATUS_BAD_VALUE,
  782. reason=str(exc),
  783. )
  784. self.ptc_percent = checked_ptc
  785. self.fan_percent = checked_fan
  786. self.solenoid = checked_solenoid
  787. self._arm_watchdog()
  788. return self._result(
  789. accepted=True,
  790. command=command,
  791. status=STATUS_OK,
  792. detail=0,
  793. result_flags=0x01,
  794. )
  795. def _apply_host(self, payload: bytes) -> ModelResult:
  796. command = payload[0] if payload else 0
  797. if len(payload) != 4:
  798. raise ModelFrameError("host payload length must be four", status=STATUS_BAD_LENGTH)
  799. if payload[3] != 0:
  800. return self._result(accepted=False, command=command, status=STATUS_BAD_FLAGS)
  801. if payload[1:3] != b"\x00\x00":
  802. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  803. if command == CMD_GET_STATUS:
  804. detail = int(self.disabled) | (int(self.watchdog_timeout) << 1)
  805. return self._result(accepted=True, command=command, status=STATUS_OK, detail=detail)
  806. if command == CMD_DISABLE:
  807. self.disable()
  808. return self._result(accepted=True, command=command, status=STATUS_OK, detail=1)
  809. if command == CMD_GET_TEMPERATURES:
  810. if not self.powerup_ready:
  811. values = DEFAULT_TEMPERATURE_VALUES
  812. elif self.temperature_bus_error:
  813. return self._result(
  814. accepted=False,
  815. command=command,
  816. status=STATUS_TEMPERATURE_BUS_ERROR,
  817. )
  818. else:
  819. values = self.temperature_values
  820. return self._result(
  821. accepted=True,
  822. command=command,
  823. status=STATUS_OK,
  824. response_type=FRAME_TEMPERATURE_SHORT,
  825. response=encode_temperature_response(values),
  826. )
  827. return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
  828. def _apply_motion(
  829. self,
  830. payload: bytes,
  831. ) -> ModelResult:
  832. command = payload[0] if payload else 0
  833. if len(payload) != 8:
  834. raise ModelFrameError("motion payload length must be eight", status=STATUS_BAD_LENGTH)
  835. if command == MOTION_JOG:
  836. return self._apply_jog(payload)
  837. if command == MOTION_MARK_CLOSED:
  838. return self._result(
  839. accepted=False,
  840. command=command,
  841. status=STATUS_UNSUPPORTED,
  842. reason="MARK_CLOSED is retired",
  843. )
  844. if command == MOTION_GET_STATUS:
  845. if payload[1:] != b"\x00" * 7:
  846. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  847. self._refresh_watchdog()
  848. return self._result(
  849. accepted=True,
  850. command=command,
  851. status=STATUS_OK,
  852. response_type=FRAME_MOTION_STATUS,
  853. result_flags=0x08,
  854. response=self.motor_status_payload(),
  855. )
  856. return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
  857. def _apply_jog(
  858. self,
  859. payload: bytes,
  860. ) -> ModelResult:
  861. axis_index = payload[1]
  862. raw_dir = payload[2]
  863. speed_code = payload[3]
  864. steps = int.from_bytes(payload[4:6], "little")
  865. if steps == 0:
  866. raise HostContractViolation(
  867. f"{RAW_STEP_POLICY}: steps=0 violates the trusted-host precondition"
  868. )
  869. if (
  870. axis_index not in (0, 1)
  871. or raw_dir not in (0, 1)
  872. or speed_code >= 4
  873. or payload[6:] != b"\x00\x00"
  874. ):
  875. return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BAD_VALUE)
  876. axis = self.axes[axis_index]
  877. self._set_xy_state(axis, AXIS_INTERMEDIATE)
  878. self._load_force_jog(
  879. axis,
  880. raw_dir=raw_dir,
  881. speed_code=speed_code,
  882. steps=steps,
  883. )
  884. axis.dir_setup_remaining_ms = 0
  885. self.begin_axis_step(axis_index)
  886. return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
  887. def _load_force_jog(
  888. self,
  889. axis: AxisState,
  890. *,
  891. raw_dir: int,
  892. speed_code: int,
  893. steps: int,
  894. ) -> None:
  895. axis.busy = False
  896. axis.drive_active = True
  897. axis.step_phase = "idle"
  898. axis.pending_jog = None
  899. axis.move_kind = "jog"
  900. axis.raw_dir = raw_dir
  901. axis.speed_code = speed_code
  902. axis.remaining_steps = steps
  903. axis.steps_executed = 0
  904. axis.step_elapsed_ms = 0
  905. axis.dir_setup_remaining_ms = DIR_SETUP_MS
  906. def _complete_motion_segment(self, axis_index: int) -> None:
  907. axis = self.axes[axis_index]
  908. if axis_index not in (0, 1) or axis.move_kind != "jog":
  909. raise AssertionError("only X/Y JOG can complete motor motion")
  910. self._set_xy_state(axis, AXIS_INTERMEDIATE)
  911. self._clear_motion(axis)
  912. def _prepare_axis_event(self, axis_index: int) -> tuple[int, str] | None:
  913. axis = self.axes[axis_index]
  914. while axis.drive_active and axis.remaining_steps <= 0:
  915. self._complete_motion_segment(axis_index)
  916. if not axis.drive_active:
  917. return None
  918. if axis.dir_setup_remaining_ms > 0:
  919. return axis.dir_setup_remaining_ms, "setup"
  920. if not axis.drive_active or axis.remaining_steps <= 0:
  921. return None
  922. speed_code = axis.speed_code if axis.speed_code is not None else 3
  923. return SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms, "step"
  924. def _commit_axis_step(self, axis_index: int) -> None:
  925. self.begin_axis_step(axis_index)
  926. self.finish_axis_step(axis_index)
  927. def begin_axis_step(self, axis_index: int) -> None:
  928. if axis_index not in (0, 1):
  929. raise ValueError("only X and Y execute motion")
  930. axis = self.axes[axis_index]
  931. if (
  932. not axis.drive_active
  933. or axis.dir_setup_remaining_ms > 0
  934. or axis.remaining_steps <= 0
  935. or axis.step_phase != "idle"
  936. ):
  937. raise ValueError("axis has no complete step ready to commit")
  938. axis.step_phase = "high"
  939. axis.busy = False
  940. def lower_axis_step(self, axis_index: int) -> None:
  941. if axis_index not in (0, 1):
  942. raise ValueError("only X and Y execute motion")
  943. axis = self.axes[axis_index]
  944. if not axis.drive_active or axis.step_phase != "high":
  945. raise ValueError("axis has no high step phase to lower")
  946. axis.step_phase = "low"
  947. def finish_axis_step(self, axis_index: int) -> None:
  948. if axis_index not in (0, 1):
  949. raise ValueError("only X and Y execute motion")
  950. axis = self.axes[axis_index]
  951. if not axis.drive_active or axis.step_phase not in ("high", "low"):
  952. raise ValueError("axis has no started step to finish")
  953. axis.step_phase = "low"
  954. axis.remaining_steps -= 1
  955. axis.steps_executed += 1
  956. axis.step_elapsed_ms = 0
  957. pending = axis.pending_jog
  958. axis.pending_jog = None
  959. axis.step_phase = "idle"
  960. if pending is not None:
  961. axis.busy = False
  962. raw_dir, speed_code, steps = pending
  963. self._load_force_jog(
  964. axis,
  965. raw_dir=raw_dir,
  966. speed_code=speed_code,
  967. steps=steps,
  968. )
  969. elif axis.drive_active and axis.remaining_steps == 0:
  970. self._complete_motion_segment(axis_index)
  971. def execute_parallel_steps(self, counts: Sequence[int]) -> tuple[int, int, int]:
  972. if len(counts) != AXIS_COUNT or any(count < 0 for count in counts):
  973. raise ValueError("counts require three non-negative axis values")
  974. if counts[2] != 0:
  975. raise ValueError("Z is protocol-only and cannot execute steps")
  976. remaining = list(counts)
  977. executed = [0, 0, 0]
  978. due_ms: list[int | None] = [None, None, None]
  979. due_kind: list[str | None] = [None, None, None]
  980. if any(remaining):
  981. omitted_active = [
  982. axis_index
  983. for axis_index, axis in enumerate(self.axes)
  984. if axis.drive_active
  985. and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
  986. and remaining[axis_index] == 0
  987. ]
  988. if omitted_active:
  989. raise ValueError(
  990. "counts must include every concurrently active axis: "
  991. + ",".join(map(str, omitted_active))
  992. )
  993. while any(remaining):
  994. for axis_index in range(AXIS_COUNT):
  995. if remaining[axis_index] and due_ms[axis_index] is None:
  996. event = self._prepare_axis_event(axis_index)
  997. if event is not None:
  998. due_ms[axis_index], due_kind[axis_index] = event
  999. active_due = [value for value in due_ms if value is not None]
  1000. if not active_due:
  1001. break
  1002. elapsed_ms = min(active_due)
  1003. self._advance_control_time(elapsed_ms)
  1004. for axis_index in range(AXIS_COUNT):
  1005. if due_ms[axis_index] is not None:
  1006. due_ms[axis_index] -= elapsed_ms
  1007. for axis_index in range(AXIS_COUNT):
  1008. if due_ms[axis_index] != 0:
  1009. continue
  1010. if due_kind[axis_index] == "setup":
  1011. if self.axes[axis_index].dir_setup_remaining_ms != 0:
  1012. raise AssertionError("DIR setup event completed early")
  1013. elif due_kind[axis_index] == "step":
  1014. self._commit_axis_step(axis_index)
  1015. executed[axis_index] += 1
  1016. remaining[axis_index] -= 1
  1017. else:
  1018. raise AssertionError("scheduled axis event has no kind")
  1019. due_ms[axis_index] = None
  1020. due_kind[axis_index] = None
  1021. if any(remaining):
  1022. frozen = [
  1023. axis_index
  1024. for axis_index, axis in enumerate(self.axes)
  1025. if axis.drive_active
  1026. and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
  1027. and remaining[axis_index] == 0
  1028. ]
  1029. if frozen:
  1030. raise ValueError(
  1031. "requested counts would freeze active axes: "
  1032. + ",".join(map(str, frozen))
  1033. )
  1034. return tuple(executed) # type: ignore[return-value]
  1035. def execute_axis_steps(self, axis_index: int, count: int) -> int:
  1036. if axis_index not in (0, 1):
  1037. raise ValueError("only X and Y execute motion")
  1038. if count < 0:
  1039. raise ValueError("count must be non-negative")
  1040. counts = [0, 0, 0]
  1041. counts[axis_index] = count
  1042. return self.execute_parallel_steps(counts)[axis_index]
  1043. def complete_axis(
  1044. self,
  1045. axis_index: int,
  1046. ) -> None:
  1047. if axis_index not in (0, 1):
  1048. raise ValueError("only X and Y execute motion")
  1049. axis = self.axes[axis_index]
  1050. if not axis.drive_active:
  1051. raise ValueError("axis is not active")
  1052. self.execute_axis_steps(axis_index, axis.remaining_steps)
  1053. def motor_status_payload(self) -> bytes:
  1054. flags = 0x02
  1055. flags |= int(self.disabled) << 2
  1056. flags |= int(self.watchdog_timeout) << 3
  1057. return bytes((
  1058. flags,
  1059. 0,
  1060. 0,
  1061. UNKNOWN_POSITION,
  1062. UNKNOWN_POSITION,
  1063. UNKNOWN_POSITION,
  1064. UNKNOWN_POSITION,
  1065. UNKNOWN_POSITION,
  1066. UNKNOWN_POSITION,
  1067. 0,
  1068. ))
  1069. def feed_stream(
  1070. self,
  1071. data: bytes | bytearray,
  1072. ) -> list[ModelResult]:
  1073. raw = bytes(data)
  1074. accepted: list[ModelResult] = []
  1075. offset = 0
  1076. while True:
  1077. start = raw.find(MAGIC, offset)
  1078. if start < 0:
  1079. break
  1080. if len(raw) - start < 16:
  1081. break
  1082. end = start + 16 + raw[start + 13]
  1083. if end > len(raw):
  1084. offset = start + 1
  1085. continue
  1086. result = self.apply_frame(raw[start:end])
  1087. if result.accepted:
  1088. accepted.append(result)
  1089. offset = end if result.accepted else start + 1
  1090. return accepted
  1091. def _verify_golden_encoders() -> list[str]:
  1092. failures: list[str] = []
  1093. generated = {
  1094. "enable": encode_snapshot_frame(
  1095. ptc_percent=(0,) * 24,
  1096. fan_percent=(30,) * 4,
  1097. solenoid=0,
  1098. xyz=(0, 0, 0),
  1099. ),
  1100. "jog_x": encode_motion_frame(bytes((MOTION_JOG, 0, 1, 0, 1, 0, 0, 0))),
  1101. "jog_y": encode_motion_frame(bytes((MOTION_JOG, 1, 0, 0, 1, 0, 0, 0))),
  1102. "mark_x": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 0, 1, 0, 0, 0, 0, 0))),
  1103. "mark_y": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 1, 0, 0, 0, 0, 0, 0))),
  1104. "open": encode_snapshot_frame(
  1105. ptc_percent=(10,) * 24,
  1106. fan_percent=(70,) * 4,
  1107. solenoid=100,
  1108. xyz=(100, 100, 100),
  1109. ),
  1110. "close": encode_snapshot_frame(
  1111. ptc_percent=(10,) * 24,
  1112. fan_percent=(70,) * 4,
  1113. solenoid=0,
  1114. xyz=(0, 0, 0),
  1115. ),
  1116. "disable": encode_host_frame(bytes((CMD_DISABLE, 0, 0, 0))),
  1117. }
  1118. for name, value in generated.items():
  1119. if value != GOLDEN_VECTORS[name]:
  1120. failures.append(name)
  1121. return failures
  1122. def run_replay() -> dict[str, object]:
  1123. checks: list[dict[str, object]] = []
  1124. golden_failures = _verify_golden_encoders()
  1125. checks.append({"name": "fixed_golden_vectors", "status": "pass" if not golden_failures else "fail", "failures": golden_failures})
  1126. subject = NormalV3Model()
  1127. enable = subject.apply_frame(GOLDEN_VECTORS["enable"])
  1128. checks.append({
  1129. "name": "snapshot_xyz_has_no_motor_effect",
  1130. "status": "pass"
  1131. if enable.accepted and subject.active_mask == 0 and subject.busy_mask == 0
  1132. else "fail",
  1133. })
  1134. before_mark = subject.state_fingerprint()
  1135. mark = subject.apply_frame(GOLDEN_VECTORS["mark_x"])
  1136. checks.append({
  1137. "name": "mark_closed_tombstone_unsupported",
  1138. "status": "pass"
  1139. if not mark.accepted
  1140. and mark.status == STATUS_UNSUPPORTED
  1141. and subject.state_fingerprint() == before_mark
  1142. else "fail",
  1143. })
  1144. opened = subject.apply_frame(GOLDEN_VECTORS["open"])
  1145. checks.append({
  1146. "name": "legacy_open_fields_are_ignored",
  1147. "status": "pass"
  1148. if opened.accepted
  1149. and subject.active_mask == 0
  1150. and all(axis.current == UNKNOWN_POSITION for axis in subject.axes[:2])
  1151. else "fail",
  1152. })
  1153. force_jog = encode_motion_frame(
  1154. bytes((MOTION_JOG, 0, 1, 3, 0xFF, 0xFF, 0, 0))
  1155. )
  1156. jog_subject = NormalV3Model()
  1157. jog = jog_subject.apply_frame(force_jog)
  1158. checks.append({
  1159. "name": "jog_preserves_u16_and_acks_on_first_step",
  1160. "status": "pass"
  1161. if jog.accepted
  1162. and jog_subject.axes[0].remaining_steps == 0xFFFF
  1163. and jog_subject.axes[0].step_phase == "high"
  1164. and jog_subject.axes[0].current == UNKNOWN_POSITION
  1165. and jog_subject.active_mask == 1
  1166. and jog_subject.busy_mask == 0
  1167. and not jog_subject.watchdog_armed
  1168. else "fail",
  1169. })
  1170. before_motion = (
  1171. jog_subject.axes[0].drive_active,
  1172. jog_subject.axes[0].raw_dir,
  1173. jog_subject.axes[0].remaining_steps,
  1174. jog_subject.axes[0].step_phase,
  1175. )
  1176. jog_subject.disabled = False
  1177. jog_subject.watchdog_armed = True
  1178. jog_subject.watchdog_expire()
  1179. checks.append({
  1180. "name": "watchdog_safes_outputs_without_motor_effect",
  1181. "status": "pass"
  1182. if before_motion
  1183. == (
  1184. jog_subject.axes[0].drive_active,
  1185. jog_subject.axes[0].raw_dir,
  1186. jog_subject.axes[0].remaining_steps,
  1187. jog_subject.axes[0].step_phase,
  1188. )
  1189. else "fail",
  1190. })
  1191. before_unknown = subject.state_fingerprint()
  1192. unknown = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
  1193. checks.append({
  1194. "name": "temperature_tombstone_unsupported",
  1195. "status": "pass" if not unknown.accepted and unknown.status == STATUS_UNSUPPORTED and subject.state_fingerprint() == before_unknown else "fail",
  1196. })
  1197. final = jog_subject.state_payload()
  1198. motion_status = jog_subject.motor_status_payload()
  1199. final_ok = (
  1200. final["ptc_percent"] == [0] * 24
  1201. and final["fan_percent"] == [30] * 4
  1202. and final["solenoid"] == 0
  1203. and final["active_mask"] == 1
  1204. and final["busy_mask"] == 0
  1205. and final["axes"][0]["current"] == UNKNOWN_POSITION
  1206. and final["watchdog_timeout"] is True
  1207. and motion_status[0] & 0x02
  1208. and motion_status[1:] == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
  1209. )
  1210. checks.append({"name": "constant_motion_status", "status": "pass" if final_ok else "fail"})
  1211. status = "pass" if all(check["status"] == "pass" for check in checks) else "fail"
  1212. return {
  1213. "status": status,
  1214. "verification_layer": "binary921_v3_replay",
  1215. "vector_set": "binary921-v3-golden-v1",
  1216. "golden_vector_count": len(GOLDEN_VECTORS),
  1217. "checks": checks,
  1218. "final_state": final,
  1219. "authority_boundary": "Deterministic offline contract replay only; no RTL or hardware is accessed.",
  1220. }
  1221. def run_model() -> dict[str, object]:
  1222. subject = NormalV3Model()
  1223. initial = subject.state_fingerprint()
  1224. bad = bytearray(GOLDEN_VECTORS["open"])
  1225. bad[-1] ^= 1
  1226. rejected = subject.apply_frame(bytes(bad))
  1227. rejected_atomically = not rejected.accepted and subject.state_fingerprint() == initial
  1228. valid = subject.apply_frame(GOLDEN_VECTORS["open"])
  1229. jog_subject = NormalV3Model()
  1230. jog = jog_subject.apply_frame(GOLDEN_VECTORS["jog_x"])
  1231. checks = {
  1232. "canonical_crc": crc16_ccitt_false(b"123456789") == 0x29B1,
  1233. "initial_safe_hash": state_hash16(SAFE_PTC, SAFE_FAN, SAFE_SOLENOID) == 0xE177,
  1234. "bad_crc_rejected_atomically": rejected_atomically,
  1235. "valid_snapshot_committed_without_motor": valid.accepted and subject.ptc_percent == (10,) * 24,
  1236. "snapshot_xyz_ignored": valid.status == STATUS_OK and valid.detail == 0,
  1237. "jog_first_step_ack": (
  1238. jog.accepted
  1239. and jog_subject.active_mask == 1
  1240. and jog_subject.axes[0].step_phase == "high"
  1241. and jog_subject.axes[0].remaining_steps == 1
  1242. and not jog_subject.watchdog_armed
  1243. and jog_subject.busy_mask == 0
  1244. ),
  1245. "status_fields_constant": (
  1246. valid.status == STATUS_OK
  1247. and jog_subject.motor_status_payload()[1:]
  1248. == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
  1249. ),
  1250. }
  1251. return {
  1252. "status": "pass" if all(checks.values()) else "fail",
  1253. "verification_layer": "binary921_v3_model",
  1254. "checks": checks,
  1255. "authority_boundary": "Independent offline state model only; no RTL or hardware is accessed.",
  1256. }
  1257. def _repair_crc(frame: bytes) -> bytes:
  1258. return frame[:-2] + crc16_ccitt_false(frame[2:-2]).to_bytes(2, "little")
  1259. def run_fuzz(*, seed: int = 921003, iterations: int = 600) -> dict[str, object]:
  1260. if iterations < 9:
  1261. raise ValueError("iterations must be at least nine")
  1262. rng = random.Random(seed)
  1263. categories = (
  1264. "frame",
  1265. "crc",
  1266. "length",
  1267. "percent",
  1268. "solenoid",
  1269. "xyz",
  1270. "motion",
  1271. "host_unknown",
  1272. "stream_noise",
  1273. )
  1274. counts = {category: 0 for category in categories}
  1275. unexpected_accepts = 0
  1276. unexpected_rejections = 0
  1277. atomicity_violations = 0
  1278. stream_resync_failures = 0
  1279. for index in range(iterations):
  1280. category = categories[index % len(categories)]
  1281. counts[category] += 1
  1282. subject = NormalV3Model()
  1283. subject.apply_frame(GOLDEN_VECTORS["enable"])
  1284. before = subject.state_fingerprint()
  1285. candidate = bytearray(GOLDEN_VECTORS["open"])
  1286. result: ModelResult | None = None
  1287. expected_accept = False
  1288. if category == "frame":
  1289. variant = rng.randrange(6)
  1290. if variant == 0:
  1291. candidate[0] ^= 1
  1292. elif variant == 1:
  1293. candidate[2] = 3
  1294. candidate = bytearray(_repair_crc(bytes(candidate)))
  1295. elif variant == 2:
  1296. candidate[3] = 5
  1297. candidate = bytearray(_repair_crc(bytes(candidate)))
  1298. elif variant == 3:
  1299. candidate[4] = 0x08
  1300. candidate = bytearray(_repair_crc(bytes(candidate)))
  1301. elif variant == 4:
  1302. candidate[5 + rng.randrange(4)] = 1
  1303. candidate = bytearray(_repair_crc(bytes(candidate)))
  1304. else:
  1305. candidate[9 + rng.randrange(4)] = 1
  1306. candidate = bytearray(_repair_crc(bytes(candidate)))
  1307. result = subject.apply_frame(bytes(candidate))
  1308. elif category == "crc":
  1309. candidate[-rng.choice((1, 2))] ^= 1 << rng.randrange(8)
  1310. result = subject.apply_frame(bytes(candidate))
  1311. elif category == "length":
  1312. candidate[13] = rng.choice(tuple(value for value in range(256) if value != 34))
  1313. candidate = bytearray(_repair_crc(bytes(candidate)))
  1314. result = subject.apply_frame(bytes(candidate))
  1315. elif category == "percent":
  1316. candidate[16 + rng.randrange(28)] = rng.randrange(101, 256)
  1317. candidate = bytearray(_repair_crc(bytes(candidate)))
  1318. result = subject.apply_frame(bytes(candidate))
  1319. elif category == "solenoid":
  1320. candidate[44] = rng.randrange(1, 100)
  1321. candidate = bytearray(_repair_crc(bytes(candidate)))
  1322. result = subject.apply_frame(bytes(candidate))
  1323. elif category == "xyz":
  1324. candidate[45 + rng.randrange(3)] = rng.randrange(1, 100)
  1325. candidate = bytearray(_repair_crc(bytes(candidate)))
  1326. result = subject.apply_frame(bytes(candidate))
  1327. expected_accept = True
  1328. elif category == "motion":
  1329. variant = rng.randrange(6)
  1330. payload = bytearray((MOTION_JOG, 0, 0, 0, 1, 0, 0, 0))
  1331. if variant == 0:
  1332. payload[1] = 3
  1333. elif variant == 1:
  1334. payload[2] = 2
  1335. elif variant == 2:
  1336. payload[3] = 4
  1337. elif variant == 3:
  1338. payload[4:6] = b"\x00\x00"
  1339. elif variant == 4:
  1340. payload[6] = 1
  1341. else:
  1342. payload[7] = 1
  1343. if variant == 3:
  1344. try:
  1345. subject.apply_frame(encode_motion_frame(payload))
  1346. except HostContractViolation:
  1347. if subject.state_fingerprint() != before:
  1348. atomicity_violations += 1
  1349. else:
  1350. result = subject.apply_frame(encode_motion_frame(payload))
  1351. elif category == "host_unknown":
  1352. result = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
  1353. else:
  1354. noise = b"\xA5\x00\xA5" + bytes(rng.randrange(256) for _ in range(rng.randrange(1, 96)))
  1355. bad_frame = bytearray(GOLDEN_VECTORS["open"])
  1356. bad_frame[-1] ^= 1
  1357. accepted = subject.feed_stream(noise + bytes(bad_frame) + GOLDEN_VECTORS["enable"])
  1358. if len(accepted) != 1 or accepted[0].command != CMD_SET_SNAPSHOT:
  1359. stream_resync_failures += 1
  1360. if result is not None and result.accepted and not expected_accept:
  1361. unexpected_accepts += 1
  1362. if result is not None and not result.accepted and expected_accept:
  1363. unexpected_rejections += 1
  1364. if (
  1365. result is not None
  1366. and not expected_accept
  1367. and subject.state_fingerprint() != before
  1368. ):
  1369. atomicity_violations += 1
  1370. return {
  1371. "status": "pass"
  1372. if unexpected_accepts == 0
  1373. and unexpected_rejections == 0
  1374. and atomicity_violations == 0
  1375. and stream_resync_failures == 0
  1376. else "fail",
  1377. "verification_layer": "binary921_v3_fuzz",
  1378. "seed": seed,
  1379. "iterations": iterations,
  1380. "category_counts": counts,
  1381. "unexpected_accepts": unexpected_accepts,
  1382. "unexpected_rejections": unexpected_rejections,
  1383. "atomicity_violations": atomicity_violations,
  1384. "stream_resync_failures": stream_resync_failures,
  1385. "authority_boundary": "Deterministic malformed-frame fuzzing only; no UART or hardware is accessed.",
  1386. }
  1387. def _extract_production_sources(harness_path: Path) -> list[str]:
  1388. try:
  1389. module = ast.parse(harness_path.read_text(encoding="utf-8-sig"), filename=str(harness_path))
  1390. except (OSError, UnicodeError, SyntaxError) as exc:
  1391. raise ValueError(f"unable to parse production source registry: {exc}") from exc
  1392. for node in module.body:
  1393. if isinstance(node, ast.Assign):
  1394. for target in node.targets:
  1395. if isinstance(target, ast.Name) and target.id == "PROD2U_P4_NORMAL_V3_SOURCES":
  1396. value = ast.literal_eval(node.value)
  1397. if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
  1398. raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES must be a literal string list")
  1399. return value
  1400. if isinstance(node, ast.FunctionDef) and node.name == "active_rtl_sources":
  1401. project_root = harness_path.resolve().parents[1]
  1402. paths = sorted((project_root / "src" / "rtl").glob("*.v"))
  1403. paths.append(project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v")
  1404. return [
  1405. path.relative_to(project_root).as_posix()
  1406. for path in paths
  1407. if path.is_file()
  1408. ]
  1409. raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES is missing")
  1410. def run_detector(root: Path | str = ROOT) -> dict[str, object]:
  1411. project_root = Path(root).resolve()
  1412. failures: list[str] = []
  1413. try:
  1414. sources = _extract_production_sources(project_root / "tools" / "prod2u_p4_harness.py")
  1415. except ValueError as exc:
  1416. sources = []
  1417. failures.append(str(exc))
  1418. forbidden_name_tokens = ("tach", "telemetry", "single_channel", "old_motion")
  1419. forbidden_source_hits = [
  1420. source for source in sources if any(token in source.casefold() for token in forbidden_name_tokens)
  1421. ]
  1422. missing_sources = [source for source in sources if not (project_root / source).is_file()]
  1423. legacy_asset_hits = sorted(
  1424. path for path in LEGACY_P4_ASSET_PATHS if (project_root / path).is_file()
  1425. )
  1426. semantic_patterns = {
  1427. "tach_or_telemetry": re.compile(r"\bFAN_(?:TACH|TELEMETRY)\b|\bTACH_CAPTURE\b", re.IGNORECASE),
  1428. "single_channel": re.compile(r"\b(?:CMD_)?SET_(?:PTC|FAN)\b|\bSINGLE_CHANNEL\b", re.IGNORECASE),
  1429. "old_motion": re.compile(r"\b(?:MOTION|CMD|OPCODE)[A-Z0-9_]*\s*=\s*8'h3[0-4]\b", re.IGNORECASE),
  1430. "ready_semantics": re.compile(r"\b(?:FT|FRAME_TYPE|TYPE|CMD)_READY\b|\bREADY_FRAME\b|\bCAPABILITY_BROADCAST\b", re.IGNORECASE),
  1431. "runtime_build_identity": re.compile(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", re.IGNORECASE),
  1432. }
  1433. forbidden_semantic_hits: list[dict[str, str]] = []
  1434. for source in sources:
  1435. path = project_root / source
  1436. if not path.is_file():
  1437. continue
  1438. try:
  1439. text = path.read_text(encoding="utf-8-sig")
  1440. except (OSError, UnicodeError) as exc:
  1441. failures.append(f"unable to read {source}: {exc}")
  1442. continue
  1443. for semantic, pattern in semantic_patterns.items():
  1444. if pattern.search(text):
  1445. forbidden_semantic_hits.append({"source": source, "semantic": semantic})
  1446. top_path = project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v"
  1447. try:
  1448. top_text = top_path.read_text(encoding="utf-8-sig")
  1449. except (OSError, UnicodeError) as exc:
  1450. top_text = ""
  1451. failures.append(f"unable to read v3 top: {exc}")
  1452. guards = {
  1453. "runtime_build_identity_absent": not bool(
  1454. re.search(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", top_text, re.IGNORECASE)
  1455. ),
  1456. "solenoid_polarity_default_explicit": bool(
  1457. re.search(
  1458. r"parameter\s+integer\s+SOLENOID_ACTIVE_HIGH\s*=\s*[01]",
  1459. top_text,
  1460. re.IGNORECASE,
  1461. )
  1462. ),
  1463. "solenoid_polarity_elaboration_block": "g_solenoid_polarity_must_be_confirmed" in top_text and "prod2u_p4_solenoid_polarity_must_be_confirmed" in top_text,
  1464. }
  1465. missing_guards = [name for name, present in guards.items() if not present]
  1466. if forbidden_source_hits:
  1467. failures.append("forbidden source names are present")
  1468. if forbidden_semantic_hits:
  1469. failures.append("forbidden v2 semantics are present")
  1470. if missing_sources:
  1471. failures.append("production sources are missing")
  1472. if missing_guards:
  1473. failures.append("top-level identity or polarity guards are missing")
  1474. if legacy_asset_hits:
  1475. failures.append("legacy Profile 4 v2 assets are still present")
  1476. if len(sources) != len(set(sources)):
  1477. failures.append("production source list contains duplicates")
  1478. return {
  1479. "status": "pass" if not failures else "fail",
  1480. "verification_layer": "binary921_v3_detector",
  1481. "production_source_count": len(sources),
  1482. "production_sources": sources,
  1483. "forbidden_source_hits": forbidden_source_hits,
  1484. "forbidden_semantic_hits": forbidden_semantic_hits,
  1485. "missing_sources": missing_sources,
  1486. "legacy_asset_hits": legacy_asset_hits,
  1487. "guards": guards,
  1488. "missing_guards": missing_guards,
  1489. "failures": failures,
  1490. "authority_boundary": "Static production-source and elaboration-guard inspection only; no build or hardware is accessed.",
  1491. }
  1492. def run_selftest(root: Path | str = ROOT) -> dict[str, object]:
  1493. reports = {
  1494. "model": run_model(),
  1495. "replay": run_replay(),
  1496. "fuzz": run_fuzz(seed=921003, iterations=60),
  1497. "detector": run_detector(root),
  1498. }
  1499. layers = {name: report["status"] for name, report in reports.items()}
  1500. return {
  1501. "status": "pass" if all(status == "pass" for status in layers.values()) else "fail",
  1502. "profile": PROFILE_ID,
  1503. "hardware_opened": False,
  1504. "layers": layers,
  1505. "reports": reports,
  1506. "authority_boundary": "Offline selftest only; it does not enumerate or open serial, JTAG, or other hardware.",
  1507. }
  1508. def _build_parser() -> argparse.ArgumentParser:
  1509. parser = argparse.ArgumentParser(description=__doc__)
  1510. subparsers = parser.add_subparsers(dest="command", required=True)
  1511. for name in ("model", "replay"):
  1512. child = subparsers.add_parser(name)
  1513. child.add_argument("--json", action="store_true")
  1514. fuzz = subparsers.add_parser("fuzz")
  1515. fuzz.add_argument("--seed", type=int, default=921003)
  1516. fuzz.add_argument("--iterations", type=int, default=600)
  1517. fuzz.add_argument("--json", action="store_true")
  1518. detector = subparsers.add_parser("detector")
  1519. detector.add_argument("--root", type=Path, default=ROOT)
  1520. detector.add_argument("--json", action="store_true")
  1521. selftest = subparsers.add_parser("selftest")
  1522. selftest.add_argument("--root", type=Path, default=ROOT)
  1523. selftest.add_argument("--json", action="store_true")
  1524. return parser
  1525. def main(argv: Sequence[str] | None = None) -> int:
  1526. args = _build_parser().parse_args(argv)
  1527. if args.command == "model":
  1528. report = run_model()
  1529. elif args.command == "replay":
  1530. report = run_replay()
  1531. elif args.command == "fuzz":
  1532. report = run_fuzz(seed=args.seed, iterations=args.iterations)
  1533. elif args.command == "detector":
  1534. report = run_detector(args.root)
  1535. else:
  1536. report = run_selftest(args.root)
  1537. print(json.dumps(report, indent=2, sort_keys=True))
  1538. return 0 if report.get("status") == "pass" else 1
  1539. if __name__ == "__main__":
  1540. raise SystemExit(main())